Compare commits
163 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4c21e3a2a9 | |||
| c4ea17507f | |||
| 19d30dd292 | |||
| 1e930af7d4 | |||
| 833227a717 | |||
| 04562fd7e7 | |||
| 4984f20e8f | |||
| fe393d2ca6 | |||
| 34c82c3488 | |||
| 00a7db2690 | |||
| 7fb839aef6 | |||
| 6713b34978 | |||
| 7a7fb71bf5 | |||
| 1c89bd8b2a | |||
| 050be0fe0e | |||
| 297240f8ef | |||
| 2b16a00464 | |||
| b31a893b13 | |||
| b9e17be855 | |||
| 900be65617 | |||
| 53a67d7573 | |||
| 7d28f5516a | |||
| 849b3a7034 | |||
| 374907b607 | |||
| 9f35088788 | |||
| fd139b28a2 | |||
| de6f80694b | |||
| b87535ad48 | |||
| 6da61d7951 | |||
| 968d147046 | |||
| 93a55df4c0 | |||
| 82592784d0 | |||
| acfa4b3c2e | |||
| a7a18dd0d1 | |||
| 1cfede28b7 | |||
| c8ef808539 | |||
| b8857e789e | |||
| 5f2d855702 | |||
| 0466528925 | |||
| e4a6aad621 | |||
| 2cec8dc4a4 | |||
| 667291a2dc | |||
| eff74bed5b | |||
| 8f29e2eee2 | |||
| 9d7a557ef0 | |||
| 2664b4956d | |||
| f7caf0de70 | |||
| 0c1dc580c6 | |||
| f867989557 | |||
| 467dea1315 | |||
| da40d5662d | |||
| 7b4e9488f6 | |||
| d7a9d2bfba | |||
| 531d5cff30 | |||
| 8ee97ba1ba | |||
| 0e8c61a776 | |||
| 9582758d1c | |||
| f204b67880 | |||
| db61365e11 | |||
| bc1e6fb22c | |||
| 64ee0459e4 | |||
| d855e9e47f | |||
| dc7b8dc72a | |||
| 57b5216306 | |||
| e249bff5d6 | |||
| 85489cff3f | |||
| 57aaca82f5 | |||
| ff1c8722c9 | |||
| 018f18fa0c | |||
| eaeee7a765 | |||
| 618c936ac9 | |||
| 0ed6397fa9 | |||
| dce9eaa597 | |||
| 628a99e7aa | |||
| 4d74afd711 | |||
| e2c9aab7ba | |||
| e23d69fcec | |||
| e850419f10 | |||
| 360d579415 | |||
| c67f55fe0d | |||
| 310edae013 | |||
| 8fb97d9359 | |||
| d33c5d6c07 | |||
| 2449a5cbbe | |||
| e5f29eb041 | |||
| 31c7e2e9c1 | |||
| e25fcfc6ef | |||
| b2cf4aaa91 | |||
| 1256ddcd1a | |||
| 58faf9eaec | |||
| ded5c899f7 | |||
| fa7de589c1 | |||
| 69868418e5 | |||
| 062c4865db | |||
| 1dfa78013c | |||
| 60c97f778b | |||
| 83c6db4834 | |||
| ed3ae14d0c | |||
| 69a9899d40 | |||
| e32e2f779d | |||
| ccb61d6473 | |||
| 2fab50c340 | |||
| 69b5ca0670 | |||
| 06c3996da4 | |||
| faba3a8ed6 | |||
| 4c72058d4a | |||
| 9c004791f2 | |||
| cdcabee80d | |||
| 9ae5d7bb60 | |||
| efdf2a3189 | |||
| 2a90f871b9 | |||
| b47678cfb0 | |||
| d708365aca | |||
| 2cdbbc09ba | |||
| 4eaedd33bf | |||
| f605d8a39c | |||
| cc5be7059f | |||
| 739ba2986f | |||
| f52e6aedac | |||
| 256cbfcadf | |||
| dc3d22f52d | |||
| 7ea8fbd584 | |||
| b96e819da4 | |||
| 399ca86561 | |||
| 200f91ef17 | |||
| 59f0e42be7 | |||
| 2044cecc6e | |||
| ffffccb389 | |||
| 28d263fc8d | |||
| bfef7cc629 | |||
| a696896d2c | |||
| fd2e419e8e | |||
| aaf0263fda | |||
| d4d5031cc2 | |||
| b2d7abf5bd | |||
| 0f9f843236 | |||
| cab425cfac | |||
| 0da0c5547d | |||
| 988d0e5c2f | |||
| 1ce91749aa | |||
| 731eb24364 | |||
| a15403b8b6 | |||
| ff8f3d02cf | |||
| 69f57eddd6 | |||
| fe567fffa8 | |||
| f300e07ce2 | |||
| 628997fb48 | |||
| 3dc0b93bdf | |||
| bea9da96d4 | |||
| 388fc7ee67 | |||
| f6b6e22a95 | |||
| 60c4fe2e23 | |||
| c1da8a4dba | |||
| af6686ccfa | |||
| 8893fc128e | |||
| 4598c2785a | |||
| 5a7dd3f164 | |||
| bc7d0612f1 | |||
| 1646f04bde | |||
| 3fee54f657 | |||
| a594a0f79f | |||
| 3642462670 | |||
| 26efb157e4 |
@@ -16,6 +16,10 @@ __pycache__/
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.venv/
|
||||
tests/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
|
||||
@@ -630,6 +630,13 @@ FREEKASSA_WEBHOOK_PORT=8088
|
||||
FREEKASSA_PAYMENT_SYSTEM_ID=
|
||||
# Использовать API для создания заказов (обязательно для NSPK СБП)
|
||||
FREEKASSA_USE_API=false
|
||||
# Раздельные методы оплаты (отображаются как отдельные кнопки)
|
||||
# СБП (QR код) — i=44
|
||||
FREEKASSA_SBP_ENABLED=false
|
||||
FREEKASSA_SBP_DISPLAY_NAME=СБП (QR код)
|
||||
# Карты РФ — i=36
|
||||
FREEKASSA_CARD_ENABLED=false
|
||||
FREEKASSA_CARD_DISPLAY_NAME=Карта РФ
|
||||
|
||||
# ===== KASSA AI (api.fk.life) =====
|
||||
# Отдельная платёжная система, работает параллельно с Freekassa
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "3.18.0"
|
||||
".": "3.23.1"
|
||||
}
|
||||
|
||||
+197
@@ -1,5 +1,202 @@
|
||||
# Changelog
|
||||
|
||||
## [3.23.1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.23.0...v3.23.1) (2026-03-06)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* complete FK migration — add 27 missing constraints, fix broadcast_history nullable ([fe393d2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/fe393d2ca6ce302d8213cc751842ea92ef277e76))
|
||||
* UniqueViolation при мерже аккаунтов с общим OAuth/telegram/email ID ([1c89bd8](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1c89bd8b2acfe49de2c97dd75446a037a54fded7))
|
||||
* дедупликация promocode_uses при мерже аккаунтов ([00a7db2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/00a7db26905d53a9a978aaf6b97800ca3042b957))
|
||||
* добавить ON DELETE CASCADE/SET NULL на все FK к users.id ([34c82c3](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/34c82c348829cf528154bd1e2f5d77006d7ed5da))
|
||||
* дубликаты системных ролей при переименовании и сброс permissions ([7a7fb71](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7a7fb71bf535e2a501f0677747ba63ca0b27ede5))
|
||||
* исправления системы реферальных конкурсов ([6713b34](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/6713b3497854e73dddc212280d7bf12db818f38a))
|
||||
* кнопка «Назад» в тарифах ведёт в админ панель, а не в настройки ([04562fd](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/04562fd7e74de26776517549730819389b24a0d0))
|
||||
* промокоды — конвертация триалов, race condition, savepoints ([7fb839a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7fb839aef6234294b95064f9575c19d5a0c3f892))
|
||||
* устранение race conditions и атомарность платёжной системы ([4984f20](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4984f20e8fb030ee338723d797d51aee21f67ca8))
|
||||
|
||||
## [3.23.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.22.0...v3.23.0) (2026-03-05)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* account linking and merge system for cabinet ([dc7b8dc](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/dc7b8dc72a3a398d6270a0a2b8ce9e2b54cb9af7))
|
||||
* account merge system — atomic user merge with full FK coverage ([2664b49](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2664b4956d8436a2720d7cd5992b8cdbb72cdbd9))
|
||||
* add dedicated sales_stats RBAC permission section ([8f29e2e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/8f29e2eee2e0c78f7f7e87a322eaf4bd4221069c))
|
||||
* add server-complete OAuth linking endpoint for Mini App flow ([f867989](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/f867989557d20378cfe815c9c88e1a842c4f6654))
|
||||
* add Telegram account linking endpoint with security hardening ([da40d56](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/da40d5662d6d064090769823d616d6f9748ab5b9))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* abs() for transaction amounts in admin notifications and subscription events ([fd139b2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/fd139b28a2c45cc3fbd2e01707fb83fbabf57c71))
|
||||
* add abs() to expenses query, display flip, contest stats, and recent payments ([de6f806](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/de6f80694ba8aa240764e2769ec04c16fe7f3672))
|
||||
* add IntegrityError handling on link commit and format fixes ([0c1dc58](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0c1dc580c67254d11ffb096c22d8c8d78ac18e2b))
|
||||
* add missing mark_as_paid_subscription, fix operation order, remove dead code ([5f2d855](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/5f2d855702dea838b38887a5f44b9ad759acd5cf))
|
||||
* auto-update permissions for system roles on bootstrap ([eff74be](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/eff74bed5bcc47a6cfa05c20cad14a40c1572d1f))
|
||||
* centralize balance deduction and fix unchecked return values ([0466528](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0466528925a24087b8522a10cbb11c947c2b7d91))
|
||||
* centralize has_had_paid_subscription into subtract_user_balance ([e4a6aad](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e4a6aad621be7ef4e7aedb21373927ede0c8d0a5))
|
||||
* clean email verification and password fields from secondary user during merge ([7b4e948](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7b4e9488f6fbd1271f063579e48ca9a3c96cb645))
|
||||
* consume promo offer in miniapp tariff-mode renewal path ([b8857e7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b8857e789ef60cf0c8766abbeadd094f62070a61))
|
||||
* consume promo offer in tariff_purchase.py, fix negative transaction amount ([c8ef808](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/c8ef80853915af3e3eb254edd07d8d78b66a9282))
|
||||
* delete cross-referral earnings before bulk reassignment, clear secondary.referred_by_id ([f204b67](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/f204b678803297ce60faad628d16f46344b11ed0))
|
||||
* from redis.exceptions import NoScriptError ([667291a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/667291a2dcaeae21e27eeb6376085e69caa4e45a))
|
||||
* harden account merge security and correctness ([d855e9e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/d855e9e47fab1a038e581437a9921bdfeb11e927))
|
||||
* **merge:** validate before consuming token, add flush, defensive balance ([bc1e6fb](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/bc1e6fb22c6e23c7a34364796f51a55c60224aff))
|
||||
* negative balance transfer, linking state validation, referrer migration ([531d5cf](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/531d5cff3019e72dde6ee64977cb801e8f8c8d0b))
|
||||
* prevent concurrent device purchases exceeding max device limit ([1cfede2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1cfede28b7570bcaf77cb53d6b2a9f3b0e4e9408))
|
||||
* prevent infinite reuse of first_purchase_only promo code discounts ([2cec8dc](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2cec8dc4a487017f4b1c5ca80710f2d70045b825))
|
||||
* prevent self-referral loops, invalidate all sessions on merge ([db61365](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/db61365e11ccec4dd45671b33da00f4b05484589))
|
||||
* reassign orphaned records on merge, eliminate TOCTOU race ([d7a9d2b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/d7a9d2bfba5b796882d3e04be6038b766cd0a4c8))
|
||||
* redis cache uses sync client due to import shadowing ([667291a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/667291a2dcaeae21e27eeb6376085e69caa4e45a))
|
||||
* restore merge token on DB failure, fix partner_status priority ([9582758](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9582758d1c85735c8ead8cbfeb56bbdae45288af))
|
||||
* review findings — exception chaining, redundant unquote, validator tightening ([467dea1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/467dea1315fbaf8d09ccbba292cd0bcc60d9f3ab))
|
||||
* second round review fixes for account merge ([64ee045](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/64ee0459e4e3d3fe87ad65387fcbcb147147ac1b))
|
||||
* use short TTL fallback in restore_merge_token on parse error ([0e8c61a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0e8c61a7762ae796284144056c0cbdbcb53b6c7c))
|
||||
* гарантировать положительный доход от подписок и исправить общий доход ([93a55df](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/93a55df4c0ac099946d440ec79fefb24327ab0e1))
|
||||
* добавить create_transaction для 6 потоков оплаты с баланса ([374907b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/374907b6078c483531061465983e23f281e841a2))
|
||||
* добавить create_transaction и admin-уведомления для автопродлений ([9f35088](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9f35088788c971cb757936dba7214abe54477af0))
|
||||
* добавить пробелы в формат тарифов (1000 ГБ / 2 📱) ([900be65](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/900be65617dd5bbc6ffdcc82bb5504e1a93ead95))
|
||||
* изолировать stored_amount от downstream consumers в create_transaction ([b87535a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b87535ad4842cbf1f99f6fc1e28b5932fa5e3baa))
|
||||
* передать явный диапазон дат для all_time_stats в дашборде ([968d147](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/968d14704610eed528bca28cbf295c1ba1644a5a))
|
||||
* показывать кнопку покупки тарифа вместо ошибки для триальных подписок ([acfa4b3](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/acfa4b3c2ea96e74d93470085265df76ec50e1e6))
|
||||
* показывать только активные провайдеры на странице /profile/accounts ([9d7a557](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9d7a557ef0e294ce9920e9953bb1358656ff9b81))
|
||||
* реактивация DISABLED подписок при покупке трафика для LIMITED пользователей ([7d28f55](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7d28f5516a52606280219cbea846fba431da80d2))
|
||||
* реактивация DISABLED подписок при покупке устройств и в REST API ([b9e17be](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b9e17be8554a65eaf765a0b5b36fee062205c66f))
|
||||
* синхронизация версии pyproject.toml с main и обновление uv в Dockerfile ([b31a893](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b31a893b13b2db911e51298ceb0107419f9a4cb3))
|
||||
* убрать WITHDRAWAL из автонегации, добавить abs() в агрегации, исправить all_time_stats ([6da61d7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/6da61d79510f7e05310f3cc020515b4dd0b3eb34))
|
||||
* убрать избыточный минус в amount_kopeks для create_transaction ([849b3a7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/849b3a7034f2291db40e049c12e1b7c71b58bab1))
|
||||
* устранение race condition при покупке устройств через re-lock после коммита ([a7a18dd](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a7a18dd0d1d59c64f7e4dd3ddc1b8cec47198077))
|
||||
* устранение каскадного PendingRollbackError при восстановлении бэкапа ([8259278](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/82592784d0da8b8718f3b3aa34076af59ad2a878))
|
||||
|
||||
|
||||
### Refactoring
|
||||
|
||||
* extract shared OAuth linking logic, add Literal types for providers ([f7caf0d](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/f7caf0de709ca6a46283f0b1928e34f8908f2c93))
|
||||
|
||||
## [3.22.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.21.0...v3.22.0) (2026-03-04)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* replace pip with uv in Dockerfile ([e23d69f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e23d69fcec7ab65a14b054fd46f6ecf87ae6fd13))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add selectinload for campaign registrations in list query ([4d74afd](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4d74afd7118524623371f904a93ae1fcbba8d64e))
|
||||
* backup restore fails on FK constraints and transaction poisoning ([ff1c872](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ff1c8722c9188fdbaf765d6b7e9192686df64850))
|
||||
* classic mode prices overridden by active tariff prices ([628a99e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/628a99e7aa0812842dabc430857190c0cd5c2680))
|
||||
* close remaining daily subscription expire paths ([618c936](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/618c936ac9ce4904cd784bf2278d3da188895f2d))
|
||||
* empty JSONB values exported as None in backup ([57aaca8](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/57aaca82f5bf9d7bdd9d4b924aa3412d85eccbb5))
|
||||
* handle duplicate remnawave_uuid on email sync ([eaeee7a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/eaeee7a765c03ff33e2928cdb41be91948eca95c))
|
||||
* MissingGreenlet on campaign registrations access ([018f18f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/018f18fa0c9bba1a1dbca8b2398b9611d0c94c36))
|
||||
* prevent daily subscriptions from being expired by middleware/CRUD/webhook ([0ed6397](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0ed6397fa9e5810fcffc9152ab2241fcf37cf85a))
|
||||
* reset traffic purchases on expired subscription renewal + pricing fixes ([dce9eaa](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/dce9eaa5971cb1dc0945747e02397a250e8e411b))
|
||||
|
||||
## [3.21.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.20.1...v3.21.0) (2026-03-02)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* add admin campaign chart data endpoint with deposits/spending split ([fa7de58](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/fa7de589c1bd0ae37ebaaa07bae0ed3d68e01720))
|
||||
* add admin sales statistics API with 6 analytics endpoints ([58faf9e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/58faf9eaeca63c458093d2a5e74a860f57712ab0))
|
||||
* add daily deposits by payment method breakdown ([d33c5d6](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/d33c5d6c07ce4a9efaf3c5aceb448e968e1b8ed7))
|
||||
* add daily device purchases chart to addons stats ([2449a5c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2449a5cbbe5179a762197414a5752896383a6ee4))
|
||||
* add desired commission percent to partner application ([7ea8fbd](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7ea8fbd584aff2127595001094ef69acb52f847f))
|
||||
* add RESET_TRAFFIC_ON_TARIFF_SWITCH admin setting ([4eaedd3](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4eaedd33bf697469fe9ed6a1bfe8b59ca43b46fb))
|
||||
* enhance sales stats with device purchases, per-tariff daily breakdown, and registration tracking ([31c7e2e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/31c7e2e9c14cb88762a62a72e4f65051e0c6c1fd))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add exc_info traceback to sync user error log ([efdf2a3](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/efdf2a3189a2f790e570f9a6e19d91469be4ea4f))
|
||||
* add local traffic_used_gb reset in all tariff switch handlers ([2cdbbc0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2cdbbc09ba9a19dcb720049ffde08ba780ac5751))
|
||||
* add min_length to state field, use exc_info for referral warning ([062c486](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/062c4865db194f9d2242772044402fa2711a69bd))
|
||||
* add missing subscription columns migration ([b96e819](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b96e819da4cc37710e9fc17467045b33bcffac4d))
|
||||
* address review findings from agent verification ([cc5be70](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/cc5be7059fdf4cefb01e97196c825b217f8b54b3))
|
||||
* correct cart notification after balance top-up ([2fab50c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2fab50c340c885fc92a4bf797a4b03da6e44af31))
|
||||
* correct referral withdrawal balance formula and commission transaction type ([83c6db4](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/83c6db48349440447305604e944fa440bdceb3fb))
|
||||
* count sales from completed payment transactions instead of subscription created_at ([06c3996](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/06c3996da4fa14eafb294651158068c7cda51e52))
|
||||
* eliminate double panel API call on tariff change, harden cart notification ([b2cf4aa](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b2cf4aaa91f3fb63dca7e70645cadb75aa158cfe))
|
||||
* eliminate referral system inconsistencies ([60c97f7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/60c97f778bc4cc18aaf4d8a31826bc831c3b3f8f))
|
||||
* email verification bypass, ban-notifications size limit, referral balance API ([256cbfc](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/256cbfcadfd2fc88d8de69557c78618639af157d))
|
||||
* enforce user restrictions in cabinet API and fix poll history crash ([faba3a8](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/faba3a8ed6d428305f9ca7d7fd9bdcc1fd72ba52))
|
||||
* freekassa OP-SP-7 error and missing telegram notification ([200f91e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/200f91ef1748bb6213d1ef3a8e83ae976290a8a7))
|
||||
* generate missing crypto link on the fly and skip unresolved templates ([4c72058](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4c72058d4ad8b0594991b17323928d9004803bfa))
|
||||
* handle expired callback queries and harden middleware error handling ([f52e6ae](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/f52e6aedac3de1c9bb2ad1a5a16b06d38b79ab63))
|
||||
* handle expired ORM attributes in sync UUID mutation ([9ae5d7b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9ae5d7bb60c57e2c29d6f3c5098c23450d5feb61))
|
||||
* handle NULL used_promocodes for migrated users ([cdcabee](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/cdcabee80d1d7f0b367a97cdec20bb49e8592115))
|
||||
* hide traffic topup button when tariff doesn't support it ([399ca86](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/399ca86561f4271e9c542bac87c0dd2931a223e0))
|
||||
* improve campaign routes, schemas, and add database indexes ([ded5c89](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ded5c899f7425707b17fef4d0d5ceafac777ef08))
|
||||
* include desired_commission_percent in admin notification ([dc3d22f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/dc3d22f52db40150d595bccf524d38790e5725d9))
|
||||
* migrate VK OAuth to VK ID OAuth 2.1 with PKCE ([1dfa780](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1dfa78013c4fb926a2b32bf4d63baa28215e7340))
|
||||
* partner system — CRUD nullable fields, per-campaign stats, atomic unassign, diagnostic logging ([ed3ae14](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ed3ae14d0c378fa0dc2d442c3aa5a70172f3132c))
|
||||
* prevent squad drop on admin subscription type change, require subscription for wheel spins ([59f0e42](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/59f0e42be7e3c679d15cf2fc6820ab7097cd2201))
|
||||
* prevent sync from overwriting subscription URLs with empty strings ([9c00479](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9c004791f28fbcf314b93c1b2a38593069605239))
|
||||
* reject promo codes for days when user has no subscription or trial ([e32e2f7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e32e2f779d014d587b58d63b513fd913ae1b7a41))
|
||||
* remove premature tariff_id assignment in _apply_extension_updates ([b47678c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b47678cfb0ba5897b37dfe1f94e3d1336af5698e))
|
||||
* renewals stats empty on all-time filter ([e25fcfc](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e25fcfc6ef941465b83f368f152304ea5a6747d9))
|
||||
* resolve GROUP BY mismatch for daily_by_tariff query ([e5f29eb](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e5f29eb041e88bc6315f0b4da3b78898d9dd7fff))
|
||||
* restore panel user discovery on admin tariff change, localize cart reminder ([1256ddc](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1256ddcd1a772f90e7bdf9437043a47ea9d84d53))
|
||||
* separate base and purchased traffic in renewal pricing ([739ba29](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/739ba2986f41b04058eb14e8b87b0699fe96f922))
|
||||
* sync traffic reset across all tariff switch code paths ([d708365](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/d708365aca9dfd5c3afda1a1de4303e0bd1d263e))
|
||||
* use .is_(True) and add or 0 guards per code review ([69b5ca0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/69b5ca06701e7381c39448e2bf6b927f0558058c))
|
||||
* use direct is_trial access, add missing error codes to promo APIs ([69a9899](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/69a9899d40dda83e83cbdba1aa43d9d1f756704b))
|
||||
* use float instead of int | float (PYI041) ([310edae](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/310edae013973d8533051088f3720cc5da3651b5))
|
||||
* use SAVEPOINT instead of full rollback in sync user creation ([2a90f87](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2a90f871b97b2b7ee8289e62294c65f8becb2539))
|
||||
|
||||
## [3.20.1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.20.0...v3.20.1) (2026-02-25)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* make migrations 0010/0011 idempotent, escape HTML in crash notification ([a696896](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a696896d2c4a3d0d6026398fcdc76ded9575375d))
|
||||
* prevent race condition expiring active daily subscriptions ([bfef7cc](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/bfef7cc6296e296f17068e519469c3deaddc1b3b))
|
||||
|
||||
## [3.20.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.19.0...v3.20.0) (2026-02-25)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* add separate Freekassa SBP and card payment methods ([0da0c55](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0da0c5547d0648a70f848fe77c13d583f4868a52))
|
||||
* add validation to animation config API ([a15403b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a15403b8b6e1ec1bb5c37fdde646e7790373e860))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* initialize logger in bot_configuration.py ([988d0e5](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/988d0e5c2f27538135d757187a0b6770f078b1d9))
|
||||
* remove gemini-effect and noise from allowed background types ([731eb24](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/731eb2436428d0e12f1e5ccdebc72cd74fd7c65e))
|
||||
* resolve ruff lint errors (import sorting, unused variable) ([b2d7abf](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b2d7abf5bd10a98fd7ad1da50b5072afc65a5b48))
|
||||
* resolve sync 404 errors, user deletion FK constraint, and device limit not sent to RemnaWave ([1ce9174](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1ce91749aa12ffcefcf66bea714cea218739f3fe))
|
||||
|
||||
## [3.19.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.18.0...v3.19.0) (2026-02-25)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* add granular user permissions (balance, subscription, promo_group, referral, send_offer) ([60c4fe2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/60c4fe2e239d8fef7726cac769711c8fcce789eb))
|
||||
* add per-channel disable settings and fix CHANNEL_REQUIRED_FOR_ALL bug ([3642462](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3642462670c876052aa668c1515af8c04234cb34))
|
||||
* add RBAC + ABAC permission system for admin cabinet ([3fee54f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3fee54f657dc6e0db1ec36697850ada2235e6968))
|
||||
* add resource_type and request body to audit log entries ([388fc7e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/388fc7ee67f5fc0edf6b7b64b977e12a2d8f0566))
|
||||
* allow editing system roles ([f6b6e22](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/f6b6e22a9528dc05b7fbfa80b63051a75c8e73cd))
|
||||
* capture query params in audit log details for all requests ([bea9da9](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/bea9da96d44965fcee5e2eba448960443152d4ea))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* address RBAC review findings (CRITICAL + HIGH) ([1646f04](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1646f04bde47a08f3fd782b7831d40760bd1ba60))
|
||||
* align RBAC route prefixes with frontend API paths ([5a7dd3f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/5a7dd3f16408f3497a9765e79a540ccdabc50e69))
|
||||
* always include details in successful audit log entries ([3dc0b93](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3dc0b93bdfc85fb97f371dc34e024272766afc65))
|
||||
* extract real client IP from X-Forwarded-For/X-Real-IP headers ([af6686c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/af6686ccfae12876e867cdabe729d0c893bd85a1))
|
||||
* grant legacy config-based admins full RBAC access ([8893fc1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/8893fc128e3d8927054f1df1647e896e780c69e7))
|
||||
* improve campaign notifications and ticket media in admin topics ([a594a0f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a594a0f79f48227f75d6102b4586179102c4d344))
|
||||
* RBAC API response format fixes and audit log user info ([4598c27](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4598c2785a42773ee8be04ada1c00d14824e07e0))
|
||||
* RBAC audit log action filter and legacy admin level ([c1da8a4](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/c1da8a4dba5d0c993d3e15b2866bdcfa09de1752))
|
||||
* restore subscription_url and crypto_link after panel sync ([26efb15](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/26efb157e476a18b036d09167628a295d7e4c10b))
|
||||
* specify foreign_keys on User.admin_roles_rel to resolve ambiguous join ([bc7d061](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/bc7d0612f1476f2fdb498cd76a9374b41fd9440a))
|
||||
* stack promo group + promo offer discounts in bot (matching cabinet) ([628997f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/628997fb48413cc4fae9ac491d1c7f6185877200))
|
||||
|
||||
## [3.18.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.17.1...v3.18.0) (2026-02-24)
|
||||
|
||||
|
||||
|
||||
+16
-17
@@ -4,27 +4,27 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN python -m venv /opt/venv
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.10.8 /uv /uvx /bin/
|
||||
|
||||
COPY requirements.txt .
|
||||
ENV UV_COMPILE_BYTECODE=1 \
|
||||
UV_LINK_MODE=copy \
|
||||
UV_PYTHON_DOWNLOADS=never
|
||||
|
||||
RUN pip install --no-cache-dir --upgrade pip && \
|
||||
pip install --no-cache-dir -r requirements.txt
|
||||
WORKDIR /app
|
||||
|
||||
RUN --mount=type=cache,target=/root/.cache/uv \
|
||||
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
|
||||
--mount=type=bind,source=uv.lock,target=uv.lock \
|
||||
uv sync --locked --no-dev
|
||||
|
||||
FROM python:3.13-slim
|
||||
|
||||
ARG VERSION="v3.18.0" # x-release-please-version
|
||||
ARG VERSION="v3.23.1" # x-release-please-version
|
||||
ARG BUILD_DATE
|
||||
ARG VCS_REF
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
wget \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& apt-get clean
|
||||
|
||||
COPY --from=builder /opt/venv /opt/venv
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
COPY --from=builder /app/.venv /app/.venv
|
||||
ENV PATH="/app/.venv/bin:$PATH"
|
||||
|
||||
RUN groupadd -g 1000 app && \
|
||||
useradd -u 1000 -g 1000 -m -s /bin/bash app
|
||||
@@ -33,8 +33,7 @@ WORKDIR /app
|
||||
|
||||
COPY --chown=app:app . .
|
||||
|
||||
RUN mkdir -p logs data && \
|
||||
chown -R app:app /app logs data
|
||||
RUN mkdir -p logs data && chown app:app logs data
|
||||
|
||||
USER app
|
||||
|
||||
@@ -56,7 +55,7 @@ LABEL org.opencontainers.image.title="Bedolaga RemnaWave Bot" \
|
||||
org.opencontainers.image.url="https://github.com/fr1ngg/remnawave-bedolaga-telegram-bot" \
|
||||
org.opencontainers.image.vendor="fr1ngg"
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
|
||||
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')" || exit 1
|
||||
|
||||
CMD ["python", "main.py"]
|
||||
|
||||
+3
-2
@@ -132,8 +132,9 @@ async def setup_bot() -> tuple[Bot, Dispatcher]:
|
||||
dp.message.middleware(blacklist_middleware)
|
||||
dp.callback_query.middleware(blacklist_middleware)
|
||||
dp.pre_checkout_query.middleware(blacklist_middleware)
|
||||
dp.message.middleware(ThrottlingMiddleware())
|
||||
dp.callback_query.middleware(ThrottlingMiddleware())
|
||||
throttling_middleware = ThrottlingMiddleware()
|
||||
dp.message.middleware(throttling_middleware)
|
||||
dp.callback_query.middleware(throttling_middleware)
|
||||
|
||||
# Middleware для автоматического логирования кликов по кнопкам
|
||||
if settings.MENU_LAYOUT_ENABLED:
|
||||
|
||||
@@ -11,13 +11,23 @@ from app.config import settings
|
||||
JWT_ALGORITHM = 'HS256'
|
||||
|
||||
|
||||
def create_access_token(user_id: int, telegram_id: int | None = None) -> str:
|
||||
def create_access_token(
|
||||
user_id: int,
|
||||
telegram_id: int | None = None,
|
||||
*,
|
||||
permissions: list[str] | None = None,
|
||||
roles: list[str] | None = None,
|
||||
role_level: int = 0,
|
||||
) -> str:
|
||||
"""
|
||||
Create a short-lived access token.
|
||||
|
||||
Args:
|
||||
user_id: Database user ID
|
||||
telegram_id: Telegram user ID (optional for email-only users)
|
||||
permissions: RBAC permission strings to embed in token
|
||||
roles: Role names to embed in token
|
||||
role_level: Maximum role level (0 = no special level)
|
||||
|
||||
Returns:
|
||||
Encoded JWT access token
|
||||
@@ -36,6 +46,14 @@ def create_access_token(user_id: int, telegram_id: int | None = None) -> str:
|
||||
if telegram_id is not None:
|
||||
payload['telegram_id'] = telegram_id
|
||||
|
||||
# RBAC data — only include when provided to keep token compact
|
||||
if permissions is not None:
|
||||
payload['permissions'] = permissions
|
||||
if roles is not None:
|
||||
payload['roles'] = roles
|
||||
if role_level > 0:
|
||||
payload['role_level'] = role_level
|
||||
|
||||
secret = settings.get_cabinet_jwt_secret()
|
||||
return jwt.encode(payload, secret, algorithm=JWT_ALGORITHM)
|
||||
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Temporary merge token management for account linking.
|
||||
|
||||
Stores short-lived tokens in Redis so the user can confirm merging
|
||||
two cabinet accounts (primary absorbs secondary) via a separate
|
||||
confirmation endpoint.
|
||||
"""
|
||||
|
||||
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__)
|
||||
|
||||
MERGE_TOKEN_TTL_SECONDS = 1800 # 30 minutes
|
||||
MERGE_TOKEN_PREFIX = 'account_merge'
|
||||
|
||||
|
||||
async def create_merge_token(
|
||||
primary_user_id: int,
|
||||
secondary_user_id: int,
|
||||
provider: str,
|
||||
provider_id: str,
|
||||
) -> str:
|
||||
"""Generate a merge token and store its payload in Redis.
|
||||
|
||||
The token is a one-time confirmation handle: whoever presents it
|
||||
within ``MERGE_TOKEN_TTL_SECONDS`` can execute the account merge.
|
||||
|
||||
Returns the raw token string (URL-safe base64, 32 bytes of entropy).
|
||||
Raises ``RuntimeError`` if Redis write fails.
|
||||
"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
value: dict[str, Any] = {
|
||||
'primary_user_id': primary_user_id,
|
||||
'secondary_user_id': secondary_user_id,
|
||||
'provider': provider,
|
||||
'provider_id': provider_id,
|
||||
'created_at': datetime.now(UTC).isoformat(),
|
||||
}
|
||||
key = cache_key(MERGE_TOKEN_PREFIX, token)
|
||||
stored = await cache.set(key, value, expire=MERGE_TOKEN_TTL_SECONDS)
|
||||
if not stored:
|
||||
logger.error(
|
||||
'Failed to store merge token in Redis',
|
||||
primary_user_id=primary_user_id,
|
||||
secondary_user_id=secondary_user_id,
|
||||
provider=provider,
|
||||
)
|
||||
raise RuntimeError('Failed to store merge token')
|
||||
|
||||
logger.info(
|
||||
'Merge token created',
|
||||
primary_user_id=primary_user_id,
|
||||
secondary_user_id=secondary_user_id,
|
||||
provider=provider,
|
||||
provider_id=provider_id,
|
||||
)
|
||||
return token
|
||||
|
||||
|
||||
async def get_merge_token_data(token: str) -> dict[str, Any] | None:
|
||||
"""Read merge token payload *without* consuming it.
|
||||
|
||||
Intended for preview / confirmation screens where the user sees
|
||||
what will happen before they press "Confirm".
|
||||
|
||||
Returns ``None`` when the token is expired, missing, or malformed.
|
||||
"""
|
||||
key = cache_key(MERGE_TOKEN_PREFIX, token)
|
||||
data: Any = await cache.get(key)
|
||||
if data is None or not isinstance(data, dict):
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
async def consume_merge_token(token: str) -> dict[str, Any] | None:
|
||||
"""Atomically read and delete a merge token (GETDEL).
|
||||
|
||||
This prevents double-merge race conditions: only the first caller
|
||||
that reaches Redis will get the payload; every subsequent attempt
|
||||
receives ``None``.
|
||||
|
||||
Returns the stored dict or ``None`` if already consumed / expired.
|
||||
"""
|
||||
key = cache_key(MERGE_TOKEN_PREFIX, token)
|
||||
data: Any = await cache.getdel(key)
|
||||
if data is None or not isinstance(data, dict):
|
||||
return None
|
||||
|
||||
logger.info(
|
||||
'Merge token consumed',
|
||||
primary_user_id=data.get('primary_user_id'),
|
||||
secondary_user_id=data.get('secondary_user_id'),
|
||||
provider=data.get('provider'),
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
_MAX_MERGE_RESTORE_ATTEMPTS = 3
|
||||
|
||||
|
||||
async def restore_merge_token(token: str, data: dict[str, Any]) -> bool:
|
||||
"""Re-store a consumed merge token so the user can retry after a DB failure.
|
||||
|
||||
Uses the remaining TTL based on the original ``created_at``.
|
||||
Uses SETNX to avoid overwriting a fresh token.
|
||||
Caps restore attempts to prevent infinite retry cycles.
|
||||
Returns ``True`` if restored, ``False`` if exhausted or Redis write failed.
|
||||
"""
|
||||
restore_count = data.get('_restore_count', 0) + 1
|
||||
if restore_count > _MAX_MERGE_RESTORE_ATTEMPTS:
|
||||
logger.warning(
|
||||
'Merge token exhausted restore attempts',
|
||||
primary_user_id=data.get('primary_user_id'),
|
||||
secondary_user_id=data.get('secondary_user_id'),
|
||||
restore_count=restore_count,
|
||||
)
|
||||
return False
|
||||
|
||||
# Shallow copy to avoid mutating the caller's dict
|
||||
data = {**data, '_restore_count': restore_count}
|
||||
|
||||
created_at_str: str = data.get('created_at', '')
|
||||
try:
|
||||
created_at = datetime.fromisoformat(created_at_str)
|
||||
if created_at.tzinfo is None:
|
||||
created_at = created_at.replace(tzinfo=UTC)
|
||||
elapsed = (datetime.now(UTC) - created_at).total_seconds()
|
||||
remaining_ttl = max(1, min(int(MERGE_TOKEN_TTL_SECONDS - elapsed), MERGE_TOKEN_TTL_SECONDS))
|
||||
except (ValueError, TypeError):
|
||||
remaining_ttl = 60 # brief retry window — fail closed
|
||||
|
||||
key = cache_key(MERGE_TOKEN_PREFIX, token)
|
||||
stored = await cache.setnx(key, data, expire=remaining_ttl)
|
||||
if stored:
|
||||
logger.info(
|
||||
'Merge token restored after failed merge',
|
||||
primary_user_id=data.get('primary_user_id'),
|
||||
secondary_user_id=data.get('secondary_user_id'),
|
||||
remaining_ttl=remaining_ttl,
|
||||
restore_count=restore_count,
|
||||
)
|
||||
else:
|
||||
logger.error(
|
||||
'Failed to restore merge token to Redis (key may already exist)',
|
||||
primary_user_id=data.get('primary_user_id'),
|
||||
secondary_user_id=data.get('secondary_user_id'),
|
||||
)
|
||||
return bool(stored)
|
||||
@@ -1,5 +1,7 @@
|
||||
"""OAuth 2.0 provider implementations for cabinet authentication."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import secrets
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any, TypedDict
|
||||
@@ -33,7 +35,7 @@ class OAuthTokenResponse(TypedDict, total=False):
|
||||
expires_in: int
|
||||
refresh_token: str
|
||||
scope: str
|
||||
# VK-specific: email and user_id come in token response
|
||||
# Provider-specific extra fields (optional)
|
||||
email: str
|
||||
user_id: int
|
||||
|
||||
@@ -67,15 +69,19 @@ class DiscordUserInfoResponse(TypedDict, total=False):
|
||||
avatar: str
|
||||
|
||||
|
||||
class VKUserInfoItem(TypedDict, total=False):
|
||||
id: int
|
||||
class VKIDUserData(TypedDict, total=False):
|
||||
"""VK ID /oauth2/user_info response user object."""
|
||||
|
||||
user_id: str
|
||||
first_name: str
|
||||
last_name: str
|
||||
photo_200: str
|
||||
phone: str
|
||||
avatar: str
|
||||
email: str
|
||||
|
||||
|
||||
class VKUserInfoResponse(TypedDict, total=False):
|
||||
response: list[VKUserInfoItem]
|
||||
class VKIDUserInfoResponse(TypedDict, total=False):
|
||||
user: VKIDUserData
|
||||
|
||||
|
||||
# --- Models ---
|
||||
@@ -97,23 +103,45 @@ class OAuthUserInfo(BaseModel):
|
||||
# --- CSRF state management (Redis) ---
|
||||
|
||||
|
||||
async def generate_oauth_state(provider: str) -> str:
|
||||
"""Generate a CSRF state token for OAuth flow. Stored in Redis with TTL."""
|
||||
async def generate_oauth_state(provider: str, extra_data: dict[str, str] | None = None) -> str:
|
||||
"""Generate a CSRF state token for OAuth flow.
|
||||
|
||||
Stores provider name and optional extra data (e.g., PKCE code_verifier) in Redis with TTL.
|
||||
Keys prefixed with '_' are ephemeral and NOT stored in Redis (e.g., _code_challenge).
|
||||
CacheService handles JSON serialization internally.
|
||||
"""
|
||||
state = secrets.token_urlsafe(32)
|
||||
await cache.set(cache_key('oauth_state', state), provider, expire=STATE_TTL_SECONDS)
|
||||
value: dict[str, Any] = {'provider': provider}
|
||||
if extra_data:
|
||||
# Filter out ephemeral keys (prefixed with '_') — they're only needed for the URL
|
||||
value.update({k: v for k, v in extra_data.items() if not k.startswith('_')})
|
||||
stored = await cache.set(cache_key('oauth_state', state), value, expire=STATE_TTL_SECONDS)
|
||||
if not stored:
|
||||
logger.error('Failed to store OAuth state in Redis')
|
||||
raise RuntimeError('Failed to store OAuth state')
|
||||
return state
|
||||
|
||||
|
||||
async def validate_oauth_state(state: str, provider: str) -> bool:
|
||||
"""Validate and consume a CSRF state token from Redis."""
|
||||
async def validate_oauth_state(state: str, provider: str | None = None) -> dict[str, Any] | None:
|
||||
"""Validate and consume a CSRF state token from Redis.
|
||||
|
||||
Uses atomic GETDEL to prevent TOCTOU race conditions.
|
||||
Returns the stored data dict (with 'provider' key + any extra data) or None if invalid.
|
||||
|
||||
Args:
|
||||
state: The state token to validate.
|
||||
provider: If provided, verifies it matches the stored provider.
|
||||
If None, skips provider check (used for server-complete flow).
|
||||
"""
|
||||
key = cache_key('oauth_state', state)
|
||||
stored_provider: str | None = await cache.get(key)
|
||||
if stored_provider is None:
|
||||
return False
|
||||
await cache.delete(key)
|
||||
if stored_provider != provider:
|
||||
return False
|
||||
return True
|
||||
data: Any = await cache.getdel(key)
|
||||
if data is None:
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
if provider is not None and data.get('provider') != provider:
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
# --- Provider implementations ---
|
||||
@@ -130,13 +158,28 @@ class OAuthProvider(ABC):
|
||||
self.client_secret = client_secret
|
||||
self.redirect_uri = redirect_uri
|
||||
|
||||
@abstractmethod
|
||||
def get_authorization_url(self, state: str) -> str:
|
||||
"""Build the authorization URL for the provider."""
|
||||
def prepare_auth_state(self) -> dict[str, str]:
|
||||
"""Return extra data to store with OAuth state (e.g., PKCE code_verifier).
|
||||
|
||||
Override in providers that need PKCE or other state-stored data.
|
||||
The returned dict is stored in Redis alongside the state token
|
||||
and passed back via validate_oauth_state().
|
||||
"""
|
||||
return {}
|
||||
|
||||
@abstractmethod
|
||||
async def exchange_code(self, code: str) -> OAuthTokenResponse:
|
||||
"""Exchange authorization code for tokens."""
|
||||
def get_authorization_url(self, state: str, **kwargs: Any) -> str:
|
||||
"""Build the authorization URL for the provider.
|
||||
|
||||
kwargs may contain extra data from prepare_auth_state() (e.g., code_challenge).
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
async def exchange_code(self, code: str, **kwargs: Any) -> OAuthTokenResponse:
|
||||
"""Exchange authorization code for tokens.
|
||||
|
||||
kwargs may contain provider-specific params (e.g., device_id, code_verifier for VK).
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
async def get_user_info(self, token_data: OAuthTokenResponse) -> OAuthUserInfo:
|
||||
@@ -151,7 +194,7 @@ class GoogleProvider(OAuthProvider):
|
||||
TOKEN_URL = 'https://oauth2.googleapis.com/token'
|
||||
USERINFO_URL = 'https://www.googleapis.com/oauth2/v3/userinfo'
|
||||
|
||||
def get_authorization_url(self, state: str) -> str:
|
||||
def get_authorization_url(self, state: str, **kwargs: Any) -> str:
|
||||
params: dict[str, str] = {
|
||||
'client_id': self.client_id,
|
||||
'redirect_uri': self.redirect_uri,
|
||||
@@ -164,7 +207,7 @@ class GoogleProvider(OAuthProvider):
|
||||
request = httpx.Request('GET', self.AUTHORIZE_URL, params=params)
|
||||
return str(request.url)
|
||||
|
||||
async def exchange_code(self, code: str) -> OAuthTokenResponse:
|
||||
async def exchange_code(self, code: str, **kwargs: Any) -> OAuthTokenResponse:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.post(
|
||||
self.TOKEN_URL,
|
||||
@@ -209,7 +252,7 @@ class YandexProvider(OAuthProvider):
|
||||
TOKEN_URL = 'https://oauth.yandex.com/token'
|
||||
USERINFO_URL = 'https://login.yandex.ru/info'
|
||||
|
||||
def get_authorization_url(self, state: str) -> str:
|
||||
def get_authorization_url(self, state: str, **kwargs: Any) -> str:
|
||||
params: dict[str, str] = {
|
||||
'client_id': self.client_id,
|
||||
'redirect_uri': self.redirect_uri,
|
||||
@@ -221,7 +264,7 @@ class YandexProvider(OAuthProvider):
|
||||
request = httpx.Request('GET', self.AUTHORIZE_URL, params=params)
|
||||
return str(request.url)
|
||||
|
||||
async def exchange_code(self, code: str) -> OAuthTokenResponse:
|
||||
async def exchange_code(self, code: str, **kwargs: Any) -> OAuthTokenResponse:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.post(
|
||||
self.TOKEN_URL,
|
||||
@@ -275,7 +318,7 @@ class DiscordProvider(OAuthProvider):
|
||||
TOKEN_URL = 'https://discord.com/api/oauth2/token'
|
||||
USERINFO_URL = 'https://discord.com/api/v10/users/@me'
|
||||
|
||||
def get_authorization_url(self, state: str) -> str:
|
||||
def get_authorization_url(self, state: str, **kwargs: Any) -> str:
|
||||
params: dict[str, str] = {
|
||||
'client_id': self.client_id,
|
||||
'redirect_uri': self.redirect_uri,
|
||||
@@ -287,7 +330,7 @@ class DiscordProvider(OAuthProvider):
|
||||
request = httpx.Request('GET', self.AUTHORIZE_URL, params=params)
|
||||
return str(request.url)
|
||||
|
||||
async def exchange_code(self, code: str) -> OAuthTokenResponse:
|
||||
async def exchange_code(self, code: str, **kwargs: Any) -> OAuthTokenResponse:
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.post(
|
||||
self.TOKEN_URL,
|
||||
@@ -329,35 +372,72 @@ class DiscordProvider(OAuthProvider):
|
||||
|
||||
|
||||
class VKProvider(OAuthProvider):
|
||||
"""VK ID OAuth 2.1 provider (id.vk.ru).
|
||||
|
||||
Uses OAuth 2.1 with mandatory PKCE (S256).
|
||||
Old oauth.vk.com endpoints deprecated since September 30, 2025.
|
||||
"""
|
||||
|
||||
name = 'vk'
|
||||
display_name = 'VK'
|
||||
|
||||
AUTHORIZE_URL = 'https://oauth.vk.com/authorize'
|
||||
TOKEN_URL = 'https://oauth.vk.com/access_token'
|
||||
USERINFO_URL = 'https://api.vk.com/method/users.get'
|
||||
API_VERSION = '5.131'
|
||||
AUTHORIZE_URL = 'https://id.vk.ru/authorize'
|
||||
TOKEN_URL = 'https://id.vk.ru/oauth2/auth'
|
||||
USERINFO_URL = 'https://id.vk.ru/oauth2/user_info'
|
||||
|
||||
def get_authorization_url(self, state: str) -> str:
|
||||
@staticmethod
|
||||
def _generate_pkce() -> tuple[str, str]:
|
||||
"""Generate PKCE code_verifier and code_challenge (S256)."""
|
||||
code_verifier = secrets.token_urlsafe(64)
|
||||
digest = hashlib.sha256(code_verifier.encode('ascii')).digest()
|
||||
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
|
||||
return code_verifier, code_challenge
|
||||
|
||||
def prepare_auth_state(self) -> dict[str, str]:
|
||||
"""Generate PKCE pair. code_verifier stored in Redis, code_challenge only goes to URL."""
|
||||
code_verifier, code_challenge = self._generate_pkce()
|
||||
# code_challenge is ephemeral — only needed for the authorization URL,
|
||||
# not stored in Redis (code_verifier is the secret used during token exchange)
|
||||
return {
|
||||
'code_verifier': code_verifier,
|
||||
'_code_challenge': code_challenge,
|
||||
}
|
||||
|
||||
def get_authorization_url(self, state: str, **kwargs: Any) -> str:
|
||||
code_challenge: str = kwargs.get('_code_challenge', '')
|
||||
params: dict[str, str] = {
|
||||
'client_id': self.client_id,
|
||||
'redirect_uri': self.redirect_uri,
|
||||
'response_type': 'code',
|
||||
'scope': 'email',
|
||||
'scope': 'vkid.personal_info email',
|
||||
'state': state,
|
||||
'v': self.API_VERSION,
|
||||
'code_challenge': code_challenge,
|
||||
'code_challenge_method': 'S256',
|
||||
}
|
||||
request = httpx.Request('GET', self.AUTHORIZE_URL, params=params)
|
||||
return str(request.url)
|
||||
|
||||
async def exchange_code(self, code: str) -> OAuthTokenResponse:
|
||||
async def exchange_code(self, code: str, **kwargs: Any) -> OAuthTokenResponse:
|
||||
device_id: str = kwargs.get('device_id', '')
|
||||
code_verifier: str = kwargs.get('code_verifier', '')
|
||||
state: str = kwargs.get('state', '')
|
||||
|
||||
if not device_id:
|
||||
raise ValueError('device_id is required for VK ID token exchange')
|
||||
if not code_verifier:
|
||||
raise ValueError('code_verifier is required for VK ID token exchange')
|
||||
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.get(
|
||||
response = await client.post(
|
||||
self.TOKEN_URL,
|
||||
params={
|
||||
'client_id': self.client_id,
|
||||
'client_secret': self.client_secret,
|
||||
data={
|
||||
'grant_type': 'authorization_code',
|
||||
'code': code,
|
||||
'redirect_uri': self.redirect_uri,
|
||||
'client_id': self.client_id,
|
||||
'device_id': device_id,
|
||||
'code_verifier': code_verifier,
|
||||
'state': state,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
@@ -366,33 +446,37 @@ class VKProvider(OAuthProvider):
|
||||
|
||||
async def get_user_info(self, token_data: OAuthTokenResponse) -> OAuthUserInfo:
|
||||
access_token = token_data['access_token']
|
||||
user_id: int | None = token_data.get('user_id')
|
||||
# VK returns email in token response, not in userinfo
|
||||
email: str | None = token_data.get('email')
|
||||
|
||||
async with httpx.AsyncClient(timeout=30) as client:
|
||||
response = await client.get(
|
||||
response = await client.post(
|
||||
self.USERINFO_URL,
|
||||
params={
|
||||
data={
|
||||
'access_token': access_token,
|
||||
'fields': 'photo_200',
|
||||
'v': self.API_VERSION,
|
||||
'client_id': self.client_id,
|
||||
},
|
||||
)
|
||||
response.raise_for_status()
|
||||
data: VKUserInfoResponse = response.json()
|
||||
data: VKIDUserInfoResponse = response.json()
|
||||
|
||||
users: list[Any] = data.get('response', [])
|
||||
user_data: VKUserInfoItem = users[0] if users else {} # type: ignore[assignment]
|
||||
user_data = data.get('user')
|
||||
if not user_data:
|
||||
raise ValueError('VK ID response missing user data')
|
||||
|
||||
user_id = user_data.get('user_id')
|
||||
if not user_id:
|
||||
raise ValueError('VK ID response missing user_id')
|
||||
|
||||
# VK ID returns email only if 'email' scope was granted and user has a verified email
|
||||
email: str | None = user_data.get('email') or None
|
||||
|
||||
return OAuthUserInfo(
|
||||
provider='vk',
|
||||
provider_id=str(user_id or user_data.get('id', '')),
|
||||
provider_id=str(user_id),
|
||||
email=email,
|
||||
email_verified=bool(email),
|
||||
first_name=user_data.get('first_name'),
|
||||
last_name=user_data.get('last_name'),
|
||||
avatar_url=user_data.get('photo_200'),
|
||||
avatar_url=user_data.get('avatar'),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -5,11 +5,15 @@ import hmac
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qsl, unquote
|
||||
from urllib.parse import parse_qsl
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
# Maximum allowed clock skew (seconds) for auth_date — tolerates minor drift between Telegram servers and ours.
|
||||
_MAX_CLOCK_SKEW_SECONDS = 300
|
||||
|
||||
|
||||
def validate_telegram_login_widget(data: dict[str, Any], max_age_seconds: int = 86400) -> bool:
|
||||
"""
|
||||
Validate Telegram Login Widget data.
|
||||
@@ -29,17 +33,17 @@ def validate_telegram_login_widget(data: dict[str, Any], max_age_seconds: int =
|
||||
if not check_hash:
|
||||
return False
|
||||
|
||||
# Check auth_date is not too old
|
||||
# Check auth_date is present and within valid range
|
||||
auth_date = auth_data.get('auth_date')
|
||||
if auth_date:
|
||||
try:
|
||||
# Use UTC timestamp to avoid timezone issues
|
||||
auth_time = datetime.fromtimestamp(int(auth_date), tz=UTC)
|
||||
age = (datetime.now(UTC) - auth_time).total_seconds()
|
||||
if age > max_age_seconds:
|
||||
return False
|
||||
except (ValueError, TypeError, OSError):
|
||||
if not auth_date:
|
||||
return False
|
||||
try:
|
||||
auth_time = datetime.fromtimestamp(int(auth_date), tz=UTC)
|
||||
age = (datetime.now(UTC) - auth_time).total_seconds()
|
||||
if age > max_age_seconds or age < -_MAX_CLOCK_SKEW_SECONDS:
|
||||
return False
|
||||
except (ValueError, TypeError, OSError):
|
||||
return False
|
||||
|
||||
# Build data-check-string (sorted key=value pairs, newline-separated)
|
||||
data_check_arr = [f'{k}={v}' for k, v in sorted(auth_data.items()) if v is not None]
|
||||
@@ -76,17 +80,17 @@ def validate_telegram_init_data(init_data: str, max_age_seconds: int = 86400) ->
|
||||
if not received_hash:
|
||||
return None
|
||||
|
||||
# Check auth_date is not too old
|
||||
# Check auth_date is present and within valid range
|
||||
auth_date = parsed.get('auth_date')
|
||||
if auth_date:
|
||||
try:
|
||||
# Use UTC timestamp to avoid timezone issues
|
||||
auth_time = datetime.fromtimestamp(int(auth_date), tz=UTC)
|
||||
age = (datetime.now(UTC) - auth_time).total_seconds()
|
||||
if age > max_age_seconds:
|
||||
return None
|
||||
except (ValueError, TypeError, OSError):
|
||||
if not auth_date:
|
||||
return None
|
||||
try:
|
||||
auth_time = datetime.fromtimestamp(int(auth_date), tz=UTC)
|
||||
age = (datetime.now(UTC) - auth_time).total_seconds()
|
||||
if age > max_age_seconds or age < -_MAX_CLOCK_SKEW_SECONDS:
|
||||
return None
|
||||
except (ValueError, TypeError, OSError):
|
||||
return None
|
||||
|
||||
# Build data-check-string
|
||||
data_check_arr = [f'{k}={v}' for k, v in sorted(parsed.items())]
|
||||
@@ -105,7 +109,7 @@ def validate_telegram_init_data(init_data: str, max_age_seconds: int = 86400) ->
|
||||
# Parse user data from the validated data
|
||||
user_data_str = parsed.get('user')
|
||||
if user_data_str:
|
||||
user_data = json.loads(unquote(user_data_str))
|
||||
user_data = json.loads(user_data_str)
|
||||
return user_data
|
||||
|
||||
return parsed
|
||||
|
||||
+126
-9
@@ -14,6 +14,7 @@ from app.services.maintenance_service import maintenance_service
|
||||
|
||||
from .auth.jwt_handler import get_token_payload
|
||||
from .auth.telegram_auth import validate_telegram_init_data
|
||||
from .ip_utils import get_client_ip
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -224,27 +225,143 @@ async def get_optional_cabinet_user(
|
||||
|
||||
|
||||
async def get_current_admin_user(
|
||||
request: Request,
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> User:
|
||||
"""
|
||||
Get current authenticated admin user.
|
||||
|
||||
Checks if the user is admin by telegram_id or email.
|
||||
Checks if the user is admin by legacy config (ADMIN_IDS / ADMIN_EMAILS)
|
||||
**or** by RBAC role assignment (any role with level > 0).
|
||||
|
||||
Args:
|
||||
request: FastAPI request object
|
||||
user: Authenticated User object
|
||||
db: Database session
|
||||
|
||||
Returns:
|
||||
Authenticated admin User object
|
||||
|
||||
Raises:
|
||||
HTTPException: If user is not an admin
|
||||
HTTPException: If user is not an admin by either mechanism
|
||||
"""
|
||||
is_admin = settings.is_admin(telegram_id=user.telegram_id, email=user.email if user.email_verified else None)
|
||||
if not is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Admin access required',
|
||||
)
|
||||
# Legacy check: config-based admin list
|
||||
is_legacy_admin = settings.is_admin(
|
||||
telegram_id=user.telegram_id,
|
||||
email=user.email if user.email_verified else None,
|
||||
)
|
||||
if is_legacy_admin:
|
||||
return user
|
||||
|
||||
return user
|
||||
# RBAC check: user has any active role with level > 0
|
||||
from app.database.crud.rbac import UserRoleCRUD
|
||||
|
||||
_permissions, _role_names, max_level = await UserRoleCRUD.get_user_permissions(db, user.id)
|
||||
if max_level > 0:
|
||||
return user
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Admin access required',
|
||||
)
|
||||
|
||||
|
||||
def require_permission(*permissions: str):
|
||||
"""
|
||||
FastAPI dependency factory for RBAC permission checks.
|
||||
|
||||
Usage::
|
||||
|
||||
@router.get("/users", dependencies=[Depends(require_permission("users:read"))])
|
||||
async def list_users(...): ...
|
||||
|
||||
# Or inject the user:
|
||||
@router.get("/users")
|
||||
async def list_users(user: User = Depends(require_permission("users:read"))): ...
|
||||
"""
|
||||
if not permissions:
|
||||
raise ValueError('require_permission() requires at least one permission argument')
|
||||
|
||||
async def dependency(
|
||||
request: Request,
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> User:
|
||||
from app.services.permission_service import PermissionService
|
||||
|
||||
try:
|
||||
client_ip = get_client_ip(request)
|
||||
except HTTPException:
|
||||
logger.warning('Unable to determine client IP in require_permission')
|
||||
client_ip = 'unknown'
|
||||
user_agent = request.headers.get('user-agent', '')
|
||||
|
||||
# Extract resource_type from the first permission (section before ':')
|
||||
resource_type = None
|
||||
if permissions:
|
||||
first_perm = permissions[0]
|
||||
if ':' in first_perm:
|
||||
resource_type = first_perm.split(':', maxsplit=1)[0]
|
||||
|
||||
for perm in permissions:
|
||||
allowed, reason = await PermissionService.check_permission(
|
||||
db,
|
||||
user,
|
||||
perm,
|
||||
ip_address=client_ip,
|
||||
)
|
||||
if not allowed:
|
||||
await PermissionService.log_action(
|
||||
db,
|
||||
user_id=user.id,
|
||||
action=perm,
|
||||
resource_type=resource_type,
|
||||
status='denied',
|
||||
ip_address=client_ip,
|
||||
user_agent=user_agent,
|
||||
request_method=request.method,
|
||||
request_path=str(request.url.path),
|
||||
details={'reason': reason},
|
||||
)
|
||||
await db.commit()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f'Permission denied: {reason}',
|
||||
)
|
||||
|
||||
# Capture request details
|
||||
details: dict = {
|
||||
'method': request.method,
|
||||
'path': str(request.url.path),
|
||||
}
|
||||
query_params = dict(request.query_params)
|
||||
if query_params:
|
||||
details['query_params'] = query_params
|
||||
if request.method in ('POST', 'PUT', 'PATCH', 'DELETE'):
|
||||
try:
|
||||
body = await request.body()
|
||||
if body:
|
||||
import json
|
||||
|
||||
details['request_body'] = json.loads(body)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Log successful access with all requested permissions
|
||||
await PermissionService.log_action(
|
||||
db,
|
||||
user_id=user.id,
|
||||
action=','.join(permissions),
|
||||
resource_type=resource_type,
|
||||
status='success',
|
||||
ip_address=client_ip,
|
||||
user_agent=user_agent,
|
||||
request_method=request.method,
|
||||
request_path=str(request.url.path),
|
||||
details=details,
|
||||
)
|
||||
await db.commit()
|
||||
return user
|
||||
|
||||
return dependency
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Shared IP extraction utilities for cabinet module."""
|
||||
|
||||
from ipaddress import ip_address, ip_network
|
||||
|
||||
from fastapi import HTTPException, Request, status
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
def _is_trusted_proxy(peer_ip: str, trusted: set[str]) -> bool:
|
||||
"""Check if peer IP matches any trusted proxy entry (IP or CIDR)."""
|
||||
if not trusted:
|
||||
return False
|
||||
try:
|
||||
addr = ip_address(peer_ip)
|
||||
except ValueError:
|
||||
return False
|
||||
for entry in trusted:
|
||||
try:
|
||||
if '/' in entry:
|
||||
if addr in ip_network(entry, strict=False):
|
||||
return True
|
||||
elif addr == ip_address(entry):
|
||||
return True
|
||||
except ValueError:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def get_client_ip(request: Request) -> str:
|
||||
"""Extract real client IP, trusting proxy headers only from known proxies.
|
||||
|
||||
Raises HTTPException 400 if the peer IP cannot be determined
|
||||
(request.client is None — e.g., test harness or broken transport).
|
||||
"""
|
||||
if not request.client:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Unable to determine client IP',
|
||||
)
|
||||
peer_ip = request.client.host
|
||||
trusted_proxies = settings.get_cabinet_trusted_proxies()
|
||||
|
||||
if trusted_proxies and _is_trusted_proxy(peer_ip, trusted_proxies):
|
||||
forwarded = request.headers.get('X-Forwarded-For', '').split(',')[0].strip()
|
||||
if forwarded:
|
||||
try:
|
||||
ip_address(forwarded)
|
||||
return forwarded
|
||||
except ValueError:
|
||||
pass # invalid IP in header — fall through to peer_ip
|
||||
real_ip = request.headers.get('X-Real-IP', '').strip()
|
||||
if real_ip:
|
||||
try:
|
||||
ip_address(real_ip)
|
||||
return real_ip
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
return peer_ip
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .account_linking import merge_router as merge_router, router as account_linking_router
|
||||
from .admin_apps import router as admin_apps_router
|
||||
from .admin_audit_log import router as admin_audit_log_router
|
||||
from .admin_ban_system import router as admin_ban_system_router
|
||||
from .admin_broadcasts import router as admin_broadcasts_router
|
||||
from .admin_button_styles import router as admin_button_styles_router
|
||||
@@ -13,9 +15,12 @@ from .admin_partners import router as admin_partners_router
|
||||
from .admin_payment_methods import router as admin_payment_methods_router
|
||||
from .admin_payments import router as admin_payments_router
|
||||
from .admin_pinned_messages import router as admin_pinned_messages_router
|
||||
from .admin_policies import router as admin_policies_router
|
||||
from .admin_promo_offers import router as admin_promo_offers_router
|
||||
from .admin_promocodes import promo_groups_router as admin_promo_groups_router, router as admin_promocodes_router
|
||||
from .admin_remnawave import router as admin_remnawave_router
|
||||
from .admin_roles import router as admin_roles_router
|
||||
from .admin_sales_stats import router as admin_sales_stats_router
|
||||
from .admin_servers import router as admin_servers_router
|
||||
from .admin_settings import router as admin_settings_router
|
||||
from .admin_stats import router as admin_stats_router
|
||||
@@ -56,6 +61,8 @@ router = APIRouter(prefix='/cabinet', tags=['Cabinet'])
|
||||
# Include all sub-routers
|
||||
router.include_router(auth_router)
|
||||
router.include_router(oauth_router)
|
||||
router.include_router(account_linking_router)
|
||||
router.include_router(merge_router)
|
||||
router.include_router(subscription_router)
|
||||
router.include_router(balance_router)
|
||||
router.include_router(referral_router)
|
||||
@@ -84,6 +91,7 @@ router.include_router(admin_wheel_router)
|
||||
router.include_router(admin_tariffs_router)
|
||||
router.include_router(admin_servers_router)
|
||||
router.include_router(admin_stats_router)
|
||||
router.include_router(admin_sales_stats_router)
|
||||
router.include_router(admin_ban_system_router)
|
||||
router.include_router(admin_broadcasts_router)
|
||||
router.include_router(admin_promocodes_router)
|
||||
@@ -103,6 +111,9 @@ router.include_router(admin_pinned_messages_router)
|
||||
router.include_router(admin_button_styles_router)
|
||||
router.include_router(admin_channels_router)
|
||||
router.include_router(admin_apps_router)
|
||||
router.include_router(admin_roles_router)
|
||||
router.include_router(admin_policies_router)
|
||||
router.include_router(admin_audit_log_router)
|
||||
|
||||
# WebSocket route
|
||||
router.include_router(websocket_router)
|
||||
|
||||
@@ -0,0 +1,825 @@
|
||||
"""Account linking and merge routes for cabinet.
|
||||
|
||||
Router 1 (`router`): JWT-protected endpoints for linking/unlinking OAuth providers.
|
||||
Exception: `link/server-complete` uses state-token auth instead of JWT (for Mini App external browser flow).
|
||||
Router 2 (`merge_router`): Public endpoints for merge preview and execution.
|
||||
"""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Literal, NotRequired, TypedDict
|
||||
|
||||
import structlog
|
||||
from fastapi import APIRouter, Depends, HTTPException, Path, Request, status
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.crud.user import (
|
||||
OAUTH_PROVIDER_COLUMNS,
|
||||
clear_user_oauth_provider_id,
|
||||
get_user_by_id,
|
||||
get_user_by_oauth_provider,
|
||||
get_user_by_telegram_id,
|
||||
set_user_oauth_provider_id,
|
||||
)
|
||||
from app.database.models import User
|
||||
from app.services.account_merge_service import compute_auth_methods, execute_merge, get_merge_preview
|
||||
from app.utils.cache import RateLimitCache
|
||||
|
||||
from ..auth.merge_service import (
|
||||
MERGE_TOKEN_TTL_SECONDS,
|
||||
consume_merge_token,
|
||||
create_merge_token,
|
||||
get_merge_token_data,
|
||||
restore_merge_token,
|
||||
)
|
||||
from ..auth.oauth_providers import (
|
||||
generate_oauth_state,
|
||||
get_provider,
|
||||
validate_oauth_state,
|
||||
)
|
||||
from ..auth.telegram_auth import validate_telegram_init_data, validate_telegram_login_widget
|
||||
from ..dependencies import get_cabinet_db, get_current_cabinet_user
|
||||
from ..ip_utils import get_client_ip
|
||||
from ..schemas.auth import UserResponse
|
||||
from .auth import _create_auth_response, _store_refresh_token, _user_to_response
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
OAuthProviderName = Literal['google', 'yandex', 'discord', 'vk']
|
||||
|
||||
# Ensure OAuthProviderName Literal stays in sync with OAUTH_PROVIDER_COLUMNS
|
||||
_EXPECTED_PROVIDERS = {'google', 'yandex', 'discord', 'vk'}
|
||||
if set(OAUTH_PROVIDER_COLUMNS.keys()) != _EXPECTED_PROVIDERS:
|
||||
raise RuntimeError(
|
||||
f'OAuthProviderName Literal is out of sync with OAUTH_PROVIDER_COLUMNS: '
|
||||
f'{set(OAUTH_PROVIDER_COLUMNS.keys())} != {_EXPECTED_PROVIDERS}'
|
||||
)
|
||||
|
||||
|
||||
class OAuthStateData(TypedDict):
|
||||
"""Typed dict for Redis-stored OAuth state data."""
|
||||
|
||||
provider: str # Always present
|
||||
linking: NotRequired[str] # 'true' if account linking flow
|
||||
user_id: NotRequired[str] # ID of user who initiated linking
|
||||
code_verifier: NotRequired[str] # PKCE code verifier (VK)
|
||||
|
||||
|
||||
def _get_active_providers() -> list[str]:
|
||||
"""Вернуть список активных провайдеров аутентификации (только включённые)."""
|
||||
from app.config import settings
|
||||
|
||||
providers: list[str] = ['telegram']
|
||||
if settings.is_cabinet_email_auth_enabled():
|
||||
providers.append('email')
|
||||
providers.extend(settings.get_enabled_oauth_provider_names())
|
||||
return providers
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Schemas
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class LinkedProvider(BaseModel):
|
||||
provider: str
|
||||
linked: bool
|
||||
identifier: str | None = None
|
||||
|
||||
|
||||
class LinkedProvidersResponse(BaseModel):
|
||||
providers: list[LinkedProvider]
|
||||
|
||||
|
||||
class LinkInitResponse(BaseModel):
|
||||
authorize_url: str
|
||||
state: str
|
||||
|
||||
|
||||
class LinkCallbackRequest(BaseModel):
|
||||
code: str = Field(..., min_length=1, max_length=2048, description='Authorization code from provider')
|
||||
state: str = Field(..., min_length=1, max_length=128, description='CSRF state token')
|
||||
device_id: str | None = Field(None, max_length=256, description='Device ID from VK ID callback')
|
||||
|
||||
|
||||
class LinkCallbackResponse(BaseModel):
|
||||
success: bool
|
||||
message: str | None = None
|
||||
merge_required: bool = False
|
||||
merge_token: str | None = None
|
||||
|
||||
|
||||
class UnlinkResponse(BaseModel):
|
||||
success: bool
|
||||
|
||||
|
||||
class LinkTelegramRequest(BaseModel):
|
||||
"""Request for linking Telegram account. Supply EITHER init_data OR widget fields."""
|
||||
|
||||
# Mini App: Telegram WebApp initData
|
||||
init_data: str | None = Field(None, max_length=4096, description='Telegram WebApp initData string')
|
||||
# Login Widget fields
|
||||
id: int | None = Field(None, description='Telegram user ID from Login Widget')
|
||||
first_name: str | None = Field(None, max_length=256, description="User's first name")
|
||||
last_name: str | None = Field(None, max_length=256, description="User's last name")
|
||||
username: str | None = Field(None, max_length=256, description="User's username")
|
||||
photo_url: str | None = Field(None, max_length=2048, description="User's photo URL")
|
||||
auth_date: int | None = Field(None, description='Unix timestamp of authentication')
|
||||
hash: str | None = Field(None, min_length=64, max_length=64, description='Authentication hash (SHA-256 hex)')
|
||||
|
||||
@model_validator(mode='after')
|
||||
def check_exclusive(self) -> 'LinkTelegramRequest':
|
||||
has_init = self.init_data is not None
|
||||
has_widget = self.id is not None or self.hash is not None or self.auth_date is not None
|
||||
if has_init and has_widget:
|
||||
raise ValueError('Provide either init_data or Login Widget fields, not both')
|
||||
if not has_init and not has_widget:
|
||||
raise ValueError('Provide either init_data or Login Widget fields (id, auth_date, hash)')
|
||||
if has_widget and not (self.id is not None and self.auth_date is not None and self.hash is not None):
|
||||
raise ValueError('Login Widget mode requires id, auth_date, and hash fields')
|
||||
return self
|
||||
|
||||
|
||||
class MergePreviewSubscription(BaseModel):
|
||||
status: str
|
||||
is_trial: bool
|
||||
end_date: datetime | None = None
|
||||
traffic_limit_gb: float
|
||||
traffic_used_gb: float
|
||||
device_limit: int
|
||||
tariff_name: str | None = None
|
||||
autopay_enabled: bool
|
||||
|
||||
|
||||
class MergePreviewUser(BaseModel):
|
||||
id: int
|
||||
username: str | None = None
|
||||
first_name: str | None = None
|
||||
email: str | None = None
|
||||
auth_methods: list[str]
|
||||
balance_kopeks: int = 0
|
||||
subscription: MergePreviewSubscription | None = None
|
||||
created_at: datetime | None = None
|
||||
|
||||
|
||||
class MergePreviewResponse(BaseModel):
|
||||
primary: MergePreviewUser
|
||||
secondary: MergePreviewUser
|
||||
expires_in_seconds: int
|
||||
|
||||
|
||||
class MergeRequest(BaseModel):
|
||||
keep_subscription_from: int = Field(..., description='User ID whose subscription to keep')
|
||||
|
||||
|
||||
class MergeResponse(BaseModel):
|
||||
success: bool
|
||||
access_token: str | None = None
|
||||
refresh_token: str | None = None
|
||||
user: UserResponse | None = None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _get_provider_identifier(user: User, provider: str) -> str | None:
|
||||
"""Return the identifier (provider_id or email) for a given provider, or None."""
|
||||
match provider:
|
||||
case 'telegram':
|
||||
return str(user.telegram_id) if user.telegram_id else None
|
||||
case 'email':
|
||||
return user.email if user.email and user.password_hash else None
|
||||
case _:
|
||||
column = OAUTH_PROVIDER_COLUMNS.get(provider)
|
||||
if not column:
|
||||
return None
|
||||
value = getattr(user, column, None)
|
||||
return str(value) if value else None
|
||||
|
||||
|
||||
def _count_auth_methods(user: User) -> int:
|
||||
"""Count how many auth methods the user has linked."""
|
||||
return len(compute_auth_methods(user))
|
||||
|
||||
|
||||
async def _exchange_and_link_oauth(
|
||||
*,
|
||||
db: AsyncSession,
|
||||
user: User,
|
||||
provider: str,
|
||||
code: str,
|
||||
state: str,
|
||||
state_data: OAuthStateData,
|
||||
device_id: str | None,
|
||||
log_context: str,
|
||||
) -> LinkCallbackResponse:
|
||||
"""Shared OAuth linking logic: exchange code, fetch user info, link or merge.
|
||||
|
||||
Used by both link_provider_callback (JWT-authed) and link_server_complete (state-authed).
|
||||
"""
|
||||
oauth_provider = get_provider(provider)
|
||||
if not oauth_provider:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Requested OAuth provider is not available',
|
||||
)
|
||||
|
||||
# Exchange code for tokens
|
||||
exchange_kwargs: dict[str, str] = {'state': state}
|
||||
code_verifier = state_data.get('code_verifier')
|
||||
if code_verifier:
|
||||
exchange_kwargs['code_verifier'] = code_verifier
|
||||
if device_id:
|
||||
exchange_kwargs['device_id'] = device_id
|
||||
|
||||
try:
|
||||
token_data = await oauth_provider.exchange_code(code, **exchange_kwargs)
|
||||
except Exception as exc:
|
||||
logger.error('OAuth code exchange failed', context=log_context, provider=provider, exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Failed to exchange authorization code',
|
||||
) from exc
|
||||
|
||||
# Fetch user info from provider
|
||||
try:
|
||||
user_info = await oauth_provider.get_user_info(token_data)
|
||||
except Exception as exc:
|
||||
logger.error('OAuth user info fetch failed', context=log_context, provider=provider, exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Failed to fetch user information from provider',
|
||||
) from exc
|
||||
|
||||
# Check if provider_id is already linked to THIS user
|
||||
column = OAUTH_PROVIDER_COLUMNS[provider]
|
||||
current_value = getattr(user, column, None)
|
||||
if current_value and str(current_value) == user_info.provider_id:
|
||||
return LinkCallbackResponse(success=True, message='already_linked')
|
||||
|
||||
# Check if provider_id is linked to ANOTHER user
|
||||
existing_user = await get_user_by_oauth_provider(db, provider, user_info.provider_id)
|
||||
if existing_user and existing_user.id != user.id:
|
||||
logger.info(
|
||||
'Account linking conflict: provider already linked to another user',
|
||||
context=log_context,
|
||||
provider=provider,
|
||||
provider_id=user_info.provider_id,
|
||||
current_user_id=user.id,
|
||||
existing_user_id=existing_user.id,
|
||||
)
|
||||
merge_token = await create_merge_token(
|
||||
primary_user_id=user.id,
|
||||
secondary_user_id=existing_user.id,
|
||||
provider=provider,
|
||||
provider_id=user_info.provider_id,
|
||||
)
|
||||
return LinkCallbackResponse(
|
||||
success=False,
|
||||
merge_required=True,
|
||||
merge_token=merge_token,
|
||||
)
|
||||
|
||||
# Link the provider to current user
|
||||
await set_user_oauth_provider_id(db, user, provider, user_info.provider_id)
|
||||
try:
|
||||
await db.commit()
|
||||
except IntegrityError as exc:
|
||||
await db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail='This provider account was just linked to another user',
|
||||
) from exc
|
||||
|
||||
logger.info(
|
||||
'OAuth provider linked to account',
|
||||
context=log_context,
|
||||
provider=provider,
|
||||
provider_id=user_info.provider_id,
|
||||
user_id=user.id,
|
||||
)
|
||||
return LinkCallbackResponse(success=True, message='linked')
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Router 1: Account linking (JWT required)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
router = APIRouter(prefix='/auth/account', tags=['Cabinet Account Linking'])
|
||||
|
||||
|
||||
@router.get('/linked-providers', response_model=LinkedProvidersResponse)
|
||||
async def get_linked_providers(
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
) -> LinkedProvidersResponse:
|
||||
"""Return all auth methods with their link status for the current user."""
|
||||
providers: list[LinkedProvider] = []
|
||||
for provider in _get_active_providers():
|
||||
identifier = _get_provider_identifier(user, provider)
|
||||
providers.append(
|
||||
LinkedProvider(
|
||||
provider=provider,
|
||||
linked=identifier is not None,
|
||||
identifier=identifier,
|
||||
)
|
||||
)
|
||||
return LinkedProvidersResponse(providers=providers)
|
||||
|
||||
|
||||
@router.get('/link/{provider}/init', response_model=LinkInitResponse)
|
||||
async def link_provider_init(
|
||||
provider: OAuthProviderName,
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
) -> LinkInitResponse:
|
||||
"""Start OAuth flow for linking a new provider to the current account."""
|
||||
|
||||
# Check if already linked
|
||||
column = OAUTH_PROVIDER_COLUMNS[provider]
|
||||
if getattr(user, column, None):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Provider is already linked to your account',
|
||||
)
|
||||
|
||||
oauth_provider = get_provider(provider)
|
||||
if not oauth_provider:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Requested OAuth provider is not available',
|
||||
)
|
||||
|
||||
# Generate PKCE data for VK (and potentially future providers)
|
||||
auth_extra = oauth_provider.prepare_auth_state()
|
||||
extra_data: dict[str, str] = {
|
||||
'linking': 'true',
|
||||
'user_id': str(user.id),
|
||||
}
|
||||
if auth_extra:
|
||||
extra_data.update(auth_extra)
|
||||
|
||||
state = await generate_oauth_state(provider, extra_data=extra_data)
|
||||
# Only pass URL-safe params (prefixed with _) to authorize URL; exclude secrets like code_verifier
|
||||
url_params = {k: v for k, v in auth_extra.items() if k.startswith('_')} if auth_extra else {}
|
||||
authorize_url = oauth_provider.get_authorization_url(state, **url_params)
|
||||
|
||||
return LinkInitResponse(authorize_url=authorize_url, state=state)
|
||||
|
||||
|
||||
@router.post('/link/{provider}/callback', response_model=LinkCallbackResponse)
|
||||
async def link_provider_callback(
|
||||
provider: OAuthProviderName,
|
||||
request: LinkCallbackRequest,
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> LinkCallbackResponse:
|
||||
"""Handle OAuth callback for linking a provider to the current account."""
|
||||
# 1. Validate CSRF state
|
||||
state_data = await validate_oauth_state(request.state, provider)
|
||||
if not state_data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Invalid or expired OAuth state',
|
||||
)
|
||||
|
||||
# 1b. Validate that this state was created for account linking (not login)
|
||||
if state_data.get('linking') != 'true' or not state_data.get('user_id'):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='OAuth state was not initiated for account linking',
|
||||
)
|
||||
|
||||
# 1c. Validate that the user who initiated the link flow is the same user completing it
|
||||
state_user_id = state_data['user_id']
|
||||
if str(user.id) != state_user_id:
|
||||
logger.warning(
|
||||
'OAuth state user_id mismatch in link callback',
|
||||
state_user_id=state_user_id,
|
||||
current_user_id=user.id,
|
||||
provider=provider,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='OAuth state was initiated by a different user',
|
||||
)
|
||||
|
||||
# 2-7. Exchange code, fetch user info, link or merge
|
||||
return await _exchange_and_link_oauth(
|
||||
db=db,
|
||||
user=user,
|
||||
provider=provider,
|
||||
code=request.code,
|
||||
state=request.state,
|
||||
state_data=state_data,
|
||||
device_id=request.device_id,
|
||||
log_context='link-callback',
|
||||
)
|
||||
|
||||
|
||||
@router.post('/unlink/{provider}', response_model=UnlinkResponse)
|
||||
async def unlink_provider(
|
||||
provider: OAuthProviderName,
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> UnlinkResponse:
|
||||
"""Unlink an OAuth provider from the current account."""
|
||||
column = OAUTH_PROVIDER_COLUMNS[provider]
|
||||
if not getattr(user, column, None):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Provider is not linked to your account',
|
||||
)
|
||||
|
||||
# Ensure at least one auth method remains
|
||||
if _count_auth_methods(user) <= 1:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Cannot unlink last authentication method',
|
||||
)
|
||||
|
||||
await clear_user_oauth_provider_id(db, user, provider)
|
||||
await db.commit()
|
||||
return UnlinkResponse(success=True)
|
||||
|
||||
|
||||
@router.post('/link/telegram', response_model=LinkCallbackResponse)
|
||||
async def link_telegram(
|
||||
request: LinkTelegramRequest,
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> LinkCallbackResponse:
|
||||
"""Link Telegram account via WebApp initData or Login Widget."""
|
||||
# 1. Already has Telegram linked?
|
||||
if user.telegram_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Telegram is already linked to your account',
|
||||
)
|
||||
|
||||
# 2. Validate and extract telegram_id
|
||||
telegram_id: int | None = None
|
||||
telegram_username: str | None = None
|
||||
telegram_first_name: str | None = None
|
||||
telegram_last_name: str | None = None
|
||||
|
||||
if request.init_data:
|
||||
# Mini App flow: validate initData
|
||||
user_data = validate_telegram_init_data(request.init_data)
|
||||
if not user_data or not user_data.get('id'):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Invalid or expired Telegram initData',
|
||||
)
|
||||
telegram_id = int(user_data['id'])
|
||||
telegram_username = user_data.get('username')
|
||||
telegram_first_name = user_data.get('first_name')
|
||||
telegram_last_name = user_data.get('last_name')
|
||||
elif request.id is not None and request.hash is not None and request.auth_date is not None:
|
||||
# Login Widget flow: validate widget hash
|
||||
widget_data = {
|
||||
'id': request.id,
|
||||
'auth_date': request.auth_date,
|
||||
'hash': request.hash,
|
||||
}
|
||||
if request.first_name is not None:
|
||||
widget_data['first_name'] = request.first_name
|
||||
if request.last_name is not None:
|
||||
widget_data['last_name'] = request.last_name
|
||||
if request.username is not None:
|
||||
widget_data['username'] = request.username
|
||||
if request.photo_url is not None:
|
||||
widget_data['photo_url'] = request.photo_url
|
||||
|
||||
if not validate_telegram_login_widget(widget_data):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Invalid or expired Telegram Login Widget data',
|
||||
)
|
||||
telegram_id = request.id
|
||||
telegram_username = request.username
|
||||
telegram_first_name = request.first_name
|
||||
telegram_last_name = request.last_name
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Provide either init_data (Mini App) or Login Widget fields (id, auth_date, hash)',
|
||||
)
|
||||
|
||||
# 3. Check if telegram_id is linked to ANOTHER user
|
||||
existing_user = await get_user_by_telegram_id(db, telegram_id)
|
||||
if existing_user and existing_user.id != user.id:
|
||||
logger.info(
|
||||
'Telegram linking conflict: telegram_id already linked to another user',
|
||||
telegram_id=telegram_id,
|
||||
current_user_id=user.id,
|
||||
existing_user_id=existing_user.id,
|
||||
)
|
||||
merge_token = await create_merge_token(
|
||||
primary_user_id=user.id,
|
||||
secondary_user_id=existing_user.id,
|
||||
provider='telegram',
|
||||
provider_id=str(telegram_id),
|
||||
)
|
||||
return LinkCallbackResponse(
|
||||
success=False,
|
||||
merge_required=True,
|
||||
merge_token=merge_token,
|
||||
)
|
||||
|
||||
# 4. Link Telegram to current user
|
||||
user.telegram_id = telegram_id
|
||||
if telegram_username and not user.username:
|
||||
user.username = telegram_username
|
||||
if telegram_first_name and not user.first_name:
|
||||
user.first_name = telegram_first_name
|
||||
if telegram_last_name and not user.last_name:
|
||||
user.last_name = telegram_last_name
|
||||
user.updated_at = datetime.now(UTC)
|
||||
|
||||
try:
|
||||
await db.commit()
|
||||
except IntegrityError as exc:
|
||||
await db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail='This Telegram account was just linked to another user',
|
||||
) from exc
|
||||
|
||||
logger.info(
|
||||
'Telegram linked to account',
|
||||
telegram_id=telegram_id,
|
||||
user_id=user.id,
|
||||
)
|
||||
return LinkCallbackResponse(success=True, message='linked')
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Server-side OAuth linking callback (NO JWT required — auth via state token)
|
||||
# Used by Telegram Mini App where OAuth must open in external browser.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class ServerCompleteRequest(BaseModel):
|
||||
code: str = Field(..., min_length=1, max_length=2048, description='Authorization code from provider')
|
||||
state: str = Field(..., min_length=1, max_length=128, description='CSRF state token')
|
||||
provider: OAuthProviderName | None = Field(None, description='OAuth provider name (resolved from state if omitted)')
|
||||
device_id: str | None = Field(None, max_length=256, description='Device ID from VK ID callback')
|
||||
|
||||
|
||||
class ServerCompleteResponse(LinkCallbackResponse):
|
||||
provider: str
|
||||
|
||||
|
||||
@router.post('/link/server-complete', response_model=ServerCompleteResponse)
|
||||
async def link_server_complete(
|
||||
request: ServerCompleteRequest,
|
||||
raw_request: Request,
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> ServerCompleteResponse:
|
||||
"""Complete OAuth account linking without JWT.
|
||||
|
||||
Authenticates via the one-time state token stored in Redis during link_provider_init.
|
||||
Used when OAuth opens in an external browser (e.g., from Telegram Mini App).
|
||||
Provider is resolved from the state token if not explicitly provided.
|
||||
"""
|
||||
# Rate limit by IP (unauthenticated endpoint)
|
||||
client_ip = get_client_ip(raw_request)
|
||||
if await RateLimitCache.is_ip_rate_limited(client_ip, 'server_complete', limit=10, window=60, fail_closed=True):
|
||||
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
|
||||
|
||||
# 1. Validate and consume state from Redis (one-time use).
|
||||
# Provider may be None — validate_oauth_state will skip provider check,
|
||||
# and we'll resolve it from state_data['provider'].
|
||||
state_data = await validate_oauth_state(request.state, request.provider)
|
||||
if not state_data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Invalid or expired OAuth state',
|
||||
)
|
||||
|
||||
# Resolve provider from state data (canonical source)
|
||||
state_provider: str = state_data.get('provider', '')
|
||||
if not state_provider or state_provider not in OAUTH_PROVIDER_COLUMNS:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Could not determine OAuth provider',
|
||||
)
|
||||
|
||||
# If request explicitly provides a provider, ensure it matches the state
|
||||
if request.provider and request.provider != state_provider:
|
||||
logger.warning(
|
||||
'Provider mismatch in server-complete',
|
||||
request_provider=request.provider,
|
||||
state_provider=state_provider,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Provider does not match OAuth state',
|
||||
)
|
||||
|
||||
provider_name: str = state_provider
|
||||
|
||||
# 2. Must be a linking state (not login)
|
||||
if state_data.get('linking') != 'true' or not state_data.get('user_id'):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='OAuth state was not initiated for account linking',
|
||||
)
|
||||
|
||||
# 3. Parse and validate user_id from state
|
||||
try:
|
||||
user_id = int(state_data['user_id'])
|
||||
except (ValueError, TypeError) as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Invalid user_id in OAuth state',
|
||||
) from exc
|
||||
|
||||
# 4. Load user from DB
|
||||
user = await get_user_by_id(db, user_id)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='User not found',
|
||||
)
|
||||
|
||||
# 5-9. Exchange code, fetch user info, link or merge
|
||||
result = await _exchange_and_link_oauth(
|
||||
db=db,
|
||||
user=user,
|
||||
provider=provider_name,
|
||||
code=request.code,
|
||||
state=request.state,
|
||||
state_data=state_data,
|
||||
device_id=request.device_id,
|
||||
log_context='server-complete',
|
||||
)
|
||||
|
||||
return ServerCompleteResponse(
|
||||
success=result.success,
|
||||
message=result.message,
|
||||
merge_required=result.merge_required,
|
||||
merge_token=result.merge_token,
|
||||
provider=provider_name,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Router 2: Merge (NO JWT required)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
merge_router = APIRouter(prefix='/auth/merge', tags=['Cabinet Account Merge'])
|
||||
|
||||
|
||||
@merge_router.get('/{merge_token}', response_model=MergePreviewResponse)
|
||||
async def get_merge_preview_endpoint(
|
||||
raw_request: Request,
|
||||
merge_token: str = Path(..., min_length=32, max_length=64),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> MergePreviewResponse:
|
||||
"""Preview the result of merging two accounts before confirming."""
|
||||
# Rate limit by IP (unauthenticated endpoint)
|
||||
client_ip = get_client_ip(raw_request)
|
||||
if await RateLimitCache.is_ip_rate_limited(client_ip, 'merge_preview', limit=15, window=60, fail_closed=True):
|
||||
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
|
||||
|
||||
token_data = await get_merge_token_data(merge_token)
|
||||
if not token_data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Merge token is invalid or expired',
|
||||
)
|
||||
|
||||
primary_user_id: int = token_data['primary_user_id']
|
||||
secondary_user_id: int = token_data['secondary_user_id']
|
||||
|
||||
try:
|
||||
preview = await get_merge_preview(db, primary_user_id, secondary_user_id)
|
||||
except ValueError as exc:
|
||||
logger.error('Merge preview failed', error=str(exc))
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='One or both users not found',
|
||||
) from exc
|
||||
|
||||
# Calculate remaining TTL
|
||||
created_at_str: str = token_data.get('created_at', '')
|
||||
try:
|
||||
created_at = datetime.fromisoformat(created_at_str)
|
||||
if created_at.tzinfo is None:
|
||||
created_at = created_at.replace(tzinfo=UTC)
|
||||
elapsed = (datetime.now(UTC) - created_at).total_seconds()
|
||||
expires_in_seconds = max(0, int(MERGE_TOKEN_TTL_SECONDS - elapsed))
|
||||
except (ValueError, TypeError):
|
||||
expires_in_seconds = 0
|
||||
|
||||
return MergePreviewResponse(
|
||||
primary=MergePreviewUser(**preview['primary']),
|
||||
secondary=MergePreviewUser(**preview['secondary']),
|
||||
expires_in_seconds=expires_in_seconds,
|
||||
)
|
||||
|
||||
|
||||
@merge_router.post('/{merge_token}', response_model=MergeResponse)
|
||||
async def execute_merge_endpoint(
|
||||
request: MergeRequest,
|
||||
raw_request: Request,
|
||||
merge_token: str = Path(..., min_length=32, max_length=64),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> MergeResponse:
|
||||
"""Execute account merge. Consumes the merge token (one-time use)."""
|
||||
# Rate limit by IP (unauthenticated endpoint)
|
||||
client_ip = get_client_ip(raw_request)
|
||||
if await RateLimitCache.is_ip_rate_limited(client_ip, 'merge_execute', limit=5, window=60, fail_closed=True):
|
||||
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
|
||||
|
||||
# 1. Consume token atomically first (GETDEL — one-time use, no TOCTOU)
|
||||
consumed = await consume_merge_token(merge_token)
|
||||
if not consumed:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Merge token is invalid, expired, or already consumed',
|
||||
)
|
||||
|
||||
primary_user_id: int = consumed['primary_user_id']
|
||||
secondary_user_id: int = consumed['secondary_user_id']
|
||||
provider: str = consumed.get('provider', '')
|
||||
provider_id: str = consumed.get('provider_id', '')
|
||||
|
||||
# 2. Validate keep_subscription_from — restore token if invalid
|
||||
if request.keep_subscription_from not in (primary_user_id, secondary_user_id):
|
||||
await restore_merge_token(merge_token, consumed)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='keep_subscription_from must be one of the two user IDs being merged',
|
||||
)
|
||||
|
||||
# Convert user_id to 'primary'/'secondary' string for execute_merge()
|
||||
keep_from: Literal['primary', 'secondary'] = (
|
||||
'primary' if request.keep_subscription_from == primary_user_id else 'secondary'
|
||||
)
|
||||
|
||||
# 3. Execute merge
|
||||
try:
|
||||
merged_user = await execute_merge(
|
||||
db=db,
|
||||
primary_user_id=primary_user_id,
|
||||
secondary_user_id=secondary_user_id,
|
||||
keep_subscription_from=keep_from,
|
||||
provider=provider,
|
||||
provider_id=provider_id,
|
||||
)
|
||||
await db.commit()
|
||||
except ValueError as exc:
|
||||
await db.rollback()
|
||||
await restore_merge_token(merge_token, consumed)
|
||||
logger.error('Merge execution failed (ValueError)', error=str(exc))
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Account merge cannot be completed. The accounts may have already been merged or deleted.',
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
await db.rollback()
|
||||
await restore_merge_token(merge_token, consumed)
|
||||
logger.exception('Merge execution failed')
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Account merge failed due to an internal error',
|
||||
) from exc
|
||||
|
||||
# 4. Re-fetch merged user with full relationships for auth response
|
||||
merged_user = await get_user_by_id(db, primary_user_id)
|
||||
if not merged_user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to load merged user',
|
||||
)
|
||||
|
||||
# 5. Create auth tokens for the merged user
|
||||
try:
|
||||
auth_response = await _create_auth_response(merged_user, db)
|
||||
await _store_refresh_token(db, merged_user.id, auth_response.refresh_token, device_info='merge')
|
||||
except Exception as exc:
|
||||
logger.exception('Failed to create auth tokens after merge')
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Merge succeeded but failed to create new session',
|
||||
) from exc
|
||||
|
||||
logger.info(
|
||||
'Account merge completed successfully',
|
||||
primary_user_id=primary_user_id,
|
||||
secondary_user_id=secondary_user_id,
|
||||
provider=provider,
|
||||
)
|
||||
|
||||
return MergeResponse(
|
||||
success=True,
|
||||
access_token=auth_response.access_token,
|
||||
refresh_token=auth_response.refresh_token,
|
||||
user=_user_to_response(merged_user),
|
||||
)
|
||||
@@ -12,7 +12,7 @@ from app.database.models import User
|
||||
from app.services.remnawave_service import RemnaWaveService
|
||||
from app.services.system_settings_service import bot_configuration_service
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -54,7 +54,7 @@ def _get_remnawave_config_uuid() -> str | None:
|
||||
|
||||
@router.get('/remnawave/status', response_model=RemnaWaveConfigStatus)
|
||||
async def get_remnawave_config_status(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('apps:read')),
|
||||
):
|
||||
"""Get RemnaWave config integration status."""
|
||||
config_uuid = _get_remnawave_config_uuid()
|
||||
@@ -67,7 +67,7 @@ async def get_remnawave_config_status(
|
||||
@router.put('/remnawave/uuid', response_model=RemnaWaveConfigStatus)
|
||||
async def set_remnawave_config_uuid(
|
||||
request: UpdateRemnaWaveUuidRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('apps:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Set RemnaWave subscription config UUID."""
|
||||
@@ -102,7 +102,7 @@ async def set_remnawave_config_uuid(
|
||||
|
||||
@router.get('/remnawave/config')
|
||||
async def get_remnawave_subscription_config(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('apps:read')),
|
||||
):
|
||||
"""Fetch subscription page config from RemnaWave panel."""
|
||||
config_uuid = _get_remnawave_config_uuid()
|
||||
@@ -140,7 +140,7 @@ async def get_remnawave_subscription_config(
|
||||
|
||||
@router.get('/remnawave/configs')
|
||||
async def list_remnawave_subscription_configs(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('apps:read')),
|
||||
):
|
||||
"""List available subscription page configs from RemnaWave panel."""
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Admin audit log routes — view and export admin action history."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
import structlog
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.crud.rbac import AuditLogCRUD
|
||||
from app.database.models import User
|
||||
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
router = APIRouter(prefix='/admin/rbac/audit-log', tags=['Admin RBAC Audit Log'])
|
||||
|
||||
|
||||
# ============ Schemas ============
|
||||
|
||||
|
||||
class AuditLogEntry(BaseModel):
|
||||
"""Single audit log entry."""
|
||||
|
||||
id: int
|
||||
user_id: int
|
||||
action: str
|
||||
resource_type: str | None = None
|
||||
resource_id: str | None = None
|
||||
details: dict[str, Any] | None = None
|
||||
ip_address: str | None = None
|
||||
user_agent: str | None = None
|
||||
status: str
|
||||
request_method: str | None = None
|
||||
request_path: str | None = None
|
||||
created_at: datetime | None = None
|
||||
user_first_name: str | None = None
|
||||
user_email: str | None = None
|
||||
|
||||
|
||||
class AuditLogListResponse(BaseModel):
|
||||
"""Paginated audit log list."""
|
||||
|
||||
items: list[AuditLogEntry]
|
||||
total: int
|
||||
limit: int
|
||||
offset: int
|
||||
|
||||
|
||||
# ============ CSV Export ============
|
||||
|
||||
_CSV_COLUMNS = [
|
||||
'id',
|
||||
'user_id',
|
||||
'action',
|
||||
'resource_type',
|
||||
'resource_id',
|
||||
'status',
|
||||
'ip_address',
|
||||
'request_method',
|
||||
'request_path',
|
||||
'created_at',
|
||||
'user_agent',
|
||||
'details',
|
||||
]
|
||||
|
||||
|
||||
def _sanitize_csv_cell(value: str) -> str:
|
||||
"""Prevent CSV formula injection by prefixing dangerous leading characters."""
|
||||
if value and value[0] in ('=', '+', '-', '@', '\t', '\r'):
|
||||
return f"'{value}"
|
||||
return value
|
||||
|
||||
|
||||
def _logs_to_csv(logs) -> str:
|
||||
"""Serialize audit log entries to CSV string."""
|
||||
output = io.StringIO()
|
||||
writer = csv.writer(output)
|
||||
writer.writerow(_CSV_COLUMNS)
|
||||
|
||||
for log in logs:
|
||||
writer.writerow(
|
||||
[
|
||||
log.id,
|
||||
log.user_id,
|
||||
log.action,
|
||||
log.resource_type or '',
|
||||
log.resource_id or '',
|
||||
log.status,
|
||||
log.ip_address or '',
|
||||
log.request_method or '',
|
||||
_sanitize_csv_cell(log.request_path or ''),
|
||||
log.created_at.isoformat() if log.created_at else '',
|
||||
_sanitize_csv_cell((log.user_agent or '')[:200]),
|
||||
_sanitize_csv_cell(str(log.details) if log.details else ''),
|
||||
]
|
||||
)
|
||||
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
# ============ Routes ============
|
||||
|
||||
|
||||
@router.get('', response_model=AuditLogListResponse)
|
||||
async def list_audit_logs(
|
||||
admin: User = Depends(require_permission('audit_log:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
user_id: int | None = Query(default=None),
|
||||
action: str | None = Query(default=None),
|
||||
resource_type: str | None = Query(default=None),
|
||||
status: str | None = Query(default=None),
|
||||
date_from: datetime | None = Query(default=None),
|
||||
date_to: datetime | None = Query(default=None),
|
||||
limit: int = Query(default=50, ge=1, le=500),
|
||||
offset: int = Query(default=0, ge=0),
|
||||
):
|
||||
"""List audit log entries with optional filters and pagination."""
|
||||
logs, total = await AuditLogCRUD.get_logs(
|
||||
db,
|
||||
user_id=user_id,
|
||||
action=action,
|
||||
resource_type=resource_type,
|
||||
status=status,
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
load_user=True,
|
||||
)
|
||||
|
||||
items = [
|
||||
AuditLogEntry(
|
||||
id=log.id,
|
||||
user_id=log.user_id,
|
||||
action=log.action,
|
||||
resource_type=log.resource_type,
|
||||
resource_id=log.resource_id,
|
||||
details=log.details,
|
||||
ip_address=log.ip_address,
|
||||
user_agent=log.user_agent,
|
||||
status=log.status,
|
||||
request_method=log.request_method,
|
||||
request_path=log.request_path,
|
||||
created_at=log.created_at,
|
||||
user_first_name=log.user.first_name if log.user else None,
|
||||
user_email=log.user.email if log.user else None,
|
||||
)
|
||||
for log in logs
|
||||
]
|
||||
|
||||
return AuditLogListResponse(
|
||||
items=items,
|
||||
total=total,
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
)
|
||||
|
||||
|
||||
@router.get('/export')
|
||||
async def export_audit_logs(
|
||||
admin: User = Depends(require_permission('audit_log:export')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
user_id: int | None = Query(default=None),
|
||||
action: str | None = Query(default=None),
|
||||
resource_type: str | None = Query(default=None),
|
||||
status: str | None = Query(default=None),
|
||||
date_from: datetime | None = Query(default=None),
|
||||
date_to: datetime | None = Query(default=None),
|
||||
limit: int = Query(default=10000, ge=1, le=50000),
|
||||
):
|
||||
"""Export audit logs as CSV file."""
|
||||
logs, _total = await AuditLogCRUD.get_logs(
|
||||
db,
|
||||
user_id=user_id,
|
||||
action=action,
|
||||
resource_type=resource_type,
|
||||
status=status,
|
||||
date_from=date_from,
|
||||
date_to=date_to,
|
||||
limit=limit,
|
||||
offset=0,
|
||||
)
|
||||
|
||||
csv_content = _logs_to_csv(logs)
|
||||
timestamp = datetime.now(UTC).strftime('%Y%m%d_%H%M%S')
|
||||
filename = f'audit_log_{timestamp}.csv'
|
||||
|
||||
logger.info(
|
||||
'Admin exported audit logs',
|
||||
admin_id=admin.id,
|
||||
rows=len(logs),
|
||||
filename=filename,
|
||||
)
|
||||
|
||||
return StreamingResponse(
|
||||
iter([csv_content]),
|
||||
media_type='text/csv',
|
||||
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
|
||||
)
|
||||
@@ -9,7 +9,7 @@ from app.config import settings
|
||||
from app.database.models import User
|
||||
from app.external.ban_system_api import BanSystemAPI, BanSystemAPIError
|
||||
|
||||
from ..dependencies import get_current_admin_user
|
||||
from ..dependencies import require_permission
|
||||
from ..schemas.ban_system import (
|
||||
BanAgentHistoryItem,
|
||||
BanAgentHistoryResponse,
|
||||
@@ -103,7 +103,7 @@ async def _api_request(api: BanSystemAPI, method: str, *args, **kwargs) -> Any:
|
||||
|
||||
@router.get('/status', response_model=BanSystemStatusResponse)
|
||||
async def get_ban_system_status(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanSystemStatusResponse:
|
||||
"""Get Ban System integration status."""
|
||||
return BanSystemStatusResponse(
|
||||
@@ -117,7 +117,7 @@ async def get_ban_system_status(
|
||||
|
||||
@router.get('/stats/raw')
|
||||
async def get_stats_raw(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> dict:
|
||||
"""Get raw stats from Ban System API for debugging."""
|
||||
api = _get_ban_api()
|
||||
@@ -127,7 +127,7 @@ async def get_stats_raw(
|
||||
|
||||
@router.get('/stats', response_model=BanSystemStatsResponse)
|
||||
async def get_stats(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanSystemStatsResponse:
|
||||
"""Get overall Ban System statistics."""
|
||||
from datetime import datetime
|
||||
@@ -181,7 +181,7 @@ async def get_users(
|
||||
offset: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
status: str | None = Query(None, description='Filter: over_limit, with_limit, unlimited'),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanUsersListResponse:
|
||||
"""Get list of users from Ban System."""
|
||||
api = _get_ban_api()
|
||||
@@ -211,7 +211,7 @@ async def get_users(
|
||||
@router.get('/users/over-limit', response_model=BanUsersListResponse)
|
||||
async def get_users_over_limit(
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanUsersListResponse:
|
||||
"""Get users who exceeded their device limit."""
|
||||
api = _get_ban_api()
|
||||
@@ -241,7 +241,7 @@ async def get_users_over_limit(
|
||||
@router.get('/users/search/{query}')
|
||||
async def search_users(
|
||||
query: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanUsersListResponse:
|
||||
"""Search for users."""
|
||||
api = _get_ban_api()
|
||||
@@ -272,7 +272,7 @@ async def search_users(
|
||||
@router.get('/users/{email}', response_model=BanUserDetailResponse)
|
||||
async def get_user_detail(
|
||||
email: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanUserDetailResponse:
|
||||
"""Get detailed user information."""
|
||||
api = _get_ban_api()
|
||||
@@ -325,7 +325,7 @@ async def get_user_detail(
|
||||
|
||||
@router.get('/punishments', response_model=BanPunishmentsListResponse)
|
||||
async def get_punishments(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanPunishmentsListResponse:
|
||||
"""Get list of active punishments (bans)."""
|
||||
api = _get_ban_api()
|
||||
@@ -360,7 +360,7 @@ async def get_punishments(
|
||||
@router.post('/punishments/{user_id}/unban', response_model=UnbanResponse)
|
||||
async def unban_user(
|
||||
user_id: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:unban')),
|
||||
) -> UnbanResponse:
|
||||
"""Unban (enable) a user."""
|
||||
api = _get_ban_api()
|
||||
@@ -377,7 +377,7 @@ async def unban_user(
|
||||
@router.post('/ban', response_model=UnbanResponse)
|
||||
async def ban_user(
|
||||
request: BanUserRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:ban')),
|
||||
) -> UnbanResponse:
|
||||
"""Manually ban a user."""
|
||||
api = _get_ban_api()
|
||||
@@ -401,7 +401,7 @@ async def ban_user(
|
||||
async def get_punishment_history(
|
||||
query: str,
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanHistoryResponse:
|
||||
"""Get punishment history for a user."""
|
||||
api = _get_ban_api()
|
||||
@@ -438,7 +438,7 @@ async def get_punishment_history(
|
||||
|
||||
@router.get('/nodes', response_model=BanNodesListResponse)
|
||||
async def get_nodes(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanNodesListResponse:
|
||||
"""Get list of connected nodes."""
|
||||
api = _get_ban_api()
|
||||
@@ -480,7 +480,7 @@ async def get_agents(
|
||||
search: str | None = Query(None),
|
||||
health: str | None = Query(None, description='healthy, warning, critical'),
|
||||
agent_status: str | None = Query(None, alias='status', description='online, offline'),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanAgentsListResponse:
|
||||
"""Get list of monitoring agents."""
|
||||
api = _get_ban_api()
|
||||
@@ -579,7 +579,7 @@ async def get_agents(
|
||||
|
||||
@router.get('/agents/summary', response_model=BanAgentsSummary)
|
||||
async def get_agents_summary(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanAgentsSummary:
|
||||
"""Get agents summary statistics."""
|
||||
api = _get_ban_api()
|
||||
@@ -603,7 +603,7 @@ async def get_agents_summary(
|
||||
@router.get('/traffic/violations', response_model=BanTrafficViolationsResponse)
|
||||
async def get_traffic_violations(
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanTrafficViolationsResponse:
|
||||
"""Get list of traffic limit violations."""
|
||||
api = _get_ban_api()
|
||||
@@ -637,7 +637,7 @@ async def get_traffic_violations(
|
||||
|
||||
@router.get('/traffic', response_model=BanTrafficResponse)
|
||||
async def get_traffic(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanTrafficResponse:
|
||||
"""Get full traffic statistics including top users."""
|
||||
api = _get_ban_api()
|
||||
@@ -681,7 +681,7 @@ async def get_traffic(
|
||||
@router.get('/traffic/top')
|
||||
async def get_traffic_top(
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> list[BanTrafficTopItem]:
|
||||
"""Get top users by traffic."""
|
||||
api = _get_ban_api()
|
||||
@@ -744,7 +744,7 @@ def _parse_setting_response(key: str, data: Any, default_type: str = 'str') -> B
|
||||
|
||||
@router.get('/settings', response_model=BanSettingsResponse)
|
||||
async def get_settings(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanSettingsResponse:
|
||||
"""Get all Ban System settings."""
|
||||
api = _get_ban_api()
|
||||
@@ -802,7 +802,7 @@ async def get_settings(
|
||||
@router.get('/settings/{key}')
|
||||
async def get_setting(
|
||||
key: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanSettingDefinition:
|
||||
"""Get a specific setting."""
|
||||
api = _get_ban_api()
|
||||
@@ -815,7 +815,7 @@ async def get_setting(
|
||||
async def set_setting(
|
||||
key: str,
|
||||
value: str = Query(...),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:edit')),
|
||||
) -> BanSettingDefinition:
|
||||
"""Set a setting value."""
|
||||
api = _get_ban_api()
|
||||
@@ -829,7 +829,7 @@ async def set_setting(
|
||||
@router.post('/settings/{key}/toggle')
|
||||
async def toggle_setting(
|
||||
key: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:edit')),
|
||||
) -> BanSettingDefinition:
|
||||
"""Toggle a boolean setting."""
|
||||
api = _get_ban_api()
|
||||
@@ -846,7 +846,7 @@ async def toggle_setting(
|
||||
@router.post('/settings/whitelist/add', response_model=UnbanResponse)
|
||||
async def whitelist_add(
|
||||
request: BanWhitelistRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:edit')),
|
||||
) -> UnbanResponse:
|
||||
"""Add user to whitelist."""
|
||||
api = _get_ban_api()
|
||||
@@ -863,7 +863,7 @@ async def whitelist_add(
|
||||
@router.post('/settings/whitelist/remove', response_model=UnbanResponse)
|
||||
async def whitelist_remove(
|
||||
request: BanWhitelistRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:edit')),
|
||||
) -> UnbanResponse:
|
||||
"""Remove user from whitelist."""
|
||||
api = _get_ban_api()
|
||||
@@ -883,7 +883,7 @@ async def whitelist_remove(
|
||||
@router.get('/report', response_model=BanReportResponse)
|
||||
async def get_report(
|
||||
hours: int = Query(24, ge=1, le=168),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanReportResponse:
|
||||
"""Get period report."""
|
||||
api = _get_ban_api()
|
||||
@@ -913,7 +913,7 @@ async def get_report(
|
||||
|
||||
@router.get('/health', response_model=BanHealthResponse)
|
||||
async def get_health(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanHealthResponse:
|
||||
"""Get Ban System health status."""
|
||||
api = _get_ban_api()
|
||||
@@ -947,7 +947,7 @@ async def get_health(
|
||||
|
||||
@router.get('/health/detailed', response_model=BanHealthDetailedResponse)
|
||||
async def get_health_detailed(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanHealthDetailedResponse:
|
||||
"""Get detailed health information."""
|
||||
api = _get_ban_api()
|
||||
@@ -967,7 +967,7 @@ async def get_health_detailed(
|
||||
async def get_agent_history(
|
||||
node_name: str,
|
||||
hours: int = Query(24, ge=1, le=168),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanAgentHistoryResponse:
|
||||
"""Get agent statistics history."""
|
||||
api = _get_ban_api()
|
||||
@@ -1003,7 +1003,7 @@ async def get_agent_history(
|
||||
async def get_user_punishment_history(
|
||||
email: str,
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('ban_system:read')),
|
||||
) -> BanHistoryResponse:
|
||||
"""Get punishment history for a specific user."""
|
||||
api = _get_ban_api()
|
||||
|
||||
@@ -18,7 +18,7 @@ from app.services.broadcast_service import (
|
||||
email_broadcast_service,
|
||||
)
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.broadcasts import (
|
||||
BroadcastButton,
|
||||
BroadcastButtonsResponse,
|
||||
@@ -247,7 +247,7 @@ def _validate_buttons(buttons: list[str]) -> bool:
|
||||
|
||||
@router.get('/filters', response_model=BroadcastFiltersResponse)
|
||||
async def get_filters(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> BroadcastFiltersResponse:
|
||||
"""Get all available filters with user counts."""
|
||||
@@ -310,7 +310,7 @@ async def get_filters(
|
||||
|
||||
@router.get('/tariffs', response_model=BroadcastTariffsResponse)
|
||||
async def get_tariffs(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> BroadcastTariffsResponse:
|
||||
"""Get tariffs for broadcast filtering."""
|
||||
@@ -333,7 +333,7 @@ async def get_tariffs(
|
||||
|
||||
@router.get('/buttons', response_model=BroadcastButtonsResponse)
|
||||
async def get_buttons(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:read')),
|
||||
) -> BroadcastButtonsResponse:
|
||||
"""Get available buttons for broadcasts."""
|
||||
default_buttons = set(DEFAULT_BROADCAST_BUTTONS)
|
||||
@@ -352,7 +352,7 @@ async def get_buttons(
|
||||
@router.post('/preview', response_model=BroadcastPreviewResponse)
|
||||
async def preview_broadcast(
|
||||
request: BroadcastPreviewRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> BroadcastPreviewResponse:
|
||||
"""Preview broadcast recipients count."""
|
||||
@@ -381,7 +381,7 @@ async def preview_broadcast(
|
||||
@router.post('', response_model=BroadcastResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_broadcast(
|
||||
request: BroadcastCreateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:create')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> BroadcastResponse:
|
||||
"""Create and start a broadcast."""
|
||||
@@ -461,7 +461,7 @@ async def create_broadcast(
|
||||
|
||||
@router.get('', response_model=BroadcastListResponse)
|
||||
async def list_broadcasts(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
offset: int = Query(0, ge=0),
|
||||
@@ -487,7 +487,7 @@ async def list_broadcasts(
|
||||
|
||||
@router.get('/email-filters', response_model=EmailFiltersResponse)
|
||||
async def get_email_filters(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> EmailFiltersResponse:
|
||||
"""Get all available email filters with user counts."""
|
||||
@@ -523,7 +523,7 @@ async def get_email_filters(
|
||||
@router.post('/email-preview', response_model=EmailPreviewResponse)
|
||||
async def preview_email_broadcast(
|
||||
request: EmailPreviewRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> EmailPreviewResponse:
|
||||
"""Preview email broadcast recipients count."""
|
||||
@@ -548,7 +548,7 @@ async def preview_email_broadcast(
|
||||
@router.post('/send', response_model=BroadcastResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_combined_broadcast(
|
||||
request: CombinedBroadcastCreateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:send')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> BroadcastResponse:
|
||||
"""Create and start a combined broadcast (telegram/email/both)."""
|
||||
@@ -679,7 +679,7 @@ async def create_combined_broadcast(
|
||||
@router.get('/{broadcast_id}', response_model=BroadcastResponse)
|
||||
async def get_broadcast(
|
||||
broadcast_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> BroadcastResponse:
|
||||
"""Get broadcast details."""
|
||||
@@ -695,7 +695,7 @@ async def get_broadcast(
|
||||
@router.post('/{broadcast_id}/stop', response_model=BroadcastResponse)
|
||||
async def stop_broadcast(
|
||||
broadcast_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('broadcasts:send')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> BroadcastResponse:
|
||||
"""Stop a running broadcast (telegram or email)."""
|
||||
|
||||
@@ -17,7 +17,7 @@ from app.utils.button_styles_cache import (
|
||||
load_button_styles_cache,
|
||||
)
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -112,7 +112,7 @@ def _build_response(styles: dict[str, dict]) -> ButtonStylesResponse:
|
||||
|
||||
@router.get('', response_model=ButtonStylesResponse)
|
||||
async def get_button_styles(
|
||||
_admin: User = Depends(get_current_admin_user),
|
||||
_admin: User = Depends(require_permission('settings:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Return current per-section button styles. Admin only."""
|
||||
@@ -145,7 +145,7 @@ async def get_button_styles(
|
||||
@router.patch('', response_model=ButtonStylesResponse)
|
||||
async def update_button_styles(
|
||||
payload: ButtonStylesUpdate,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Partially update per-section button styles. Admin only."""
|
||||
@@ -243,7 +243,7 @@ async def update_button_styles(
|
||||
|
||||
@router.post('/reset', response_model=ButtonStylesResponse)
|
||||
async def reset_button_styles(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Reset all button styles to defaults. Admin only."""
|
||||
|
||||
@@ -7,7 +7,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.cabinet.utils.links import get_campaign_deep_link, get_campaign_web_link
|
||||
from app.database.crud.campaign import (
|
||||
create_campaign,
|
||||
delete_campaign,
|
||||
@@ -29,9 +29,11 @@ from app.database.models import (
|
||||
Tariff,
|
||||
User,
|
||||
)
|
||||
from app.services.partner_stats_service import PartnerStatsService
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.campaigns import (
|
||||
AdminCampaignChartDataResponse,
|
||||
AvailablePartnerItem,
|
||||
CampaignCreateRequest,
|
||||
CampaignDetailResponse,
|
||||
@@ -54,20 +56,9 @@ logger = structlog.get_logger(__name__)
|
||||
router = APIRouter(prefix='/admin/campaigns', tags=['Cabinet Admin Campaigns'])
|
||||
|
||||
|
||||
def _get_deep_link(start_parameter: str) -> str:
|
||||
"""Generate deep link for campaign."""
|
||||
bot_username = settings.get_bot_username()
|
||||
if bot_username:
|
||||
return f'https://t.me/{bot_username}?start={start_parameter}'
|
||||
return f'?start={start_parameter}'
|
||||
|
||||
|
||||
def _get_web_link(start_parameter: str) -> str | None:
|
||||
"""Generate web link for campaign."""
|
||||
base_url = (settings.MINIAPP_CUSTOM_URL or '').rstrip('/')
|
||||
if base_url:
|
||||
return f'{base_url}/?campaign={start_parameter}'
|
||||
return None
|
||||
def _safe_div(value: float | None, divisor: int = 100) -> float:
|
||||
"""Safely divide kopeks to rubles, handling None values."""
|
||||
return (value or 0) / divisor
|
||||
|
||||
|
||||
def _get_partner_name(campaign: AdvertisingCampaign) -> str | None:
|
||||
@@ -80,35 +71,44 @@ def _get_partner_name(campaign: AdvertisingCampaign) -> str | None:
|
||||
|
||||
@router.get('/overview', response_model=CampaignsOverviewResponse)
|
||||
async def get_overview(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get campaigns overview statistics."""
|
||||
overview = await get_campaigns_overview(db)
|
||||
try:
|
||||
overview = await get_campaigns_overview(db)
|
||||
|
||||
# Count tariff bonuses
|
||||
tariff_result = await db.execute(
|
||||
select(func.count(AdvertisingCampaignRegistration.id)).where(
|
||||
AdvertisingCampaignRegistration.bonus_type == 'tariff'
|
||||
# Count tariff bonuses
|
||||
tariff_result = await db.execute(
|
||||
select(func.count(AdvertisingCampaignRegistration.id)).where(
|
||||
AdvertisingCampaignRegistration.bonus_type == 'tariff'
|
||||
)
|
||||
)
|
||||
)
|
||||
tariff_count = tariff_result.scalar() or 0
|
||||
tariff_count = tariff_result.scalar() or 0
|
||||
|
||||
return CampaignsOverviewResponse(
|
||||
total=overview['total'],
|
||||
active=overview['active'],
|
||||
inactive=overview['inactive'],
|
||||
total_registrations=overview['registrations'],
|
||||
total_balance_issued_kopeks=overview['balance_total'],
|
||||
total_balance_issued_rubles=overview['balance_total'] / 100,
|
||||
total_subscription_issued=overview['subscription_total'],
|
||||
total_tariff_issued=tariff_count,
|
||||
)
|
||||
return CampaignsOverviewResponse(
|
||||
total=overview['total'],
|
||||
active=overview['active'],
|
||||
inactive=overview['inactive'],
|
||||
total_registrations=overview['registrations'],
|
||||
total_balance_issued_kopeks=overview['balance_total'],
|
||||
total_balance_issued_rubles=_safe_div(overview['balance_total']),
|
||||
total_subscription_issued=overview['subscription_total'],
|
||||
total_tariff_issued=tariff_count,
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error('Failed to get campaigns overview', error=str(e), exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to load campaigns overview',
|
||||
)
|
||||
|
||||
|
||||
@router.get('/available-servers', response_model=list[ServerSquadInfo])
|
||||
async def get_available_servers(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get list of available server squads for campaign subscription bonus."""
|
||||
@@ -126,7 +126,7 @@ async def get_available_servers(
|
||||
|
||||
@router.get('/available-tariffs', response_model=list[TariffListItem])
|
||||
async def get_available_tariffs(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get list of available tariffs for campaign tariff bonus."""
|
||||
@@ -155,7 +155,7 @@ async def get_available_tariffs(
|
||||
|
||||
@router.get('/available-partners', response_model=list[AvailablePartnerItem])
|
||||
async def get_available_partners(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get list of approved partners for campaign partner selector."""
|
||||
@@ -178,12 +178,12 @@ async def list_campaigns(
|
||||
include_inactive: bool = True,
|
||||
offset: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get list of all campaigns."""
|
||||
campaigns = await get_campaigns_list(db, offset=offset, limit=limit, include_inactive=include_inactive)
|
||||
total = await get_campaigns_count(db)
|
||||
total = await get_campaigns_count(db, is_active=True if not include_inactive else None)
|
||||
|
||||
items = []
|
||||
for campaign in campaigns:
|
||||
@@ -211,7 +211,7 @@ async def list_campaigns(
|
||||
@router.get('/{campaign_id}', response_model=CampaignDetailResponse)
|
||||
async def get_campaign(
|
||||
campaign_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get detailed campaign info."""
|
||||
@@ -236,7 +236,7 @@ async def get_campaign(
|
||||
bonus_type=campaign.bonus_type,
|
||||
is_active=campaign.is_active,
|
||||
balance_bonus_kopeks=campaign.balance_bonus_kopeks or 0,
|
||||
balance_bonus_rubles=(campaign.balance_bonus_kopeks or 0) / 100,
|
||||
balance_bonus_rubles=_safe_div(campaign.balance_bonus_kopeks),
|
||||
subscription_duration_days=campaign.subscription_duration_days,
|
||||
subscription_traffic_gb=campaign.subscription_traffic_gb,
|
||||
subscription_device_limit=campaign.subscription_device_limit,
|
||||
@@ -249,53 +249,89 @@ async def get_campaign(
|
||||
created_by=campaign.created_by,
|
||||
created_at=campaign.created_at,
|
||||
updated_at=campaign.updated_at,
|
||||
deep_link=_get_deep_link(campaign.start_parameter),
|
||||
web_link=_get_web_link(campaign.start_parameter),
|
||||
deep_link=get_campaign_deep_link(campaign.start_parameter),
|
||||
web_link=get_campaign_web_link(campaign.start_parameter),
|
||||
)
|
||||
|
||||
|
||||
@router.get('/{campaign_id}/chart-data', response_model=AdminCampaignChartDataResponse)
|
||||
async def get_campaign_chart_data(
|
||||
campaign_id: int,
|
||||
admin: User = Depends(require_permission('campaigns:stats')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get chart data for admin campaign analytics."""
|
||||
try:
|
||||
campaign = await get_campaign_by_id(db, campaign_id)
|
||||
if not campaign:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Campaign not found',
|
||||
)
|
||||
|
||||
data = await PartnerStatsService.get_admin_campaign_chart_data(db, campaign_id)
|
||||
return AdminCampaignChartDataResponse(**data)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error('Failed to get campaign chart data', error=str(e), campaign_id=campaign_id, exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to load campaign chart data',
|
||||
)
|
||||
|
||||
|
||||
@router.get('/{campaign_id}/stats', response_model=CampaignStatisticsResponse)
|
||||
async def get_campaign_stats(
|
||||
campaign_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:stats')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get detailed campaign statistics."""
|
||||
campaign = await get_campaign_by_id(db, campaign_id)
|
||||
if not campaign:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Campaign not found',
|
||||
try:
|
||||
campaign = await get_campaign_by_id(db, campaign_id)
|
||||
if not campaign:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Campaign not found',
|
||||
)
|
||||
|
||||
stats = await get_campaign_statistics(db, campaign_id)
|
||||
|
||||
return CampaignStatisticsResponse(
|
||||
id=campaign.id,
|
||||
name=campaign.name,
|
||||
start_parameter=campaign.start_parameter,
|
||||
bonus_type=campaign.bonus_type,
|
||||
is_active=campaign.is_active,
|
||||
registrations=stats['registrations'],
|
||||
balance_issued_kopeks=stats['balance_issued'],
|
||||
balance_issued_rubles=_safe_div(stats['balance_issued']),
|
||||
subscription_issued=stats['subscription_issued'],
|
||||
last_registration=stats['last_registration'],
|
||||
total_revenue_kopeks=stats['total_revenue_kopeks'],
|
||||
total_revenue_rubles=_safe_div(stats['total_revenue_kopeks']),
|
||||
avg_revenue_per_user_kopeks=stats['avg_revenue_per_user_kopeks'],
|
||||
avg_revenue_per_user_rubles=_safe_div(stats['avg_revenue_per_user_kopeks']),
|
||||
avg_first_payment_kopeks=stats['avg_first_payment_kopeks'],
|
||||
avg_first_payment_rubles=_safe_div(stats['avg_first_payment_kopeks']),
|
||||
trial_users_count=stats['trial_users_count'],
|
||||
active_trials_count=stats['active_trials_count'],
|
||||
conversion_count=stats['conversion_count'],
|
||||
paid_users_count=stats['paid_users_count'],
|
||||
conversion_rate=stats['conversion_rate'],
|
||||
trial_conversion_rate=stats['trial_conversion_rate'],
|
||||
deep_link=get_campaign_deep_link(campaign.start_parameter),
|
||||
web_link=get_campaign_web_link(campaign.start_parameter),
|
||||
)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error('Failed to get campaign stats', error=str(e), campaign_id=campaign_id, exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to load campaign statistics',
|
||||
)
|
||||
|
||||
stats = await get_campaign_statistics(db, campaign_id)
|
||||
|
||||
return CampaignStatisticsResponse(
|
||||
id=campaign.id,
|
||||
name=campaign.name,
|
||||
start_parameter=campaign.start_parameter,
|
||||
bonus_type=campaign.bonus_type,
|
||||
is_active=campaign.is_active,
|
||||
registrations=stats['registrations'],
|
||||
balance_issued_kopeks=stats['balance_issued'],
|
||||
balance_issued_rubles=stats['balance_issued'] / 100,
|
||||
subscription_issued=stats['subscription_issued'],
|
||||
last_registration=stats['last_registration'],
|
||||
total_revenue_kopeks=stats['total_revenue_kopeks'],
|
||||
total_revenue_rubles=stats['total_revenue_kopeks'] / 100,
|
||||
avg_revenue_per_user_kopeks=stats['avg_revenue_per_user_kopeks'],
|
||||
avg_revenue_per_user_rubles=stats['avg_revenue_per_user_kopeks'] / 100,
|
||||
avg_first_payment_kopeks=stats['avg_first_payment_kopeks'],
|
||||
avg_first_payment_rubles=stats['avg_first_payment_kopeks'] / 100,
|
||||
trial_users_count=stats['trial_users_count'],
|
||||
active_trials_count=stats['active_trials_count'],
|
||||
conversion_count=stats['conversion_count'],
|
||||
paid_users_count=stats['paid_users_count'],
|
||||
conversion_rate=stats['conversion_rate'],
|
||||
trial_conversion_rate=stats['trial_conversion_rate'],
|
||||
deep_link=_get_deep_link(campaign.start_parameter),
|
||||
web_link=_get_web_link(campaign.start_parameter),
|
||||
)
|
||||
|
||||
|
||||
@router.get('/{campaign_id}/registrations', response_model=CampaignRegistrationsResponse)
|
||||
@@ -303,7 +339,7 @@ async def get_campaign_registrations(
|
||||
campaign_id: int,
|
||||
page: int = Query(1, ge=1),
|
||||
per_page: int = Query(50, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get list of users registered through campaign."""
|
||||
@@ -381,7 +417,7 @@ async def get_campaign_registrations(
|
||||
@router.post('', response_model=CampaignDetailResponse)
|
||||
async def create_new_campaign(
|
||||
request: CampaignCreateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:create')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Create a new advertising campaign."""
|
||||
@@ -411,7 +447,7 @@ async def create_new_campaign(
|
||||
# Validate partner exists and is approved
|
||||
if request.partner_user_id is not None:
|
||||
partner_user = await db.get(User, request.partner_user_id)
|
||||
if not partner_user or partner_user.partner_status != 'approved':
|
||||
if not partner_user or partner_user.partner_status != PartnerStatus.APPROVED.value:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Partner not found or not approved',
|
||||
@@ -434,9 +470,6 @@ async def create_new_campaign(
|
||||
partner_user_id=request.partner_user_id,
|
||||
)
|
||||
|
||||
# Reload to get tariff relationship
|
||||
campaign = await get_campaign_by_id(db, campaign.id)
|
||||
|
||||
logger.info('Admin created campaign', admin_id=admin.id, campaign_id=campaign.id, campaign_name=campaign.name)
|
||||
|
||||
return await get_campaign(campaign.id, admin, db)
|
||||
@@ -446,7 +479,7 @@ async def create_new_campaign(
|
||||
async def update_existing_campaign(
|
||||
campaign_id: int,
|
||||
request: CampaignUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update an existing campaign."""
|
||||
@@ -478,29 +511,29 @@ async def update_existing_campaign(
|
||||
detail='Tariff not found',
|
||||
)
|
||||
|
||||
# Build updates
|
||||
# Build updates using model_fields_set to distinguish "not sent" from "sent as None"
|
||||
updates = {}
|
||||
if request.name is not None:
|
||||
if 'name' in request.model_fields_set:
|
||||
updates['name'] = request.name
|
||||
if request.start_parameter is not None:
|
||||
if 'start_parameter' in request.model_fields_set:
|
||||
updates['start_parameter'] = request.start_parameter
|
||||
if request.bonus_type is not None:
|
||||
if 'bonus_type' in request.model_fields_set:
|
||||
updates['bonus_type'] = request.bonus_type
|
||||
if request.is_active is not None:
|
||||
if 'is_active' in request.model_fields_set:
|
||||
updates['is_active'] = request.is_active
|
||||
if request.balance_bonus_kopeks is not None:
|
||||
if 'balance_bonus_kopeks' in request.model_fields_set:
|
||||
updates['balance_bonus_kopeks'] = request.balance_bonus_kopeks
|
||||
if request.subscription_duration_days is not None:
|
||||
if 'subscription_duration_days' in request.model_fields_set:
|
||||
updates['subscription_duration_days'] = request.subscription_duration_days
|
||||
if request.subscription_traffic_gb is not None:
|
||||
if 'subscription_traffic_gb' in request.model_fields_set:
|
||||
updates['subscription_traffic_gb'] = request.subscription_traffic_gb
|
||||
if request.subscription_device_limit is not None:
|
||||
if 'subscription_device_limit' in request.model_fields_set:
|
||||
updates['subscription_device_limit'] = request.subscription_device_limit
|
||||
if request.subscription_squads is not None:
|
||||
if 'subscription_squads' in request.model_fields_set:
|
||||
updates['subscription_squads'] = request.subscription_squads
|
||||
if request.tariff_id is not None:
|
||||
if 'tariff_id' in request.model_fields_set:
|
||||
updates['tariff_id'] = request.tariff_id
|
||||
if request.tariff_duration_days is not None:
|
||||
if 'tariff_duration_days' in request.model_fields_set:
|
||||
updates['tariff_duration_days'] = request.tariff_duration_days
|
||||
|
||||
# Handle partner_user_id separately (allows explicit None to unassign)
|
||||
@@ -509,7 +542,7 @@ async def update_existing_campaign(
|
||||
new_partner_id = request.partner_user_id
|
||||
if new_partner_id is not None:
|
||||
partner_user = await db.get(User, new_partner_id)
|
||||
if not partner_user or partner_user.partner_status != 'approved':
|
||||
if not partner_user or partner_user.partner_status != PartnerStatus.APPROVED.value:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Partner not found or not approved',
|
||||
@@ -532,7 +565,7 @@ async def update_existing_campaign(
|
||||
@router.delete('/{campaign_id}')
|
||||
async def delete_existing_campaign(
|
||||
campaign_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:delete')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Delete a campaign."""
|
||||
@@ -543,8 +576,13 @@ async def delete_existing_campaign(
|
||||
detail='Campaign not found',
|
||||
)
|
||||
|
||||
# Check if campaign has registrations
|
||||
reg_count = len(campaign.registrations) if campaign.registrations else 0
|
||||
# Check if campaign has registrations (COUNT query instead of loading all)
|
||||
reg_count_result = await db.execute(
|
||||
select(func.count(AdvertisingCampaignRegistration.id)).where(
|
||||
AdvertisingCampaignRegistration.campaign_id == campaign_id
|
||||
)
|
||||
)
|
||||
reg_count = reg_count_result.scalar() or 0
|
||||
if reg_count > 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
@@ -560,7 +598,7 @@ async def delete_existing_campaign(
|
||||
@router.post('/{campaign_id}/toggle', response_model=CampaignToggleResponse)
|
||||
async def toggle_campaign(
|
||||
campaign_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('campaigns:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Toggle campaign active status."""
|
||||
|
||||
@@ -14,7 +14,7 @@ from app.database.crud.required_channel import (
|
||||
from app.database.models import User
|
||||
from app.services.channel_subscription_service import channel_subscription_service
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.channel import (
|
||||
ChannelCreateRequest,
|
||||
ChannelListResponse,
|
||||
@@ -31,7 +31,7 @@ router = APIRouter(prefix='/admin/channel-subscriptions', tags=['Cabinet Admin C
|
||||
@router.get('', response_model=ChannelListResponse)
|
||||
async def list_channels(
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
_admin: User = Depends(get_current_admin_user),
|
||||
_admin: User = Depends(require_permission('channels:read')),
|
||||
) -> ChannelListResponse:
|
||||
channels = await get_all_channels(db)
|
||||
return ChannelListResponse(
|
||||
@@ -44,9 +44,16 @@ async def list_channels(
|
||||
async def create_channel(
|
||||
data: ChannelCreateRequest,
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
_admin: User = Depends(get_current_admin_user),
|
||||
_admin: User = Depends(require_permission('channels:edit')),
|
||||
) -> ChannelResponse:
|
||||
ch = await add_channel(db, channel_id=data.channel_id, channel_link=data.channel_link, title=data.title)
|
||||
ch = await add_channel(
|
||||
db,
|
||||
channel_id=data.channel_id,
|
||||
channel_link=data.channel_link,
|
||||
title=data.title,
|
||||
disable_trial_on_leave=data.disable_trial_on_leave,
|
||||
disable_paid_on_leave=data.disable_paid_on_leave,
|
||||
)
|
||||
await channel_subscription_service.invalidate_channels_cache()
|
||||
return ChannelResponse.model_validate(ch)
|
||||
|
||||
@@ -56,7 +63,7 @@ async def update_channel_endpoint(
|
||||
channel_db_id: int,
|
||||
data: ChannelUpdateRequest,
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
_admin: User = Depends(get_current_admin_user),
|
||||
_admin: User = Depends(require_permission('channels:edit')),
|
||||
) -> ChannelResponse:
|
||||
update_data = data.model_dump(exclude_unset=True)
|
||||
ch = await update_channel(db, channel_db_id, **update_data)
|
||||
@@ -70,7 +77,7 @@ async def update_channel_endpoint(
|
||||
async def toggle_channel_endpoint(
|
||||
channel_db_id: int,
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
_admin: User = Depends(get_current_admin_user),
|
||||
_admin: User = Depends(require_permission('channels:edit')),
|
||||
) -> ChannelResponse:
|
||||
ch = await toggle_channel(db, channel_db_id)
|
||||
if not ch:
|
||||
@@ -83,7 +90,7 @@ async def toggle_channel_endpoint(
|
||||
async def delete_channel_endpoint(
|
||||
channel_db_id: int,
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
_admin: User = Depends(get_current_admin_user),
|
||||
_admin: User = Depends(require_permission('channels:edit')),
|
||||
) -> None:
|
||||
ok = await delete_channel(db, channel_db_id)
|
||||
if not ok:
|
||||
|
||||
@@ -10,7 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.models import User
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..services.email_template_overrides import (
|
||||
delete_template_override,
|
||||
get_all_overrides,
|
||||
@@ -370,7 +370,7 @@ class EmailTemplateSendTestRequest(BaseModel):
|
||||
|
||||
@router.get('', summary='List all email template types')
|
||||
async def list_template_types(
|
||||
_admin: User = Depends(get_current_admin_user),
|
||||
_admin: User = Depends(require_permission('email_templates:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> dict[str, Any]:
|
||||
"""List all available email template types with override status."""
|
||||
@@ -405,7 +405,7 @@ async def list_template_types(
|
||||
@router.get('/{notification_type}', summary='Get templates for a notification type')
|
||||
async def get_templates_for_type(
|
||||
notification_type: str,
|
||||
_admin: User = Depends(get_current_admin_user),
|
||||
_admin: User = Depends(require_permission('email_templates:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Get all language templates for a specific notification type."""
|
||||
@@ -479,7 +479,7 @@ async def update_template(
|
||||
notification_type: str,
|
||||
language: str,
|
||||
data: EmailTemplateUpdate,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('email_templates:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Save a custom email template override."""
|
||||
@@ -515,7 +515,7 @@ async def update_template(
|
||||
async def reset_template(
|
||||
notification_type: str,
|
||||
language: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('email_templates:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Delete custom template override, reverting to default."""
|
||||
@@ -543,7 +543,7 @@ async def reset_template(
|
||||
async def preview_template(
|
||||
notification_type: str,
|
||||
data: EmailTemplatePreviewRequest,
|
||||
_admin: User = Depends(get_current_admin_user),
|
||||
_admin: User = Depends(require_permission('email_templates:read')),
|
||||
) -> dict[str, Any]:
|
||||
"""Preview a rendered email template with sample data."""
|
||||
valid_types = [t['type'] for t in TEMPLATE_TYPES]
|
||||
@@ -588,7 +588,7 @@ async def preview_template(
|
||||
async def send_test_email(
|
||||
notification_type: str,
|
||||
data: EmailTemplateSendTestRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('email_templates:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Send a test email to the admin's email address."""
|
||||
|
||||
@@ -20,7 +20,7 @@ from app.database.models import (
|
||||
from app.services.partner_application_service import partner_application_service
|
||||
from app.services.partner_stats_service import PartnerStatsService
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.partners import (
|
||||
AdminApproveRequest,
|
||||
AdminPartnerApplicationItem,
|
||||
@@ -73,7 +73,7 @@ def _build_partner_settings_response() -> PartnerSettingsResponse:
|
||||
|
||||
@router.get('/settings', response_model=PartnerSettingsResponse)
|
||||
async def get_partner_settings(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:settings')),
|
||||
):
|
||||
"""Get partner system settings."""
|
||||
return _build_partner_settings_response()
|
||||
@@ -82,7 +82,7 @@ async def get_partner_settings(
|
||||
@router.patch('/settings', response_model=PartnerSettingsResponse)
|
||||
async def update_partner_settings(
|
||||
request: PartnerSettingsUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:settings')),
|
||||
):
|
||||
"""Update partner system settings."""
|
||||
from pathlib import Path
|
||||
@@ -159,7 +159,7 @@ async def list_applications(
|
||||
application_status: Literal['pending', 'approved', 'rejected', 'none'] | None = Query(None, alias='status'),
|
||||
offset: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""List partner applications."""
|
||||
@@ -190,6 +190,7 @@ async def list_applications(
|
||||
telegram_channel=app.telegram_channel,
|
||||
description=app.description,
|
||||
expected_monthly_referrals=app.expected_monthly_referrals,
|
||||
desired_commission_percent=app.desired_commission_percent,
|
||||
status=app.status,
|
||||
admin_comment=app.admin_comment,
|
||||
approved_commission_percent=app.approved_commission_percent,
|
||||
@@ -205,7 +206,7 @@ async def list_applications(
|
||||
async def approve_application(
|
||||
application_id: int,
|
||||
request: AdminApproveRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:approve')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Approve a partner application."""
|
||||
@@ -259,7 +260,7 @@ async def approve_application(
|
||||
async def reject_application(
|
||||
application_id: int,
|
||||
request: AdminRejectRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:approve')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Reject a partner application."""
|
||||
@@ -310,7 +311,7 @@ async def reject_application(
|
||||
|
||||
@router.get('/stats')
|
||||
async def get_partner_stats(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get overall partner statistics."""
|
||||
@@ -340,7 +341,7 @@ async def get_partner_stats(
|
||||
async def list_partners(
|
||||
offset: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""List approved partners."""
|
||||
@@ -404,7 +405,7 @@ async def list_partners(
|
||||
@router.get('/{user_id}', response_model=AdminPartnerDetailResponse)
|
||||
async def get_partner_detail(
|
||||
user_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get detailed partner info."""
|
||||
@@ -417,17 +418,24 @@ async def get_partner_detail(
|
||||
|
||||
stats = await PartnerStatsService.get_referrer_detailed_stats(db, user_id)
|
||||
|
||||
# Get assigned campaigns
|
||||
# Get assigned campaigns with per-campaign stats
|
||||
campaigns_result = await db.execute(
|
||||
select(AdvertisingCampaign).where(AdvertisingCampaign.partner_user_id == user_id)
|
||||
)
|
||||
campaigns = campaigns_result.scalars().all()
|
||||
|
||||
campaign_ids = [c.id for c in campaigns]
|
||||
per_campaign_stats = await PartnerStatsService.get_per_campaign_stats(db, user_id, campaign_ids)
|
||||
|
||||
campaign_list = [
|
||||
CampaignSummary(
|
||||
id=c.id,
|
||||
name=c.name,
|
||||
start_parameter=c.start_parameter,
|
||||
is_active=c.is_active,
|
||||
registrations_count=per_campaign_stats.get(c.id, {}).get('registrations_count', 0),
|
||||
referrals_count=per_campaign_stats.get(c.id, {}).get('referrals_count', 0),
|
||||
earnings_kopeks=per_campaign_stats.get(c.id, {}).get('earnings_kopeks', 0),
|
||||
)
|
||||
for c in campaigns
|
||||
]
|
||||
@@ -460,7 +468,7 @@ async def get_partner_detail(
|
||||
async def update_commission(
|
||||
user_id: int,
|
||||
request: AdminUpdateCommissionRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update partner commission percent."""
|
||||
@@ -495,7 +503,7 @@ async def update_commission(
|
||||
@router.post('/{user_id}/revoke')
|
||||
async def revoke_partner(
|
||||
user_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:revoke')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Revoke partner status."""
|
||||
@@ -514,7 +522,7 @@ async def revoke_partner(
|
||||
async def assign_campaign(
|
||||
user_id: int,
|
||||
campaign_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Assign a campaign to a partner."""
|
||||
@@ -551,6 +559,12 @@ async def assign_campaign(
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Кампания привязана к партнёру',
|
||||
campaign_id=campaign_id,
|
||||
partner_user_id=user_id,
|
||||
admin_id=admin.id,
|
||||
)
|
||||
return {'success': True}
|
||||
|
||||
|
||||
@@ -558,25 +572,36 @@ async def assign_campaign(
|
||||
async def unassign_campaign(
|
||||
user_id: int,
|
||||
campaign_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('partners:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Unassign a campaign from a partner."""
|
||||
campaign = await db.get(AdvertisingCampaign, campaign_id)
|
||||
if not campaign:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Кампания не найдена',
|
||||
# Atomic check-and-unset to prevent race conditions
|
||||
result = await db.execute(
|
||||
update(AdvertisingCampaign)
|
||||
.where(
|
||||
AdvertisingCampaign.id == campaign_id,
|
||||
AdvertisingCampaign.partner_user_id == user_id,
|
||||
)
|
||||
|
||||
if campaign.partner_user_id != user_id:
|
||||
.values(partner_user_id=None, updated_at=datetime.now(UTC))
|
||||
)
|
||||
if result.rowcount == 0:
|
||||
campaign = await db.get(AdvertisingCampaign, campaign_id)
|
||||
if not campaign:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Кампания не найдена',
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Кампания не привязана к этому партнёру',
|
||||
)
|
||||
|
||||
campaign.partner_user_id = None
|
||||
campaign.updated_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Кампания откреплена от партнёра',
|
||||
campaign_id=campaign_id,
|
||||
partner_user_id=user_id,
|
||||
admin_id=admin.id,
|
||||
)
|
||||
return {'success': True}
|
||||
|
||||
@@ -17,7 +17,7 @@ from app.services.payment_method_config_service import (
|
||||
update_sort_order,
|
||||
)
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -124,7 +124,7 @@ def _enrich_config(config, defaults: dict) -> PaymentMethodConfigResponse:
|
||||
|
||||
@router.get('', response_model=list[PaymentMethodConfigResponse])
|
||||
async def list_payment_methods(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('payment_methods:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""List all payment method configurations."""
|
||||
@@ -135,7 +135,7 @@ async def list_payment_methods(
|
||||
|
||||
@router.get('/promo-groups', response_model=list[PromoGroupSimple])
|
||||
async def list_promo_groups(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('payment_methods:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""List all promo groups for filter selector."""
|
||||
@@ -146,7 +146,7 @@ async def list_promo_groups(
|
||||
@router.get('/{method_id}', response_model=PaymentMethodConfigResponse)
|
||||
async def get_payment_method(
|
||||
method_id: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('payment_methods:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get a single payment method configuration."""
|
||||
@@ -163,7 +163,7 @@ async def get_payment_method(
|
||||
@router.put('/order')
|
||||
async def update_payment_methods_order(
|
||||
request: SortOrderRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('payment_methods:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Batch update sort order for payment methods."""
|
||||
@@ -176,7 +176,7 @@ async def update_payment_methods_order(
|
||||
async def update_payment_method(
|
||||
method_id: str,
|
||||
request: PaymentMethodConfigUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('payment_methods:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update a payment method configuration."""
|
||||
|
||||
@@ -4,10 +4,14 @@ import math
|
||||
from datetime import datetime
|
||||
|
||||
import structlog
|
||||
from aiogram import Bot
|
||||
from aiogram.client.default import DefaultBotProperties
|
||||
from aiogram.enums import ParseMode
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database.models import PaymentMethod, User
|
||||
from app.services.payment_service import PaymentService
|
||||
from app.services.payment_verification_service import (
|
||||
@@ -19,7 +23,7 @@ from app.services.payment_verification_service import (
|
||||
run_manual_check,
|
||||
)
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -272,7 +276,7 @@ async def get_all_pending_payments(
|
||||
page: int = Query(1, ge=1, description='Page number'),
|
||||
per_page: int = Query(20, ge=1, le=100, description='Items per page'),
|
||||
method_filter: str | None = Query(None, description='Filter by payment method'),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('payments:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get all pending payments for admin verification."""
|
||||
@@ -306,7 +310,7 @@ async def get_all_pending_payments(
|
||||
|
||||
@router.get('/stats', response_model=PaymentsStatsResponse)
|
||||
async def get_payments_stats(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('payments:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get statistics about pending payments."""
|
||||
@@ -329,7 +333,7 @@ async def get_payments_stats(
|
||||
async def get_pending_payment_details(
|
||||
method: str,
|
||||
payment_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('payments:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get details of a specific pending payment."""
|
||||
@@ -356,7 +360,7 @@ async def get_pending_payment_details(
|
||||
async def check_payment_status(
|
||||
method: str,
|
||||
payment_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('payments:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Manually check and update payment status."""
|
||||
@@ -390,8 +394,12 @@ async def check_payment_status(
|
||||
old_is_paid = record.is_paid
|
||||
|
||||
# Run manual check
|
||||
payment_service = PaymentService()
|
||||
updated = await run_manual_check(db, payment_method, payment_id, payment_service)
|
||||
bot = Bot(token=settings.BOT_TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
|
||||
try:
|
||||
payment_service = PaymentService(bot=bot)
|
||||
updated = await run_manual_check(db, payment_method, payment_id, payment_service)
|
||||
finally:
|
||||
await bot.session.close()
|
||||
|
||||
if not updated:
|
||||
return ManualCheckResponse(
|
||||
|
||||
@@ -22,7 +22,7 @@ from app.services.pinned_message_service import (
|
||||
)
|
||||
from app.utils.validators import sanitize_html, validate_html_tags
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.pinned_messages import (
|
||||
PinnedMessageBroadcastResponse,
|
||||
PinnedMessageCreateRequest,
|
||||
@@ -89,7 +89,7 @@ def _get_bot() -> Bot:
|
||||
|
||||
@router.get('', response_model=PinnedMessageListResponse)
|
||||
async def list_pinned_messages(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
limit: int = Query(20, ge=1, le=100),
|
||||
offset: int = Query(0, ge=0),
|
||||
@@ -117,7 +117,7 @@ async def list_pinned_messages(
|
||||
|
||||
@router.get('/active', response_model=PinnedMessageResponse | None)
|
||||
async def get_active_message(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PinnedMessageResponse | None:
|
||||
"""Get current active pinned message."""
|
||||
@@ -130,7 +130,7 @@ async def get_active_message(
|
||||
@router.get('/{message_id}', response_model=PinnedMessageResponse)
|
||||
async def get_pinned_message(
|
||||
message_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PinnedMessageResponse:
|
||||
"""Get pinned message by ID."""
|
||||
@@ -147,7 +147,7 @@ async def get_pinned_message(
|
||||
@router.post('', response_model=PinnedMessageBroadcastResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_pinned_message(
|
||||
payload: PinnedMessageCreateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:create')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PinnedMessageBroadcastResponse:
|
||||
"""
|
||||
@@ -201,7 +201,7 @@ async def create_pinned_message(
|
||||
async def update_pinned_message(
|
||||
message_id: int,
|
||||
payload: PinnedMessageUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PinnedMessageResponse:
|
||||
"""Update a pinned message content, media, or settings."""
|
||||
@@ -240,7 +240,7 @@ async def update_pinned_message(
|
||||
async def update_pinned_message_settings(
|
||||
message_id: int,
|
||||
payload: PinnedMessageSettingsRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PinnedMessageResponse:
|
||||
"""Update only pinned message display settings."""
|
||||
@@ -267,7 +267,7 @@ async def update_pinned_message_settings(
|
||||
|
||||
@router.post('/active/deactivate', response_model=PinnedMessageResponse | None)
|
||||
async def deactivate_active_message(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PinnedMessageResponse | None:
|
||||
"""Deactivate the current active pinned message without unpinning from users."""
|
||||
@@ -282,7 +282,7 @@ async def deactivate_active_message(
|
||||
|
||||
@router.post('/active/unpin', response_model=PinnedMessageUnpinResponse)
|
||||
async def unpin_active_message(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PinnedMessageUnpinResponse:
|
||||
"""Unpin messages from all users and deactivate the active pinned message."""
|
||||
@@ -311,7 +311,7 @@ async def unpin_active_message(
|
||||
async def activate_pinned_message(
|
||||
message_id: int,
|
||||
broadcast: bool = Query(False),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PinnedMessageBroadcastResponse:
|
||||
"""
|
||||
@@ -360,7 +360,7 @@ async def activate_pinned_message(
|
||||
@router.post('/{message_id}/broadcast', response_model=PinnedMessageBroadcastResponse)
|
||||
async def broadcast_message(
|
||||
message_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PinnedMessageBroadcastResponse:
|
||||
"""Broadcast a pinned message to all active users."""
|
||||
@@ -391,7 +391,7 @@ async def broadcast_message(
|
||||
@router.delete('/{message_id}', status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||
async def delete_pinned_message(
|
||||
message_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('pinned_messages:delete')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> None:
|
||||
"""Delete a pinned message. Active messages must be deactivated first."""
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
"""Admin RBAC access policies management routes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import structlog
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.crud.rbac import AccessPolicyCRUD, AdminRoleCRUD
|
||||
from app.database.models import User
|
||||
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
router = APIRouter(prefix='/admin/rbac/policies', tags=['Admin RBAC Policies'])
|
||||
|
||||
|
||||
# ============ Schemas ============
|
||||
|
||||
|
||||
class PolicyResponse(BaseModel):
|
||||
"""Access policy response."""
|
||||
|
||||
id: int
|
||||
name: str
|
||||
description: str | None = None
|
||||
role_id: int | None = None
|
||||
role_name: str | None = None
|
||||
priority: int
|
||||
effect: str
|
||||
conditions: dict[str, Any] = Field(default_factory=dict)
|
||||
resource: str
|
||||
actions: list[str] = Field(default_factory=list)
|
||||
is_active: bool
|
||||
created_by: int | None = None
|
||||
created_at: datetime | None = None
|
||||
|
||||
|
||||
class PolicyCreateRequest(BaseModel):
|
||||
"""Create a new access policy."""
|
||||
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
description: str | None = None
|
||||
role_id: int | None = None
|
||||
priority: int = Field(default=0, ge=0, le=1000)
|
||||
effect: str = Field(pattern=r'^(allow|deny)$')
|
||||
conditions: dict[str, Any] = Field(default_factory=dict)
|
||||
resource: str = Field(min_length=1, max_length=100)
|
||||
actions: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class PolicyUpdateRequest(BaseModel):
|
||||
"""Update policy fields (all optional)."""
|
||||
|
||||
name: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
description: str | None = None
|
||||
role_id: int | None = None
|
||||
priority: int | None = Field(default=None, ge=0, le=1000)
|
||||
effect: str | None = Field(default=None, pattern=r'^(allow|deny)$')
|
||||
conditions: dict[str, Any] | None = None
|
||||
resource: str | None = Field(default=None, min_length=1, max_length=100)
|
||||
actions: list[str] | None = None
|
||||
is_active: bool | None = None
|
||||
|
||||
|
||||
# ============ Helper Functions ============
|
||||
|
||||
|
||||
async def _policy_to_response(db: AsyncSession, policy) -> PolicyResponse:
|
||||
"""Convert AccessPolicy model to PolicyResponse with role name."""
|
||||
role_name = None
|
||||
if policy.role_id is not None:
|
||||
role = await AdminRoleCRUD.get_by_id(db, policy.role_id)
|
||||
if role:
|
||||
role_name = role.name
|
||||
|
||||
return PolicyResponse(
|
||||
id=policy.id,
|
||||
name=policy.name,
|
||||
description=policy.description,
|
||||
role_id=policy.role_id,
|
||||
role_name=role_name,
|
||||
priority=policy.priority,
|
||||
effect=policy.effect,
|
||||
conditions=policy.conditions or {},
|
||||
resource=policy.resource,
|
||||
actions=policy.actions or [],
|
||||
is_active=policy.is_active,
|
||||
created_by=policy.created_by,
|
||||
created_at=policy.created_at,
|
||||
)
|
||||
|
||||
|
||||
# ============ Routes ============
|
||||
|
||||
|
||||
@router.get('', response_model=list[PolicyResponse])
|
||||
async def list_policies(
|
||||
admin: User = Depends(require_permission('roles:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
role_id: int | None = None,
|
||||
):
|
||||
"""List all access policies. Optionally filter by role_id."""
|
||||
policies = await AccessPolicyCRUD.get_all(db, role_id=role_id)
|
||||
return [await _policy_to_response(db, p) for p in policies]
|
||||
|
||||
|
||||
@router.post('', response_model=PolicyResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_policy(
|
||||
payload: PolicyCreateRequest,
|
||||
admin: User = Depends(require_permission('roles:create')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Create a new access policy (ABAC rule)."""
|
||||
# Validate role_id if provided
|
||||
if payload.role_id is not None:
|
||||
role = await AdminRoleCRUD.get_by_id(db, payload.role_id)
|
||||
if not role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Referenced role not found',
|
||||
)
|
||||
|
||||
policy = await AccessPolicyCRUD.create(
|
||||
db,
|
||||
name=payload.name,
|
||||
description=payload.description,
|
||||
role_id=payload.role_id,
|
||||
priority=payload.priority,
|
||||
effect=payload.effect,
|
||||
conditions=payload.conditions,
|
||||
resource=payload.resource,
|
||||
actions=payload.actions,
|
||||
created_by=admin.id,
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Admin created access policy',
|
||||
admin_id=admin.id,
|
||||
policy_id=policy.id,
|
||||
policy_name=policy.name,
|
||||
effect=policy.effect,
|
||||
)
|
||||
return await _policy_to_response(db, policy)
|
||||
|
||||
|
||||
@router.put('/{policy_id}', response_model=PolicyResponse)
|
||||
async def update_policy(
|
||||
policy_id: int,
|
||||
payload: PolicyUpdateRequest,
|
||||
admin: User = Depends(require_permission('roles:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update an existing access policy."""
|
||||
existing = await AccessPolicyCRUD.get_by_id(db, policy_id)
|
||||
if not existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Policy not found',
|
||||
)
|
||||
|
||||
update_data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
# Validate role_id if changing
|
||||
if 'role_id' in update_data and update_data['role_id'] is not None:
|
||||
role = await AdminRoleCRUD.get_by_id(db, update_data['role_id'])
|
||||
if not role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Referenced role not found',
|
||||
)
|
||||
|
||||
updated = await AccessPolicyCRUD.update(db, policy_id, **update_data)
|
||||
if not updated:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Policy not found',
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Admin updated access policy',
|
||||
admin_id=admin.id,
|
||||
policy_id=policy_id,
|
||||
fields=list(update_data.keys()),
|
||||
)
|
||||
return await _policy_to_response(db, updated)
|
||||
|
||||
|
||||
@router.delete('/{policy_id}')
|
||||
async def delete_policy(
|
||||
policy_id: int,
|
||||
admin: User = Depends(require_permission('roles:delete')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Delete an access policy."""
|
||||
existing = await AccessPolicyCRUD.get_by_id(db, policy_id)
|
||||
if not existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Policy not found',
|
||||
)
|
||||
|
||||
deleted = await AccessPolicyCRUD.delete(db, policy_id)
|
||||
if not deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Failed to delete policy',
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Admin deleted access policy',
|
||||
admin_id=admin.id,
|
||||
policy_id=policy_id,
|
||||
policy_name=existing.name,
|
||||
)
|
||||
return {'message': 'Policy deleted', 'policy_id': policy_id}
|
||||
@@ -34,7 +34,7 @@ from app.database.models import DiscountOffer, PromoOfferLog, PromoOfferTemplate
|
||||
from app.handlers.admin.messages import get_custom_users, get_target_users
|
||||
from app.utils.miniapp_buttons import build_miniapp_or_callback_button
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -272,7 +272,7 @@ async def _resolve_target_users(db: AsyncSession, target: str) -> list[User]:
|
||||
|
||||
@router.get('/templates', response_model=PromoOfferTemplateListResponse)
|
||||
async def list_templates(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_offers:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PromoOfferTemplateListResponse:
|
||||
"""Get list of promo offer templates."""
|
||||
@@ -288,7 +288,7 @@ async def list_templates(
|
||||
@router.get('/templates/{template_id}', response_model=PromoOfferTemplateResponse)
|
||||
async def get_template(
|
||||
template_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_offers:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PromoOfferTemplateResponse:
|
||||
"""Get a promo offer template."""
|
||||
@@ -302,7 +302,7 @@ async def get_template(
|
||||
async def update_template(
|
||||
template_id: int,
|
||||
payload: PromoOfferTemplateUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_offers:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PromoOfferTemplateResponse:
|
||||
"""Update a promo offer template."""
|
||||
@@ -338,7 +338,7 @@ async def update_template(
|
||||
|
||||
@router.get('', response_model=PromoOfferListResponse)
|
||||
async def list_offers(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_offers:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
offset: int = Query(0, ge=0),
|
||||
@@ -491,7 +491,7 @@ async def _send_promo_notifications(
|
||||
@router.post('/broadcast', response_model=PromoOfferBroadcastResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def broadcast_offer(
|
||||
payload: PromoOfferBroadcastRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_offers:send')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PromoOfferBroadcastResponse:
|
||||
"""Broadcast promo offer to users with optional Telegram notification."""
|
||||
@@ -605,7 +605,7 @@ async def broadcast_offer(
|
||||
|
||||
@router.get('/logs', response_model=PromoOfferLogListResponse)
|
||||
async def get_logs(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_offers:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
offset: int = Query(0, ge=0),
|
||||
|
||||
@@ -30,7 +30,7 @@ from app.database.crud.promocode import (
|
||||
)
|
||||
from app.database.models import PromoCode, PromoCodeType, PromoCodeUse, PromoGroup, User
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
router = APIRouter(prefix='/admin/promocodes', tags=['Admin Promocodes'])
|
||||
@@ -305,7 +305,7 @@ def _validate_update_payload(payload: PromoCodeUpdateRequest, promocode: PromoCo
|
||||
|
||||
@router.get('', response_model=PromoCodeListResponse)
|
||||
async def list_promocodes(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promocodes:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
offset: int = Query(0, ge=0),
|
||||
@@ -326,7 +326,7 @@ async def list_promocodes(
|
||||
@router.get('/{promocode_id}', response_model=PromoCodeDetailResponse)
|
||||
async def get_promocode(
|
||||
promocode_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promocodes:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PromoCodeDetailResponse:
|
||||
"""Get promocode details with usage statistics."""
|
||||
@@ -349,7 +349,7 @@ async def get_promocode(
|
||||
@router.post('', response_model=PromoCodeResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_promocode_endpoint(
|
||||
payload: PromoCodeCreateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promocodes:create')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PromoCodeResponse:
|
||||
"""Create a new promocode."""
|
||||
@@ -399,7 +399,7 @@ async def create_promocode_endpoint(
|
||||
async def update_promocode_endpoint(
|
||||
promocode_id: int,
|
||||
payload: PromoCodeUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promocodes:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PromoCodeResponse:
|
||||
"""Update an existing promocode."""
|
||||
@@ -460,7 +460,7 @@ async def update_promocode_endpoint(
|
||||
)
|
||||
async def delete_promocode_endpoint(
|
||||
promocode_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promocodes:delete')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> Response:
|
||||
"""Delete a promocode."""
|
||||
@@ -486,7 +486,7 @@ class DeactivateDiscountResponse(BaseModel):
|
||||
@router.post('/deactivate-discount/{user_id}', response_model=DeactivateDiscountResponse)
|
||||
async def admin_deactivate_discount_promocode(
|
||||
user_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promocodes:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> DeactivateDiscountResponse:
|
||||
"""Admin: deactivate a user's active discount promo code."""
|
||||
@@ -537,7 +537,7 @@ promo_groups_router = APIRouter(prefix='/admin/promo-groups', tags=['Admin Promo
|
||||
|
||||
@promo_groups_router.get('', response_model=PromoGroupListResponse)
|
||||
async def list_promo_groups(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_groups:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
offset: int = Query(0, ge=0),
|
||||
@@ -561,7 +561,7 @@ async def list_promo_groups(
|
||||
@promo_groups_router.get('/{group_id}', response_model=PromoGroupResponse)
|
||||
async def get_promo_group(
|
||||
group_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_groups:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PromoGroupResponse:
|
||||
"""Get promo group details."""
|
||||
@@ -576,7 +576,7 @@ async def get_promo_group(
|
||||
@promo_groups_router.post('', response_model=PromoGroupResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_promo_group_endpoint(
|
||||
payload: PromoGroupCreateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_groups:create')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PromoGroupResponse:
|
||||
"""Create a new promo group."""
|
||||
@@ -608,7 +608,7 @@ async def create_promo_group_endpoint(
|
||||
async def update_promo_group_endpoint(
|
||||
group_id: int,
|
||||
payload: PromoGroupUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_groups:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> PromoGroupResponse:
|
||||
"""Update a promo group."""
|
||||
@@ -645,7 +645,7 @@ async def update_promo_group_endpoint(
|
||||
@promo_groups_router.delete('/{group_id}', status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_promo_group_endpoint(
|
||||
group_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('promo_groups:delete')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> Response:
|
||||
"""Delete a promo group."""
|
||||
|
||||
@@ -16,7 +16,7 @@ from app.database.crud.server_squad import (
|
||||
from app.database.models import User
|
||||
from app.utils.cache import cache
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.remnawave import (
|
||||
AutoSyncRunResponse,
|
||||
# Auto Sync
|
||||
@@ -153,7 +153,7 @@ def _serialize_node(node_data: dict[str, Any]) -> NodeInfo:
|
||||
|
||||
@router.get('/status', response_model=RemnaWaveStatusResponse)
|
||||
async def get_remnawave_status(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
) -> RemnaWaveStatusResponse:
|
||||
"""Get RemnaWave configuration and connection status."""
|
||||
service = _get_service()
|
||||
@@ -176,7 +176,7 @@ async def get_remnawave_status(
|
||||
|
||||
@router.get('/system', response_model=SystemStatsResponse)
|
||||
async def get_system_statistics(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
) -> SystemStatsResponse:
|
||||
"""Get full system statistics from RemnaWave."""
|
||||
service = _get_service()
|
||||
@@ -238,7 +238,7 @@ async def get_system_statistics(
|
||||
|
||||
@router.get('/nodes', response_model=NodesListResponse)
|
||||
async def list_nodes(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
) -> NodesListResponse:
|
||||
"""Get list of all nodes."""
|
||||
service = _get_service()
|
||||
@@ -252,7 +252,7 @@ async def list_nodes(
|
||||
|
||||
@router.get('/nodes/overview', response_model=NodesOverview)
|
||||
async def get_nodes_overview(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
) -> NodesOverview:
|
||||
"""Get nodes overview with statistics."""
|
||||
service = _get_service()
|
||||
@@ -278,7 +278,7 @@ async def get_nodes_overview(
|
||||
|
||||
@router.get('/nodes/realtime')
|
||||
async def get_nodes_realtime(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get realtime node usage data."""
|
||||
service = _get_service()
|
||||
@@ -290,7 +290,7 @@ async def get_nodes_realtime(
|
||||
@router.get('/nodes/{node_uuid}', response_model=NodeInfo)
|
||||
async def get_node_details(
|
||||
node_uuid: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
) -> NodeInfo:
|
||||
"""Get detailed information about a specific node."""
|
||||
service = _get_service()
|
||||
@@ -309,7 +309,7 @@ async def get_node_details(
|
||||
@router.get('/nodes/{node_uuid}/statistics', response_model=NodeStatisticsResponse)
|
||||
async def get_node_statistics(
|
||||
node_uuid: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
) -> NodeStatisticsResponse:
|
||||
"""Get node statistics with usage history."""
|
||||
service = _get_service()
|
||||
@@ -335,7 +335,7 @@ async def get_node_usage(
|
||||
node_uuid: str,
|
||||
start: datetime | None = Query(default=None),
|
||||
end: datetime | None = Query(default=None),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
) -> NodeUsageResponse:
|
||||
"""Get node usage history for a date range."""
|
||||
service = _get_service()
|
||||
@@ -358,7 +358,7 @@ async def get_node_usage(
|
||||
async def perform_node_action(
|
||||
node_uuid: str,
|
||||
payload: NodeActionRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:manage')),
|
||||
) -> NodeActionResponse:
|
||||
"""Perform an action on a node (enable/disable/restart)."""
|
||||
service = _get_service()
|
||||
@@ -399,7 +399,7 @@ async def perform_node_action(
|
||||
|
||||
@router.post('/nodes/restart-all', response_model=NodeActionResponse)
|
||||
async def restart_all_nodes(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:manage')),
|
||||
) -> NodeActionResponse:
|
||||
"""Restart all nodes."""
|
||||
service = _get_service()
|
||||
@@ -421,7 +421,7 @@ async def restart_all_nodes(
|
||||
|
||||
@router.get('/squads', response_model=SquadsListResponse)
|
||||
async def list_squads(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> SquadsListResponse:
|
||||
"""Get list of all squads with local database info."""
|
||||
@@ -463,7 +463,7 @@ async def list_squads(
|
||||
@router.get('/squads/{squad_uuid}', response_model=SquadDetailResponse)
|
||||
async def get_squad_details(
|
||||
squad_uuid: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> SquadDetailResponse:
|
||||
"""Get detailed information about a squad."""
|
||||
@@ -506,7 +506,7 @@ async def get_squad_details(
|
||||
@router.post('/squads', response_model=SquadOperationResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_squad(
|
||||
payload: SquadCreateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:manage')),
|
||||
) -> SquadOperationResponse:
|
||||
"""Create a new squad in RemnaWave."""
|
||||
service = _get_service()
|
||||
@@ -533,7 +533,7 @@ async def create_squad(
|
||||
async def update_squad(
|
||||
squad_uuid: str,
|
||||
payload: SquadUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:manage')),
|
||||
) -> SquadOperationResponse:
|
||||
"""Update a squad in RemnaWave."""
|
||||
service = _get_service()
|
||||
@@ -564,7 +564,7 @@ async def update_squad(
|
||||
async def perform_squad_action(
|
||||
squad_uuid: str,
|
||||
payload: SquadActionRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:manage')),
|
||||
) -> SquadOperationResponse:
|
||||
"""Perform an action on a squad."""
|
||||
service = _get_service()
|
||||
@@ -609,7 +609,7 @@ async def perform_squad_action(
|
||||
@router.delete('/squads/{squad_uuid}', response_model=SquadOperationResponse)
|
||||
async def delete_squad(
|
||||
squad_uuid: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:manage')),
|
||||
) -> SquadOperationResponse:
|
||||
"""Delete a squad."""
|
||||
service = _get_service()
|
||||
@@ -632,7 +632,7 @@ async def delete_squad(
|
||||
@router.get('/squads/{squad_uuid}/migration-preview', response_model=MigrationPreviewResponse)
|
||||
async def preview_migration(
|
||||
squad_uuid: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> MigrationPreviewResponse:
|
||||
"""Get migration preview for a squad."""
|
||||
@@ -657,7 +657,7 @@ async def preview_migration(
|
||||
@router.post('/squads/migrate', response_model=MigrationResponse)
|
||||
async def migrate_squad_users(
|
||||
payload: MigrationRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:manage')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> MigrationResponse:
|
||||
"""Migrate users from one squad to another."""
|
||||
@@ -731,7 +731,7 @@ async def migrate_squad_users(
|
||||
|
||||
@router.get('/inbounds', response_model=InboundsListResponse)
|
||||
async def list_inbounds(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
) -> InboundsListResponse:
|
||||
"""Get list of all available inbounds."""
|
||||
service = _get_service()
|
||||
@@ -746,7 +746,7 @@ async def list_inbounds(
|
||||
|
||||
@router.get('/sync/auto/status', response_model=AutoSyncStatus)
|
||||
async def get_auto_sync_status(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
) -> AutoSyncStatus:
|
||||
"""Get auto sync status."""
|
||||
if remnawave_sync_service is None:
|
||||
@@ -775,7 +775,7 @@ async def get_auto_sync_status(
|
||||
@router.post('/sync/auto/toggle', response_model=SyncResponse)
|
||||
async def toggle_auto_sync(
|
||||
payload: AutoSyncToggleRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:sync')),
|
||||
) -> SyncResponse:
|
||||
"""Toggle auto sync on/off."""
|
||||
if remnawave_sync_service is None:
|
||||
@@ -811,7 +811,7 @@ async def toggle_auto_sync(
|
||||
|
||||
@router.post('/sync/auto/run', response_model=AutoSyncRunResponse)
|
||||
async def run_auto_sync_now(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:sync')),
|
||||
) -> AutoSyncRunResponse:
|
||||
"""Run auto sync immediately."""
|
||||
if remnawave_sync_service is None:
|
||||
@@ -839,7 +839,7 @@ async def run_auto_sync_now(
|
||||
@router.post('/sync/from-panel', response_model=SyncResponse)
|
||||
async def sync_from_panel(
|
||||
payload: SyncMode,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:sync')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> SyncResponse:
|
||||
"""Sync users from RemnaWave panel to bot."""
|
||||
@@ -863,7 +863,7 @@ async def sync_from_panel(
|
||||
|
||||
@router.post('/sync/to-panel', response_model=SyncResponse)
|
||||
async def sync_to_panel(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:sync')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> SyncResponse:
|
||||
"""Sync users from bot to RemnaWave panel."""
|
||||
@@ -882,7 +882,7 @@ async def sync_to_panel(
|
||||
|
||||
@router.post('/sync/servers', response_model=SyncResponse)
|
||||
async def sync_servers(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:sync')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> SyncResponse:
|
||||
"""Sync servers/squads from RemnaWave."""
|
||||
@@ -925,7 +925,7 @@ async def sync_servers(
|
||||
|
||||
@router.post('/sync/subscriptions/validate', response_model=SyncResponse)
|
||||
async def validate_subscriptions(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:sync')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> SyncResponse:
|
||||
"""Validate and fix subscriptions."""
|
||||
@@ -944,7 +944,7 @@ async def validate_subscriptions(
|
||||
|
||||
@router.post('/sync/subscriptions/cleanup', response_model=SyncResponse)
|
||||
async def cleanup_subscriptions(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:sync')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> SyncResponse:
|
||||
"""Cleanup orphaned subscriptions."""
|
||||
@@ -963,7 +963,7 @@ async def cleanup_subscriptions(
|
||||
|
||||
@router.post('/sync/subscriptions/statuses', response_model=SyncResponse)
|
||||
async def sync_subscription_statuses(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:sync')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> SyncResponse:
|
||||
"""Sync subscription statuses."""
|
||||
@@ -982,7 +982,7 @@ async def sync_subscription_statuses(
|
||||
|
||||
@router.get('/sync/recommendations', response_model=SyncResponse)
|
||||
async def get_sync_recommendations(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> SyncResponse:
|
||||
"""Get sync recommendations."""
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
"""Admin RBAC roles management routes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import structlog
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.crud.rbac import AdminRoleCRUD, UserRoleCRUD
|
||||
from app.database.models import User
|
||||
from app.services.permission_service import PERMISSION_REGISTRY, get_all_permissions
|
||||
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
router = APIRouter(prefix='/admin/rbac', tags=['Admin RBAC'])
|
||||
|
||||
|
||||
# ============ Schemas ============
|
||||
|
||||
|
||||
class RoleResponse(BaseModel):
|
||||
"""Admin role with user count."""
|
||||
|
||||
id: int
|
||||
name: str
|
||||
description: str | None = None
|
||||
level: int
|
||||
permissions: list[str] = Field(default_factory=list)
|
||||
color: str | None = None
|
||||
icon: str | None = None
|
||||
is_system: bool
|
||||
is_active: bool
|
||||
user_count: int = 0
|
||||
created_at: datetime | None = None
|
||||
|
||||
|
||||
class RoleCreateRequest(BaseModel):
|
||||
"""Create a new custom role."""
|
||||
|
||||
name: str = Field(min_length=1, max_length=100)
|
||||
description: str | None = None
|
||||
level: int = Field(ge=0, le=998)
|
||||
permissions: list[str] = Field(default_factory=list)
|
||||
color: str | None = Field(default=None, max_length=7)
|
||||
icon: str | None = Field(default=None, max_length=50)
|
||||
|
||||
|
||||
class RoleUpdateRequest(BaseModel):
|
||||
"""Update role fields (all optional)."""
|
||||
|
||||
name: str | None = Field(default=None, min_length=1, max_length=100)
|
||||
description: str | None = None
|
||||
level: int | None = Field(default=None, ge=0, le=998)
|
||||
permissions: list[str] | None = None
|
||||
color: str | None = Field(default=None, max_length=7)
|
||||
icon: str | None = Field(default=None, max_length=50)
|
||||
is_active: bool | None = None
|
||||
|
||||
|
||||
class RoleAssignRequest(BaseModel):
|
||||
"""Assign a role to a user."""
|
||||
|
||||
user_id: int
|
||||
role_id: int
|
||||
expires_at: datetime | None = None
|
||||
|
||||
|
||||
class PermissionSection(BaseModel):
|
||||
"""Permission section with available actions."""
|
||||
|
||||
section: str
|
||||
actions: list[str]
|
||||
|
||||
|
||||
class UserRoleResponse(BaseModel):
|
||||
"""User-role assignment details."""
|
||||
|
||||
id: int
|
||||
user_id: int
|
||||
role_id: int
|
||||
role_name: str | None = None
|
||||
user_telegram_id: int | None = None
|
||||
user_username: str | None = None
|
||||
user_first_name: str | None = None
|
||||
user_email: str | None = None
|
||||
assigned_by: int | None = None
|
||||
assigned_at: datetime | None = None
|
||||
expires_at: datetime | None = None
|
||||
is_active: bool
|
||||
|
||||
|
||||
class AdminWithRolesResponse(BaseModel):
|
||||
"""User that has at least one admin role."""
|
||||
|
||||
user_id: int
|
||||
telegram_id: int | None = None
|
||||
username: str | None = None
|
||||
first_name: str | None = None
|
||||
last_name: str | None = None
|
||||
email: str | None = None
|
||||
role_names: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
# ============ Helper Functions ============
|
||||
|
||||
|
||||
async def _role_to_response(db: AsyncSession, role) -> RoleResponse:
|
||||
"""Convert AdminRole model to RoleResponse with user count."""
|
||||
user_count = await AdminRoleCRUD.count_users(db, role.id)
|
||||
return RoleResponse(
|
||||
id=role.id,
|
||||
name=role.name,
|
||||
description=role.description,
|
||||
level=role.level,
|
||||
permissions=role.permissions or [],
|
||||
color=role.color,
|
||||
icon=role.icon,
|
||||
is_system=role.is_system,
|
||||
is_active=role.is_active,
|
||||
user_count=user_count,
|
||||
created_at=role.created_at,
|
||||
)
|
||||
|
||||
|
||||
async def _get_admin_level(db: AsyncSession, admin: User) -> int:
|
||||
"""Get the maximum role level of the current admin.
|
||||
|
||||
Legacy config-based admins (ADMIN_IDS) get superadmin level (999+1=1000)
|
||||
so they can manage all roles including level 999.
|
||||
"""
|
||||
from app.config import settings
|
||||
|
||||
_perms, _names, max_level = await UserRoleCRUD.get_user_permissions(db, admin.id)
|
||||
|
||||
# Legacy config-based admins always get the highest level
|
||||
if settings.is_admin(
|
||||
telegram_id=admin.telegram_id,
|
||||
email=admin.email if admin.email_verified else None,
|
||||
):
|
||||
max_level = max(max_level, 1000)
|
||||
|
||||
return max_level
|
||||
|
||||
|
||||
def _validate_permissions(permissions: list[str]) -> None:
|
||||
"""Validate that all provided permissions exist in the registry."""
|
||||
all_valid = set(get_all_permissions())
|
||||
# Also allow wildcard patterns
|
||||
all_valid.add('*:*')
|
||||
for section in PERMISSION_REGISTRY:
|
||||
all_valid.add(f'{section}:*')
|
||||
|
||||
invalid = [p for p in permissions if p not in all_valid]
|
||||
if invalid:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f'Invalid permissions: {", ".join(invalid)}',
|
||||
)
|
||||
|
||||
|
||||
# ============ Routes ============
|
||||
|
||||
|
||||
@router.get('/permissions', response_model=list[PermissionSection])
|
||||
async def get_permission_registry(
|
||||
admin: User = Depends(require_permission('roles:read')),
|
||||
):
|
||||
"""Get all available permissions grouped by section."""
|
||||
return [
|
||||
PermissionSection(section=section, actions=list(actions)) for section, actions in PERMISSION_REGISTRY.items()
|
||||
]
|
||||
|
||||
|
||||
@router.get('/roles/{role_id}/users', response_model=list[UserRoleResponse])
|
||||
async def list_role_users(
|
||||
role_id: int,
|
||||
admin: User = Depends(require_permission('roles:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""List user-role assignments for a specific role."""
|
||||
from sqlalchemy.orm import selectinload as _sel
|
||||
|
||||
role = await AdminRoleCRUD.get_by_id(db, role_id)
|
||||
if not role:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Role not found')
|
||||
|
||||
from sqlalchemy import select as _sa_select
|
||||
|
||||
from app.database.models import UserRole as _UserRole
|
||||
|
||||
result = await db.execute(
|
||||
_sa_select(_UserRole)
|
||||
.options(_sel(_UserRole.user), _sel(_UserRole.role))
|
||||
.where(_UserRole.role_id == role_id, _UserRole.is_active.is_(True))
|
||||
.order_by(_UserRole.assigned_at.desc())
|
||||
)
|
||||
assignments = result.scalars().all()
|
||||
|
||||
return [
|
||||
UserRoleResponse(
|
||||
id=a.id,
|
||||
user_id=a.user_id,
|
||||
role_id=a.role_id,
|
||||
role_name=a.role.name if a.role else None,
|
||||
user_telegram_id=a.user.telegram_id if a.user else None,
|
||||
user_username=a.user.username if a.user else None,
|
||||
user_first_name=a.user.first_name if a.user else None,
|
||||
user_email=a.user.email if a.user else None,
|
||||
assigned_by=a.assigned_by,
|
||||
assigned_at=a.assigned_at,
|
||||
expires_at=a.expires_at,
|
||||
is_active=a.is_active,
|
||||
)
|
||||
for a in assignments
|
||||
]
|
||||
|
||||
|
||||
@router.get('/roles', response_model=list[RoleResponse])
|
||||
async def list_roles(
|
||||
admin: User = Depends(require_permission('roles:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
include_inactive: bool = False,
|
||||
):
|
||||
"""List all admin roles with user counts."""
|
||||
roles = await AdminRoleCRUD.get_all(db, include_inactive=include_inactive)
|
||||
return [await _role_to_response(db, role) for role in roles]
|
||||
|
||||
|
||||
@router.post('/roles', response_model=RoleResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_role(
|
||||
payload: RoleCreateRequest,
|
||||
admin: User = Depends(require_permission('roles:create')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Create a new custom admin role."""
|
||||
# Validate permissions list
|
||||
_validate_permissions(payload.permissions)
|
||||
|
||||
# Hierarchy enforcement: cannot create role with level >= own level
|
||||
admin_level = await _get_admin_level(db, admin)
|
||||
if payload.level >= admin_level:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Cannot create a role with level >= your own role level',
|
||||
)
|
||||
|
||||
# Check name uniqueness
|
||||
existing = await AdminRoleCRUD.get_by_name(db, payload.name)
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail='Role with this name already exists',
|
||||
)
|
||||
|
||||
role = await AdminRoleCRUD.create(
|
||||
db,
|
||||
name=payload.name,
|
||||
description=payload.description,
|
||||
level=payload.level,
|
||||
permissions=payload.permissions,
|
||||
color=payload.color,
|
||||
icon=payload.icon,
|
||||
created_by=admin.id,
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
logger.info('Admin created role', admin_id=admin.id, role_id=role.id, role_name=role.name)
|
||||
return await _role_to_response(db, role)
|
||||
|
||||
|
||||
@router.put('/roles/{role_id}', response_model=RoleResponse)
|
||||
async def update_role(
|
||||
role_id: int,
|
||||
payload: RoleUpdateRequest,
|
||||
admin: User = Depends(require_permission('roles:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update an existing admin role."""
|
||||
role = await AdminRoleCRUD.get_by_id(db, role_id)
|
||||
if not role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Role not found',
|
||||
)
|
||||
|
||||
admin_level = await _get_admin_level(db, admin)
|
||||
|
||||
# Cannot edit a role at or above own level
|
||||
if role.level >= admin_level:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Cannot edit a role at or above your own level',
|
||||
)
|
||||
|
||||
update_data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
# Validate level change
|
||||
if 'level' in update_data and update_data['level'] >= admin_level:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Cannot set role level >= your own role level',
|
||||
)
|
||||
|
||||
# Validate permissions
|
||||
if 'permissions' in update_data and update_data['permissions'] is not None:
|
||||
_validate_permissions(update_data['permissions'])
|
||||
|
||||
# Check name uniqueness if name is changing
|
||||
if 'name' in update_data and update_data['name'] != role.name:
|
||||
existing = await AdminRoleCRUD.get_by_name(db, update_data['name'])
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail='Role with this name already exists',
|
||||
)
|
||||
|
||||
updated = await AdminRoleCRUD.update(db, role_id, **update_data)
|
||||
if not updated:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Role not found',
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
|
||||
logger.info('Admin updated role', admin_id=admin.id, role_id=role_id, fields=list(update_data.keys()))
|
||||
return await _role_to_response(db, updated)
|
||||
|
||||
|
||||
@router.delete('/roles/{role_id}')
|
||||
async def delete_role(
|
||||
role_id: int,
|
||||
admin: User = Depends(require_permission('roles:delete')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Delete a custom admin role. System roles cannot be deleted."""
|
||||
role = await AdminRoleCRUD.get_by_id(db, role_id)
|
||||
if not role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Role not found',
|
||||
)
|
||||
|
||||
if role.is_system:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Cannot delete a system role',
|
||||
)
|
||||
|
||||
admin_level = await _get_admin_level(db, admin)
|
||||
if role.level >= admin_level:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Cannot delete a role at or above your own level',
|
||||
)
|
||||
|
||||
deleted = await AdminRoleCRUD.delete(db, role_id)
|
||||
if not deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Failed to delete role',
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
|
||||
logger.info('Admin deleted role', admin_id=admin.id, role_id=role_id, role_name=role.name)
|
||||
return {'message': 'Role deleted', 'role_id': role_id}
|
||||
|
||||
|
||||
@router.post('/assignments', response_model=UserRoleResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def assign_role(
|
||||
payload: RoleAssignRequest,
|
||||
admin: User = Depends(require_permission('roles:assign')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Assign a role to a user. Hierarchy enforcement applies."""
|
||||
role = await AdminRoleCRUD.get_by_id(db, payload.role_id)
|
||||
if not role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Role not found',
|
||||
)
|
||||
|
||||
admin_level = await _get_admin_level(db, admin)
|
||||
|
||||
# Cannot assign a role with level >= own level
|
||||
if role.level >= admin_level:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Cannot assign a role with level >= your own role level',
|
||||
)
|
||||
|
||||
# Verify target user exists
|
||||
from app.database.crud.user import get_user_by_id
|
||||
|
||||
target_user = await get_user_by_id(db, payload.user_id)
|
||||
if not target_user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Target user not found',
|
||||
)
|
||||
|
||||
user_role = await UserRoleCRUD.assign_role(
|
||||
db,
|
||||
user_id=payload.user_id,
|
||||
role_id=payload.role_id,
|
||||
assigned_by=admin.id,
|
||||
expires_at=payload.expires_at,
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Admin assigned role',
|
||||
admin_id=admin.id,
|
||||
target_user_id=payload.user_id,
|
||||
role_id=payload.role_id,
|
||||
role_name=role.name,
|
||||
)
|
||||
return UserRoleResponse(
|
||||
id=user_role.id,
|
||||
user_id=user_role.user_id,
|
||||
role_id=user_role.role_id,
|
||||
role_name=role.name,
|
||||
user_telegram_id=target_user.telegram_id,
|
||||
user_username=target_user.username,
|
||||
user_first_name=target_user.first_name,
|
||||
user_email=target_user.email,
|
||||
assigned_by=user_role.assigned_by,
|
||||
assigned_at=user_role.assigned_at,
|
||||
expires_at=user_role.expires_at,
|
||||
is_active=user_role.is_active,
|
||||
)
|
||||
|
||||
|
||||
@router.delete('/assignments/{assignment_id}')
|
||||
async def revoke_role(
|
||||
assignment_id: int,
|
||||
admin: User = Depends(require_permission('roles:assign')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Revoke a role assignment. Cannot remove the last superadmin."""
|
||||
from sqlalchemy import select as sa_select
|
||||
|
||||
from app.database.models import UserRole
|
||||
|
||||
# Load the assignment to check hierarchy
|
||||
result = await db.execute(sa_select(UserRole).where(UserRole.id == assignment_id))
|
||||
user_role = result.scalar_one_or_none()
|
||||
if not user_role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Role assignment not found',
|
||||
)
|
||||
|
||||
role = await AdminRoleCRUD.get_by_id(db, user_role.role_id)
|
||||
if not role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Associated role not found',
|
||||
)
|
||||
|
||||
admin_level = await _get_admin_level(db, admin)
|
||||
|
||||
# Cannot revoke a role at or above own level
|
||||
if role.level >= admin_level:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Cannot revoke a role at or above your own level',
|
||||
)
|
||||
|
||||
# Protect last superadmin (level 999)
|
||||
superadmin_level = 999
|
||||
if role.level == superadmin_level:
|
||||
superadmin_count = await UserRoleCRUD.get_superadmin_count(db)
|
||||
if superadmin_count <= 1:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Cannot remove the last superadmin',
|
||||
)
|
||||
|
||||
revoked = await UserRoleCRUD.revoke_role(db, assignment_id)
|
||||
if not revoked:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Failed to revoke role',
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Admin revoked role assignment',
|
||||
admin_id=admin.id,
|
||||
assignment_id=assignment_id,
|
||||
target_user_id=user_role.user_id,
|
||||
role_name=role.name,
|
||||
)
|
||||
return {'message': 'Role revoked', 'assignment_id': assignment_id}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -16,7 +16,7 @@ from app.database.crud.server_squad import (
|
||||
from app.database.models import PromoGroup, ServerSquad, Subscription, Tariff, User
|
||||
from app.services.subscription_service import SubscriptionService
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.servers import (
|
||||
PromoGroupInfo,
|
||||
ServerDetailResponse,
|
||||
@@ -66,7 +66,7 @@ async def _get_tariffs_using_server(db: AsyncSession, squad_uuid: str) -> list[s
|
||||
@router.get('', response_model=ServerListResponse)
|
||||
async def list_servers(
|
||||
include_unavailable: bool = True,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('servers:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get list of all servers."""
|
||||
@@ -103,7 +103,7 @@ async def list_servers(
|
||||
@router.get('/{server_id}', response_model=ServerDetailResponse)
|
||||
async def get_server(
|
||||
server_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('servers:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get detailed server info."""
|
||||
@@ -146,7 +146,7 @@ async def get_server(
|
||||
async def update_existing_server(
|
||||
server_id: int,
|
||||
request: ServerUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('servers:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update an existing server."""
|
||||
@@ -191,7 +191,7 @@ async def update_existing_server(
|
||||
@router.post('/{server_id}/toggle', response_model=ServerToggleResponse)
|
||||
async def toggle_server(
|
||||
server_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('servers:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Toggle server availability."""
|
||||
@@ -218,7 +218,7 @@ async def toggle_server(
|
||||
@router.post('/{server_id}/trial', response_model=ServerTrialToggleResponse)
|
||||
async def toggle_server_trial(
|
||||
server_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('servers:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Toggle server trial eligibility."""
|
||||
@@ -245,7 +245,7 @@ async def toggle_server_trial(
|
||||
@router.get('/{server_id}/stats', response_model=ServerStatsResponse)
|
||||
async def get_server_stats(
|
||||
server_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('servers:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get server statistics."""
|
||||
@@ -287,7 +287,7 @@ async def get_server_stats(
|
||||
|
||||
@router.post('/sync', response_model=ServerSyncResponse)
|
||||
async def sync_servers(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('servers:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Sync servers with RemnaWave."""
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.services.system_settings_service import (
|
||||
bot_configuration_service,
|
||||
)
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -179,7 +179,7 @@ def _serialize_definition(definition, include_choices: bool = True) -> SettingDe
|
||||
|
||||
@router.get('/categories', response_model=list[SettingCategorySummary])
|
||||
async def list_categories(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:read')),
|
||||
):
|
||||
"""Get list of setting categories."""
|
||||
categories = bot_configuration_service.get_categories()
|
||||
@@ -196,7 +196,7 @@ async def list_categories(
|
||||
|
||||
@router.get('', response_model=list[SettingDefinition])
|
||||
async def list_settings(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:read')),
|
||||
category: str | None = Query(default=None, alias='category_key'),
|
||||
):
|
||||
"""Get list of all settings or settings for a specific category."""
|
||||
@@ -217,7 +217,7 @@ async def list_settings(
|
||||
@router.get('/{key}', response_model=SettingDefinition)
|
||||
async def get_setting(
|
||||
key: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:read')),
|
||||
):
|
||||
"""Get a specific setting by key."""
|
||||
try:
|
||||
@@ -232,7 +232,7 @@ async def get_setting(
|
||||
async def update_setting(
|
||||
key: str,
|
||||
payload: SettingUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update a setting value."""
|
||||
@@ -255,7 +255,7 @@ async def update_setting(
|
||||
@router.delete('/{key}', response_model=SettingDefinition)
|
||||
async def reset_setting(
|
||||
key: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Reset a setting to its default value."""
|
||||
|
||||
@@ -26,7 +26,7 @@ from app.database.models import (
|
||||
from app.services.remnawave_service import RemnaWaveService
|
||||
from app.services.version_service import version_service
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -246,7 +246,7 @@ class RecentPaymentsResponse(BaseModel):
|
||||
|
||||
@router.get('/dashboard', response_model=DashboardStats)
|
||||
async def get_dashboard_stats(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('stats:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get complete dashboard statistics for admin panel."""
|
||||
@@ -262,6 +262,9 @@ async def get_dashboard_stats(
|
||||
month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
trans_stats = await get_transactions_statistics(db, month_start, now)
|
||||
all_time_stats = await get_transactions_statistics(
|
||||
db, start_date=datetime(2020, 1, 1, tzinfo=UTC), end_date=now
|
||||
)
|
||||
|
||||
# Get revenue chart data (last 30 days)
|
||||
revenue_data = await get_revenue_by_period(db, days=30)
|
||||
@@ -291,10 +294,11 @@ async def get_dashboard_stats(
|
||||
income_today_rubles=trans_stats.get('today', {}).get('income_kopeks', 0) / 100,
|
||||
income_month_kopeks=trans_stats.get('totals', {}).get('income_kopeks', 0),
|
||||
income_month_rubles=trans_stats.get('totals', {}).get('income_kopeks', 0) / 100,
|
||||
income_total_kopeks=trans_stats.get('totals', {}).get('income_kopeks', 0),
|
||||
income_total_rubles=trans_stats.get('totals', {}).get('income_kopeks', 0) / 100,
|
||||
subscription_income_kopeks=trans_stats.get('totals', {}).get('subscription_income_kopeks', 0),
|
||||
subscription_income_rubles=trans_stats.get('totals', {}).get('subscription_income_kopeks', 0) / 100,
|
||||
income_total_kopeks=all_time_stats.get('totals', {}).get('income_kopeks', 0),
|
||||
income_total_rubles=all_time_stats.get('totals', {}).get('income_kopeks', 0) / 100,
|
||||
subscription_income_kopeks=abs(all_time_stats.get('totals', {}).get('subscription_income_kopeks', 0)),
|
||||
subscription_income_rubles=abs(all_time_stats.get('totals', {}).get('subscription_income_kopeks', 0))
|
||||
/ 100,
|
||||
),
|
||||
servers=ServerStats(
|
||||
total_servers=server_stats.get('total_servers', 0),
|
||||
@@ -326,7 +330,7 @@ async def get_dashboard_stats(
|
||||
|
||||
@router.get('/system-info', response_model=SystemInfoResponse)
|
||||
async def get_system_info(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('stats:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get system information for admin dashboard."""
|
||||
@@ -358,7 +362,7 @@ async def get_system_info(
|
||||
|
||||
@router.get('/nodes', response_model=NodesOverview)
|
||||
async def get_nodes_status(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('stats:read')),
|
||||
):
|
||||
"""Get status of all nodes."""
|
||||
try:
|
||||
@@ -374,7 +378,7 @@ async def get_nodes_status(
|
||||
@router.post('/nodes/{node_uuid}/restart')
|
||||
async def restart_node(
|
||||
node_uuid: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:manage')),
|
||||
):
|
||||
"""Restart a node."""
|
||||
try:
|
||||
@@ -401,7 +405,7 @@ async def restart_node(
|
||||
@router.post('/nodes/{node_uuid}/toggle')
|
||||
async def toggle_node(
|
||||
node_uuid: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('remnawave:manage')),
|
||||
):
|
||||
"""Enable or disable a node."""
|
||||
try:
|
||||
@@ -596,7 +600,7 @@ async def _get_tariff_stats(db: AsyncSession) -> TariffStats | None:
|
||||
@router.get('/referrals/top', response_model=TopReferrersResponse)
|
||||
async def get_top_referrers(
|
||||
limit: int = 20,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('stats:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get top referrers with earnings breakdown by period."""
|
||||
@@ -686,53 +690,6 @@ async def get_top_referrers(
|
||||
if row.referrer_id in referrers_data:
|
||||
referrers_data[row.referrer_id]['earnings_month'] = row.total or 0
|
||||
|
||||
# Also add REFERRAL_REWARD transactions
|
||||
trans_total_query = await db.execute(
|
||||
select(Transaction.user_id.label('referrer_id'), func.sum(Transaction.amount_kopeks).label('total'))
|
||||
.where(Transaction.type == TransactionType.REFERRAL_REWARD.value)
|
||||
.group_by(Transaction.user_id)
|
||||
)
|
||||
for row in trans_total_query:
|
||||
if row.referrer_id in referrers_data:
|
||||
referrers_data[row.referrer_id]['earnings_total'] = referrers_data[row.referrer_id].get(
|
||||
'earnings_total', 0
|
||||
) + (row.total or 0)
|
||||
|
||||
trans_today_query = await db.execute(
|
||||
select(Transaction.user_id.label('referrer_id'), func.sum(Transaction.amount_kopeks).label('total'))
|
||||
.where(
|
||||
and_(Transaction.type == TransactionType.REFERRAL_REWARD.value, Transaction.created_at >= today_start)
|
||||
)
|
||||
.group_by(Transaction.user_id)
|
||||
)
|
||||
for row in trans_today_query:
|
||||
if row.referrer_id in referrers_data:
|
||||
referrers_data[row.referrer_id]['earnings_today'] = referrers_data[row.referrer_id].get(
|
||||
'earnings_today', 0
|
||||
) + (row.total or 0)
|
||||
|
||||
trans_week_query = await db.execute(
|
||||
select(Transaction.user_id.label('referrer_id'), func.sum(Transaction.amount_kopeks).label('total'))
|
||||
.where(and_(Transaction.type == TransactionType.REFERRAL_REWARD.value, Transaction.created_at >= week_ago))
|
||||
.group_by(Transaction.user_id)
|
||||
)
|
||||
for row in trans_week_query:
|
||||
if row.referrer_id in referrers_data:
|
||||
referrers_data[row.referrer_id]['earnings_week'] = referrers_data[row.referrer_id].get(
|
||||
'earnings_week', 0
|
||||
) + (row.total or 0)
|
||||
|
||||
trans_month_query = await db.execute(
|
||||
select(Transaction.user_id.label('referrer_id'), func.sum(Transaction.amount_kopeks).label('total'))
|
||||
.where(and_(Transaction.type == TransactionType.REFERRAL_REWARD.value, Transaction.created_at >= month_ago))
|
||||
.group_by(Transaction.user_id)
|
||||
)
|
||||
for row in trans_month_query:
|
||||
if row.referrer_id in referrers_data:
|
||||
referrers_data[row.referrer_id]['earnings_month'] = referrers_data[row.referrer_id].get(
|
||||
'earnings_month', 0
|
||||
) + (row.total or 0)
|
||||
|
||||
# Get user info for all referrers
|
||||
referrer_ids = list(referrers_data.keys())
|
||||
if referrer_ids:
|
||||
@@ -812,7 +769,7 @@ async def get_top_referrers(
|
||||
@router.get('/campaigns/top', response_model=TopCampaignsResponse)
|
||||
async def get_top_campaigns(
|
||||
limit: int = 20,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('stats:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get top advertising campaigns with statistics."""
|
||||
@@ -869,7 +826,7 @@ async def get_top_campaigns(
|
||||
@router.get('/payments/recent', response_model=RecentPaymentsResponse)
|
||||
async def get_recent_payments(
|
||||
limit: int = 50,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('stats:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get recent payments with user info."""
|
||||
@@ -944,8 +901,8 @@ async def get_recent_payments(
|
||||
email=user.email,
|
||||
username=user.username,
|
||||
display_name=display_name,
|
||||
amount_kopeks=trans.amount_kopeks,
|
||||
amount_rubles=trans.amount_kopeks / 100,
|
||||
amount_kopeks=abs(trans.amount_kopeks),
|
||||
amount_rubles=abs(trans.amount_kopeks) / 100,
|
||||
type=trans.type,
|
||||
type_display=type_display.get(trans.type, trans.type),
|
||||
payment_method=trans.payment_method,
|
||||
|
||||
@@ -19,7 +19,7 @@ from app.database.crud.tariff import (
|
||||
)
|
||||
from app.database.models import PromoGroup, Subscription, Tariff, Transaction, TransactionType, User
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.tariffs import (
|
||||
PeriodPrice,
|
||||
PromoGroupInfo,
|
||||
@@ -107,7 +107,7 @@ def _period_prices_to_dict(period_prices: list[PeriodPrice]) -> dict:
|
||||
@router.get('', response_model=TariffListResponse)
|
||||
async def list_tariffs(
|
||||
include_inactive: bool = True,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tariffs:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get list of all tariffs."""
|
||||
@@ -141,7 +141,7 @@ async def list_tariffs(
|
||||
|
||||
@router.get('/available-servers', response_model=list[ServerInfo])
|
||||
async def get_available_servers(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tariffs:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get list of all servers for tariff selection."""
|
||||
@@ -161,7 +161,7 @@ async def get_available_servers(
|
||||
@router.put('/order')
|
||||
async def update_tariff_order(
|
||||
request: TariffSortOrderRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tariffs:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update the display order of tariffs."""
|
||||
@@ -176,7 +176,7 @@ async def update_tariff_order(
|
||||
@router.get('/{tariff_id}', response_model=TariffDetailResponse)
|
||||
async def get_tariff(
|
||||
tariff_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tariffs:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get detailed tariff info."""
|
||||
@@ -246,7 +246,7 @@ async def get_tariff(
|
||||
@router.post('', response_model=TariffDetailResponse)
|
||||
async def create_new_tariff(
|
||||
request: TariffCreateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tariffs:create')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Create a new tariff."""
|
||||
@@ -307,7 +307,7 @@ async def create_new_tariff(
|
||||
async def update_existing_tariff(
|
||||
tariff_id: int,
|
||||
request: TariffUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tariffs:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update an existing tariff."""
|
||||
@@ -400,7 +400,7 @@ async def update_existing_tariff(
|
||||
@router.delete('/{tariff_id}')
|
||||
async def delete_existing_tariff(
|
||||
tariff_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tariffs:delete')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Delete a tariff."""
|
||||
@@ -430,7 +430,7 @@ async def delete_existing_tariff(
|
||||
@router.post('/{tariff_id}/toggle', response_model=TariffToggleResponse)
|
||||
async def toggle_tariff(
|
||||
tariff_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tariffs:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Toggle tariff active status."""
|
||||
@@ -460,7 +460,7 @@ async def toggle_tariff(
|
||||
@router.post('/{tariff_id}/trial', response_model=TariffTrialResponse)
|
||||
async def toggle_trial_tariff(
|
||||
tariff_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tariffs:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Toggle tariff trial availability.
|
||||
@@ -500,7 +500,7 @@ async def toggle_trial_tariff(
|
||||
@router.get('/{tariff_id}/stats', response_model=TariffStatsResponse)
|
||||
async def get_tariff_stats(
|
||||
tariff_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tariffs:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get tariff statistics."""
|
||||
|
||||
@@ -16,7 +16,7 @@ from app.database.crud.ticket import TicketCRUD
|
||||
from app.database.crud.ticket_notification import TicketNotificationCRUD
|
||||
from app.database.models import Ticket, TicketMessage, User
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.tickets import TicketMessageResponse
|
||||
|
||||
|
||||
@@ -197,7 +197,7 @@ def _ticket_to_admin_response(ticket: Ticket, include_messages: bool = False) ->
|
||||
|
||||
@router.get('/stats', response_model=AdminStatsResponse)
|
||||
async def get_ticket_stats(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get ticket statistics."""
|
||||
@@ -222,7 +222,7 @@ async def get_ticket_stats(
|
||||
|
||||
@router.get('/settings', response_model=TicketSettingsResponse)
|
||||
async def get_ticket_settings(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:settings')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get ticket system settings."""
|
||||
@@ -242,7 +242,7 @@ async def get_ticket_settings(
|
||||
@router.patch('/settings', response_model=TicketSettingsResponse)
|
||||
async def update_ticket_settings(
|
||||
request: TicketSettingsUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:settings')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update ticket system settings."""
|
||||
@@ -337,7 +337,7 @@ async def get_all_tickets(
|
||||
status_filter: str | None = Query(None, alias='status', description='Filter by status'),
|
||||
priority_filter: str | None = Query(None, alias='priority', description='Filter by priority'),
|
||||
user_id: int | None = Query(None, description='Filter by user ID'),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get all tickets for admin."""
|
||||
@@ -386,7 +386,7 @@ async def get_all_tickets(
|
||||
@router.get('/{ticket_id}', response_model=AdminTicketDetailResponse)
|
||||
async def get_ticket_detail(
|
||||
ticket_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get ticket with all messages for admin."""
|
||||
@@ -428,7 +428,7 @@ async def get_ticket_detail(
|
||||
async def reply_to_ticket(
|
||||
ticket_id: int,
|
||||
request: AdminReplyRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:reply')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Reply to a ticket as admin."""
|
||||
@@ -497,7 +497,7 @@ async def reply_to_ticket(
|
||||
async def update_ticket_status(
|
||||
ticket_id: int,
|
||||
request: AdminStatusUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:close')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update ticket status."""
|
||||
@@ -556,7 +556,7 @@ async def update_ticket_status(
|
||||
async def update_ticket_priority(
|
||||
ticket_id: int,
|
||||
request: AdminPriorityUpdateRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:close')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update ticket priority."""
|
||||
|
||||
@@ -20,7 +20,7 @@ from app.config import settings
|
||||
from app.database.models import Subscription, Transaction, TransactionType, User
|
||||
from app.services.remnawave_service import RemnaWaveService
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.traffic import (
|
||||
ExportCsvRequest,
|
||||
ExportCsvResponse,
|
||||
@@ -262,7 +262,7 @@ def _build_traffic_items(
|
||||
|
||||
@router.get('', response_model=TrafficUsageResponse)
|
||||
async def get_traffic_usage(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('traffic:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
period: int = Query(30, ge=1, le=30),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
@@ -497,7 +497,7 @@ async def _build_enrichment(db: AsyncSession, user_map: dict[str, User]) -> dict
|
||||
|
||||
@router.get('/enrichment', response_model=TrafficEnrichmentResponse)
|
||||
async def get_traffic_enrichment(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('traffic:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Return enrichment data: device counts, spending, dates, last node."""
|
||||
@@ -530,7 +530,7 @@ async def get_traffic_enrichment(
|
||||
@router.post('/export-csv', response_model=ExportCsvResponse)
|
||||
async def export_traffic_csv(
|
||||
request: ExportCsvRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('traffic:export')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Generate CSV with traffic usage and send to admin's Telegram DM."""
|
||||
|
||||
@@ -10,7 +10,7 @@ from pydantic import BaseModel
|
||||
from app.database.models import User
|
||||
from app.services.version_service import version_service
|
||||
|
||||
from ..dependencies import get_current_admin_user
|
||||
from ..dependencies import require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -93,7 +93,7 @@ async def _fetch_cabinet_releases(force: bool = False) -> list[dict]:
|
||||
|
||||
@router.get('/releases', response_model=ReleasesResponse)
|
||||
async def get_releases(
|
||||
current_user: User = Depends(get_current_admin_user),
|
||||
current_user: User = Depends(require_permission('updates:read')),
|
||||
) -> ReleasesResponse:
|
||||
"""Get release information for bot and cabinet."""
|
||||
# Bot releases
|
||||
|
||||
@@ -26,6 +26,7 @@ from app.database.crud.user import (
|
||||
)
|
||||
from app.database.models import (
|
||||
PromoGroup,
|
||||
ReferralEarning,
|
||||
Subscription,
|
||||
SubscriptionServer,
|
||||
SubscriptionStatus,
|
||||
@@ -37,7 +38,7 @@ from app.database.models import (
|
||||
)
|
||||
from app.utils.timezone import panel_datetime_to_utc
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.users import (
|
||||
DeleteDeviceResponse,
|
||||
DeleteUserRequest,
|
||||
@@ -205,10 +206,17 @@ async def _build_subscription_info_async(db: AsyncSession, subscription: Subscri
|
||||
return info
|
||||
|
||||
|
||||
async def _sync_subscription_to_panel(db: AsyncSession, user: User, subscription: Subscription) -> dict:
|
||||
async def _sync_subscription_to_panel(
|
||||
db: AsyncSession,
|
||||
user: User,
|
||||
subscription: Subscription,
|
||||
reset_traffic: bool = False,
|
||||
reset_traffic_reason: str | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
Sync user subscription to Remnawave panel.
|
||||
Creates user if not exists, updates if exists.
|
||||
Optionally resets traffic after sync.
|
||||
Returns dict with changes/errors.
|
||||
"""
|
||||
try:
|
||||
@@ -297,7 +305,10 @@ async def _sync_subscription_to_panel(db: AsyncSession, user: User, subscription
|
||||
update_kwargs['hwid_device_limit'] = hwid_limit
|
||||
|
||||
try:
|
||||
await api.update_user(**update_kwargs)
|
||||
updated_panel_user = await api.update_user(**update_kwargs)
|
||||
subscription.subscription_url = updated_panel_user.subscription_url
|
||||
subscription.subscription_crypto_link = updated_panel_user.happ_crypto_link
|
||||
subscription.remnawave_short_uuid = updated_panel_user.short_uuid
|
||||
changes['action'] = 'updated'
|
||||
logger.info('Updated user in Remnawave panel', user_id=user.id)
|
||||
except Exception as update_error:
|
||||
@@ -326,10 +337,21 @@ async def _sync_subscription_to_panel(db: AsyncSession, user: User, subscription
|
||||
user.remnawave_uuid = new_panel_user.uuid
|
||||
subscription.remnawave_short_uuid = new_panel_user.short_uuid
|
||||
subscription.subscription_url = new_panel_user.subscription_url
|
||||
subscription.subscription_crypto_link = new_panel_user.happ_crypto_link
|
||||
changes['action'] = 'created'
|
||||
changes['panel_uuid'] = new_panel_user.uuid
|
||||
logger.info('Created user in Remnawave panel', user_id=user.id, uuid=new_panel_user.uuid)
|
||||
|
||||
# Reset traffic on panel if requested
|
||||
if reset_traffic and user.remnawave_uuid:
|
||||
try:
|
||||
await api.reset_user_traffic(user.remnawave_uuid)
|
||||
changes['traffic_reset'] = True
|
||||
reason_text = f' ({reset_traffic_reason})' if reset_traffic_reason else ''
|
||||
logger.info('Reset RemnaWave traffic for user', user_id=user.id, reason=reason_text)
|
||||
except Exception as reset_exc:
|
||||
logger.warning('Failed to reset RemnaWave traffic', user_id=user.id, error=reset_exc)
|
||||
|
||||
user.last_remnawave_sync = datetime.now(UTC)
|
||||
await db.commit()
|
||||
|
||||
@@ -351,7 +373,7 @@ async def list_users(
|
||||
email: str | None = Query(None, max_length=255),
|
||||
status: UserStatusEnum | None = Query(None),
|
||||
sort_by: SortByEnum = Query(SortByEnum.CREATED_AT),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -408,7 +430,7 @@ async def list_users(
|
||||
|
||||
@router.get('/stats', response_model=UsersStatsResponse)
|
||||
async def get_users_stats(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get overall users statistics."""
|
||||
@@ -509,7 +531,7 @@ async def get_users_stats(
|
||||
@router.get('/{user_id}', response_model=UserDetailResponse)
|
||||
async def get_user_detail(
|
||||
user_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get detailed user information by ID."""
|
||||
@@ -542,11 +564,9 @@ async def get_user_detail(
|
||||
referrals = await get_referrals(db, user.id)
|
||||
referrals_count = len(referrals)
|
||||
|
||||
# Calculate total referral earnings
|
||||
referral_earnings_q = select(func.sum(Transaction.amount_kopeks)).where(
|
||||
Transaction.user_id == user.id,
|
||||
Transaction.type == TransactionType.REFERRAL_REWARD.value,
|
||||
Transaction.is_completed == True,
|
||||
# Calculate total referral earnings (canonical source: ReferralEarning)
|
||||
referral_earnings_q = select(func.coalesce(func.sum(ReferralEarning.amount_kopeks), 0)).where(
|
||||
ReferralEarning.user_id == user.id
|
||||
)
|
||||
referral_earnings = (await db.execute(referral_earnings_q)).scalar() or 0
|
||||
|
||||
@@ -581,8 +601,8 @@ async def get_user_detail(
|
||||
UserTransactionItem(
|
||||
id=t.id,
|
||||
type=t.type,
|
||||
amount_kopeks=-t.amount_kopeks if t.type in _EXPENSE_TYPES else t.amount_kopeks,
|
||||
amount_rubles=-t.amount_kopeks / 100 if t.type in _EXPENSE_TYPES else t.amount_kopeks / 100,
|
||||
amount_kopeks=abs(t.amount_kopeks) if t.type in _EXPENSE_TYPES else t.amount_kopeks,
|
||||
amount_rubles=abs(t.amount_kopeks) / 100 if t.type in _EXPENSE_TYPES else t.amount_kopeks / 100,
|
||||
description=t.description,
|
||||
payment_method=t.payment_method,
|
||||
is_completed=t.is_completed,
|
||||
@@ -621,7 +641,7 @@ async def get_user_detail(
|
||||
referral=referral_info,
|
||||
total_spent_kopeks=user_stats.get('total_spent', 0),
|
||||
purchase_count=user_stats.get('purchase_count', 0),
|
||||
used_promocodes=user.used_promocodes,
|
||||
used_promocodes=user.used_promocodes or 0,
|
||||
has_had_paid_subscription=user.has_had_paid_subscription,
|
||||
lifetime_used_traffic_bytes=user.lifetime_used_traffic_bytes or 0,
|
||||
campaign_name=campaign_name,
|
||||
@@ -640,7 +660,7 @@ async def get_user_detail(
|
||||
@router.get('/by-telegram/{telegram_id}', response_model=UserDetailResponse)
|
||||
async def get_user_by_telegram(
|
||||
telegram_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get user by Telegram ID."""
|
||||
@@ -659,7 +679,7 @@ async def get_user_by_telegram(
|
||||
@router.get('/{user_id}/panel-info', response_model=UserPanelInfoResponse)
|
||||
async def get_user_panel_info(
|
||||
user_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get user panel info from Remnawave (config links, traffic, connection data)."""
|
||||
@@ -737,7 +757,7 @@ async def get_user_panel_info(
|
||||
@router.get('/{user_id}/node-usage', response_model=UserNodeUsageResponse)
|
||||
async def get_user_node_usage(
|
||||
user_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get user per-node traffic usage (always 30 days with daily breakdown)."""
|
||||
@@ -825,7 +845,7 @@ async def get_user_node_usage(
|
||||
async def update_user_balance(
|
||||
user_id: int,
|
||||
request: UpdateBalanceRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:balance')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -902,7 +922,7 @@ async def update_user_balance(
|
||||
async def update_user_subscription(
|
||||
user_id: int,
|
||||
request: UpdateSubscriptionRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:subscription')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -1052,11 +1072,33 @@ async def update_user_subscription(
|
||||
# Set squads from tariff
|
||||
if tariff.allowed_squads:
|
||||
subscription.connected_squads = tariff.allowed_squads
|
||||
|
||||
# Сбрасываем докупленный трафик при смене тарифа
|
||||
from sqlalchemy import delete as sql_delete
|
||||
|
||||
await db.execute(sql_delete(TrafficPurchase).where(TrafficPurchase.subscription_id == subscription.id))
|
||||
subscription.purchased_traffic_gb = 0
|
||||
subscription.traffic_reset_at = None
|
||||
|
||||
from app.config import settings
|
||||
|
||||
if settings.RESET_TRAFFIC_ON_TARIFF_SWITCH:
|
||||
subscription.traffic_used_gb = 0.0
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(subscription)
|
||||
|
||||
# Sync to Remnawave panel
|
||||
await _sync_subscription_to_panel(db, user, subscription)
|
||||
# Синхронизируем с RemnaWave (discovery/create + сброс трафика по админ-настройке)
|
||||
try:
|
||||
await _sync_subscription_to_panel(
|
||||
db,
|
||||
user,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_traffic_reason='смена тарифа (cabinet admin)',
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Failed to sync tariff switch with RemnaWave', error=e)
|
||||
|
||||
logger.info('Admin changed tariff for user to', admin_id=admin.id, user_id=user_id, tariff_name=tariff.name)
|
||||
|
||||
@@ -1150,10 +1192,13 @@ async def update_user_subscription(
|
||||
detail='traffic_gb parameter is required for add_traffic action',
|
||||
)
|
||||
|
||||
from app.database.crud.subscription import add_subscription_traffic
|
||||
from app.database.crud.subscription import add_subscription_traffic, reactivate_subscription
|
||||
|
||||
await add_subscription_traffic(db, subscription, request.traffic_gb)
|
||||
await db.commit()
|
||||
|
||||
# Реактивируем подписку если она была DISABLED (например, после LIMITED в RemnaWave)
|
||||
await reactivate_subscription(db, subscription)
|
||||
|
||||
await db.refresh(subscription)
|
||||
|
||||
# Sync to Remnawave panel
|
||||
@@ -1269,7 +1314,7 @@ async def update_user_subscription(
|
||||
async def get_user_available_tariffs(
|
||||
user_id: int,
|
||||
include_inactive: bool = Query(False, description='Include inactive tariffs'),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -1367,7 +1412,7 @@ async def get_user_available_tariffs(
|
||||
async def update_user_status(
|
||||
user_id: int,
|
||||
request: UpdateUserStatusRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update user status (active, blocked, deleted)."""
|
||||
@@ -1412,7 +1457,7 @@ async def update_user_status(
|
||||
async def block_user(
|
||||
user_id: int,
|
||||
reason: str | None = None,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:block')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Block a user (shortcut for status update)."""
|
||||
@@ -1423,7 +1468,7 @@ async def block_user(
|
||||
@router.post('/{user_id}/unblock', response_model=UpdateUserStatusResponse)
|
||||
async def unblock_user(
|
||||
user_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:block')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Unblock a user (shortcut for status update)."""
|
||||
@@ -1438,7 +1483,7 @@ async def unblock_user(
|
||||
async def update_user_restrictions(
|
||||
user_id: int,
|
||||
request: UpdateRestrictionsRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update user restrictions (topup, subscription)."""
|
||||
@@ -1486,7 +1531,7 @@ async def update_user_restrictions(
|
||||
async def update_user_promo_group(
|
||||
user_id: int,
|
||||
request: UpdatePromoGroupRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:promo_group')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update user promo group."""
|
||||
@@ -1541,7 +1586,7 @@ async def update_user_promo_group(
|
||||
async def update_user_referral_commission(
|
||||
user_id: int,
|
||||
request: UpdateReferralCommissionRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:referral')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update user's individual referral commission percentage."""
|
||||
@@ -1579,7 +1624,7 @@ async def update_user_referral_commission(
|
||||
@router.get('/{user_id}/devices', response_model=UserDevicesResponse)
|
||||
async def get_user_devices(
|
||||
user_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get user devices from Remnawave panel."""
|
||||
@@ -1633,7 +1678,7 @@ async def get_user_devices(
|
||||
async def delete_user_device(
|
||||
user_id: int,
|
||||
hwid: str,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Delete a single device for user."""
|
||||
@@ -1664,7 +1709,7 @@ async def delete_user_device(
|
||||
@router.delete('/{user_id}/devices', response_model=ResetDevicesResponse)
|
||||
async def reset_user_devices(
|
||||
user_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Reset all devices for user."""
|
||||
@@ -1712,7 +1757,7 @@ async def reset_user_devices(
|
||||
async def delete_user(
|
||||
user_id: int,
|
||||
request: DeleteUserRequest = DeleteUserRequest(),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:delete')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -1750,7 +1795,7 @@ async def delete_user(
|
||||
async def full_delete_user(
|
||||
user_id: int,
|
||||
request: FullDeleteUserRequest = FullDeleteUserRequest(),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:delete')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -1799,7 +1844,7 @@ async def full_delete_user(
|
||||
async def reset_user_trial(
|
||||
user_id: int,
|
||||
request: ResetTrialRequest = ResetTrialRequest(),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:subscription')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -1870,7 +1915,7 @@ async def reset_user_trial(
|
||||
async def reset_user_subscription(
|
||||
user_id: int,
|
||||
request: ResetSubscriptionRequest = ResetSubscriptionRequest(),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:subscription')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -1955,7 +2000,7 @@ async def reset_user_subscription(
|
||||
async def disable_user(
|
||||
user_id: int,
|
||||
request: DisableUserRequest = DisableUserRequest(),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:block')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -2032,7 +2077,7 @@ async def get_user_referrals(
|
||||
user_id: int,
|
||||
offset: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get list of users referred by this user."""
|
||||
@@ -2072,7 +2117,7 @@ async def get_user_transactions(
|
||||
offset: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=200),
|
||||
transaction_type: str | None = Query(None),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get user transactions."""
|
||||
@@ -2105,8 +2150,8 @@ async def get_user_transactions(
|
||||
UserTransactionItem(
|
||||
id=t.id,
|
||||
type=t.type,
|
||||
amount_kopeks=-t.amount_kopeks if t.type in _EXPENSE_TYPES else t.amount_kopeks,
|
||||
amount_rubles=-t.amount_kopeks / 100 if t.type in _EXPENSE_TYPES else t.amount_kopeks / 100,
|
||||
amount_kopeks=abs(t.amount_kopeks) if t.type in _EXPENSE_TYPES else t.amount_kopeks,
|
||||
amount_rubles=abs(t.amount_kopeks) / 100 if t.type in _EXPENSE_TYPES else t.amount_kopeks / 100,
|
||||
description=t.description,
|
||||
payment_method=t.payment_method,
|
||||
is_completed=t.is_completed,
|
||||
@@ -2129,7 +2174,7 @@ async def get_user_transactions(
|
||||
@router.get('/{user_id}/sync/status', response_model=PanelSyncStatusResponse)
|
||||
async def get_user_sync_status(
|
||||
user_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:sync')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -2286,7 +2331,7 @@ async def get_user_sync_status(
|
||||
async def sync_user_from_panel(
|
||||
user_id: int,
|
||||
request: SyncFromPanelRequest = SyncFromPanelRequest(),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:sync')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
@@ -2488,7 +2533,7 @@ async def sync_user_from_panel(
|
||||
async def sync_user_to_panel(
|
||||
user_id: int,
|
||||
request: SyncToPanelRequest = SyncToPanelRequest(),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('users:sync')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""
|
||||
|
||||
@@ -9,7 +9,7 @@ import structlog
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.cabinet.dependencies import get_cabinet_db, get_current_admin_user
|
||||
from app.cabinet.dependencies import get_cabinet_db, require_permission
|
||||
from app.cabinet.schemas.wheel import (
|
||||
AdminSpinItem,
|
||||
AdminSpinsResponse,
|
||||
@@ -42,7 +42,7 @@ router = APIRouter(prefix='/admin/wheel', tags=['Admin Fortune Wheel'])
|
||||
|
||||
@router.get('/config', response_model=AdminWheelConfigResponse)
|
||||
async def get_admin_wheel_config(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('wheel:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Получить полную конфигурацию колеса."""
|
||||
@@ -93,7 +93,7 @@ async def get_admin_wheel_config(
|
||||
@router.put('/config', response_model=AdminWheelConfigResponse)
|
||||
async def update_admin_wheel_config(
|
||||
request: UpdateWheelConfigRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('wheel:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Обновить конфигурацию колеса."""
|
||||
@@ -155,7 +155,7 @@ async def update_admin_wheel_config(
|
||||
|
||||
@router.get('/prizes', response_model=list[WheelPrizeAdminResponse])
|
||||
async def get_prizes(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('wheel:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Получить список призов."""
|
||||
@@ -188,7 +188,7 @@ async def get_prizes(
|
||||
@router.post('/prizes', response_model=WheelPrizeAdminResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_prize(
|
||||
request: CreatePrizeRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('wheel:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Создать новый приз."""
|
||||
@@ -237,7 +237,7 @@ async def create_prize(
|
||||
async def update_prize(
|
||||
prize_id: int,
|
||||
request: UpdatePrizeRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('wheel:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Обновить приз."""
|
||||
@@ -286,7 +286,7 @@ async def update_prize(
|
||||
@router.delete('/prizes/{prize_id}', status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_prize_endpoint(
|
||||
prize_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('wheel:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Удалить приз."""
|
||||
@@ -304,7 +304,7 @@ async def delete_prize_endpoint(
|
||||
@router.post('/prizes/reorder', status_code=status.HTTP_200_OK)
|
||||
async def reorder_prizes(
|
||||
request: ReorderPrizesRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('wheel:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Переупорядочить призы."""
|
||||
@@ -317,7 +317,7 @@ async def reorder_prizes(
|
||||
async def get_statistics(
|
||||
date_from: datetime | None = Query(None),
|
||||
date_to: datetime | None = Query(None),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('wheel:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Получить статистику колеса."""
|
||||
@@ -344,7 +344,7 @@ async def get_all_spins_endpoint(
|
||||
date_to: datetime | None = Query(None),
|
||||
page: int = Query(1, ge=1),
|
||||
per_page: int = Query(50, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('wheel:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Получить все спины с фильтрами."""
|
||||
|
||||
@@ -16,7 +16,7 @@ from app.database.models import (
|
||||
)
|
||||
from app.services.referral_withdrawal_service import referral_withdrawal_service
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
from ..schemas.withdrawals import (
|
||||
AdminApproveWithdrawalRequest,
|
||||
AdminRejectWithdrawalRequest,
|
||||
@@ -49,7 +49,7 @@ async def list_withdrawals(
|
||||
),
|
||||
offset: int = Query(0, ge=0),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('withdrawals:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""List all withdrawal requests."""
|
||||
@@ -123,7 +123,7 @@ async def list_withdrawals(
|
||||
@router.get('/{withdrawal_id}', response_model=AdminWithdrawalDetailResponse)
|
||||
async def get_withdrawal_detail(
|
||||
withdrawal_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('withdrawals:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get detailed withdrawal request with risk analysis."""
|
||||
@@ -180,7 +180,7 @@ async def get_withdrawal_detail(
|
||||
async def approve_withdrawal(
|
||||
withdrawal_id: int,
|
||||
request: AdminApproveWithdrawalRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('withdrawals:approve')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Approve a withdrawal request."""
|
||||
@@ -232,7 +232,7 @@ async def approve_withdrawal(
|
||||
async def reject_withdrawal(
|
||||
withdrawal_id: int,
|
||||
request: AdminRejectWithdrawalRequest,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('withdrawals:reject')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Reject a withdrawal request."""
|
||||
@@ -283,7 +283,7 @@ async def reject_withdrawal(
|
||||
@router.post('/{withdrawal_id}/complete')
|
||||
async def complete_withdrawal(
|
||||
withdrawal_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('withdrawals:approve')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Mark a withdrawal as completed (money transferred)."""
|
||||
|
||||
+118
-57
@@ -15,6 +15,7 @@ from app.database.crud.campaign import (
|
||||
get_campaign_by_start_parameter,
|
||||
get_campaign_registration_by_user,
|
||||
)
|
||||
from app.database.crud.rbac import UserRoleCRUD
|
||||
from app.database.crud.user import (
|
||||
clear_email_change_pending,
|
||||
create_user,
|
||||
@@ -99,9 +100,17 @@ def _user_to_response(user: User) -> UserResponse:
|
||||
)
|
||||
|
||||
|
||||
def _create_auth_response(user: User) -> AuthResponse:
|
||||
"""Create full auth response with tokens."""
|
||||
access_token = create_access_token(user.id, user.telegram_id)
|
||||
async def _create_auth_response(user: User, db: AsyncSession) -> AuthResponse:
|
||||
"""Create full auth response with tokens and RBAC permissions."""
|
||||
user_permissions, user_role_names, user_role_level = await UserRoleCRUD.get_user_permissions(db, user.id)
|
||||
|
||||
access_token = create_access_token(
|
||||
user.id,
|
||||
user.telegram_id,
|
||||
permissions=user_permissions,
|
||||
roles=user_role_names,
|
||||
role_level=user_role_level,
|
||||
)
|
||||
refresh_token = create_refresh_token(user.id)
|
||||
expires_in = settings.get_cabinet_access_token_expire_minutes() * 60
|
||||
|
||||
@@ -241,6 +250,8 @@ async def _sync_subscription_from_panel_by_email(db: AsyncSession, user: User) -
|
||||
if not user.email:
|
||||
return
|
||||
|
||||
user_email = user.email # Save before try block — ORM access may fail after rollback
|
||||
|
||||
try:
|
||||
from app.services.remnawave_service import RemnaWaveService
|
||||
|
||||
@@ -260,6 +271,19 @@ async def _sync_subscription_from_panel_by_email(db: AsyncSession, user: User) -
|
||||
panel_user = panel_users[0]
|
||||
logger.info('Found subscription in panel for email', email=user.email, uuid=panel_user.uuid)
|
||||
|
||||
# Check if another user already owns this remnawave_uuid
|
||||
from app.database.crud.user import get_user_by_remnawave_uuid
|
||||
|
||||
existing_owner = await get_user_by_remnawave_uuid(db, panel_user.uuid)
|
||||
if existing_owner and existing_owner.id != user.id:
|
||||
logger.warning(
|
||||
'Panel UUID already belongs to another user, skipping sync',
|
||||
email=user.email,
|
||||
panel_uuid=panel_user.uuid,
|
||||
existing_owner_id=existing_owner.id,
|
||||
)
|
||||
return
|
||||
|
||||
# Link user to panel
|
||||
user.remnawave_uuid = panel_user.uuid
|
||||
|
||||
@@ -335,9 +359,10 @@ async def _sync_subscription_from_panel_by_email(db: AsyncSession, user: User) -
|
||||
await db.commit()
|
||||
|
||||
except Exception as e:
|
||||
logger.warning('Failed to sync subscription from panel for', email=user.email, error=e)
|
||||
# Don't rollback - it detaches user object and breaks subsequent operations
|
||||
# The sync is non-critical, main verification already succeeded
|
||||
logger.warning('Failed to sync subscription from panel for', email=user_email, error=e)
|
||||
await db.rollback()
|
||||
# Refresh user after rollback — object is expired and lazy loads fail in async
|
||||
await db.refresh(user)
|
||||
|
||||
|
||||
@router.post('/telegram', response_model=AuthResponse)
|
||||
@@ -422,7 +447,7 @@ async def auth_telegram(
|
||||
user.cabinet_last_login = datetime.now(UTC)
|
||||
await db.commit()
|
||||
|
||||
response = _create_auth_response(user)
|
||||
response = await _create_auth_response(user, db)
|
||||
|
||||
# Store refresh token
|
||||
await _store_refresh_token(db, user.id, response.refresh_token)
|
||||
@@ -502,7 +527,7 @@ async def auth_telegram_widget(
|
||||
user.cabinet_last_login = datetime.now(UTC)
|
||||
await db.commit()
|
||||
|
||||
response = _create_auth_response(user)
|
||||
response = await _create_auth_response(user, db)
|
||||
await _store_refresh_token(db, user.id, response.refresh_token)
|
||||
|
||||
# Process referral code (before campaign bonus, which may also set referrer)
|
||||
@@ -550,53 +575,61 @@ async def register_email(
|
||||
detail='You already have a verified email',
|
||||
)
|
||||
|
||||
# Generate verification token
|
||||
verification_token = generate_verification_token()
|
||||
verification_expires = get_verification_expires_at()
|
||||
|
||||
# Update user
|
||||
user.email = request.email
|
||||
user.email_verified = False
|
||||
user.password_hash = hash_password(request.password)
|
||||
user.email_verification_token = verification_token
|
||||
user.email_verification_expires = verification_expires
|
||||
|
||||
await db.commit()
|
||||
if not settings.is_cabinet_email_verification_enabled():
|
||||
# Верификация отключена — сразу помечаем email как verified
|
||||
user.email_verified = True
|
||||
user.email_verified_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
else:
|
||||
# Generate verification token
|
||||
verification_token = generate_verification_token()
|
||||
verification_expires = get_verification_expires_at()
|
||||
|
||||
# Send verification email asynchronously (smtplib is blocking)
|
||||
if settings.is_cabinet_email_verification_enabled() and email_service.is_configured():
|
||||
cabinet_url = settings.CABINET_URL
|
||||
verification_url = f'{cabinet_url}/verify-email'
|
||||
lang = user.language or 'ru'
|
||||
full_url = f'{verification_url}?token={verification_token}'
|
||||
expire_hours = settings.get_cabinet_email_verification_expire_hours()
|
||||
user.email_verified = False
|
||||
user.email_verification_token = verification_token
|
||||
user.email_verification_expires = verification_expires
|
||||
await db.commit()
|
||||
|
||||
# Check for admin template override
|
||||
override = await get_rendered_override(
|
||||
'email_verification',
|
||||
lang,
|
||||
context={
|
||||
'username': user.first_name or '',
|
||||
'verification_url': full_url,
|
||||
'expire_hours': str(expire_hours),
|
||||
},
|
||||
db=db,
|
||||
)
|
||||
custom_subject, custom_body = override if override else (None, None)
|
||||
# Send verification email asynchronously (smtplib is blocking)
|
||||
if email_service.is_configured():
|
||||
cabinet_url = settings.CABINET_URL
|
||||
verification_url = f'{cabinet_url}/verify-email'
|
||||
lang = user.language or 'ru'
|
||||
full_url = f'{verification_url}?token={verification_token}'
|
||||
expire_hours = settings.get_cabinet_email_verification_expire_hours()
|
||||
|
||||
await asyncio.to_thread(
|
||||
email_service.send_verification_email,
|
||||
to_email=request.email,
|
||||
verification_token=verification_token,
|
||||
verification_url=verification_url,
|
||||
username=user.first_name,
|
||||
language=lang,
|
||||
custom_subject=custom_subject,
|
||||
custom_body_html=custom_body,
|
||||
)
|
||||
# Check for admin template override
|
||||
override = await get_rendered_override(
|
||||
'email_verification',
|
||||
lang,
|
||||
context={
|
||||
'username': user.first_name or '',
|
||||
'verification_url': full_url,
|
||||
'expire_hours': str(expire_hours),
|
||||
},
|
||||
db=db,
|
||||
)
|
||||
custom_subject, custom_body = override if override else (None, None)
|
||||
|
||||
await asyncio.to_thread(
|
||||
email_service.send_verification_email,
|
||||
to_email=request.email,
|
||||
verification_token=verification_token,
|
||||
verification_url=verification_url,
|
||||
username=user.first_name,
|
||||
language=lang,
|
||||
custom_subject=custom_subject,
|
||||
custom_body_html=custom_body,
|
||||
)
|
||||
|
||||
return {
|
||||
'message': 'Verification email sent',
|
||||
'message': 'Email linked successfully'
|
||||
if not settings.is_cabinet_email_verification_enabled()
|
||||
else 'Verification email sent',
|
||||
'email': request.email,
|
||||
}
|
||||
|
||||
@@ -676,12 +709,12 @@ async def register_email_standalone(
|
||||
referred_by_id=referrer.id if referrer else None,
|
||||
)
|
||||
|
||||
# Для тестового email - автоматически верифицировать
|
||||
if is_test_email:
|
||||
# Для тестового email или отключённой верификации - автоматически верифицировать
|
||||
if is_test_email or not settings.is_cabinet_email_verification_enabled():
|
||||
user.email_verified = True
|
||||
user.email_verified_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
logger.info('Test email auto-verified: user_id', email=request.email, user_id=user.id)
|
||||
logger.info('Email auto-verified (test or verification disabled)', email=request.email, user_id=user.id)
|
||||
else:
|
||||
# Сгенерировать токен верификации
|
||||
verification_token = generate_verification_token()
|
||||
@@ -734,11 +767,12 @@ async def register_email_standalone(
|
||||
# Не прерываем регистрацию из-за ошибки реферальной системы
|
||||
|
||||
# Для тестового email - сразу можно логиниться (уже verified)
|
||||
# Для обычного email - требуется верификация
|
||||
# Для обычного email - требуется верификация (если включена)
|
||||
verification_required = not is_test_email and settings.is_cabinet_email_verification_enabled()
|
||||
return RegisterResponse(
|
||||
message='Verification email sent. Please check your inbox.',
|
||||
email=request.email,
|
||||
requires_verification=not is_test_email,
|
||||
requires_verification=verification_required,
|
||||
)
|
||||
|
||||
|
||||
@@ -777,7 +811,7 @@ async def verify_email(
|
||||
await _sync_subscription_from_panel_by_email(db, user)
|
||||
|
||||
# Return auth tokens so user is logged in after verification
|
||||
response = _create_auth_response(user)
|
||||
response = await _create_auth_response(user, db)
|
||||
await _store_refresh_token(db, user.id, response.refresh_token)
|
||||
|
||||
# Process campaign bonus
|
||||
@@ -908,8 +942,8 @@ async def login_email(
|
||||
detail='Invalid email or password',
|
||||
)
|
||||
|
||||
# Test email bypasses verification check
|
||||
if not user.email_verified and not is_test_email:
|
||||
# Test email and disabled verification bypass the check
|
||||
if not user.email_verified and not is_test_email and settings.is_cabinet_email_verification_enabled():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Please verify your email first',
|
||||
@@ -924,7 +958,7 @@ async def login_email(
|
||||
user.cabinet_last_login = datetime.now(UTC)
|
||||
await db.commit()
|
||||
|
||||
response = _create_auth_response(user)
|
||||
response = await _create_auth_response(user, db)
|
||||
await _store_refresh_token(db, user.id, response.refresh_token)
|
||||
|
||||
# Process campaign bonus
|
||||
@@ -987,7 +1021,14 @@ async def refresh_token(
|
||||
detail='User not found or inactive',
|
||||
)
|
||||
|
||||
access_token = create_access_token(user.id, user.telegram_id)
|
||||
user_permissions, user_role_names, user_role_level = await UserRoleCRUD.get_user_permissions(db, user.id)
|
||||
access_token = create_access_token(
|
||||
user.id,
|
||||
user.telegram_id,
|
||||
permissions=user_permissions,
|
||||
roles=user_role_names,
|
||||
role_level=user_role_level,
|
||||
)
|
||||
expires_in = settings.get_cabinet_access_token_expire_minutes() * 60
|
||||
|
||||
return TokenResponse(
|
||||
@@ -1111,12 +1152,32 @@ async def get_current_user(
|
||||
return _user_to_response(user)
|
||||
|
||||
|
||||
@router.get('/me/permissions')
|
||||
async def get_my_permissions(
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get current user's RBAC permissions, roles, and level."""
|
||||
from app.services.permission_service import PermissionService
|
||||
|
||||
return await PermissionService.get_user_permissions(db, user.id, user=user)
|
||||
|
||||
|
||||
@router.get('/me/is-admin')
|
||||
async def check_is_admin(
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Check if current user is an admin."""
|
||||
"""Check if current user is an admin (legacy config or RBAC)."""
|
||||
# Legacy check: config-based admin list
|
||||
is_admin = settings.is_admin(telegram_id=user.telegram_id, email=user.email if user.email_verified else None)
|
||||
|
||||
if not is_admin:
|
||||
# RBAC check: user has any active role with level > 0
|
||||
_permissions, _role_names, max_level = await UserRoleCRUD.get_user_permissions(db, user.id)
|
||||
if max_level > 0:
|
||||
is_admin = True
|
||||
|
||||
return {'is_admin': is_admin}
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
|
||||
import httpx
|
||||
import structlog
|
||||
from aiogram import Bot
|
||||
from aiogram.client.default import DefaultBotProperties
|
||||
from aiogram.enums import ParseMode
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import desc, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
@@ -314,6 +317,12 @@ async def create_topup(
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Create payment for balance top-up."""
|
||||
if getattr(user, 'restriction_topup', False):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Balance top-up is restricted for this account',
|
||||
)
|
||||
|
||||
# Validate payment method
|
||||
methods = await get_payment_methods(user=user, db=db)
|
||||
method = next((m for m in methods if m.id == request.payment_method), None)
|
||||
@@ -1035,8 +1044,12 @@ async def check_payment_status(
|
||||
old_is_paid = record.is_paid
|
||||
|
||||
# Run manual check
|
||||
payment_service = PaymentService()
|
||||
updated = await run_manual_check(db, payment_method, payment_id, payment_service)
|
||||
bot = Bot(token=settings.BOT_TOKEN, default=DefaultBotProperties(parse_mode=ParseMode.HTML))
|
||||
try:
|
||||
payment_service = PaymentService(bot=bot)
|
||||
updated = await run_manual_check(db, payment_method, payment_id, payment_service)
|
||||
finally:
|
||||
await bot.session.close()
|
||||
|
||||
if not updated:
|
||||
return ManualCheckResponse(
|
||||
|
||||
+174
-13
@@ -3,18 +3,19 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import structlog
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, UploadFile, status
|
||||
from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database.models import SystemSetting, User
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user
|
||||
from ..dependencies import get_cabinet_db, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -37,6 +38,17 @@ YANDEX_METRIKA_ID_KEY = 'CABINET_YANDEX_METRIKA_ID' # Stores counter ID (numeri
|
||||
GOOGLE_ADS_ID_KEY = 'CABINET_GOOGLE_ADS_ID' # Stores conversion ID (e.g. "AW-123456789")
|
||||
GOOGLE_ADS_LABEL_KEY = 'CABINET_GOOGLE_ADS_LABEL' # Stores conversion label (alphanumeric)
|
||||
LITE_MODE_ENABLED_KEY = 'CABINET_LITE_MODE_ENABLED' # Stores "true" or "false"
|
||||
ANIMATION_CONFIG_KEY = 'CABINET_ANIMATION_CONFIG' # Stores JSON with animation config
|
||||
|
||||
# Default animation config
|
||||
DEFAULT_ANIMATION_CONFIG = {
|
||||
'enabled': True,
|
||||
'type': 'aurora',
|
||||
'settings': {},
|
||||
'opacity': 1.0,
|
||||
'blur': 0,
|
||||
'reducedOnMobile': True,
|
||||
}
|
||||
|
||||
# Allowed image types
|
||||
ALLOWED_CONTENT_TYPES = {'image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/svg+xml'}
|
||||
@@ -121,6 +133,92 @@ class AnimationEnabledUpdate(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
ALLOWED_BG_TYPES = (
|
||||
'aurora',
|
||||
'sparkles',
|
||||
'vortex',
|
||||
'shooting-stars',
|
||||
'background-beams',
|
||||
'background-beams-collision',
|
||||
'gradient-animation',
|
||||
'wavy',
|
||||
'background-lines',
|
||||
'boxes',
|
||||
'meteors',
|
||||
'grid',
|
||||
'dots',
|
||||
'spotlight',
|
||||
'ripple',
|
||||
'none',
|
||||
)
|
||||
|
||||
MAX_SETTINGS_KEYS = 20
|
||||
MAX_SETTINGS_VALUE_LEN = 200
|
||||
|
||||
|
||||
def _validate_settings(v: dict) -> dict:
|
||||
"""Validate settings dict: flat structure, bounded size, no nested objects."""
|
||||
if len(v) > MAX_SETTINGS_KEYS:
|
||||
raise ValueError(f'Settings must have at most {MAX_SETTINGS_KEYS} keys')
|
||||
for key, val in v.items():
|
||||
if not isinstance(key, str) or len(key) > 50:
|
||||
raise ValueError('Setting keys must be strings under 50 characters')
|
||||
if isinstance(val, dict | list):
|
||||
raise ValueError('Nested objects/arrays not allowed in settings')
|
||||
if isinstance(val, str) and len(val) > MAX_SETTINGS_VALUE_LEN:
|
||||
raise ValueError(f'String setting values must be under {MAX_SETTINGS_VALUE_LEN} characters')
|
||||
return v
|
||||
|
||||
|
||||
class AnimationConfigResponse(BaseModel):
|
||||
"""Full animation config."""
|
||||
|
||||
enabled: bool = True
|
||||
type: str = 'aurora'
|
||||
settings: dict = Field(default_factory=dict)
|
||||
opacity: float = Field(default=1.0, ge=0.0, le=1.0)
|
||||
blur: float = Field(default=0, ge=0, le=100)
|
||||
reducedOnMobile: bool = True
|
||||
|
||||
|
||||
class AnimationConfigUpdate(BaseModel):
|
||||
"""Request to update animation config (partial update)."""
|
||||
|
||||
enabled: bool | None = None
|
||||
type: (
|
||||
Literal[
|
||||
'aurora',
|
||||
'sparkles',
|
||||
'vortex',
|
||||
'shooting-stars',
|
||||
'background-beams',
|
||||
'background-beams-collision',
|
||||
'gradient-animation',
|
||||
'wavy',
|
||||
'background-lines',
|
||||
'boxes',
|
||||
'meteors',
|
||||
'grid',
|
||||
'dots',
|
||||
'spotlight',
|
||||
'ripple',
|
||||
'none',
|
||||
]
|
||||
| None
|
||||
) = None
|
||||
settings: dict | None = None
|
||||
opacity: float | None = Field(default=None, ge=0.0, le=1.0)
|
||||
blur: float | None = Field(default=None, ge=0, le=100)
|
||||
reducedOnMobile: bool | None = None
|
||||
|
||||
@field_validator('settings')
|
||||
@classmethod
|
||||
def validate_settings(cls, v: dict | None) -> dict | None:
|
||||
if v is None:
|
||||
return v
|
||||
return _validate_settings(v)
|
||||
|
||||
|
||||
class FullscreenEnabledResponse(BaseModel):
|
||||
"""Fullscreen enabled setting."""
|
||||
|
||||
@@ -296,7 +394,7 @@ async def get_logo():
|
||||
@router.put('/name', response_model=BrandingResponse)
|
||||
async def update_branding_name(
|
||||
payload: BrandingNameUpdate,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update the project name. Admin only. Empty name allowed (logo only mode)."""
|
||||
@@ -324,7 +422,7 @@ async def update_branding_name(
|
||||
@router.post('/logo', response_model=BrandingResponse)
|
||||
async def upload_logo(
|
||||
file: UploadFile = File(...),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Upload a custom logo. Admin only."""
|
||||
@@ -387,7 +485,7 @@ async def upload_logo(
|
||||
|
||||
@router.delete('/logo', response_model=BrandingResponse)
|
||||
async def delete_logo(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Delete custom logo and revert to letter. Admin only."""
|
||||
@@ -459,7 +557,7 @@ async def get_theme_colors(
|
||||
@router.patch('/colors', response_model=ThemeColorsResponse)
|
||||
async def update_theme_colors(
|
||||
payload: ThemeColorsUpdate,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update theme colors. Admin only. Partial update supported."""
|
||||
@@ -493,7 +591,7 @@ async def update_theme_colors(
|
||||
|
||||
@router.post('/colors/reset', response_model=ThemeColorsResponse)
|
||||
async def reset_theme_colors(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Reset theme colors to defaults. Admin only."""
|
||||
@@ -533,7 +631,7 @@ async def get_enabled_themes(
|
||||
@router.patch('/themes', response_model=EnabledThemesResponse)
|
||||
async def update_enabled_themes(
|
||||
payload: EnabledThemesUpdate,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update which themes are enabled. Admin only. At least one theme must be enabled."""
|
||||
@@ -587,7 +685,7 @@ async def get_animation_enabled(
|
||||
@router.patch('/animation', response_model=AnimationEnabledResponse)
|
||||
async def update_animation_enabled(
|
||||
payload: AnimationEnabledUpdate,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update animation enabled setting. Admin only."""
|
||||
@@ -598,6 +696,69 @@ async def update_animation_enabled(
|
||||
return AnimationEnabledResponse(enabled=payload.enabled)
|
||||
|
||||
|
||||
# ============ Animation Config Routes (new JSON-based) ============
|
||||
|
||||
|
||||
@router.get('/animation-config', response_model=AnimationConfigResponse)
|
||||
async def get_animation_config(
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get full animation config. Public endpoint."""
|
||||
config_value = await get_setting_value(db, ANIMATION_CONFIG_KEY)
|
||||
|
||||
if config_value is not None:
|
||||
try:
|
||||
config = json.loads(config_value)
|
||||
return AnimationConfigResponse(**config)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
pass
|
||||
|
||||
# Auto-migrate from old ANIMATION_ENABLED_KEY
|
||||
old_value = await get_setting_value(db, ANIMATION_ENABLED_KEY)
|
||||
if old_value is not None:
|
||||
config = {**DEFAULT_ANIMATION_CONFIG, 'enabled': old_value.lower() == 'true'}
|
||||
await set_setting_value(db, ANIMATION_CONFIG_KEY, json.dumps(config))
|
||||
return AnimationConfigResponse(**config)
|
||||
|
||||
return AnimationConfigResponse(**DEFAULT_ANIMATION_CONFIG)
|
||||
|
||||
|
||||
@router.patch('/animation-config', response_model=AnimationConfigResponse)
|
||||
async def update_animation_config(
|
||||
payload: AnimationConfigUpdate,
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update animation config (partial update). Admin only."""
|
||||
# Get current config
|
||||
config_value = await get_setting_value(db, ANIMATION_CONFIG_KEY)
|
||||
if config_value:
|
||||
try:
|
||||
current = json.loads(config_value)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
current = dict(DEFAULT_ANIMATION_CONFIG)
|
||||
else:
|
||||
current = dict(DEFAULT_ANIMATION_CONFIG)
|
||||
|
||||
# Merge only provided fields
|
||||
update_data = payload.model_dump(exclude_none=True)
|
||||
current.update(update_data)
|
||||
|
||||
await set_setting_value(db, ANIMATION_CONFIG_KEY, json.dumps(current))
|
||||
|
||||
# Also sync old key for backwards compat
|
||||
await set_setting_value(db, ANIMATION_ENABLED_KEY, str(current.get('enabled', True)).lower())
|
||||
|
||||
logger.info(
|
||||
'Admin updated animation config',
|
||||
telegram_id=admin.telegram_id,
|
||||
type=current.get('type'),
|
||||
enabled=current.get('enabled'),
|
||||
)
|
||||
|
||||
return AnimationConfigResponse(**current)
|
||||
|
||||
|
||||
# ============ Fullscreen Routes ============
|
||||
|
||||
|
||||
@@ -622,7 +783,7 @@ async def get_fullscreen_enabled(
|
||||
@router.patch('/fullscreen', response_model=FullscreenEnabledResponse)
|
||||
async def update_fullscreen_enabled(
|
||||
payload: FullscreenEnabledUpdate,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update fullscreen enabled setting. Admin only."""
|
||||
@@ -658,7 +819,7 @@ async def get_email_auth_enabled(
|
||||
@router.patch('/email-auth', response_model=EmailAuthEnabledResponse)
|
||||
async def update_email_auth_enabled(
|
||||
payload: EmailAuthEnabledUpdate,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update email auth enabled setting. Admin only."""
|
||||
@@ -694,7 +855,7 @@ async def get_analytics_counters(
|
||||
@router.patch('/analytics', response_model=AnalyticsCountersResponse)
|
||||
async def update_analytics_counters(
|
||||
payload: AnalyticsCountersUpdate,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update analytics counter settings. Admin only. Partial update supported."""
|
||||
@@ -758,7 +919,7 @@ async def get_lite_mode_enabled(
|
||||
@router.patch('/lite-mode', response_model=LiteModeEnabledResponse)
|
||||
async def update_lite_mode_enabled(
|
||||
payload: LiteModeEnabledUpdate,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('settings:edit')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Update lite mode enabled setting. Admin only."""
|
||||
|
||||
@@ -121,7 +121,7 @@ async def _award_prize(db: AsyncSession, user_id: int, prize_type: str, prize_va
|
||||
if not user:
|
||||
return 'Error: user not found'
|
||||
|
||||
user.balance += amount
|
||||
user.balance_kopeks += int(round(amount * 100))
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
|
||||
+44
-20
@@ -24,6 +24,7 @@ from ..auth.oauth_providers import (
|
||||
validate_oauth_state,
|
||||
)
|
||||
from ..dependencies import get_cabinet_db
|
||||
from ..routes.account_linking import OAuthProviderName
|
||||
from ..schemas.auth import AuthResponse
|
||||
from .auth import _create_auth_response, _process_campaign_bonus, _store_refresh_token
|
||||
|
||||
@@ -43,7 +44,7 @@ async def _finalize_oauth_login(
|
||||
"""Update last login, create tokens, store refresh token."""
|
||||
user.cabinet_last_login = datetime.now(UTC)
|
||||
await db.commit()
|
||||
auth_response = _create_auth_response(user)
|
||||
auth_response = await _create_auth_response(user, db)
|
||||
await _store_refresh_token(db, user.id, auth_response.refresh_token, device_info=f'oauth:{provider}')
|
||||
|
||||
# Process referral code (before campaign bonus, which may also set referrer)
|
||||
@@ -75,8 +76,9 @@ class OAuthAuthorizeResponse(BaseModel):
|
||||
|
||||
|
||||
class OAuthCallbackRequest(BaseModel):
|
||||
code: str = Field(..., description='Authorization code from provider')
|
||||
state: str = Field(..., description='CSRF state token')
|
||||
code: str = Field(..., min_length=1, max_length=2048, description='Authorization code from provider')
|
||||
state: str = Field(..., min_length=1, max_length=128, description='CSRF state token')
|
||||
device_id: str | None = Field(None, max_length=256, description='Device ID from VK ID callback')
|
||||
campaign_slug: str | None = Field(
|
||||
None, min_length=1, max_length=64, pattern=r'^[a-zA-Z0-9_-]+$', description='Campaign slug from web link'
|
||||
)
|
||||
@@ -99,48 +101,68 @@ async def get_oauth_providers():
|
||||
|
||||
|
||||
@router.get('/{provider}/authorize', response_model=OAuthAuthorizeResponse)
|
||||
async def get_oauth_authorize_url(provider: str):
|
||||
async def get_oauth_authorize_url(provider: OAuthProviderName):
|
||||
"""Get authorization URL for an OAuth provider."""
|
||||
oauth_provider = get_provider(provider)
|
||||
if not oauth_provider:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f'OAuth provider "{provider}" is not enabled',
|
||||
detail='Requested OAuth provider is not available',
|
||||
)
|
||||
|
||||
state = await generate_oauth_state(provider)
|
||||
authorize_url = oauth_provider.get_authorization_url(state)
|
||||
# Generate extra state data (e.g., PKCE code_verifier for VK)
|
||||
auth_extra = oauth_provider.prepare_auth_state()
|
||||
state = await generate_oauth_state(provider, extra_data=auth_extra or None)
|
||||
# Only pass URL-safe params (prefixed with _) to authorize URL; exclude secrets like code_verifier
|
||||
url_params = {k: v for k, v in auth_extra.items() if k.startswith('_')} if auth_extra else {}
|
||||
authorize_url = oauth_provider.get_authorization_url(state, **url_params)
|
||||
|
||||
return OAuthAuthorizeResponse(authorize_url=authorize_url, state=state)
|
||||
|
||||
|
||||
@router.post('/{provider}/callback', response_model=AuthResponse)
|
||||
async def oauth_callback(
|
||||
provider: str,
|
||||
provider: OAuthProviderName,
|
||||
request: OAuthCallbackRequest,
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Handle OAuth callback: exchange code, find/create user, return JWT."""
|
||||
# 1. Validate CSRF state
|
||||
if not await validate_oauth_state(request.state, provider):
|
||||
# 1. Validate CSRF state and retrieve stored data (e.g., PKCE code_verifier)
|
||||
state_data = await validate_oauth_state(request.state, provider)
|
||||
if not state_data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Invalid or expired OAuth state',
|
||||
)
|
||||
|
||||
# 1b. Reject linking-flow state tokens (must use link_provider_callback instead)
|
||||
if state_data.get('linking') == 'true':
|
||||
logger.warning('Linking-flow state token used in login callback', provider=provider)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='OAuth state was initiated for account linking, not login',
|
||||
)
|
||||
|
||||
# 2. Get provider instance
|
||||
oauth_provider = get_provider(provider)
|
||||
if not oauth_provider:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f'OAuth provider "{provider}" is not enabled',
|
||||
detail='Requested OAuth provider is not available',
|
||||
)
|
||||
|
||||
# 3. Exchange code for tokens
|
||||
# 3. Exchange code for tokens (pass PKCE code_verifier and device_id if present)
|
||||
exchange_kwargs: dict[str, str] = {'state': request.state}
|
||||
code_verifier = state_data.get('code_verifier')
|
||||
if code_verifier:
|
||||
exchange_kwargs['code_verifier'] = code_verifier
|
||||
if request.device_id:
|
||||
exchange_kwargs['device_id'] = request.device_id
|
||||
|
||||
try:
|
||||
token_data = await oauth_provider.exchange_code(request.code)
|
||||
token_data = await oauth_provider.exchange_code(request.code, **exchange_kwargs)
|
||||
except Exception as exc:
|
||||
logger.error('OAuth code exchange failed for', provider=provider, exc=exc)
|
||||
logger.error('OAuth code exchange failed', provider=provider, exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Failed to exchange authorization code',
|
||||
@@ -150,7 +172,7 @@ async def oauth_callback(
|
||||
try:
|
||||
user_info: OAuthUserInfo = await oauth_provider.get_user_info(token_data)
|
||||
except Exception as exc:
|
||||
logger.error('OAuth user info fetch failed for', provider=provider, exc=exc)
|
||||
logger.error('OAuth user info fetch failed', provider=provider, exc_info=True)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Failed to fetch user information from provider',
|
||||
@@ -159,7 +181,7 @@ async def oauth_callback(
|
||||
# 5. Find user by provider ID
|
||||
user = await get_user_by_oauth_provider(db, provider, user_info.provider_id)
|
||||
if user:
|
||||
logger.info('OAuth login via for existing user', provider=provider, user_id=user.id)
|
||||
logger.info('OAuth login for existing user', provider=provider, user_id=user.id)
|
||||
return await _finalize_oauth_login(db, user, provider, request.campaign_slug, request.referral_code)
|
||||
|
||||
# 6. Find user by email (if verified) and link provider
|
||||
@@ -167,7 +189,7 @@ async def oauth_callback(
|
||||
user = await get_user_by_email(db, user_info.email)
|
||||
if user:
|
||||
await set_user_oauth_provider_id(db, user, provider, user_info.provider_id)
|
||||
logger.info('OAuth login via linked to existing email user', provider=provider, user_id=user.id)
|
||||
logger.info('OAuth provider linked to existing email user', provider=provider, user_id=user.id)
|
||||
return await _finalize_oauth_login(db, user, provider, request.campaign_slug, request.referral_code)
|
||||
|
||||
# 7. Resolve referral code for new user
|
||||
@@ -190,8 +212,10 @@ async def oauth_callback(
|
||||
)
|
||||
else:
|
||||
referrer_id = referrer.id
|
||||
except Exception as e:
|
||||
logger.warning('Failed to resolve referral code during OAuth', referral_code=request.referral_code, error=e)
|
||||
except Exception:
|
||||
logger.warning(
|
||||
'Failed to resolve referral code during OAuth', referral_code=request.referral_code, exc_info=True
|
||||
)
|
||||
|
||||
# 8. Create new user
|
||||
user = await create_user_by_oauth(
|
||||
@@ -205,5 +229,5 @@ async def oauth_callback(
|
||||
username=user_info.username,
|
||||
referred_by_id=referrer_id,
|
||||
)
|
||||
logger.info('OAuth new user created via with id', provider=provider, user_id=user.id)
|
||||
logger.info('New OAuth user created', provider=provider, user_id=user.id)
|
||||
return await _finalize_oauth_login(db, user, provider, request.campaign_slug, request.referral_code)
|
||||
|
||||
@@ -5,16 +5,24 @@ from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.cabinet.utils.links import get_campaign_deep_link, get_campaign_web_link
|
||||
from app.config import settings
|
||||
from app.database.models import AdvertisingCampaign, User
|
||||
from app.services.partner_application_service import partner_application_service
|
||||
from app.services.partner_stats_service import PartnerStatsService
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_cabinet_user
|
||||
from ..schemas.partners import (
|
||||
CampaignReferralItem,
|
||||
DailyStatItem,
|
||||
PartnerApplicationInfo,
|
||||
PartnerApplicationRequest,
|
||||
PartnerCampaignDetailedStats,
|
||||
PartnerCampaignInfo,
|
||||
PartnerStatusResponse,
|
||||
PeriodChange,
|
||||
PeriodComparison,
|
||||
PeriodStats,
|
||||
)
|
||||
|
||||
|
||||
@@ -23,22 +31,6 @@ logger = structlog.get_logger(__name__)
|
||||
router = APIRouter(prefix='/referral/partner', tags=['Cabinet Partner'])
|
||||
|
||||
|
||||
def _get_campaign_deep_link(start_parameter: str) -> str | None:
|
||||
"""Generate Telegram deep link for campaign."""
|
||||
bot_username = settings.get_bot_username()
|
||||
if bot_username:
|
||||
return f'https://t.me/{bot_username}?start={start_parameter}'
|
||||
return None
|
||||
|
||||
|
||||
def _get_campaign_web_link(start_parameter: str) -> str | None:
|
||||
"""Generate web link for campaign."""
|
||||
base_url = (settings.MINIAPP_CUSTOM_URL or '').rstrip('/')
|
||||
if base_url:
|
||||
return f'{base_url}/?campaign={start_parameter}'
|
||||
return None
|
||||
|
||||
|
||||
@router.get('/status', response_model=PartnerStatusResponse)
|
||||
async def get_partner_status(
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
@@ -57,6 +49,7 @@ async def get_partner_status(
|
||||
telegram_channel=latest_app.telegram_channel,
|
||||
description=latest_app.description,
|
||||
expected_monthly_referrals=latest_app.expected_monthly_referrals,
|
||||
desired_commission_percent=latest_app.desired_commission_percent,
|
||||
admin_comment=latest_app.admin_comment,
|
||||
approved_commission_percent=latest_app.approved_commission_percent,
|
||||
created_at=latest_app.created_at,
|
||||
@@ -76,7 +69,14 @@ async def get_partner_status(
|
||||
AdvertisingCampaign.is_active.is_(True),
|
||||
)
|
||||
)
|
||||
for c in result.scalars().all():
|
||||
campaign_models = result.scalars().all()
|
||||
|
||||
# Fetch per-campaign stats in one batch
|
||||
campaign_ids = [c.id for c in campaign_models]
|
||||
campaign_stats = await PartnerStatsService.get_per_campaign_stats(db, user.id, campaign_ids)
|
||||
|
||||
for c in campaign_models:
|
||||
stats = campaign_stats.get(c.id, {})
|
||||
campaigns.append(
|
||||
PartnerCampaignInfo(
|
||||
id=c.id,
|
||||
@@ -86,8 +86,11 @@ async def get_partner_status(
|
||||
balance_bonus_kopeks=c.balance_bonus_kopeks or 0,
|
||||
subscription_duration_days=c.subscription_duration_days,
|
||||
subscription_traffic_gb=c.subscription_traffic_gb,
|
||||
deep_link=_get_campaign_deep_link(c.start_parameter),
|
||||
web_link=_get_campaign_web_link(c.start_parameter),
|
||||
deep_link=get_campaign_deep_link(c.start_parameter),
|
||||
web_link=get_campaign_web_link(c.start_parameter),
|
||||
registrations_count=stats.get('registrations_count', 0),
|
||||
referrals_count=stats.get('referrals_count', 0),
|
||||
earnings_kopeks=stats.get('earnings_kopeks', 0),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -99,6 +102,56 @@ async def get_partner_status(
|
||||
)
|
||||
|
||||
|
||||
@router.get('/campaigns/{campaign_id}/stats', response_model=PartnerCampaignDetailedStats)
|
||||
async def get_campaign_stats(
|
||||
campaign_id: int,
|
||||
user: User = Depends(get_current_cabinet_user),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get detailed stats for a single campaign belonging to the current partner."""
|
||||
if not user.is_partner:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Partner status required',
|
||||
)
|
||||
|
||||
# Verify campaign belongs to this partner
|
||||
campaign_result = await db.execute(
|
||||
select(AdvertisingCampaign).where(
|
||||
AdvertisingCampaign.id == campaign_id,
|
||||
AdvertisingCampaign.partner_user_id == user.id,
|
||||
)
|
||||
)
|
||||
campaign = campaign_result.scalar_one_or_none()
|
||||
if not campaign:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='Campaign not found or not assigned to you',
|
||||
)
|
||||
|
||||
raw = await PartnerStatsService.get_campaign_detailed_stats(db, user.id, campaign_id)
|
||||
|
||||
return PartnerCampaignDetailedStats(
|
||||
campaign_id=raw['campaign_id'],
|
||||
campaign_name=campaign.name,
|
||||
registrations_count=raw['registrations_count'],
|
||||
referrals_count=raw['referrals_count'],
|
||||
earnings_kopeks=raw['earnings_kopeks'],
|
||||
conversion_rate=raw['conversion_rate'],
|
||||
earnings_today=raw['earnings_today'],
|
||||
earnings_week=raw['earnings_week'],
|
||||
earnings_month=raw['earnings_month'],
|
||||
daily_stats=[DailyStatItem(**d) for d in raw['daily_stats']],
|
||||
period_comparison=PeriodComparison(
|
||||
current=PeriodStats(**raw['period_comparison']['current']),
|
||||
previous=PeriodStats(**raw['period_comparison']['previous']),
|
||||
referrals_change=PeriodChange(**raw['period_comparison']['referrals_change']),
|
||||
earnings_change=PeriodChange(**raw['period_comparison']['earnings_change']),
|
||||
),
|
||||
top_referrals=[CampaignReferralItem(**r) for r in raw['top_referrals']],
|
||||
)
|
||||
|
||||
|
||||
@router.post('/apply', response_model=PartnerApplicationInfo)
|
||||
async def apply_for_partner(
|
||||
request: PartnerApplicationRequest,
|
||||
@@ -114,6 +167,7 @@ async def apply_for_partner(
|
||||
telegram_channel=request.telegram_channel,
|
||||
description=request.description,
|
||||
expected_monthly_referrals=request.expected_monthly_referrals,
|
||||
desired_commission_percent=request.desired_commission_percent,
|
||||
)
|
||||
|
||||
if not application:
|
||||
@@ -140,6 +194,7 @@ async def apply_for_partner(
|
||||
'website_url': request.website_url,
|
||||
'description': request.description,
|
||||
'expected_monthly_referrals': request.expected_monthly_referrals,
|
||||
'desired_commission_percent': request.desired_commission_percent,
|
||||
},
|
||||
)
|
||||
finally:
|
||||
@@ -155,6 +210,7 @@ async def apply_for_partner(
|
||||
telegram_channel=application.telegram_channel,
|
||||
description=application.description,
|
||||
expected_monthly_referrals=application.expected_monthly_referrals,
|
||||
desired_commission_percent=application.desired_commission_percent,
|
||||
admin_comment=application.admin_comment,
|
||||
approved_commission_percent=application.approved_commission_percent,
|
||||
created_at=application.created_at,
|
||||
|
||||
@@ -71,7 +71,9 @@ async def activate_promocode(
|
||||
'used': 'Promo code has been fully used',
|
||||
'already_used_by_user': 'You have already used this promo code',
|
||||
'active_discount_exists': 'You already have an active discount. Deactivate it first via /deactivate-discount',
|
||||
'no_subscription_for_days': 'This promo code requires an active or expired subscription',
|
||||
'not_first_purchase': 'This promo code is only available for first purchase',
|
||||
'daily_limit': 'Too many promo code activations today',
|
||||
'user_not_found': 'User not found',
|
||||
'server_error': 'Server error occurred',
|
||||
}
|
||||
|
||||
@@ -9,7 +9,15 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.config import settings
|
||||
from app.database.models import AdvertisingCampaign, ReferralEarning, User
|
||||
from app.database.models import (
|
||||
AdvertisingCampaign,
|
||||
ReferralEarning,
|
||||
Subscription,
|
||||
SubscriptionStatus,
|
||||
User,
|
||||
WithdrawalRequest,
|
||||
WithdrawalRequestStatus,
|
||||
)
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_cabinet_user
|
||||
from ..schemas.referral import (
|
||||
@@ -38,12 +46,15 @@ async def get_referral_info(
|
||||
total_result = await db.execute(total_query)
|
||||
total_referrals = total_result.scalar() or 0
|
||||
|
||||
# Get active referrals (with subscription)
|
||||
# Get active referrals (with active subscription right now)
|
||||
active_query = (
|
||||
select(func.count())
|
||||
.select_from(User)
|
||||
.where(User.referred_by_id == user.id)
|
||||
.where(User.has_had_paid_subscription == True)
|
||||
select(func.count(func.distinct(User.id)))
|
||||
.join(Subscription, User.id == Subscription.user_id)
|
||||
.where(
|
||||
User.referred_by_id == user.id,
|
||||
Subscription.status == SubscriptionStatus.ACTIVE.value,
|
||||
Subscription.end_date > func.now(),
|
||||
)
|
||||
)
|
||||
active_result = await db.execute(active_query)
|
||||
active_referrals = active_result.scalar() or 0
|
||||
@@ -60,6 +71,26 @@ async def get_referral_info(
|
||||
if commission_percent is None:
|
||||
commission_percent = settings.REFERRAL_COMMISSION_PERCENT
|
||||
|
||||
# Get withdrawn amount (approved + completed withdrawal requests)
|
||||
withdrawn_query = select(func.coalesce(func.sum(WithdrawalRequest.amount_kopeks), 0)).where(
|
||||
WithdrawalRequest.user_id == user.id,
|
||||
WithdrawalRequest.status.in_([WithdrawalRequestStatus.APPROVED.value, WithdrawalRequestStatus.COMPLETED.value]),
|
||||
)
|
||||
withdrawn_result = await db.execute(withdrawn_query)
|
||||
withdrawn = withdrawn_result.scalar() or 0
|
||||
|
||||
# Get pending withdrawal amount
|
||||
pending_query = select(func.coalesce(func.sum(WithdrawalRequest.amount_kopeks), 0)).where(
|
||||
WithdrawalRequest.user_id == user.id,
|
||||
WithdrawalRequest.status == WithdrawalRequestStatus.PENDING.value,
|
||||
)
|
||||
pending_result = await db.execute(pending_query)
|
||||
pending = pending_result.scalar() or 0
|
||||
|
||||
# Доступный баланс: мин(кошелёк, заработано - выведено - в ожидании)
|
||||
referral_entitlement = max(0, total_earnings - withdrawn - pending)
|
||||
available_balance = min(user.balance_kopeks, referral_entitlement)
|
||||
|
||||
# Build referral link
|
||||
bot_username = settings.get_bot_username() or 'bot'
|
||||
referral_link = f'https://t.me/{bot_username}?start={user.referral_code}'
|
||||
@@ -72,6 +103,9 @@ async def get_referral_info(
|
||||
total_earnings_kopeks=total_earnings,
|
||||
total_earnings_rubles=total_earnings / 100,
|
||||
commission_percent=commission_percent,
|
||||
available_balance_kopeks=available_balance,
|
||||
available_balance_rubles=available_balance / 100,
|
||||
withdrawn_kopeks=withdrawn,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ from app.database.crud.subscription import (
|
||||
from app.database.crud.tariff import get_tariff_by_id, get_tariffs_for_user
|
||||
from app.database.crud.transaction import create_transaction
|
||||
from app.database.crud.user import subtract_user_balance
|
||||
from app.database.models import ServerSquad, Subscription, Tariff, TransactionType, User
|
||||
from app.database.models import PaymentMethod, ServerSquad, Subscription, Tariff, TransactionType, User
|
||||
from app.services.notification_delivery_service import (
|
||||
NotificationType,
|
||||
notification_delivery_service,
|
||||
@@ -204,7 +204,10 @@ def _subscription_to_response(
|
||||
if is_daily and not is_daily_paused:
|
||||
last_charge = getattr(subscription, 'last_daily_charge_at', None)
|
||||
if last_charge:
|
||||
next_daily_charge_at = last_charge + timedelta(days=1)
|
||||
next_charge = last_charge + timedelta(days=1)
|
||||
# Если время списания уже прошло — не показываем (DailySubscriptionService обработает)
|
||||
if next_charge > datetime.now(UTC):
|
||||
next_daily_charge_at = next_charge
|
||||
|
||||
# Проверяем настройку скрытия ссылки (скрывается только текст, кнопки работают)
|
||||
hide_link = settings.should_hide_subscription_link()
|
||||
@@ -337,7 +340,11 @@ async def get_renewal_options(
|
||||
# Учитываем докупленные устройства сверх тарифа
|
||||
extra_devices = max(0, (subscription.device_limit or 0) - (tariff.device_limit or 0))
|
||||
if extra_devices > 0:
|
||||
tariff_device_price = tariff.device_price_kopeks or settings.PRICE_PER_DEVICE
|
||||
tariff_device_price = (
|
||||
tariff.device_price_kopeks
|
||||
if tariff.device_price_kopeks is not None
|
||||
else settings.PRICE_PER_DEVICE
|
||||
)
|
||||
|
||||
# Используем периоды тарифа или стандартные
|
||||
if tariff_periods:
|
||||
@@ -363,23 +370,32 @@ async def get_renewal_options(
|
||||
price_kopeks += extra_devices * tariff_device_price * months
|
||||
|
||||
# Apply user's discount if any
|
||||
original_price = price_kopeks
|
||||
discount_percent = 0
|
||||
if hasattr(user, 'get_promo_discount'):
|
||||
discount_percent = user.get_promo_discount('period', period)
|
||||
|
||||
if discount_percent > 0:
|
||||
original_price = price_kopeks
|
||||
price_kopeks = int(price_kopeks * (100 - discount_percent) / 100)
|
||||
else:
|
||||
original_price = None
|
||||
|
||||
# Apply promo_offer discount (временная скидка, как в /renew)
|
||||
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
|
||||
|
||||
# Комбинированный процент скидки для отображения
|
||||
combined_discount = discount_percent
|
||||
if original_price > 0 and original_price != price_kopeks:
|
||||
total_discount = original_price - price_kopeks
|
||||
combined_discount = int(total_discount * 100 / original_price)
|
||||
|
||||
options.append(
|
||||
RenewalOptionResponse(
|
||||
period_days=period,
|
||||
price_kopeks=price_kopeks,
|
||||
price_rubles=price_kopeks / 100,
|
||||
discount_percent=discount_percent,
|
||||
original_price_kopeks=original_price,
|
||||
discount_percent=combined_discount,
|
||||
original_price_kopeks=original_price if combined_discount > 0 else None,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -393,6 +409,12 @@ async def renew_subscription(
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Renew subscription (pay from balance)."""
|
||||
if getattr(user, 'restriction_subscription', False):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Subscription renewal is restricted for this account',
|
||||
)
|
||||
|
||||
await db.refresh(user, ['subscription'])
|
||||
|
||||
if not user.subscription:
|
||||
@@ -425,7 +447,9 @@ async def renew_subscription(
|
||||
if extra_devices > 0:
|
||||
from app.utils.pricing_utils import calculate_months_from_days
|
||||
|
||||
device_price = tariff.device_price_kopeks or settings.PRICE_PER_DEVICE
|
||||
device_price = (
|
||||
tariff.device_price_kopeks if tariff.device_price_kopeks is not None else settings.PRICE_PER_DEVICE
|
||||
)
|
||||
months = calculate_months_from_days(request.period_days)
|
||||
price_kopeks += extra_devices * device_price * months
|
||||
|
||||
@@ -482,6 +506,7 @@ async def renew_subscription(
|
||||
'description': f'Продление подписки на {request.period_days} дней'
|
||||
+ (f' ({tariff_name})' if tariff_name else ''),
|
||||
'discount_percent': discount_percent,
|
||||
'consume_promo_offer': promo_offer_discount_value > 0,
|
||||
'source': 'cabinet',
|
||||
}
|
||||
|
||||
@@ -509,17 +534,45 @@ async def renew_subscription(
|
||||
},
|
||||
)
|
||||
|
||||
# Deduct balance and extend subscription
|
||||
user.balance_kopeks -= price_kopeks
|
||||
# Deduct balance (centralized: row-level lock, promo consumption, paid subscription flag)
|
||||
from app.database.crud.user import subtract_user_balance
|
||||
|
||||
# Consume promo offer discount if it was used
|
||||
if promo_offer_discount_value > 0:
|
||||
user.promo_offer_discount_percent = 0
|
||||
user.promo_offer_discount_source = None
|
||||
user.promo_offer_discount_expires_at = None
|
||||
renewal_description = f'Продление подписки на {request.period_days} дней' + (f' ({tariff.name})' if tariff else '')
|
||||
success = await subtract_user_balance(
|
||||
db,
|
||||
user,
|
||||
price_kopeks,
|
||||
renewal_description,
|
||||
consume_promo_offer=promo_offer_discount_value > 0,
|
||||
mark_as_paid_subscription=True,
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_402_PAYMENT_REQUIRED,
|
||||
detail={
|
||||
'code': 'insufficient_funds',
|
||||
'message': 'Недостаточно средств (concurrent check)',
|
||||
},
|
||||
)
|
||||
|
||||
# Создаём транзакцию для учёта списания
|
||||
transaction = await create_transaction(
|
||||
db,
|
||||
user_id=user.id,
|
||||
type=TransactionType.SUBSCRIPTION_PAYMENT,
|
||||
amount_kopeks=price_kopeks,
|
||||
description=renewal_description,
|
||||
payment_method=PaymentMethod.BALANCE,
|
||||
)
|
||||
|
||||
await db.refresh(user, ['subscription'])
|
||||
|
||||
# Extend from end_date or now if expired
|
||||
now = datetime.now(UTC)
|
||||
was_expired = user.subscription.status in ('expired', 'disabled') or (
|
||||
user.subscription.end_date is not None and user.subscription.end_date <= now
|
||||
)
|
||||
|
||||
if user.subscription.end_date and user.subscription.end_date > now:
|
||||
user.subscription.end_date = user.subscription.end_date + timedelta(days=request.period_days)
|
||||
else:
|
||||
@@ -529,8 +582,49 @@ async def renew_subscription(
|
||||
user.subscription.status = 'active'
|
||||
user.subscription.is_trial = False
|
||||
|
||||
# При продлении истёкшей подписки — сбрасываем докупки трафика (новый период)
|
||||
if was_expired:
|
||||
from sqlalchemy import delete as sql_delete
|
||||
|
||||
from app.database.models import TrafficPurchase
|
||||
|
||||
await db.execute(sql_delete(TrafficPurchase).where(TrafficPurchase.subscription_id == user.subscription.id))
|
||||
purchased = user.subscription.purchased_traffic_gb or 0
|
||||
if purchased > 0:
|
||||
old_traffic = user.subscription.traffic_limit_gb
|
||||
user.subscription.traffic_limit_gb = max(0, (user.subscription.traffic_limit_gb or 0) - purchased)
|
||||
logger.info(
|
||||
'Сброс докупок трафика при продлении истёкшей подписки',
|
||||
old_traffic=old_traffic,
|
||||
new_traffic=user.subscription.traffic_limit_gb,
|
||||
)
|
||||
user.subscription.purchased_traffic_gb = 0
|
||||
user.subscription.traffic_reset_at = None
|
||||
if settings.RESET_TRAFFIC_ON_PAYMENT:
|
||||
user.subscription.traffic_used_gb = 0.0
|
||||
|
||||
await db.commit()
|
||||
|
||||
# Синхронизируем с RemnaWave
|
||||
try:
|
||||
subscription_service = SubscriptionService()
|
||||
if getattr(user, 'remnawave_uuid', None):
|
||||
await subscription_service.update_remnawave_user(
|
||||
db,
|
||||
user.subscription,
|
||||
reset_traffic=was_expired and settings.RESET_TRAFFIC_ON_PAYMENT,
|
||||
reset_reason='subscription renewal (cabinet)',
|
||||
)
|
||||
else:
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
user.subscription,
|
||||
reset_traffic=was_expired and settings.RESET_TRAFFIC_ON_PAYMENT,
|
||||
reset_reason='subscription renewal (cabinet)',
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Failed to sync subscription renewal with RemnaWave', error=e)
|
||||
|
||||
# Отправляем уведомление админам о продлении подписки
|
||||
try:
|
||||
from aiogram import Bot
|
||||
@@ -545,7 +639,7 @@ async def renew_subscription(
|
||||
db=db,
|
||||
user=user,
|
||||
subscription=user.subscription,
|
||||
transaction=None,
|
||||
transaction=transaction,
|
||||
period_days=request.period_days,
|
||||
was_trial_conversion=False,
|
||||
amount_kopeks=price_kopeks,
|
||||
@@ -653,6 +747,12 @@ async def purchase_traffic(
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Purchase additional traffic."""
|
||||
if getattr(user, 'restriction_subscription', False):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Subscription purchases are restricted for this account',
|
||||
)
|
||||
|
||||
from app.database.crud.subscription import add_subscription_traffic
|
||||
from app.database.crud.tariff import get_tariff_by_id
|
||||
from app.utils.pricing_utils import calculate_prorated_price
|
||||
@@ -826,24 +926,13 @@ async def purchase_traffic(
|
||||
detail='Failed to charge balance',
|
||||
)
|
||||
|
||||
# Добавляем трафик
|
||||
# Добавляем трафик (add_subscription_traffic обновляет purchased_traffic_gb, traffic_reset_at и коммитит)
|
||||
await add_subscription_traffic(db, subscription, request.gb)
|
||||
|
||||
# Обновляем purchased_traffic_gb
|
||||
current_purchased = getattr(subscription, 'purchased_traffic_gb', 0) or 0
|
||||
subscription.purchased_traffic_gb = current_purchased + request.gb
|
||||
# Реактивируем подписку если она была DISABLED (например, после LIMITED в RemnaWave)
|
||||
from app.database.crud.subscription import reactivate_subscription
|
||||
|
||||
# Устанавливаем дату сброса трафика (только при первой докупке)
|
||||
# При повторной докупке дата НЕ продлевается
|
||||
if not subscription.traffic_reset_at:
|
||||
subscription.traffic_reset_at = datetime.now(UTC) + timedelta(days=30)
|
||||
logger.info(
|
||||
'Set traffic_reset_at for subscription',
|
||||
subscription_id=subscription.id,
|
||||
traffic_reset_at=subscription.traffic_reset_at,
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
await reactivate_subscription(db, subscription)
|
||||
|
||||
# Синхронизируем с RemnaWave
|
||||
try:
|
||||
@@ -919,9 +1008,22 @@ async def purchase_devices_legacy(
|
||||
|
||||
DEPRECATED: Use /devices/purchase instead for full tariff and discount support.
|
||||
"""
|
||||
await db.refresh(user, ['subscription'])
|
||||
if getattr(user, 'restriction_subscription', False):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Subscription purchases are restricted for this account',
|
||||
)
|
||||
|
||||
if not user.subscription:
|
||||
# Lock subscription row to prevent concurrent device purchases exceeding the limit
|
||||
result = await db.execute(
|
||||
select(Subscription)
|
||||
.where(Subscription.user_id == user.id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
subscription = result.scalar_one_or_none()
|
||||
|
||||
if not subscription:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='No subscription found',
|
||||
@@ -939,6 +1041,17 @@ async def purchase_devices_legacy(
|
||||
if devices_discount_percent < 100 and total_price > 0:
|
||||
total_price = max(100, total_price)
|
||||
|
||||
# Check max devices limit (under row lock — prevents concurrent purchases exceeding limit)
|
||||
current_devices = subscription.device_limit or 1
|
||||
new_devices = current_devices + request.devices
|
||||
max_devices = settings.MAX_DEVICES_LIMIT
|
||||
|
||||
if new_devices > max_devices:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f'Maximum device limit is {max_devices}',
|
||||
)
|
||||
|
||||
# Check balance
|
||||
if user.balance_kopeks < total_price:
|
||||
missing = total_price - user.balance_kopeks
|
||||
@@ -974,17 +1087,6 @@ async def purchase_devices_legacy(
|
||||
},
|
||||
)
|
||||
|
||||
# Check max devices limit
|
||||
current_devices = user.subscription.device_limit or 1
|
||||
new_devices = current_devices + request.devices
|
||||
max_devices = settings.MAX_DEVICES_LIMIT
|
||||
|
||||
if new_devices > max_devices:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f'Maximum device limit is {max_devices}',
|
||||
)
|
||||
|
||||
# Deduct balance and create transaction
|
||||
from app.database.crud.user import subtract_user_balance
|
||||
from app.database.models import PaymentMethod
|
||||
@@ -995,7 +1097,7 @@ async def purchase_devices_legacy(
|
||||
else:
|
||||
description = f'Покупка {request.devices} доп. устройств'
|
||||
|
||||
await subtract_user_balance(
|
||||
success = await subtract_user_balance(
|
||||
db=db,
|
||||
user=user,
|
||||
amount_kopeks=total_price,
|
||||
@@ -1003,10 +1105,39 @@ async def purchase_devices_legacy(
|
||||
create_transaction=True,
|
||||
payment_method=PaymentMethod.BALANCE,
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_402_PAYMENT_REQUIRED,
|
||||
detail='Insufficient funds',
|
||||
)
|
||||
|
||||
# Add devices
|
||||
user.subscription.device_limit = new_devices
|
||||
# Re-lock subscription after subtract_user_balance committed (which released all locks).
|
||||
# Re-validate max device limit to prevent concurrent purchases exceeding the limit.
|
||||
relock_result = await db.execute(
|
||||
select(Subscription)
|
||||
.where(Subscription.id == subscription.id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
subscription = relock_result.scalar_one()
|
||||
|
||||
actual_current = subscription.device_limit or 1
|
||||
actual_new = actual_current + request.devices
|
||||
if max_devices > 0 and actual_new > max_devices:
|
||||
# Concurrent purchase already exceeded limit — refund balance
|
||||
user_refund = await db.execute(
|
||||
select(User).where(User.id == user.id).with_for_update().execution_options(populate_existing=True)
|
||||
)
|
||||
refund_user = user_refund.scalar_one()
|
||||
refund_user.balance_kopeks += total_price
|
||||
await db.commit()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f'Maximum device limit is {max_devices}. Balance refunded.',
|
||||
)
|
||||
|
||||
# Add devices (under lock)
|
||||
subscription.device_limit = actual_new
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
@@ -1023,10 +1154,10 @@ async def purchase_devices_legacy(
|
||||
await notification_service.send_subscription_update_notification(
|
||||
db=db,
|
||||
user=user,
|
||||
subscription=user.subscription,
|
||||
subscription=subscription,
|
||||
update_type='devices',
|
||||
old_value=current_devices,
|
||||
new_value=new_devices,
|
||||
new_value=actual_new,
|
||||
price_paid=total_price,
|
||||
)
|
||||
finally:
|
||||
@@ -1037,7 +1168,7 @@ async def purchase_devices_legacy(
|
||||
response = {
|
||||
'message': 'Devices added successfully',
|
||||
'devices_added': request.devices,
|
||||
'new_device_limit': new_devices,
|
||||
'new_device_limit': actual_new,
|
||||
'amount_paid_kopeks': total_price,
|
||||
}
|
||||
|
||||
@@ -1216,13 +1347,38 @@ async def activate_trial(
|
||||
# Check if trial requires payment
|
||||
requires_payment = bool(settings.TRIAL_PAYMENT_ENABLED)
|
||||
if requires_payment:
|
||||
from app.database.crud.user import subtract_user_balance
|
||||
|
||||
price_kopeks = settings.TRIAL_ACTIVATION_PRICE
|
||||
if user.balance_kopeks < price_kopeks:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f'Insufficient balance. Need {price_kopeks / 100:.2f} RUB',
|
||||
)
|
||||
user.balance_kopeks -= price_kopeks
|
||||
trial_description = 'Активация триальной подписки'
|
||||
success = await subtract_user_balance(
|
||||
db,
|
||||
user,
|
||||
price_kopeks,
|
||||
trial_description,
|
||||
mark_as_paid_subscription=True,
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_402_PAYMENT_REQUIRED,
|
||||
detail='Failed to charge trial activation fee',
|
||||
)
|
||||
|
||||
# Создаём транзакцию для учёта списания за триал
|
||||
await create_transaction(
|
||||
db,
|
||||
user_id=user.id,
|
||||
type=TransactionType.SUBSCRIPTION_PAYMENT,
|
||||
amount_kopeks=price_kopeks,
|
||||
description=trial_description,
|
||||
payment_method=PaymentMethod.BALANCE,
|
||||
)
|
||||
|
||||
logger.info('User paid kopeks for trial activation', user_id=user.id, price_kopeks=price_kopeks)
|
||||
|
||||
# Get trial parameters from tariff if configured (same logic as bot handler)
|
||||
@@ -1351,7 +1507,9 @@ async def _build_tariff_response(
|
||||
if subscription and subscription.tariff_id == tariff.id:
|
||||
extra_devices_count = max(0, (subscription.device_limit or 0) - (tariff.device_limit or 0))
|
||||
if extra_devices_count > 0:
|
||||
extra_device_price_per_month = tariff.device_price_kopeks or settings.PRICE_PER_DEVICE
|
||||
extra_device_price_per_month = (
|
||||
tariff.device_price_kopeks if tariff.device_price_kopeks is not None else settings.PRICE_PER_DEVICE
|
||||
)
|
||||
|
||||
periods = []
|
||||
if tariff.period_prices:
|
||||
@@ -1436,7 +1594,7 @@ async def _build_tariff_response(
|
||||
price_per_day = price_per_day - discount_amount
|
||||
|
||||
# Apply discount to device price if applicable
|
||||
device_price = tariff.device_price_kopeks or 0
|
||||
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:
|
||||
@@ -1629,6 +1787,12 @@ async def submit_purchase(
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Submit subscription purchase (deduct from balance, classic mode only)."""
|
||||
if getattr(user, 'restriction_subscription', False):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Subscription purchases are restricted for this account',
|
||||
)
|
||||
|
||||
# This endpoint is for classic mode only, tariffs mode uses /purchase-tariff
|
||||
if settings.is_tariffs_mode():
|
||||
raise HTTPException(
|
||||
@@ -1694,7 +1858,7 @@ async def submit_purchase(
|
||||
db=db,
|
||||
user=user,
|
||||
subscription=subscription,
|
||||
transaction=None,
|
||||
transaction=result.get('transaction'),
|
||||
period_days=selection.period.days,
|
||||
was_trial_conversion=result.get('was_trial_conversion', False),
|
||||
amount_kopeks=pricing.final_total,
|
||||
@@ -1766,6 +1930,12 @@ async def purchase_tariff(
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
) -> dict[str, Any]:
|
||||
"""Purchase a tariff (for tariffs mode)."""
|
||||
if getattr(user, 'restriction_subscription', False):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Subscription purchases are restricted for this account',
|
||||
)
|
||||
|
||||
try:
|
||||
# Check tariffs mode
|
||||
if not settings.is_tariffs_mode():
|
||||
@@ -1871,7 +2041,11 @@ async def purchase_tariff(
|
||||
if not is_daily_tariff:
|
||||
from app.utils.pricing_utils import calculate_months_from_days
|
||||
|
||||
device_price_per_month = tariff.device_price_kopeks or settings.PRICE_PER_DEVICE
|
||||
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
|
||||
# Применяем скидку промогруппы на устройства
|
||||
@@ -1909,6 +2083,7 @@ async def purchase_tariff(
|
||||
'traffic_limit_gb': tariff.traffic_limit_gb,
|
||||
'device_limit': effective_device_limit,
|
||||
'allowed_squads': tariff.allowed_squads or [],
|
||||
'consume_promo_offer': promo_offer_discount_value > 0,
|
||||
'source': 'cabinet',
|
||||
}
|
||||
else:
|
||||
@@ -1926,6 +2101,7 @@ async def purchase_tariff(
|
||||
'device_limit': effective_device_limit,
|
||||
'allowed_squads': tariff.allowed_squads or [],
|
||||
'discount_percent': discount_percent,
|
||||
'consume_promo_offer': promo_offer_discount_value > 0,
|
||||
'source': 'cabinet',
|
||||
}
|
||||
|
||||
@@ -1967,26 +2143,28 @@ async def purchase_tariff(
|
||||
description += f' (скидка {discount_percent}%)'
|
||||
if promo_offer_discount_value > 0:
|
||||
description += f' (промо -{promo_offer_discount_percent}%)'
|
||||
success = await subtract_user_balance(db, user, price_kopeks, description)
|
||||
success = await subtract_user_balance(
|
||||
db,
|
||||
user,
|
||||
price_kopeks,
|
||||
description,
|
||||
consume_promo_offer=promo_offer_discount_value > 0,
|
||||
mark_as_paid_subscription=True,
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail='Failed to charge balance',
|
||||
)
|
||||
|
||||
# Consume promo offer discount if it was used
|
||||
if promo_offer_discount_value > 0:
|
||||
user.promo_offer_discount_percent = 0
|
||||
user.promo_offer_discount_source = None
|
||||
user.promo_offer_discount_expires_at = None
|
||||
|
||||
# Create transaction
|
||||
await create_transaction(
|
||||
transaction = await create_transaction(
|
||||
db=db,
|
||||
user_id=user.id,
|
||||
type=TransactionType.SUBSCRIPTION_PAYMENT,
|
||||
amount_kopeks=price_kopeks,
|
||||
description=description,
|
||||
payment_method=PaymentMethod.BALANCE,
|
||||
)
|
||||
|
||||
if subscription:
|
||||
@@ -2134,7 +2312,7 @@ async def purchase_tariff(
|
||||
db=db,
|
||||
user=user,
|
||||
subscription=subscription,
|
||||
transaction=None,
|
||||
transaction=transaction,
|
||||
period_days=period_days,
|
||||
was_trial_conversion=False,
|
||||
amount_kopeks=price_kopeks,
|
||||
@@ -2167,9 +2345,21 @@ async def purchase_devices(
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Purchase additional device slots for subscription."""
|
||||
if getattr(user, 'restriction_subscription', False):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail='Subscription purchases are restricted for this account',
|
||||
)
|
||||
|
||||
try:
|
||||
await db.refresh(user, ['subscription'])
|
||||
subscription = user.subscription
|
||||
# Lock subscription row to prevent concurrent device purchases exceeding the limit
|
||||
result = await db.execute(
|
||||
select(Subscription)
|
||||
.where(Subscription.user_id == user.id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
subscription = result.scalar_one_or_none()
|
||||
|
||||
if not subscription:
|
||||
raise HTTPException(
|
||||
@@ -2191,7 +2381,7 @@ async def purchase_devices(
|
||||
tariff = await get_tariff_by_id(db, subscription.tariff_id)
|
||||
|
||||
# Determine device price and max limit from tariff or settings
|
||||
if tariff and tariff.device_price_kopeks:
|
||||
if tariff and tariff.device_price_kopeks is not None:
|
||||
device_price = tariff.device_price_kopeks
|
||||
max_device_limit = tariff.max_device_limit
|
||||
else:
|
||||
@@ -2205,7 +2395,7 @@ async def purchase_devices(
|
||||
detail='Докупка устройств недоступна',
|
||||
)
|
||||
|
||||
# Check max device limit
|
||||
# Check max device limit (under row lock — prevents concurrent purchases exceeding limit)
|
||||
current_devices = subscription.device_limit or 1
|
||||
new_device_count = current_devices + request.devices
|
||||
if max_device_limit and new_device_count > max_device_limit:
|
||||
@@ -2285,7 +2475,7 @@ async def purchase_devices(
|
||||
else:
|
||||
description = f'Покупка {request.devices} доп. устройств'
|
||||
|
||||
await subtract_user_balance(
|
||||
success = await subtract_user_balance(
|
||||
db=db,
|
||||
user=user,
|
||||
amount_kopeks=price_kopeks,
|
||||
@@ -2293,9 +2483,39 @@ async def purchase_devices(
|
||||
create_transaction=True,
|
||||
payment_method=PaymentMethod.BALANCE,
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_402_PAYMENT_REQUIRED,
|
||||
detail='Insufficient funds',
|
||||
)
|
||||
|
||||
# Increase device limit
|
||||
subscription.device_limit += request.devices
|
||||
# Re-lock subscription after subtract_user_balance committed (which released all locks).
|
||||
# Re-validate max device limit to prevent concurrent purchases exceeding the limit.
|
||||
relock_result = await db.execute(
|
||||
select(Subscription)
|
||||
.where(Subscription.id == subscription.id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
subscription = relock_result.scalar_one()
|
||||
|
||||
actual_current = subscription.device_limit or 1
|
||||
actual_new = actual_current + request.devices
|
||||
if max_device_limit and actual_new > max_device_limit:
|
||||
# Concurrent purchase already exceeded limit — refund balance
|
||||
user_refund = await db.execute(
|
||||
select(User).where(User.id == user.id).with_for_update().execution_options(populate_existing=True)
|
||||
)
|
||||
refund_user = user_refund.scalar_one()
|
||||
refund_user.balance_kopeks += price_kopeks
|
||||
await db.commit()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=f'Максимальное количество устройств: {max_device_limit}. Баланс возвращён.',
|
||||
)
|
||||
|
||||
# Increase device limit (under lock)
|
||||
subscription.device_limit = actual_new
|
||||
await db.commit()
|
||||
await db.refresh(subscription)
|
||||
|
||||
@@ -2521,7 +2741,7 @@ async def save_devices_cart(
|
||||
tariff = await get_tariff_by_id(db, subscription.tariff_id)
|
||||
|
||||
# Determine device price and max limit from tariff or settings
|
||||
if tariff and tariff.device_price_kopeks:
|
||||
if tariff and tariff.device_price_kopeks is not None:
|
||||
device_price = tariff.device_price_kopeks
|
||||
max_device_limit = tariff.max_device_limit
|
||||
else:
|
||||
@@ -2593,7 +2813,7 @@ async def get_device_price(
|
||||
tariff = await get_tariff_by_id(db, subscription.tariff_id)
|
||||
|
||||
# Determine device price and max limit from tariff or settings
|
||||
if tariff and tariff.device_price_kopeks:
|
||||
if tariff and tariff.device_price_kopeks is not None:
|
||||
device_price = tariff.device_price_kopeks
|
||||
max_device_limit = tariff.max_device_limit
|
||||
else:
|
||||
@@ -3202,6 +3422,25 @@ async def get_app_config(
|
||||
subscription_url = user.subscription.subscription_url
|
||||
subscription_crypto_link = user.subscription.subscription_crypto_link
|
||||
|
||||
# Generate crypto link on the fly if subscription_url exists but crypto link is missing.
|
||||
# This covers synced users where enrich_happ_links was not called.
|
||||
if subscription_url and not subscription_crypto_link:
|
||||
try:
|
||||
service = RemnaWaveService()
|
||||
async with service.get_api_client() as api:
|
||||
encrypted = await api.encrypt_happ_crypto_link(subscription_url)
|
||||
if encrypted:
|
||||
subscription_crypto_link = encrypted
|
||||
if user.subscription:
|
||||
user.subscription.subscription_crypto_link = encrypted
|
||||
await db.commit()
|
||||
logger.info(
|
||||
'Generated and saved crypto link for user',
|
||||
user_id=user.id,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.debug('Could not generate crypto link', error=e)
|
||||
|
||||
config = await _load_app_config_async()
|
||||
|
||||
if not config:
|
||||
@@ -3262,11 +3501,15 @@ async def get_app_config(
|
||||
if btn_type in ('subscriptionLink', 'copyButton'):
|
||||
url = btn.get('url', '') or btn.get('link', '')
|
||||
if url and '{{' in url:
|
||||
btn['resolvedUrl'] = _resolve_button_url(
|
||||
resolved = _resolve_button_url(
|
||||
url,
|
||||
subscription_url,
|
||||
subscription_crypto_link,
|
||||
)
|
||||
# Only set resolvedUrl if ALL templates were resolved;
|
||||
# otherwise let the frontend fall through to deepLink/subscriptionUrl
|
||||
if '{{' not in resolved:
|
||||
btn['resolvedUrl'] = resolved
|
||||
|
||||
enriched_apps.append(app)
|
||||
|
||||
@@ -3561,16 +3804,21 @@ async def reduce_devices(
|
||||
detail='Invalid new_device_limit',
|
||||
)
|
||||
|
||||
await db.refresh(user, ['subscription'])
|
||||
# Lock subscription to prevent concurrent device modifications
|
||||
result = await db.execute(
|
||||
select(Subscription)
|
||||
.where(Subscription.user_id == user.id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
subscription = result.scalar_one_or_none()
|
||||
|
||||
if not user.subscription:
|
||||
if not subscription:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail='No subscription found',
|
||||
)
|
||||
|
||||
subscription = user.subscription
|
||||
|
||||
if subscription.is_trial:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
@@ -4035,7 +4283,13 @@ async def switch_tariff(
|
||||
if period_discount_percent > 0 and discount_value > 0:
|
||||
description += f' (скидка {period_discount_percent}%)'
|
||||
|
||||
success = await subtract_user_balance(db, user, upgrade_cost, description)
|
||||
success = await subtract_user_balance(
|
||||
db,
|
||||
user,
|
||||
upgrade_cost,
|
||||
description,
|
||||
mark_as_paid_subscription=True,
|
||||
)
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
@@ -4043,12 +4297,13 @@ async def switch_tariff(
|
||||
)
|
||||
|
||||
# Create transaction
|
||||
await create_transaction(
|
||||
switch_transaction = await create_transaction(
|
||||
db=db,
|
||||
user_id=user.id,
|
||||
type=TransactionType.SUBSCRIPTION_PAYMENT,
|
||||
amount_kopeks=upgrade_cost,
|
||||
description=description,
|
||||
payment_method=PaymentMethod.BALANCE,
|
||||
)
|
||||
|
||||
# Update subscription
|
||||
@@ -4067,6 +4322,9 @@ async def switch_tariff(
|
||||
user.subscription.purchased_traffic_gb = 0
|
||||
user.subscription.traffic_reset_at = None
|
||||
|
||||
if settings.RESET_TRAFFIC_ON_TARIFF_SWITCH:
|
||||
user.subscription.traffic_used_gb = 0.0
|
||||
|
||||
if switching_to_daily:
|
||||
# Switching TO daily - reset end_date to 1 day, set last_daily_charge_at
|
||||
user.subscription.end_date = datetime.now(UTC) + timedelta(days=1)
|
||||
@@ -4079,13 +4337,24 @@ async def switch_tariff(
|
||||
user.subscription.updated_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
|
||||
# Sync with RemnaWave
|
||||
# Sync with RemnaWave (optionally reset traffic based on admin setting)
|
||||
should_reset_traffic = settings.RESET_TRAFFIC_ON_TARIFF_SWITCH
|
||||
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,
|
||||
reset_traffic=should_reset_traffic,
|
||||
reset_reason='смена тарифа',
|
||||
)
|
||||
else:
|
||||
await subscription_service.create_remnawave_user(db, user.subscription)
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
user.subscription,
|
||||
reset_traffic=should_reset_traffic,
|
||||
reset_reason='смена тарифа',
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Failed to sync tariff switch with RemnaWave', error=e)
|
||||
|
||||
@@ -4118,7 +4387,7 @@ async def switch_tariff(
|
||||
db=db,
|
||||
user=user,
|
||||
subscription=user.subscription,
|
||||
transaction=None,
|
||||
transaction=switch_transaction if upgrade_cost > 0 else None,
|
||||
period_days=remaining_days if remaining_days > 0 else new_period_days,
|
||||
was_trial_conversion=False,
|
||||
amount_kopeks=upgrade_cost,
|
||||
@@ -4343,7 +4612,12 @@ async def switch_traffic_package(
|
||||
# Downgrade - no charge, no refund
|
||||
charged = 0
|
||||
|
||||
# Update subscription
|
||||
# Update subscription — delete TrafficPurchase records before resetting purchased_traffic_gb
|
||||
from sqlalchemy import delete as sql_delete
|
||||
|
||||
from app.database.models import TrafficPurchase
|
||||
|
||||
await db.execute(sql_delete(TrafficPurchase).where(TrafficPurchase.subscription_id == user.subscription.id))
|
||||
user.subscription.traffic_limit_gb = new_traffic
|
||||
user.subscription.purchased_traffic_gb = 0 # Reset purchased traffic on switch
|
||||
user.subscription.traffic_reset_at = None # Reset traffic reset date
|
||||
|
||||
@@ -10,7 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.database.crud.ticket_notification import TicketNotificationCRUD
|
||||
from app.database.models import User
|
||||
|
||||
from ..dependencies import get_cabinet_db, get_current_admin_user, get_current_cabinet_user
|
||||
from ..dependencies import get_cabinet_db, get_current_cabinet_user, require_permission
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -132,7 +132,7 @@ async def get_admin_notifications(
|
||||
unread_only: bool = Query(False, description='Only return unread notifications'),
|
||||
limit: int = Query(50, ge=1, le=100),
|
||||
offset: int = Query(0, ge=0),
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get ticket notifications for admins."""
|
||||
@@ -149,7 +149,7 @@ async def get_admin_notifications(
|
||||
|
||||
@admin_router.get('/unread-count', response_model=UnreadCountResponse)
|
||||
async def get_admin_unread_count(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:read')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Get unread notifications count for admins."""
|
||||
@@ -160,7 +160,7 @@ async def get_admin_unread_count(
|
||||
@admin_router.post('/{notification_id}/read')
|
||||
async def mark_admin_notification_as_read(
|
||||
notification_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:settings')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Mark an admin notification as read."""
|
||||
@@ -185,7 +185,7 @@ async def mark_admin_notification_as_read(
|
||||
|
||||
@admin_router.post('/read-all')
|
||||
async def mark_all_admin_notifications_as_read(
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:settings')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Mark all admin notifications as read."""
|
||||
@@ -196,7 +196,7 @@ async def mark_all_admin_notifications_as_read(
|
||||
@admin_router.post('/ticket/{ticket_id}/read')
|
||||
async def mark_admin_ticket_notifications_as_read(
|
||||
ticket_id: int,
|
||||
admin: User = Depends(get_current_admin_user),
|
||||
admin: User = Depends(require_permission('tickets:settings')),
|
||||
db: AsyncSession = Depends(get_cabinet_db),
|
||||
):
|
||||
"""Mark all admin notifications for a specific ticket as read."""
|
||||
|
||||
@@ -282,7 +282,13 @@ async def add_ticket_message(
|
||||
|
||||
# Уведомить админов об ответе пользователя (Telegram)
|
||||
try:
|
||||
await notify_admins_about_ticket_reply(ticket, request.message, db)
|
||||
await notify_admins_about_ticket_reply(
|
||||
ticket,
|
||||
request.message,
|
||||
db,
|
||||
media_file_id=request.media_file_id,
|
||||
media_type=request.media_type,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Error notifying admins about ticket reply from cabinet', error=e)
|
||||
|
||||
|
||||
@@ -50,6 +50,12 @@ async def get_wheel_config(
|
||||
# Проверяем доступность
|
||||
availability = await wheel_service.check_availability(db, user)
|
||||
|
||||
# Проверяем наличие подписки
|
||||
from app.database.crud.subscription import get_subscription_by_user_id
|
||||
|
||||
subscription = await get_subscription_by_user_id(db, user.id)
|
||||
has_subscription = subscription is not None and subscription.is_active
|
||||
|
||||
prizes_display = [
|
||||
WheelPrizeDisplay(
|
||||
id=p.id,
|
||||
@@ -77,6 +83,7 @@ async def get_wheel_config(
|
||||
can_pay_days=availability.can_pay_days,
|
||||
user_balance_kopeks=availability.user_balance_kopeks,
|
||||
required_balance_kopeks=availability.required_balance_kopeks,
|
||||
has_subscription=has_subscription,
|
||||
)
|
||||
|
||||
|
||||
@@ -213,6 +220,16 @@ async def create_stars_invoice(
|
||||
detail='Оплата Stars не включена',
|
||||
)
|
||||
|
||||
# Проверяем наличие активной подписки
|
||||
from app.database.crud.subscription import get_subscription_by_user_id
|
||||
|
||||
subscription = await get_subscription_by_user_id(db, user.id)
|
||||
if not subscription or not subscription.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Для использования колеса необходима активная подписка',
|
||||
)
|
||||
|
||||
# Проверяем лимит спинов
|
||||
spins_today = await get_user_spins_today(db, user.id)
|
||||
if config.daily_spin_limit > 0 and spins_today >= config.daily_spin_limit:
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
CampaignBonusType = Literal['balance', 'subscription', 'none', 'tariff']
|
||||
@@ -31,8 +31,7 @@ class CampaignListItem(BaseModel):
|
||||
partner_name: str | None = None
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class CampaignListResponse(BaseModel):
|
||||
@@ -73,8 +72,7 @@ class CampaignDetailResponse(BaseModel):
|
||||
deep_link: str | None = None
|
||||
web_link: str | None = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class CampaignCreateRequest(BaseModel):
|
||||
@@ -179,8 +177,7 @@ class CampaignRegistrationItem(BaseModel):
|
||||
has_subscription: bool = False
|
||||
has_paid: bool = False
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class CampaignRegistrationsResponse(BaseModel):
|
||||
@@ -220,3 +217,61 @@ class ServerSquadInfo(BaseModel):
|
||||
squad_uuid: str
|
||||
display_name: str
|
||||
country_code: str | None = None
|
||||
|
||||
|
||||
# --- Admin campaign chart data schemas ---
|
||||
|
||||
|
||||
class AdminDailyStatItem(BaseModel):
|
||||
"""Daily stat item for admin campaign charts."""
|
||||
|
||||
date: str
|
||||
referrals_count: int = 0 # actually registrations, named for frontend compat
|
||||
earnings_kopeks: int = 0 # actually revenue, named for frontend compat
|
||||
|
||||
|
||||
class AdminPeriodStats(BaseModel):
|
||||
"""Period stats for admin campaign comparison."""
|
||||
|
||||
days: int
|
||||
referrals_count: int = 0
|
||||
earnings_kopeks: int = 0
|
||||
|
||||
|
||||
class AdminPeriodChange(BaseModel):
|
||||
"""Change metrics between periods."""
|
||||
|
||||
absolute: int = 0
|
||||
percent: float = 0.0
|
||||
trend: str = 'stable'
|
||||
|
||||
|
||||
class AdminPeriodComparison(BaseModel):
|
||||
"""Comparison of current vs previous period."""
|
||||
|
||||
current: AdminPeriodStats
|
||||
previous: AdminPeriodStats
|
||||
referrals_change: AdminPeriodChange
|
||||
earnings_change: AdminPeriodChange
|
||||
|
||||
|
||||
class AdminTopRegistrationItem(BaseModel):
|
||||
"""Top user by spending in a campaign."""
|
||||
|
||||
id: int
|
||||
full_name: str
|
||||
created_at: datetime
|
||||
has_paid: bool = False
|
||||
is_active: bool = False
|
||||
total_earnings_kopeks: int = 0 # actually total spending, named for frontend compat
|
||||
|
||||
|
||||
class AdminCampaignChartDataResponse(BaseModel):
|
||||
"""Chart data for admin campaign stats page."""
|
||||
|
||||
campaign_id: int
|
||||
total_deposits_kopeks: int = 0
|
||||
total_spending_kopeks: int = 0
|
||||
daily_stats: list[AdminDailyStatItem] = []
|
||||
period_comparison: AdminPeriodComparison
|
||||
top_registrations: list[AdminTopRegistrationItem] = []
|
||||
|
||||
@@ -28,6 +28,8 @@ class ChannelResponse(BaseModel):
|
||||
title: str | None
|
||||
is_active: bool
|
||||
sort_order: int
|
||||
disable_trial_on_leave: bool
|
||||
disable_paid_on_leave: bool
|
||||
|
||||
|
||||
class ChannelListResponse(BaseModel):
|
||||
@@ -39,6 +41,8 @@ class ChannelCreateRequest(BaseModel):
|
||||
channel_id: str
|
||||
channel_link: str | None = None
|
||||
title: str | None = Field(None, max_length=255)
|
||||
disable_trial_on_leave: bool = True
|
||||
disable_paid_on_leave: bool = False
|
||||
|
||||
@field_validator('channel_id')
|
||||
@classmethod
|
||||
@@ -57,6 +61,8 @@ class ChannelUpdateRequest(BaseModel):
|
||||
title: str | None = Field(None, max_length=255)
|
||||
is_active: bool | None = None
|
||||
sort_order: int | None = None
|
||||
disable_trial_on_leave: bool | None = None
|
||||
disable_paid_on_leave: bool | None = None
|
||||
|
||||
@field_validator('channel_id')
|
||||
@classmethod
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
# ==================== User-facing ====================
|
||||
@@ -16,6 +16,7 @@ class PartnerApplicationRequest(BaseModel):
|
||||
telegram_channel: str | None = Field(None, max_length=255)
|
||||
description: str | None = Field(None, max_length=2000)
|
||||
expected_monthly_referrals: int | None = Field(None, ge=0, le=2_000_000_000)
|
||||
desired_commission_percent: int | None = Field(None, ge=1, le=100)
|
||||
|
||||
|
||||
class PartnerApplicationInfo(BaseModel):
|
||||
@@ -28,13 +29,13 @@ class PartnerApplicationInfo(BaseModel):
|
||||
telegram_channel: str | None = None
|
||||
description: str | None = None
|
||||
expected_monthly_referrals: int | None = None
|
||||
desired_commission_percent: int | None = None
|
||||
admin_comment: str | None = None
|
||||
approved_commission_percent: int | None = None
|
||||
created_at: datetime
|
||||
processed_at: datetime | None = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class PartnerCampaignInfo(BaseModel):
|
||||
@@ -49,6 +50,10 @@ class PartnerCampaignInfo(BaseModel):
|
||||
subscription_traffic_gb: int | None = None
|
||||
deep_link: str | None = None
|
||||
web_link: str | None = None
|
||||
# Per-campaign statistics
|
||||
registrations_count: int = 0
|
||||
referrals_count: int = 0
|
||||
earnings_kopeks: int = 0
|
||||
|
||||
|
||||
class PartnerStatusResponse(BaseModel):
|
||||
@@ -60,6 +65,75 @@ class PartnerStatusResponse(BaseModel):
|
||||
campaigns: list[PartnerCampaignInfo] = []
|
||||
|
||||
|
||||
# ==================== Campaign detailed stats ====================
|
||||
|
||||
|
||||
class DailyStatItem(BaseModel):
|
||||
"""Single day of campaign stats."""
|
||||
|
||||
date: str
|
||||
referrals_count: int = 0
|
||||
earnings_kopeks: int = 0
|
||||
|
||||
|
||||
class PeriodStats(BaseModel):
|
||||
"""Stats for a single period."""
|
||||
|
||||
days: int
|
||||
referrals_count: int = 0
|
||||
earnings_kopeks: int = 0
|
||||
|
||||
|
||||
class PeriodChange(BaseModel):
|
||||
"""Change metrics between periods."""
|
||||
|
||||
absolute: int = 0
|
||||
percent: float = 0.0
|
||||
trend: str = 'stable'
|
||||
|
||||
|
||||
class PeriodComparison(BaseModel):
|
||||
"""Comparison between current and previous period."""
|
||||
|
||||
current: PeriodStats
|
||||
previous: PeriodStats
|
||||
referrals_change: PeriodChange
|
||||
earnings_change: PeriodChange
|
||||
|
||||
|
||||
class CampaignReferralItem(BaseModel):
|
||||
"""Referral user in campaign stats."""
|
||||
|
||||
id: int
|
||||
full_name: str
|
||||
created_at: datetime
|
||||
has_paid: bool = False
|
||||
is_active: bool = False
|
||||
total_earnings_kopeks: int = 0
|
||||
|
||||
|
||||
class PartnerCampaignDetailedStats(BaseModel):
|
||||
"""Detailed stats for a single campaign."""
|
||||
|
||||
campaign_id: int
|
||||
campaign_name: str
|
||||
# Summary
|
||||
registrations_count: int = 0
|
||||
referrals_count: int = 0
|
||||
earnings_kopeks: int = 0
|
||||
conversion_rate: float = 0.0
|
||||
# Period earnings
|
||||
earnings_today: int = 0
|
||||
earnings_week: int = 0
|
||||
earnings_month: int = 0
|
||||
# Daily chart (30 days)
|
||||
daily_stats: list[DailyStatItem] = []
|
||||
# Period comparison (this week vs last week)
|
||||
period_comparison: PeriodComparison
|
||||
# Top referrals
|
||||
top_referrals: list[CampaignReferralItem] = []
|
||||
|
||||
|
||||
# ==================== Admin-facing ====================
|
||||
|
||||
|
||||
@@ -76,6 +150,7 @@ class AdminPartnerApplicationItem(BaseModel):
|
||||
telegram_channel: str | None = None
|
||||
description: str | None = None
|
||||
expected_monthly_referrals: int | None = None
|
||||
desired_commission_percent: int | None = None
|
||||
status: str
|
||||
admin_comment: str | None = None
|
||||
approved_commission_percent: int | None = None
|
||||
@@ -132,6 +207,9 @@ class CampaignSummary(BaseModel):
|
||||
name: str
|
||||
start_parameter: str
|
||||
is_active: bool
|
||||
registrations_count: int = 0
|
||||
referrals_count: int = 0
|
||||
earnings_kopeks: int = 0
|
||||
|
||||
|
||||
class AdminPartnerDetailResponse(BaseModel):
|
||||
|
||||
@@ -15,6 +15,9 @@ class ReferralInfoResponse(BaseModel):
|
||||
total_earnings_kopeks: int
|
||||
total_earnings_rubles: float
|
||||
commission_percent: int
|
||||
available_balance_kopeks: int = 0
|
||||
available_balance_rubles: float = 0
|
||||
withdrawn_kopeks: int = 0
|
||||
|
||||
|
||||
class ReferralItemResponse(BaseModel):
|
||||
|
||||
@@ -60,6 +60,7 @@ class WheelConfigResponse(BaseModel):
|
||||
can_pay_days: bool = False
|
||||
user_balance_kopeks: int = 0
|
||||
required_balance_kopeks: int = 0
|
||||
has_subscription: bool = False
|
||||
|
||||
|
||||
class SpinAvailabilityResponse(BaseModel):
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Shared utility for generating campaign deep links and web links."""
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
def get_campaign_deep_link(start_parameter: str) -> str:
|
||||
"""Generate a Telegram deep link for a campaign."""
|
||||
bot_username = settings.get_bot_username()
|
||||
if bot_username:
|
||||
return f'https://t.me/{bot_username}?start={start_parameter}'
|
||||
return f'?start={start_parameter}'
|
||||
|
||||
|
||||
def get_campaign_web_link(start_parameter: str) -> str | None:
|
||||
"""Generate a web app link for a campaign."""
|
||||
base_url = (settings.MINIAPP_CUSTOM_URL or '').rstrip('/')
|
||||
if base_url:
|
||||
return f'{base_url}/?campaign={start_parameter}'
|
||||
return None
|
||||
+48
-6
@@ -134,6 +134,7 @@ class Settings(BaseSettings):
|
||||
DEFAULT_DEVICE_LIMIT: int = 1
|
||||
DEFAULT_TRAFFIC_RESET_STRATEGY: str = 'MONTH'
|
||||
RESET_TRAFFIC_ON_PAYMENT: bool = False
|
||||
RESET_TRAFFIC_ON_TARIFF_SWITCH: bool = True
|
||||
MAX_DEVICES_LIMIT: int = 20
|
||||
|
||||
TRIAL_WARNING_HOURS: int = 2
|
||||
@@ -500,6 +501,11 @@ class Settings(BaseSettings):
|
||||
FREEKASSA_USE_API: bool = False
|
||||
# Публичный IP сервера для Freekassa API (если не задан - определяется автоматически)
|
||||
SERVER_PUBLIC_IP: str | None = None
|
||||
# Раздельные методы оплаты Freekassa (отображаются как отдельные кнопки)
|
||||
FREEKASSA_SBP_ENABLED: bool = False # СБП (QR код) — i=44
|
||||
FREEKASSA_SBP_DISPLAY_NAME: str = 'СБП (QR код)'
|
||||
FREEKASSA_CARD_ENABLED: bool = False # Карты РФ — i=36
|
||||
FREEKASSA_CARD_DISPLAY_NAME: str = 'Карта РФ'
|
||||
|
||||
# KassaAI (api.fk.life) - отдельная платёжка
|
||||
KASSA_AI_ENABLED: bool = False
|
||||
@@ -708,6 +714,9 @@ class Settings(BaseSettings):
|
||||
CABINET_EMAIL_CHANGE_CODE_EXPIRE_MINUTES: int = 15 # Email change verification code expiration
|
||||
CABINET_EMAIL_AUTH_ENABLED: bool = True # Enable email registration/login in cabinet
|
||||
CABINET_URL: str = 'https://example.com/cabinet' # Base URL for cabinet (used in verification emails)
|
||||
CABINET_TRUSTED_PROXIES: str = (
|
||||
'' # Comma-separated IPs/CIDRs of trusted reverse proxies (e.g. '127.0.0.1,10.0.0.0/8')
|
||||
)
|
||||
|
||||
# OAuth 2.0 provider settings for cabinet
|
||||
OAUTH_GOOGLE_CLIENT_ID: str = ''
|
||||
@@ -1525,8 +1534,8 @@ class Settings(BaseSettings):
|
||||
logger.warning('Некорректное значение DEVICES_SELECTION_DISABLED_AMOUNT', raw_value=raw_value)
|
||||
return None
|
||||
|
||||
if value < 0:
|
||||
return 0
|
||||
if value <= 0:
|
||||
return None
|
||||
|
||||
return value
|
||||
|
||||
@@ -1750,6 +1759,26 @@ class Settings(BaseSettings):
|
||||
def get_freekassa_display_name_html(self) -> str:
|
||||
return html.escape(self.get_freekassa_display_name())
|
||||
|
||||
def is_freekassa_sbp_enabled(self) -> bool:
|
||||
return self.FREEKASSA_SBP_ENABLED and self.is_freekassa_enabled()
|
||||
|
||||
def get_freekassa_sbp_display_name(self) -> str:
|
||||
name = (self.FREEKASSA_SBP_DISPLAY_NAME or '').strip()
|
||||
return name if name else 'СБП (QR код)'
|
||||
|
||||
def get_freekassa_sbp_display_name_html(self) -> str:
|
||||
return html.escape(self.get_freekassa_sbp_display_name())
|
||||
|
||||
def is_freekassa_card_enabled(self) -> bool:
|
||||
return self.FREEKASSA_CARD_ENABLED and self.is_freekassa_enabled()
|
||||
|
||||
def get_freekassa_card_display_name(self) -> str:
|
||||
name = (self.FREEKASSA_CARD_DISPLAY_NAME or '').strip()
|
||||
return name if name else 'Карта РФ'
|
||||
|
||||
def get_freekassa_card_display_name_html(self) -> str:
|
||||
return html.escape(self.get_freekassa_card_display_name())
|
||||
|
||||
def is_kassa_ai_enabled(self) -> bool:
|
||||
return (
|
||||
self.KASSA_AI_ENABLED
|
||||
@@ -2467,6 +2496,12 @@ class Settings(BaseSettings):
|
||||
def is_cabinet_email_auth_enabled(self) -> bool:
|
||||
return bool(self.CABINET_EMAIL_AUTH_ENABLED)
|
||||
|
||||
def get_cabinet_trusted_proxies(self) -> set[str]:
|
||||
"""Parse CABINET_TRUSTED_PROXIES into a set of IP strings/CIDRs."""
|
||||
if not self.CABINET_TRUSTED_PROXIES:
|
||||
return set()
|
||||
return {p.strip() for p in self.CABINET_TRUSTED_PROXIES.split(',') if p.strip()}
|
||||
|
||||
def is_smtp_configured(self) -> bool:
|
||||
# For servers without AUTH, only host and from_email are required
|
||||
has_from = bool(self.SMTP_FROM_EMAIL or self.SMTP_USER)
|
||||
@@ -2572,18 +2607,25 @@ def get_db_period_prices() -> dict[int, int] | None:
|
||||
return _DB_PERIOD_PRICES
|
||||
|
||||
|
||||
def clear_db_period_prices() -> None:
|
||||
"""Очищает кеш цен из тарифов (при переключении в classic mode)."""
|
||||
global _DB_PERIOD_PRICES
|
||||
_DB_PERIOD_PRICES = None
|
||||
|
||||
|
||||
def refresh_period_prices() -> None:
|
||||
"""
|
||||
Rebuild cached period price mapping.
|
||||
Приоритет: БД > .env
|
||||
В режиме tariffs: приоритет у _DB_PERIOD_PRICES (из таблицы Tariff).
|
||||
В режиме classic: ВСЕГДА используются settings.PRICE_*_DAYS.
|
||||
"""
|
||||
PERIOD_PRICES.clear()
|
||||
|
||||
if _DB_PERIOD_PRICES:
|
||||
# Используем цены из БД
|
||||
if _DB_PERIOD_PRICES and settings.is_tariffs_mode():
|
||||
# Используем цены из БД тарифов (только в режиме tariffs)
|
||||
PERIOD_PRICES.update(_DB_PERIOD_PRICES)
|
||||
else:
|
||||
# Fallback на .env
|
||||
# Classic mode или нет цен в БД — берём из settings
|
||||
PERIOD_PRICES.update(
|
||||
{days: getattr(settings, field_name, 0) for days, field_name in _PERIOD_PRICE_FIELDS.items()}
|
||||
)
|
||||
|
||||
@@ -104,9 +104,9 @@ async def get_campaigns_list(
|
||||
stmt = (
|
||||
select(AdvertisingCampaign)
|
||||
.options(
|
||||
selectinload(AdvertisingCampaign.registrations),
|
||||
selectinload(AdvertisingCampaign.tariff),
|
||||
selectinload(AdvertisingCampaign.partner),
|
||||
selectinload(AdvertisingCampaign.registrations),
|
||||
)
|
||||
.order_by(AdvertisingCampaign.created_at.desc())
|
||||
.offset(offset)
|
||||
@@ -148,10 +148,22 @@ async def update_campaign(
|
||||
'partner_user_id',
|
||||
}
|
||||
|
||||
nullable_fields = {
|
||||
'partner_user_id',
|
||||
'tariff_id',
|
||||
'subscription_duration_days',
|
||||
'subscription_traffic_gb',
|
||||
'subscription_device_limit',
|
||||
'tariff_duration_days',
|
||||
}
|
||||
|
||||
update_data = {}
|
||||
for key, value in kwargs.items():
|
||||
if key in allowed_fields and value is not None:
|
||||
update_data[key] = value
|
||||
if key not in allowed_fields:
|
||||
continue
|
||||
if value is None and key not in nullable_fields:
|
||||
continue
|
||||
update_data[key] = value
|
||||
|
||||
if not update_data:
|
||||
return campaign
|
||||
|
||||
@@ -92,6 +92,16 @@ async def get_cloudpayments_payment_by_id(
|
||||
return result.scalars().first()
|
||||
|
||||
|
||||
async def get_cloudpayments_payment_by_id_for_update(
|
||||
db: AsyncSession,
|
||||
payment_id: int,
|
||||
) -> CloudPaymentsPayment | None:
|
||||
result = await db.execute(
|
||||
select(CloudPaymentsPayment).where(CloudPaymentsPayment.id == payment_id).with_for_update()
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_cloudpayments_payment_by_transaction_id(
|
||||
db: AsyncSession,
|
||||
transaction_id_cp: int,
|
||||
|
||||
@@ -67,6 +67,11 @@ async def get_cryptobot_payment_by_id(db: AsyncSession, payment_id: int) -> Cryp
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_cryptobot_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> CryptoBotPayment | None:
|
||||
result = await db.execute(select(CryptoBotPayment).where(CryptoBotPayment.id == payment_id).with_for_update())
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def update_cryptobot_payment_status(
|
||||
db: AsyncSession, invoice_id: str, status: str, paid_at: datetime | None = None
|
||||
) -> CryptoBotPayment | None:
|
||||
@@ -99,7 +104,7 @@ async def link_cryptobot_payment_to_transaction(
|
||||
payment.transaction_id = transaction_id
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
|
||||
await db.commit()
|
||||
await db.flush()
|
||||
await db.refresh(payment)
|
||||
|
||||
logger.info('Связан CryptoBot платеж с транзакцией', invoice_id=invoice_id, transaction_id=transaction_id)
|
||||
|
||||
@@ -63,6 +63,11 @@ async def get_freekassa_payment_by_id(db: AsyncSession, payment_id: int) -> Free
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_freekassa_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> FreekassaPayment | None:
|
||||
result = await db.execute(select(FreekassaPayment).where(FreekassaPayment.id == payment_id).with_for_update())
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def update_freekassa_payment_status(
|
||||
db: AsyncSession,
|
||||
payment: FreekassaPayment,
|
||||
|
||||
@@ -91,6 +91,11 @@ async def get_heleket_payment_by_id(
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_heleket_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> HeleketPayment | None:
|
||||
result = await db.execute(select(HeleketPayment).where(HeleketPayment.id == payment_id).with_for_update())
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def update_heleket_payment(
|
||||
db: AsyncSession,
|
||||
uuid: str,
|
||||
@@ -159,7 +164,7 @@ async def link_heleket_payment_to_transaction(
|
||||
payment.transaction_id = transaction_id
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
|
||||
await db.commit()
|
||||
await db.flush()
|
||||
await db.refresh(payment)
|
||||
|
||||
logger.info('Heleket платеж связан с транзакцией', uuid=uuid, transaction_id=transaction_id)
|
||||
|
||||
@@ -65,6 +65,11 @@ async def get_kassa_ai_payment_by_id(db: AsyncSession, payment_id: int) -> Kassa
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_kassa_ai_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> KassaAiPayment | None:
|
||||
result = await db.execute(select(KassaAiPayment).where(KassaAiPayment.id == payment_id).with_for_update())
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def update_kassa_ai_payment_status(
|
||||
db: AsyncSession,
|
||||
payment: KassaAiPayment,
|
||||
|
||||
@@ -57,6 +57,11 @@ async def get_mulenpay_payment_by_local_id(db: AsyncSession, payment_id: int) ->
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_mulenpay_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> MulenPayPayment | None:
|
||||
result = await db.execute(select(MulenPayPayment).where(MulenPayPayment.id == payment_id).with_for_update())
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_mulenpay_payment_by_uuid(db: AsyncSession, uuid: str) -> MulenPayPayment | None:
|
||||
result = await db.execute(select(MulenPayPayment).where(MulenPayPayment.uuid == uuid))
|
||||
return result.scalar_one_or_none()
|
||||
@@ -117,6 +122,6 @@ async def link_mulenpay_payment_to_transaction(
|
||||
) -> MulenPayPayment:
|
||||
payment.transaction_id = transaction_id
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await db.flush()
|
||||
await db.refresh(payment)
|
||||
return payment
|
||||
|
||||
@@ -66,6 +66,11 @@ async def get_pal24_payment_by_id(db: AsyncSession, payment_id: int) -> Pal24Pay
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_pal24_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> Pal24Payment | None:
|
||||
result = await db.execute(select(Pal24Payment).where(Pal24Payment.id == payment_id).with_for_update())
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_pal24_payment_by_bill_id(db: AsyncSession, bill_id: str) -> Pal24Payment | None:
|
||||
result = await db.execute(select(Pal24Payment).where(Pal24Payment.bill_id == bill_id))
|
||||
return result.scalar_one_or_none()
|
||||
@@ -143,7 +148,7 @@ async def link_pal24_payment_to_transaction(
|
||||
transaction_id: int,
|
||||
) -> Pal24Payment:
|
||||
await db.execute(update(Pal24Payment).where(Pal24Payment.id == payment.id).values(transaction_id=transaction_id))
|
||||
await db.commit()
|
||||
await db.flush()
|
||||
await db.refresh(payment)
|
||||
logger.info('Pal24 платеж привязан к транзакции', bill_id=payment.bill_id, transaction_id=transaction_id)
|
||||
return payment
|
||||
|
||||
@@ -130,6 +130,6 @@ async def link_platega_payment_to_transaction(
|
||||
) -> PlategaPayment:
|
||||
payment.transaction_id = transaction_id
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await db.flush()
|
||||
await db.refresh(payment)
|
||||
return payment
|
||||
|
||||
@@ -84,28 +84,6 @@ async def create_promocode(
|
||||
return promocode
|
||||
|
||||
|
||||
async def use_promocode(db: AsyncSession, promocode_id: int, user_id: int) -> bool:
|
||||
try:
|
||||
promocode = await get_promocode_by_id(db, promocode_id)
|
||||
if not promocode:
|
||||
return False
|
||||
|
||||
usage = PromoCodeUse(promocode_id=promocode_id, user_id=user_id)
|
||||
db.add(usage)
|
||||
|
||||
promocode.current_uses += 1
|
||||
|
||||
await db.commit()
|
||||
|
||||
logger.info('✅ Промокод использован пользователем', code=promocode.code, user_id=user_id)
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error('Ошибка использования промокода', error=e)
|
||||
await db.rollback()
|
||||
return False
|
||||
|
||||
|
||||
async def check_user_promocode_usage(db: AsyncSession, user_id: int, promocode_id: int) -> bool:
|
||||
result = await db.execute(
|
||||
select(PromoCodeUse).where(and_(PromoCodeUse.user_id == user_id, PromoCodeUse.promocode_id == promocode_id))
|
||||
@@ -113,12 +91,22 @@ async def check_user_promocode_usage(db: AsyncSession, user_id: int, promocode_i
|
||||
return result.scalar_one_or_none() is not None
|
||||
|
||||
|
||||
async def create_promocode_use(db: AsyncSession, promocode_id: int, user_id: int) -> PromoCodeUse:
|
||||
async def create_promocode_use(db: AsyncSession, promocode_id: int, user_id: int) -> PromoCodeUse | None:
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
promocode_use = PromoCodeUse(promocode_id=promocode_id, user_id=user_id, used_at=datetime.now(UTC))
|
||||
|
||||
db.add(promocode_use)
|
||||
await db.commit()
|
||||
await db.refresh(promocode_use)
|
||||
try:
|
||||
async with db.begin_nested():
|
||||
db.add(promocode_use)
|
||||
await db.flush()
|
||||
except IntegrityError:
|
||||
logger.warning(
|
||||
'⚠️ Дублирующая запись использования промокода (race condition)',
|
||||
promocode_id=promocode_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
return None
|
||||
|
||||
logger.info('📝 Записано использование промокода пользователем', promocode_id=promocode_id, user_id=user_id)
|
||||
return promocode_use
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import structlog
|
||||
from sqlalchemy import and_, delete, func, or_, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.database.models import AccessPolicy, AdminAuditLog, AdminRole, User, UserRole
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
# Fields allowed for AdminRole.update()
|
||||
_ROLE_UPDATABLE_FIELDS = frozenset(
|
||||
{
|
||||
'name',
|
||||
'description',
|
||||
'level',
|
||||
'permissions',
|
||||
'color',
|
||||
'icon',
|
||||
'is_active',
|
||||
}
|
||||
)
|
||||
|
||||
# Fields allowed for AccessPolicy.update()
|
||||
_POLICY_UPDATABLE_FIELDS = frozenset(
|
||||
{
|
||||
'name',
|
||||
'description',
|
||||
'role_id',
|
||||
'priority',
|
||||
'effect',
|
||||
'conditions',
|
||||
'resource',
|
||||
'actions',
|
||||
'is_active',
|
||||
}
|
||||
)
|
||||
|
||||
# Superadmin level constant
|
||||
_SUPERADMIN_LEVEL = 999
|
||||
|
||||
|
||||
class AdminRoleCRUD:
|
||||
"""CRUD operations for admin_roles table."""
|
||||
|
||||
@staticmethod
|
||||
async def get_all(db: AsyncSession, *, include_inactive: bool = False) -> list[AdminRole]:
|
||||
"""Get all admin roles ordered by level descending."""
|
||||
stmt = select(AdminRole).order_by(AdminRole.level.desc())
|
||||
if not include_inactive:
|
||||
stmt = stmt.where(AdminRole.is_active.is_(True))
|
||||
result = await db.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
@staticmethod
|
||||
async def get_by_id(db: AsyncSession, role_id: int) -> AdminRole | None:
|
||||
result = await db.execute(select(AdminRole).where(AdminRole.id == role_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
@staticmethod
|
||||
async def get_by_name(db: AsyncSession, name: str) -> AdminRole | None:
|
||||
result = await db.execute(select(AdminRole).where(AdminRole.name == name))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
@staticmethod
|
||||
async def create(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
name: str,
|
||||
description: str | None,
|
||||
level: int,
|
||||
permissions: list[str],
|
||||
color: str | None = None,
|
||||
icon: str | None = None,
|
||||
is_system: bool = False,
|
||||
created_by: int | None = None,
|
||||
) -> AdminRole:
|
||||
role = AdminRole(
|
||||
name=name,
|
||||
description=description,
|
||||
level=level,
|
||||
permissions=permissions,
|
||||
color=color,
|
||||
icon=icon,
|
||||
is_system=is_system,
|
||||
created_by=created_by,
|
||||
)
|
||||
db.add(role)
|
||||
await db.flush()
|
||||
await db.refresh(role)
|
||||
logger.info('Created admin role', role_id=role.id, name=name, level=level)
|
||||
return role
|
||||
|
||||
@staticmethod
|
||||
async def update(db: AsyncSession, role_id: int, **kwargs: object) -> AdminRole | None:
|
||||
"""Update only provided fields. Rejects unknown/non-updatable keys."""
|
||||
role = await AdminRoleCRUD.get_by_id(db, role_id)
|
||||
if not role:
|
||||
return None
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if key not in _ROLE_UPDATABLE_FIELDS:
|
||||
logger.warning('Rejected update of non-updatable AdminRole field', field=key)
|
||||
continue
|
||||
setattr(role, key, value)
|
||||
|
||||
await db.flush()
|
||||
await db.refresh(role)
|
||||
logger.info('Updated admin role', role_id=role_id, fields=list(kwargs.keys()))
|
||||
return role
|
||||
|
||||
@staticmethod
|
||||
async def delete(db: AsyncSession, role_id: int) -> bool:
|
||||
"""Delete a role. Returns False if the role is a system role or does not exist.
|
||||
|
||||
Cascades are handled by DB-level ON DELETE CASCADE on user_roles and access_policies.
|
||||
"""
|
||||
role = await AdminRoleCRUD.get_by_id(db, role_id)
|
||||
if not role:
|
||||
return False
|
||||
if role.is_system:
|
||||
logger.warning('Attempted to delete system role', role_id=role_id, name=role.name)
|
||||
return False
|
||||
|
||||
# Explicitly delete dependent user_roles and access_policies in application layer
|
||||
# to keep audit trail clear (DB cascade would also work, but explicit is better)
|
||||
await db.execute(delete(UserRole).where(UserRole.role_id == role_id))
|
||||
await db.execute(delete(AccessPolicy).where(AccessPolicy.role_id == role_id))
|
||||
await db.delete(role)
|
||||
await db.flush()
|
||||
logger.info('Deleted admin role', role_id=role_id, name=role.name)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
async def count_users(db: AsyncSession, role_id: int) -> int:
|
||||
"""Count active user_roles assigned to this role."""
|
||||
result = await db.execute(
|
||||
select(func.count(UserRole.id)).where(
|
||||
UserRole.role_id == role_id,
|
||||
UserRole.is_active.is_(True),
|
||||
)
|
||||
)
|
||||
return result.scalar() or 0
|
||||
|
||||
|
||||
class UserRoleCRUD:
|
||||
"""CRUD operations for user_roles table + permission aggregation."""
|
||||
|
||||
@staticmethod
|
||||
async def get_user_roles(db: AsyncSession, user_id: int) -> list[UserRole]:
|
||||
"""Get active user roles with eager-loaded AdminRole."""
|
||||
result = await db.execute(
|
||||
select(UserRole)
|
||||
.options(selectinload(UserRole.role))
|
||||
.where(
|
||||
UserRole.user_id == user_id,
|
||||
UserRole.is_active.is_(True),
|
||||
)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
@staticmethod
|
||||
async def get_user_permissions(
|
||||
db: AsyncSession,
|
||||
user_id: int,
|
||||
) -> tuple[list[str], list[str], int]:
|
||||
"""Aggregate permissions from all active, non-expired roles.
|
||||
|
||||
Returns:
|
||||
(sorted_permissions, role_names, max_level)
|
||||
"""
|
||||
now = datetime.now(UTC)
|
||||
result = await db.execute(
|
||||
select(UserRole)
|
||||
.options(selectinload(UserRole.role))
|
||||
.where(
|
||||
UserRole.user_id == user_id,
|
||||
UserRole.is_active.is_(True),
|
||||
)
|
||||
)
|
||||
user_roles = result.scalars().all()
|
||||
|
||||
permissions: set[str] = set()
|
||||
role_names: list[str] = []
|
||||
max_level: int = 0
|
||||
|
||||
for ur in user_roles:
|
||||
# Skip expired assignments
|
||||
if ur.expires_at is not None and ur.expires_at <= now:
|
||||
continue
|
||||
role = ur.role
|
||||
if role is None or not role.is_active:
|
||||
continue
|
||||
permissions.update(role.permissions or [])
|
||||
role_names.append(role.name)
|
||||
max_level = max(max_level, role.level)
|
||||
|
||||
return sorted(permissions), role_names, max_level
|
||||
|
||||
@staticmethod
|
||||
async def assign_role(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: int,
|
||||
role_id: int,
|
||||
assigned_by: int | None = None,
|
||||
expires_at: datetime | None = None,
|
||||
) -> UserRole:
|
||||
"""Assign a role to a user. Reactivates existing inactive assignment if present."""
|
||||
# Check for existing assignment (active or inactive) due to unique constraint
|
||||
result = await db.execute(
|
||||
select(UserRole).where(
|
||||
UserRole.user_id == user_id,
|
||||
UserRole.role_id == role_id,
|
||||
)
|
||||
)
|
||||
existing = result.scalar_one_or_none()
|
||||
|
||||
if existing is not None:
|
||||
existing.is_active = True
|
||||
existing.assigned_by = assigned_by
|
||||
existing.assigned_at = datetime.now(UTC)
|
||||
existing.expires_at = expires_at
|
||||
await db.flush()
|
||||
await db.refresh(existing)
|
||||
logger.info('Reactivated user role', user_role_id=existing.id, user_id=user_id, role_id=role_id)
|
||||
return existing
|
||||
|
||||
user_role = UserRole(
|
||||
user_id=user_id,
|
||||
role_id=role_id,
|
||||
assigned_by=assigned_by,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
db.add(user_role)
|
||||
await db.flush()
|
||||
await db.refresh(user_role)
|
||||
logger.info('Assigned role to user', user_role_id=user_role.id, user_id=user_id, role_id=role_id)
|
||||
return user_role
|
||||
|
||||
@staticmethod
|
||||
async def revoke_role(db: AsyncSession, user_role_id: int) -> bool:
|
||||
"""Soft-revoke: set is_active=False. Returns False if not found."""
|
||||
result = await db.execute(select(UserRole).where(UserRole.id == user_role_id))
|
||||
user_role = result.scalar_one_or_none()
|
||||
if not user_role:
|
||||
return False
|
||||
|
||||
user_role.is_active = False
|
||||
await db.flush()
|
||||
logger.info(
|
||||
'Revoked user role', user_role_id=user_role_id, user_id=user_role.user_id, role_id=user_role.role_id
|
||||
)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
async def get_all_admins(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> list[dict]:
|
||||
"""Get users that have at least one active role.
|
||||
|
||||
Returns list of dicts: [{'user': User, 'role_names': [str, ...]}]
|
||||
"""
|
||||
# Subquery: aggregate role names per user
|
||||
role_agg = (
|
||||
select(
|
||||
UserRole.user_id,
|
||||
func.array_agg(AdminRole.name).label('role_names'),
|
||||
)
|
||||
.join(AdminRole, UserRole.role_id == AdminRole.id)
|
||||
.where(
|
||||
UserRole.is_active.is_(True),
|
||||
AdminRole.is_active.is_(True),
|
||||
)
|
||||
.group_by(UserRole.user_id)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
stmt = (
|
||||
select(User, role_agg.c.role_names)
|
||||
.join(role_agg, User.id == role_agg.c.user_id)
|
||||
.order_by(User.id)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
)
|
||||
|
||||
result = await db.execute(stmt)
|
||||
rows = result.all()
|
||||
|
||||
return [{'user': row[0], 'role_names': list(row[1] or [])} for row in rows]
|
||||
|
||||
@staticmethod
|
||||
async def get_superadmin_count(db: AsyncSession) -> int:
|
||||
"""Count users with an active role at superadmin level (999)."""
|
||||
result = await db.execute(
|
||||
select(func.count(func.distinct(UserRole.user_id)))
|
||||
.join(AdminRole, UserRole.role_id == AdminRole.id)
|
||||
.where(
|
||||
UserRole.is_active.is_(True),
|
||||
AdminRole.is_active.is_(True),
|
||||
AdminRole.level == _SUPERADMIN_LEVEL,
|
||||
)
|
||||
)
|
||||
return result.scalar() or 0
|
||||
|
||||
|
||||
class AccessPolicyCRUD:
|
||||
"""CRUD operations for access_policies table (ABAC)."""
|
||||
|
||||
@staticmethod
|
||||
async def get_all(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
role_id: int | None = None,
|
||||
) -> list[AccessPolicy]:
|
||||
"""Get active policies ordered by priority descending. Optionally filter by role_id."""
|
||||
stmt = select(AccessPolicy).where(AccessPolicy.is_active.is_(True)).order_by(AccessPolicy.priority.desc())
|
||||
if role_id is not None:
|
||||
stmt = stmt.where(AccessPolicy.role_id == role_id)
|
||||
result = await db.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
@staticmethod
|
||||
async def get_by_id(db: AsyncSession, policy_id: int) -> AccessPolicy | None:
|
||||
result = await db.execute(select(AccessPolicy).where(AccessPolicy.id == policy_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
@staticmethod
|
||||
async def create(db: AsyncSession, **kwargs: object) -> AccessPolicy:
|
||||
policy = AccessPolicy(**kwargs)
|
||||
db.add(policy)
|
||||
await db.flush()
|
||||
await db.refresh(policy)
|
||||
logger.info('Created access policy', policy_id=policy.id, name=policy.name, effect=policy.effect)
|
||||
return policy
|
||||
|
||||
@staticmethod
|
||||
async def update(db: AsyncSession, policy_id: int, **kwargs: object) -> AccessPolicy | None:
|
||||
"""Update only provided fields. Rejects unknown/non-updatable keys."""
|
||||
policy = await AccessPolicyCRUD.get_by_id(db, policy_id)
|
||||
if not policy:
|
||||
return None
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if key not in _POLICY_UPDATABLE_FIELDS:
|
||||
logger.warning('Rejected update of non-updatable AccessPolicy field', field=key)
|
||||
continue
|
||||
setattr(policy, key, value)
|
||||
|
||||
await db.flush()
|
||||
await db.refresh(policy)
|
||||
logger.info('Updated access policy', policy_id=policy_id, fields=list(kwargs.keys()))
|
||||
return policy
|
||||
|
||||
@staticmethod
|
||||
async def delete(db: AsyncSession, policy_id: int) -> bool:
|
||||
policy = await AccessPolicyCRUD.get_by_id(db, policy_id)
|
||||
if not policy:
|
||||
return False
|
||||
await db.delete(policy)
|
||||
await db.flush()
|
||||
logger.info('Deleted access policy', policy_id=policy_id, name=policy.name)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
async def get_policies_for_user(
|
||||
db: AsyncSession,
|
||||
role_ids: list[int],
|
||||
) -> list[AccessPolicy]:
|
||||
"""Get active policies matching any of the given role_ids OR global (role_id IS NULL).
|
||||
|
||||
Ordered by priority descending for correct evaluation order.
|
||||
"""
|
||||
if not role_ids:
|
||||
# Only global policies
|
||||
stmt = (
|
||||
select(AccessPolicy)
|
||||
.where(
|
||||
AccessPolicy.is_active.is_(True),
|
||||
AccessPolicy.role_id.is_(None),
|
||||
)
|
||||
.order_by(AccessPolicy.priority.desc())
|
||||
)
|
||||
else:
|
||||
stmt = (
|
||||
select(AccessPolicy)
|
||||
.where(
|
||||
AccessPolicy.is_active.is_(True),
|
||||
or_(
|
||||
AccessPolicy.role_id.in_(role_ids),
|
||||
AccessPolicy.role_id.is_(None),
|
||||
),
|
||||
)
|
||||
.order_by(AccessPolicy.priority.desc())
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
class AuditLogCRUD:
|
||||
"""Create + filtered query for admin_audit_log table."""
|
||||
|
||||
@staticmethod
|
||||
async def create(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: int,
|
||||
action: str,
|
||||
resource_type: str | None = None,
|
||||
resource_id: str | None = None,
|
||||
details: dict | None = None,
|
||||
ip_address: str | None = None,
|
||||
user_agent: str | None = None,
|
||||
status: str = 'success',
|
||||
request_method: str | None = None,
|
||||
request_path: str | None = None,
|
||||
) -> AdminAuditLog:
|
||||
entry = AdminAuditLog(
|
||||
user_id=user_id,
|
||||
action=action,
|
||||
resource_type=resource_type,
|
||||
resource_id=resource_id,
|
||||
details=details,
|
||||
ip_address=ip_address,
|
||||
user_agent=user_agent,
|
||||
status=status,
|
||||
request_method=request_method,
|
||||
request_path=request_path,
|
||||
)
|
||||
db.add(entry)
|
||||
await db.flush()
|
||||
await db.refresh(entry)
|
||||
logger.debug(
|
||||
'Audit log created',
|
||||
audit_id=entry.id,
|
||||
user_id=user_id,
|
||||
action=action,
|
||||
status=status,
|
||||
)
|
||||
return entry
|
||||
|
||||
@staticmethod
|
||||
async def get_logs(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
action: str | None = None,
|
||||
resource_type: str | None = None,
|
||||
status: str | None = None,
|
||||
date_from: datetime | None = None,
|
||||
date_to: datetime | None = None,
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
load_user: bool = False,
|
||||
) -> tuple[list[AdminAuditLog], int]:
|
||||
"""Get filtered audit logs with total count.
|
||||
|
||||
Returns:
|
||||
(logs, total_count)
|
||||
"""
|
||||
filters = []
|
||||
if user_id is not None:
|
||||
filters.append(AdminAuditLog.user_id == user_id)
|
||||
if action is not None:
|
||||
filters.append(AdminAuditLog.action.ilike(f'%{action}%'))
|
||||
if resource_type is not None:
|
||||
filters.append(AdminAuditLog.resource_type == resource_type)
|
||||
if status is not None:
|
||||
filters.append(AdminAuditLog.status == status)
|
||||
if date_from is not None:
|
||||
filters.append(AdminAuditLog.created_at >= date_from)
|
||||
if date_to is not None:
|
||||
filters.append(AdminAuditLog.created_at <= date_to)
|
||||
|
||||
where_clause = and_(*filters) if filters else True
|
||||
|
||||
# Total count
|
||||
count_result = await db.execute(select(func.count(AdminAuditLog.id)).where(where_clause))
|
||||
total_count = count_result.scalar() or 0
|
||||
|
||||
# Paginated results
|
||||
stmt = (
|
||||
select(AdminAuditLog)
|
||||
.where(where_clause)
|
||||
.order_by(AdminAuditLog.created_at.desc())
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
)
|
||||
if load_user:
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
stmt = stmt.options(selectinload(AdminAuditLog.user))
|
||||
result = await db.execute(stmt)
|
||||
logs = list(result.scalars().all())
|
||||
|
||||
return logs, total_count
|
||||
@@ -5,7 +5,7 @@ from sqlalchemy import and_, func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.database.models import AdvertisingCampaignRegistration, ReferralEarning, User
|
||||
from app.database.models import AdvertisingCampaignRegistration, ReferralEarning, Subscription, SubscriptionStatus, User
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
@@ -89,7 +89,7 @@ async def get_referral_earnings_sum(
|
||||
query = query.where(ReferralEarning.created_at <= end_date)
|
||||
|
||||
result = await db.execute(query)
|
||||
return result.scalar()
|
||||
return result.scalar() or 0
|
||||
|
||||
|
||||
async def get_referral_statistics(db: AsyncSession) -> dict:
|
||||
@@ -104,18 +104,7 @@ async def get_referral_statistics(db: AsyncSession) -> dict:
|
||||
active_referrers = active_referrers_result.scalar()
|
||||
|
||||
referral_paid_result = await db.execute(select(func.coalesce(func.sum(ReferralEarning.amount_kopeks), 0)))
|
||||
referral_paid = referral_paid_result.scalar()
|
||||
|
||||
from app.database.models import Transaction, TransactionType
|
||||
|
||||
transaction_paid_result = await db.execute(
|
||||
select(func.coalesce(func.sum(Transaction.amount_kopeks), 0)).where(
|
||||
Transaction.type == TransactionType.REFERRAL_REWARD.value
|
||||
)
|
||||
)
|
||||
transaction_paid = transaction_paid_result.scalar()
|
||||
|
||||
total_paid = referral_paid + transaction_paid
|
||||
total_paid = referral_paid_result.scalar()
|
||||
|
||||
referrals_stats_result = await db.execute(
|
||||
select(User.referred_by_id.label('referrer_id'), func.count(User.id).label('referrals_count'))
|
||||
@@ -132,15 +121,6 @@ async def get_referral_statistics(db: AsyncSession) -> dict:
|
||||
)
|
||||
referral_earnings = {row.referrer_id: row.referral_earnings for row in referral_earnings_result.all()}
|
||||
|
||||
transaction_earnings_result = await db.execute(
|
||||
select(
|
||||
Transaction.user_id.label('referrer_id'), func.sum(Transaction.amount_kopeks).label('transaction_earnings')
|
||||
)
|
||||
.where(Transaction.type == TransactionType.REFERRAL_REWARD.value)
|
||||
.group_by(Transaction.user_id)
|
||||
)
|
||||
transaction_earnings = {row.referrer_id: row.transaction_earnings for row in transaction_earnings_result.all()}
|
||||
|
||||
top_referrers_data = {}
|
||||
|
||||
for referrer_id, count in referrals_stats.items():
|
||||
@@ -153,11 +133,6 @@ async def get_referral_statistics(db: AsyncSession) -> dict:
|
||||
top_referrers_data[referrer_id] = {'referrals_count': 0, 'total_earned': 0}
|
||||
top_referrers_data[referrer_id]['total_earned'] += earnings or 0
|
||||
|
||||
for referrer_id, earnings in transaction_earnings.items():
|
||||
if referrer_id not in top_referrers_data:
|
||||
top_referrers_data[referrer_id] = {'referrals_count': 0, 'total_earned': 0}
|
||||
top_referrers_data[referrer_id]['total_earned'] += earnings or 0
|
||||
|
||||
sorted_referrers = sorted(
|
||||
top_referrers_data.items(), key=lambda x: (x[1]['total_earned'], x[1]['referrals_count']), reverse=True
|
||||
)
|
||||
@@ -197,37 +172,22 @@ async def get_referral_statistics(db: AsyncSession) -> dict:
|
||||
|
||||
today = datetime.now(UTC).replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
today_referral_earnings_result = await db.execute(
|
||||
today_earnings_result = await db.execute(
|
||||
select(func.coalesce(func.sum(ReferralEarning.amount_kopeks), 0)).where(ReferralEarning.created_at >= today)
|
||||
)
|
||||
today_transaction_earnings_result = await db.execute(
|
||||
select(func.coalesce(func.sum(Transaction.amount_kopeks), 0)).where(
|
||||
and_(Transaction.type == TransactionType.REFERRAL_REWARD.value, Transaction.created_at >= today)
|
||||
)
|
||||
)
|
||||
today_earnings = today_referral_earnings_result.scalar() + today_transaction_earnings_result.scalar()
|
||||
today_earnings = today_earnings_result.scalar()
|
||||
|
||||
week_ago = datetime.now(UTC) - timedelta(days=7)
|
||||
week_referral_earnings_result = await db.execute(
|
||||
week_earnings_result = await db.execute(
|
||||
select(func.coalesce(func.sum(ReferralEarning.amount_kopeks), 0)).where(ReferralEarning.created_at >= week_ago)
|
||||
)
|
||||
week_transaction_earnings_result = await db.execute(
|
||||
select(func.coalesce(func.sum(Transaction.amount_kopeks), 0)).where(
|
||||
and_(Transaction.type == TransactionType.REFERRAL_REWARD.value, Transaction.created_at >= week_ago)
|
||||
)
|
||||
)
|
||||
week_earnings = week_referral_earnings_result.scalar() + week_transaction_earnings_result.scalar()
|
||||
week_earnings = week_earnings_result.scalar()
|
||||
|
||||
month_ago = datetime.now(UTC) - timedelta(days=30)
|
||||
month_referral_earnings_result = await db.execute(
|
||||
month_earnings_result = await db.execute(
|
||||
select(func.coalesce(func.sum(ReferralEarning.amount_kopeks), 0)).where(ReferralEarning.created_at >= month_ago)
|
||||
)
|
||||
month_transaction_earnings_result = await db.execute(
|
||||
select(func.coalesce(func.sum(Transaction.amount_kopeks), 0)).where(
|
||||
and_(Transaction.type == TransactionType.REFERRAL_REWARD.value, Transaction.created_at >= month_ago)
|
||||
)
|
||||
)
|
||||
month_earnings = month_referral_earnings_result.scalar() + month_transaction_earnings_result.scalar()
|
||||
month_earnings = month_earnings_result.scalar()
|
||||
|
||||
logger.info(
|
||||
'Реферальная статистика: рефералов, рефереров, выплачено копеек',
|
||||
@@ -264,8 +224,6 @@ async def get_top_referrers_by_period(
|
||||
Returns:
|
||||
Список словарей с данными рефереров
|
||||
"""
|
||||
from app.database.models import Transaction, TransactionType
|
||||
|
||||
now = datetime.now(UTC)
|
||||
if period == 'week':
|
||||
start_date = now - timedelta(days=7)
|
||||
@@ -292,18 +250,6 @@ async def get_top_referrers_by_period(
|
||||
)
|
||||
earnings = earnings_result.scalar() or 0
|
||||
|
||||
# Добавляем транзакции REFERRAL_REWARD
|
||||
trans_earnings_result = await db.execute(
|
||||
select(func.coalesce(func.sum(Transaction.amount_kopeks), 0)).where(
|
||||
and_(
|
||||
Transaction.user_id == row.referrer_id,
|
||||
Transaction.type == TransactionType.REFERRAL_REWARD.value,
|
||||
Transaction.created_at >= start_date,
|
||||
)
|
||||
)
|
||||
)
|
||||
earnings += trans_earnings_result.scalar() or 0
|
||||
|
||||
top_data.append(
|
||||
{'referrer_id': row.referrer_id, 'invited_count': row.invited_count, 'earnings_kopeks': earnings}
|
||||
)
|
||||
@@ -320,27 +266,8 @@ async def get_top_referrers_by_period(
|
||||
)
|
||||
referral_earnings = {row.referrer_id: row.ref_earnings for row in referral_earnings_result}
|
||||
|
||||
# Добавляем транзакции REFERRAL_REWARD
|
||||
transaction_earnings_result = await db.execute(
|
||||
select(
|
||||
Transaction.user_id.label('referrer_id'), func.sum(Transaction.amount_kopeks).label('trans_earnings')
|
||||
)
|
||||
.where(
|
||||
and_(Transaction.type == TransactionType.REFERRAL_REWARD.value, Transaction.created_at >= start_date)
|
||||
)
|
||||
.group_by(Transaction.user_id)
|
||||
)
|
||||
|
||||
# Объединяем заработки
|
||||
combined_earnings = dict(referral_earnings)
|
||||
for row in transaction_earnings_result:
|
||||
if row.referrer_id in combined_earnings:
|
||||
combined_earnings[row.referrer_id] += row.trans_earnings or 0
|
||||
else:
|
||||
combined_earnings[row.referrer_id] = row.trans_earnings or 0
|
||||
|
||||
# Сортируем и берём топ
|
||||
sorted_referrers = sorted(combined_earnings.items(), key=lambda x: x[1], reverse=True)[:limit]
|
||||
sorted_referrers = sorted(referral_earnings.items(), key=lambda x: x[1], reverse=True)[:limit]
|
||||
|
||||
top_data = []
|
||||
for referrer_id, earnings in sorted_referrers:
|
||||
@@ -400,22 +327,18 @@ async def get_user_referral_stats(db: AsyncSession, user_id: int) -> dict:
|
||||
month_ago = datetime.now(UTC) - timedelta(days=30)
|
||||
month_earned = await get_referral_earnings_sum(db, user_id, start_date=month_ago)
|
||||
|
||||
from app.database.models import Subscription, SubscriptionStatus
|
||||
|
||||
current_time = datetime.now(UTC)
|
||||
|
||||
active_referrals_result = await db.execute(
|
||||
select(func.count(User.id))
|
||||
select(func.count(func.distinct(User.id)))
|
||||
.join(Subscription, User.id == Subscription.user_id)
|
||||
.where(
|
||||
and_(
|
||||
User.referred_by_id == user_id,
|
||||
Subscription.status == SubscriptionStatus.ACTIVE.value,
|
||||
Subscription.end_date > current_time,
|
||||
Subscription.end_date > func.now(),
|
||||
)
|
||||
)
|
||||
)
|
||||
active_referrals = active_referrals_result.scalar()
|
||||
active_referrals = active_referrals_result.scalar() or 0
|
||||
|
||||
return {
|
||||
'invited_count': invited_count,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from collections.abc import Sequence
|
||||
from datetime import UTC, date, datetime, time
|
||||
from datetime import UTC, date, datetime, time, timedelta
|
||||
|
||||
import structlog
|
||||
from sqlalchemy import and_, desc, func, select
|
||||
@@ -120,18 +120,29 @@ async def get_contests_for_events(
|
||||
*,
|
||||
contest_types: list[str] | None = None,
|
||||
) -> list[ReferralContest]:
|
||||
# Расширяем SQL-фильтр на 1 день для полночных end_at (нормализуются в 23:59:59)
|
||||
query = select(ReferralContest).where(
|
||||
and_(
|
||||
ReferralContest.is_active.is_(True),
|
||||
ReferralContest.start_at <= now_utc,
|
||||
ReferralContest.end_at >= now_utc,
|
||||
ReferralContest.end_at >= now_utc - timedelta(days=1),
|
||||
)
|
||||
)
|
||||
if contest_types:
|
||||
query = query.where(ReferralContest.contest_type.in_(contest_types))
|
||||
|
||||
result = await db.execute(query)
|
||||
return list(result.scalars().all())
|
||||
contests = list(result.scalars().all())
|
||||
|
||||
# Точная фильтрация с нормализацией полночных end_at
|
||||
filtered = []
|
||||
for contest in contests:
|
||||
contest_end = contest.end_at
|
||||
if contest_end.hour == 0 and contest_end.minute == 0 and contest_end.second == 0:
|
||||
contest_end = contest_end.replace(hour=23, minute=59, second=59, microsecond=999999)
|
||||
if contest_end >= now_utc:
|
||||
filtered.append(contest)
|
||||
return filtered
|
||||
|
||||
|
||||
async def get_contests_for_summaries(db: AsyncSession) -> list[ReferralContest]:
|
||||
@@ -148,7 +159,7 @@ async def add_contest_event(
|
||||
amount_kopeks: int = 0,
|
||||
event_type: str = 'subscription_purchase',
|
||||
) -> ReferralContestEvent | None:
|
||||
existing = await db.execute(
|
||||
existing_result = await db.execute(
|
||||
select(ReferralContestEvent).where(
|
||||
and_(
|
||||
ReferralContestEvent.contest_id == contest_id,
|
||||
@@ -156,7 +167,13 @@ async def add_contest_event(
|
||||
)
|
||||
)
|
||||
)
|
||||
if existing.scalar_one_or_none():
|
||||
existing = existing_result.scalar_one_or_none()
|
||||
if existing:
|
||||
# Обновляем amount_kopeks если повторная покупка (upsert)
|
||||
if amount_kopeks and existing.amount_kopeks != amount_kopeks:
|
||||
existing.amount_kopeks = amount_kopeks
|
||||
await db.commit()
|
||||
await db.refresh(existing)
|
||||
return None
|
||||
|
||||
event = ReferralContestEvent(
|
||||
@@ -197,7 +214,7 @@ async def get_contest_leaderboard(
|
||||
select(
|
||||
User,
|
||||
func.count(ReferralContestEvent.id).label('referral_count'),
|
||||
func.coalesce(func.sum(ReferralContestEvent.amount_kopeks), 0).label('total_amount'),
|
||||
func.coalesce(func.sum(func.abs(ReferralContestEvent.amount_kopeks)), 0).label('total_amount'),
|
||||
)
|
||||
.join(User, User.id == ReferralContestEvent.referrer_id)
|
||||
.where(
|
||||
@@ -383,7 +400,7 @@ async def get_contest_payment_stats(
|
||||
|
||||
# Общая сумма (только за рефералов зарегистрированных в период конкурса)
|
||||
total_result = await db.execute(
|
||||
select(func.coalesce(func.sum(ReferralContestEvent.amount_kopeks), 0)).where(
|
||||
select(func.coalesce(func.sum(func.abs(ReferralContestEvent.amount_kopeks)), 0)).where(
|
||||
and_(
|
||||
ReferralContestEvent.contest_id == contest_id,
|
||||
ReferralContestEvent.occurred_at >= contest_start,
|
||||
|
||||
@@ -12,7 +12,17 @@ from app.database.models import RequiredChannel, UserChannelSubscription
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
# Explicit allowlist of fields that can be updated via update_channel()
|
||||
_UPDATABLE_FIELDS = frozenset({'channel_id', 'channel_link', 'title', 'is_active', 'sort_order'})
|
||||
_UPDATABLE_FIELDS = frozenset(
|
||||
{
|
||||
'channel_id',
|
||||
'channel_link',
|
||||
'title',
|
||||
'is_active',
|
||||
'sort_order',
|
||||
'disable_trial_on_leave',
|
||||
'disable_paid_on_leave',
|
||||
}
|
||||
)
|
||||
|
||||
# Validation patterns for channel_id
|
||||
_CHANNEL_ID_NUMERIC = re.compile(r'^-100\d{10,13}$')
|
||||
@@ -69,12 +79,16 @@ async def add_channel(
|
||||
channel_id: str,
|
||||
channel_link: str | None = None,
|
||||
title: str | None = None,
|
||||
disable_trial_on_leave: bool = True,
|
||||
disable_paid_on_leave: bool = False,
|
||||
) -> RequiredChannel:
|
||||
channel_id = validate_channel_id(channel_id)
|
||||
channel = RequiredChannel(
|
||||
channel_id=channel_id,
|
||||
channel_link=channel_link,
|
||||
title=title,
|
||||
disable_trial_on_leave=disable_trial_on_leave,
|
||||
disable_paid_on_leave=disable_paid_on_leave,
|
||||
)
|
||||
db.add(channel)
|
||||
await db.commit()
|
||||
|
||||
@@ -15,6 +15,8 @@ from app.database.models import (
|
||||
Subscription,
|
||||
SubscriptionServer,
|
||||
SubscriptionStatus,
|
||||
Transaction,
|
||||
TransactionType,
|
||||
User,
|
||||
UserPromoGroup,
|
||||
UserStatus,
|
||||
@@ -279,6 +281,11 @@ async def replace_subscription(
|
||||
subscription.end_date = current_time + timedelta(days=duration_days)
|
||||
subscription.traffic_limit_gb = traffic_limit_gb
|
||||
subscription.traffic_used_gb = 0.0
|
||||
|
||||
# Удаляем записи TrafficPurchase перед сбросом purchased_traffic_gb
|
||||
from app.database.models import TrafficPurchase
|
||||
|
||||
await db.execute(delete(TrafficPurchase).where(TrafficPurchase.subscription_id == subscription.id))
|
||||
subscription.purchased_traffic_gb = 0 # Сбрасываем докупленный трафик при замене подписки
|
||||
subscription.traffic_reset_at = None # Сбрасываем дату сброса трафика
|
||||
subscription.device_limit = device_limit
|
||||
@@ -354,6 +361,8 @@ async def extend_subscription(
|
||||
device_limit: Лимит устройств (опционально, для режима тарифов)
|
||||
connected_squads: Список UUID сквадов (опционально, для режима тарифов)
|
||||
"""
|
||||
from app.database.models import TrafficPurchase
|
||||
|
||||
current_time = datetime.now(UTC)
|
||||
|
||||
logger.info('🔄 Продление подписки на дней', subscription_id=subscription.id, days=days)
|
||||
@@ -368,6 +377,12 @@ async def extend_subscription(
|
||||
# Включает переход из классического режима (tariff_id=None) в тарифный
|
||||
is_tariff_change = tariff_id is not None and (subscription.tariff_id is None or tariff_id != subscription.tariff_id)
|
||||
|
||||
# Определяем, была ли подписка истёкшей ДО продления (статус меняется ниже)
|
||||
was_expired = subscription.status in (
|
||||
SubscriptionStatus.EXPIRED.value,
|
||||
SubscriptionStatus.DISABLED.value,
|
||||
) or (subscription.end_date is not None and subscription.end_date <= current_time)
|
||||
|
||||
if is_tariff_change:
|
||||
logger.info('🔄 Обнаружена СМЕНА тарифа: →', tariff_id=subscription.tariff_id, tariff_id_2=tariff_id)
|
||||
|
||||
@@ -428,6 +443,9 @@ async def extend_subscription(
|
||||
logger.info(
|
||||
'🔄 Статус подписки изменён с на ACTIVE', subscription_id=subscription.id, previous_status=previous_status
|
||||
)
|
||||
elif days > 0 and subscription.status == SubscriptionStatus.TRIAL.value:
|
||||
subscription.status = SubscriptionStatus.ACTIVE.value
|
||||
logger.info('🔄 Статус подписки изменён с trial на ACTIVE', subscription_id=subscription.id)
|
||||
elif days > 0 and subscription.status == SubscriptionStatus.PENDING.value:
|
||||
logger.warning('⚠️ Попытка продлить PENDING подписку , дни', subscription_id=subscription.id, days=days)
|
||||
|
||||
@@ -444,25 +462,28 @@ async def extend_subscription(
|
||||
|
||||
if traffic_limit_gb is not None:
|
||||
old_traffic = subscription.traffic_limit_gb
|
||||
subscription.traffic_used_gb = 0.0
|
||||
|
||||
# Сброс использованного трафика: при смене тарифа — по настройке, при продлении — всегда
|
||||
if is_tariff_change:
|
||||
# При СМЕНЕ тарифа сбрасываем все докупки трафика
|
||||
if settings.RESET_TRAFFIC_ON_TARIFF_SWITCH:
|
||||
subscription.traffic_used_gb = 0.0
|
||||
else:
|
||||
subscription.traffic_used_gb = 0.0
|
||||
|
||||
if is_tariff_change or was_expired:
|
||||
# При СМЕНЕ тарифа или ИСТЁКШЕЙ подписке — сбрасываем все докупки трафика
|
||||
subscription.traffic_limit_gb = traffic_limit_gb
|
||||
from sqlalchemy import delete as sql_delete
|
||||
|
||||
from app.database.models import TrafficPurchase
|
||||
|
||||
await db.execute(sql_delete(TrafficPurchase).where(TrafficPurchase.subscription_id == subscription.id))
|
||||
await db.execute(delete(TrafficPurchase).where(TrafficPurchase.subscription_id == subscription.id))
|
||||
subscription.purchased_traffic_gb = 0
|
||||
subscription.traffic_reset_at = None
|
||||
reason = 'смена тарифа' if is_tariff_change else 'подписка была истёкшей'
|
||||
logger.info(
|
||||
'📊 Обновлен лимит трафика: ГБ → ГБ (смена тарифа, докупки сброшены)',
|
||||
'📊 Обновлен лимит трафика: ГБ → ГБ (докупки сброшены)',
|
||||
old_traffic=old_traffic,
|
||||
traffic_limit_gb=traffic_limit_gb,
|
||||
reason=reason,
|
||||
)
|
||||
else:
|
||||
# При ПРОДЛЕНИИ того же тарифа — сохраняем докупленный трафик
|
||||
# Подписка активна, тот же тариф — сохраняем докупленный трафик
|
||||
purchased = subscription.purchased_traffic_gb or 0
|
||||
subscription.traffic_limit_gb = traffic_limit_gb + purchased
|
||||
logger.info(
|
||||
@@ -473,13 +494,18 @@ async def extend_subscription(
|
||||
)
|
||||
elif settings.RESET_TRAFFIC_ON_PAYMENT:
|
||||
subscription.traffic_used_gb = 0.0
|
||||
# В режиме тарифов сохраняем докупленный трафик при продлении
|
||||
if subscription.tariff_id is None:
|
||||
if subscription.tariff_id is None or was_expired:
|
||||
# Классический режим или истёкшая подписка — сбрасываем докупки
|
||||
await db.execute(delete(TrafficPurchase).where(TrafficPurchase.subscription_id == subscription.id))
|
||||
subscription.purchased_traffic_gb = 0
|
||||
subscription.traffic_reset_at = None # Сбрасываем дату сброса трафика
|
||||
logger.info('🔄 Сбрасываем использованный и докупленный трафик согласно настройке RESET_TRAFFIC_ON_PAYMENT')
|
||||
subscription.traffic_reset_at = None
|
||||
logger.info(
|
||||
'🔄 Сбрасываем использованный и докупленный трафик',
|
||||
was_expired=was_expired,
|
||||
tariff_id=subscription.tariff_id,
|
||||
)
|
||||
else:
|
||||
# При продлении в режиме тарифов - сохраняем purchased_traffic_gb и traffic_reset_at
|
||||
# Активная подписка в режиме тарифов — сохраняем purchased_traffic_gb и traffic_reset_at
|
||||
logger.info('🔄 Сбрасываем использованный трафик, докупленный сохранен (режим тарифов)')
|
||||
|
||||
if device_limit is not None:
|
||||
@@ -522,6 +548,7 @@ async def extend_subscription(
|
||||
old_limit = subscription.traffic_limit_gb
|
||||
if subscription.traffic_limit_gb != fixed_limit or (subscription.purchased_traffic_gb or 0) > 0:
|
||||
subscription.traffic_limit_gb = fixed_limit
|
||||
await db.execute(delete(TrafficPurchase).where(TrafficPurchase.subscription_id == subscription.id))
|
||||
subscription.purchased_traffic_gb = 0
|
||||
subscription.traffic_reset_at = None # Сбрасываем дату сброса трафика
|
||||
logger.info(
|
||||
@@ -589,7 +616,29 @@ async def add_subscription_traffic(db: AsyncSession, subscription: Subscription,
|
||||
|
||||
|
||||
async def add_subscription_devices(db: AsyncSession, subscription: Subscription, devices: int) -> Subscription:
|
||||
subscription.device_limit += devices
|
||||
# Lock subscription to prevent concurrent modifications
|
||||
locked_result = await db.execute(
|
||||
select(Subscription)
|
||||
.where(Subscription.id == subscription.id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
subscription = locked_result.scalar_one()
|
||||
|
||||
# Check max device limit
|
||||
max_devices = settings.MAX_DEVICES_LIMIT
|
||||
new_limit = (subscription.device_limit or 1) + devices
|
||||
if max_devices > 0 and new_limit > max_devices:
|
||||
logger.warning(
|
||||
'📱 Попытка превысить лимит устройств',
|
||||
user_id=subscription.user_id,
|
||||
current=subscription.device_limit,
|
||||
requested=devices,
|
||||
max_devices=max_devices,
|
||||
)
|
||||
new_limit = max_devices
|
||||
|
||||
subscription.device_limit = new_limit
|
||||
subscription.updated_at = datetime.now(UTC)
|
||||
|
||||
await db.commit()
|
||||
@@ -739,18 +788,26 @@ async def reactivate_subscription(db: AsyncSession, subscription: Subscription)
|
||||
|
||||
|
||||
async def get_expiring_subscriptions(db: AsyncSession, days_before: int = 3) -> list[Subscription]:
|
||||
from app.database.models import Tariff
|
||||
|
||||
threshold_date = datetime.now(UTC) + timedelta(days=days_before)
|
||||
|
||||
result = await db.execute(
|
||||
select(Subscription)
|
||||
.join(User, Subscription.user_id == User.id)
|
||||
.options(selectinload(Subscription.user))
|
||||
.outerjoin(Tariff, Subscription.tariff_id == Tariff.id)
|
||||
.options(selectinload(Subscription.user), selectinload(Subscription.tariff))
|
||||
.where(
|
||||
and_(
|
||||
Subscription.status == SubscriptionStatus.ACTIVE.value,
|
||||
User.status == UserStatus.ACTIVE.value,
|
||||
Subscription.end_date <= threshold_date,
|
||||
Subscription.end_date > datetime.now(UTC),
|
||||
# Не включаем активные суточные подписки — у них end_date всегда +24ч
|
||||
~and_(
|
||||
Tariff.is_daily.is_(True),
|
||||
Subscription.is_daily_paused.is_(False),
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -758,15 +815,23 @@ async def get_expiring_subscriptions(db: AsyncSession, days_before: int = 3) ->
|
||||
|
||||
|
||||
async def get_expired_subscriptions(db: AsyncSession) -> list[Subscription]:
|
||||
from app.database.models import Tariff
|
||||
|
||||
result = await db.execute(
|
||||
select(Subscription)
|
||||
.join(User, Subscription.user_id == User.id)
|
||||
.options(selectinload(Subscription.user))
|
||||
.outerjoin(Tariff, Subscription.tariff_id == Tariff.id)
|
||||
.options(selectinload(Subscription.user), selectinload(Subscription.tariff))
|
||||
.where(
|
||||
and_(
|
||||
Subscription.status == SubscriptionStatus.ACTIVE.value,
|
||||
User.status == UserStatus.ACTIVE.value,
|
||||
Subscription.end_date <= datetime.now(UTC),
|
||||
# Не трогаем активные суточные подписки — ими управляет DailySubscriptionService
|
||||
~and_(
|
||||
Tariff.is_daily.is_(True),
|
||||
Subscription.is_daily_paused.is_(False),
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -827,29 +892,43 @@ async def get_subscriptions_statistics(db: AsyncSession) -> dict:
|
||||
|
||||
paid_subscriptions = active_subscriptions - trial_subscriptions
|
||||
|
||||
today = datetime.now(UTC).date()
|
||||
now = datetime.now(UTC)
|
||||
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
week_ago = today_start - timedelta(days=7)
|
||||
month_ago = today_start - timedelta(days=30)
|
||||
|
||||
today_result = await db.execute(
|
||||
select(func.count(Subscription.id)).where(
|
||||
and_(Subscription.created_at >= today, Subscription.is_trial == False)
|
||||
select(func.count(Transaction.id)).where(
|
||||
and_(
|
||||
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
|
||||
Transaction.is_completed.is_(True),
|
||||
Transaction.created_at >= today_start,
|
||||
)
|
||||
)
|
||||
)
|
||||
purchased_today = today_result.scalar()
|
||||
purchased_today = today_result.scalar() or 0
|
||||
|
||||
week_ago = datetime.now(UTC) - timedelta(days=7)
|
||||
week_result = await db.execute(
|
||||
select(func.count(Subscription.id)).where(
|
||||
and_(Subscription.created_at >= week_ago, Subscription.is_trial == False)
|
||||
select(func.count(Transaction.id)).where(
|
||||
and_(
|
||||
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
|
||||
Transaction.is_completed.is_(True),
|
||||
Transaction.created_at >= week_ago,
|
||||
)
|
||||
)
|
||||
)
|
||||
purchased_week = week_result.scalar()
|
||||
purchased_week = week_result.scalar() or 0
|
||||
|
||||
month_ago = datetime.now(UTC) - timedelta(days=30)
|
||||
month_result = await db.execute(
|
||||
select(func.count(Subscription.id)).where(
|
||||
and_(Subscription.created_at >= month_ago, Subscription.is_trial == False)
|
||||
select(func.count(Transaction.id)).where(
|
||||
and_(
|
||||
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
|
||||
Transaction.is_completed.is_(True),
|
||||
Transaction.created_at >= month_ago,
|
||||
)
|
||||
)
|
||||
)
|
||||
purchased_month = month_result.scalar()
|
||||
purchased_month = month_result.scalar() or 0
|
||||
|
||||
try:
|
||||
from app.database.crud.subscription_conversion import get_conversion_statistics
|
||||
@@ -1002,7 +1081,7 @@ async def get_all_subscriptions(db: AsyncSession, page: int = 1, limit: int = 10
|
||||
|
||||
result = await db.execute(
|
||||
select(Subscription)
|
||||
.options(selectinload(Subscription.user))
|
||||
.options(selectinload(Subscription.user), selectinload(Subscription.tariff))
|
||||
.order_by(Subscription.created_at.desc())
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
@@ -1018,10 +1097,10 @@ async def get_subscriptions_batch(
|
||||
offset: int = 0,
|
||||
limit: int = 500,
|
||||
) -> list[Subscription]:
|
||||
"""Получает подписки пачками для синхронизации. Загружает связанных пользователей."""
|
||||
"""Получает подписки пачками для синхронизации. Загружает связанных пользователей и тарифы."""
|
||||
result = await db.execute(
|
||||
select(Subscription)
|
||||
.options(selectinload(Subscription.user))
|
||||
.options(selectinload(Subscription.user), selectinload(Subscription.tariff))
|
||||
.order_by(Subscription.id)
|
||||
.offset(offset)
|
||||
.limit(limit)
|
||||
@@ -1383,11 +1462,26 @@ async def get_subscription_renewal_cost(
|
||||
total_servers_discount = servers_discount_per_month * months_in_period
|
||||
|
||||
# В режиме fixed_with_topup при продлении используем фиксированный лимит
|
||||
purchased_traffic = subscription.purchased_traffic_gb or 0
|
||||
if settings.is_traffic_fixed():
|
||||
renewal_traffic_gb = settings.get_fixed_traffic_limit()
|
||||
traffic_price_per_month = settings.get_traffic_price(settings.get_fixed_traffic_limit())
|
||||
# Separate base traffic from purchased to avoid wrong tier lookup
|
||||
elif purchased_traffic > 0:
|
||||
base_traffic_gb = (subscription.traffic_limit_gb or 0) - purchased_traffic
|
||||
if base_traffic_gb <= 0:
|
||||
logger.warning(
|
||||
'Purchased traffic >= total limit, pricing purchased portion only',
|
||||
subscription_id=subscription.id,
|
||||
traffic_limit_gb=subscription.traffic_limit_gb,
|
||||
purchased_traffic_gb=purchased_traffic,
|
||||
)
|
||||
traffic_price_per_month = settings.get_traffic_price(purchased_traffic)
|
||||
else:
|
||||
traffic_price_per_month = settings.get_traffic_price(base_traffic_gb) + settings.get_traffic_price(
|
||||
purchased_traffic
|
||||
)
|
||||
else:
|
||||
renewal_traffic_gb = subscription.traffic_limit_gb
|
||||
traffic_price_per_month = settings.get_traffic_price(renewal_traffic_gb)
|
||||
traffic_price_per_month = settings.get_traffic_price(subscription.traffic_limit_gb)
|
||||
traffic_discount_percent = _get_discount_percent(
|
||||
user,
|
||||
promo_group,
|
||||
@@ -1565,6 +1659,19 @@ async def check_and_update_subscription_status(db: AsyncSession, subscription: S
|
||||
logger.info('⏸️ Суточная подписка на паузе, пропускаем проверку истечения', subscription_id=subscription.id)
|
||||
return subscription
|
||||
|
||||
# Активные суточные подписки управляются DailySubscriptionService — не экспайрим их тут.
|
||||
# end_date у них всего +24ч, и между проверками (30 мин) она может формально истечь.
|
||||
# Используем getattr(subscription, 'tariff', None) вместо property is_daily_tariff,
|
||||
# т.к. property может вызвать MissingGreenlet при ленивой загрузке в async-контексте.
|
||||
tariff = getattr(subscription, 'tariff', None)
|
||||
is_active_daily = tariff is not None and getattr(tariff, 'is_daily', False) and not is_daily_paused
|
||||
if is_active_daily:
|
||||
logger.debug(
|
||||
'⏩ Активная суточная подписка — пропускаем проверку истечения (управляет DailySubscriptionService)',
|
||||
subscription_id=subscription.id,
|
||||
)
|
||||
return subscription
|
||||
|
||||
if subscription.status == SubscriptionStatus.ACTIVE.value and subscription.end_date <= current_time:
|
||||
# Детальное логирование для отладки проблемы с деактивацией
|
||||
time_diff = current_time - subscription.end_date
|
||||
@@ -2001,6 +2108,55 @@ async def get_disabled_daily_subscriptions_for_resume(
|
||||
return list(subscriptions)
|
||||
|
||||
|
||||
async def get_expired_daily_subscriptions_for_recovery(db: AsyncSession) -> list[Subscription]:
|
||||
"""
|
||||
Получает EXPIRED суточные подписки, которые были ошибочно экспайрены
|
||||
middleware или check_and_update_subscription_status.
|
||||
|
||||
Суточные подписки не должны экспайриться — ими управляет DailySubscriptionService.
|
||||
Если баланс пользователя достаточен, подписку нужно восстановить и списать.
|
||||
"""
|
||||
from app.database.models import Tariff
|
||||
|
||||
# Берём только недавно экспайренные (до 24ч) — старые не трогаем
|
||||
recovery_threshold = datetime.now(UTC) - timedelta(hours=24)
|
||||
|
||||
query = (
|
||||
select(Subscription)
|
||||
.join(Tariff, Subscription.tariff_id == Tariff.id)
|
||||
.join(User, Subscription.user_id == User.id)
|
||||
.options(
|
||||
selectinload(Subscription.user),
|
||||
selectinload(Subscription.tariff),
|
||||
)
|
||||
.where(
|
||||
and_(
|
||||
Tariff.is_daily.is_(True),
|
||||
Tariff.is_active.is_(True),
|
||||
Subscription.status == SubscriptionStatus.EXPIRED.value,
|
||||
User.status == UserStatus.ACTIVE.value,
|
||||
Subscription.is_daily_paused.is_(False),
|
||||
Subscription.is_trial.is_(False),
|
||||
# Только недавно экспайренные
|
||||
Subscription.updated_at >= recovery_threshold,
|
||||
# Баланс достаточен для списания
|
||||
User.balance_kopeks >= Tariff.daily_price_kopeks,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
result = await db.execute(query)
|
||||
subscriptions = result.scalars().all()
|
||||
|
||||
if subscriptions:
|
||||
logger.warning(
|
||||
'⚠️ Найдено EXPIRED суточных подписок для восстановления (ошибочно экспайрены)',
|
||||
subscriptions_count=len(subscriptions),
|
||||
)
|
||||
|
||||
return list(subscriptions)
|
||||
|
||||
|
||||
async def pause_daily_subscription(
|
||||
db: AsyncSession,
|
||||
subscription: Subscription,
|
||||
|
||||
@@ -459,6 +459,19 @@ class TicketMessageCRUD:
|
||||
result = await db.execute(query)
|
||||
return result.scalars().all()
|
||||
|
||||
@staticmethod
|
||||
async def get_first_message(db: AsyncSession, ticket_id: int) -> TicketMessage | None:
|
||||
"""Получить первое сообщение в тикете"""
|
||||
query = (
|
||||
select(TicketMessage)
|
||||
.where(TicketMessage.ticket_id == ticket_id)
|
||||
.order_by(TicketMessage.created_at)
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
result = await db.execute(query)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
@staticmethod
|
||||
async def get_last_message(db: AsyncSession, ticket_id: int) -> TicketMessage | None:
|
||||
"""Получить последнее сообщение в тикете"""
|
||||
|
||||
@@ -38,11 +38,19 @@ async def create_transaction(
|
||||
external_id: str | None = None,
|
||||
is_completed: bool = True,
|
||||
created_at: datetime | None = None,
|
||||
*,
|
||||
commit: bool = True,
|
||||
) -> Transaction:
|
||||
# SUBSCRIPTION_PAYMENT — always store as negative (debit from user balance)
|
||||
# Keep original for downstream consumers (events, contests)
|
||||
stored_amount = (
|
||||
-amount_kopeks if type == TransactionType.SUBSCRIPTION_PAYMENT and amount_kopeks > 0 else amount_kopeks
|
||||
)
|
||||
|
||||
transaction = Transaction(
|
||||
user_id=user_id,
|
||||
type=type.value,
|
||||
amount_kopeks=amount_kopeks,
|
||||
amount_kopeks=stored_amount,
|
||||
description=description,
|
||||
payment_method=payment_method.value if payment_method else None,
|
||||
external_id=external_id,
|
||||
@@ -52,17 +60,82 @@ async def create_transaction(
|
||||
)
|
||||
|
||||
db.add(transaction)
|
||||
await db.commit()
|
||||
if commit:
|
||||
await db.commit()
|
||||
else:
|
||||
await db.flush()
|
||||
await db.refresh(transaction)
|
||||
|
||||
logger.info(
|
||||
'💳 Создана транзакция: на ₽ для пользователя',
|
||||
type_value=type.value,
|
||||
amount_kopeks=amount_kopeks / 100,
|
||||
amount_kopeks=stored_amount / 100,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
# Отправляем событие о транзакции
|
||||
# Side-effects skipped when commit=False to preserve caller's transaction atomicity.
|
||||
# Callers using commit=False should call emit_transaction_side_effects() after their own db.commit().
|
||||
if commit:
|
||||
try:
|
||||
from app.services.event_emitter import event_emitter
|
||||
|
||||
await event_emitter.emit(
|
||||
'payment.completed' if type == TransactionType.DEPOSIT else 'transaction.created',
|
||||
{
|
||||
'transaction_id': transaction.id,
|
||||
'user_id': user_id,
|
||||
'type': type.value,
|
||||
'amount_kopeks': abs(amount_kopeks),
|
||||
'amount_rubles': abs(amount_kopeks) / 100,
|
||||
'payment_method': payment_method.value if payment_method else None,
|
||||
'external_id': external_id,
|
||||
'is_completed': is_completed,
|
||||
'description': description,
|
||||
},
|
||||
db=db,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.warning('Failed to emit transaction event', error=error)
|
||||
|
||||
try:
|
||||
from app.services.promo_group_assignment import (
|
||||
maybe_assign_promo_group_by_total_spent,
|
||||
)
|
||||
|
||||
await maybe_assign_promo_group_by_total_spent(db, user_id)
|
||||
except Exception as exc:
|
||||
logger.debug('Не удалось проверить автовыдачу промогруппы для пользователя', user_id=user_id, exc=exc)
|
||||
if type == TransactionType.SUBSCRIPTION_PAYMENT and is_completed:
|
||||
try:
|
||||
from app.services.referral_contest_service import referral_contest_service
|
||||
|
||||
await referral_contest_service.on_subscription_payment(
|
||||
db,
|
||||
user_id,
|
||||
abs(amount_kopeks),
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.debug('Не удалось записать событие конкурса для пользователя', user_id=user_id, exc=exc)
|
||||
|
||||
return transaction
|
||||
|
||||
|
||||
async def emit_transaction_side_effects(
|
||||
db: AsyncSession,
|
||||
transaction: Transaction,
|
||||
*,
|
||||
amount_kopeks: int,
|
||||
user_id: int,
|
||||
type: TransactionType,
|
||||
payment_method: PaymentMethod | None = None,
|
||||
external_id: str | None = None,
|
||||
is_completed: bool = True,
|
||||
description: str = '',
|
||||
) -> None:
|
||||
"""Fire side-effects that were deferred when create_transaction(commit=False) was used.
|
||||
|
||||
Call this AFTER db.commit() to emit events and run promo checks.
|
||||
"""
|
||||
try:
|
||||
from app.services.event_emitter import event_emitter
|
||||
|
||||
@@ -72,8 +145,8 @@ async def create_transaction(
|
||||
'transaction_id': transaction.id,
|
||||
'user_id': user_id,
|
||||
'type': type.value,
|
||||
'amount_kopeks': amount_kopeks,
|
||||
'amount_rubles': amount_kopeks / 100,
|
||||
'amount_kopeks': abs(amount_kopeks),
|
||||
'amount_rubles': abs(amount_kopeks) / 100,
|
||||
'payment_method': payment_method.value if payment_method else None,
|
||||
'external_id': external_id,
|
||||
'is_completed': is_completed,
|
||||
@@ -82,7 +155,7 @@ async def create_transaction(
|
||||
db=db,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.warning('Failed to emit transaction event', error=error)
|
||||
logger.warning('Failed to emit deferred transaction event', error=error)
|
||||
|
||||
try:
|
||||
from app.services.promo_group_assignment import (
|
||||
@@ -92,20 +165,19 @@ async def create_transaction(
|
||||
await maybe_assign_promo_group_by_total_spent(db, user_id)
|
||||
except Exception as exc:
|
||||
logger.debug('Не удалось проверить автовыдачу промогруппы для пользователя', user_id=user_id, exc=exc)
|
||||
if type == TransactionType.SUBSCRIPTION_PAYMENT:
|
||||
|
||||
if type == TransactionType.SUBSCRIPTION_PAYMENT and is_completed:
|
||||
try:
|
||||
from app.services.referral_contest_service import referral_contest_service
|
||||
|
||||
await referral_contest_service.on_subscription_payment(
|
||||
db,
|
||||
user_id,
|
||||
amount_kopeks,
|
||||
abs(amount_kopeks),
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.debug('Не удалось записать событие конкурса для пользователя', user_id=user_id, exc=exc)
|
||||
|
||||
return transaction
|
||||
|
||||
|
||||
async def get_transaction_by_id(db: AsyncSession, transaction_id: int) -> Transaction | None:
|
||||
result = await db.execute(
|
||||
@@ -217,7 +289,7 @@ async def get_transactions_statistics(
|
||||
total_income = income_result.scalar()
|
||||
|
||||
expenses_result = await db.execute(
|
||||
select(func.coalesce(func.sum(Transaction.amount_kopeks), 0)).where(
|
||||
select(func.coalesce(func.sum(func.abs(Transaction.amount_kopeks)), 0)).where(
|
||||
and_(
|
||||
Transaction.type == TransactionType.WITHDRAWAL.value,
|
||||
Transaction.is_completed == True,
|
||||
@@ -244,7 +316,7 @@ async def get_transactions_statistics(
|
||||
select(
|
||||
Transaction.type,
|
||||
func.count(Transaction.id).label('count'),
|
||||
func.coalesce(func.sum(Transaction.amount_kopeks), 0).label('total_amount'),
|
||||
func.coalesce(func.sum(func.abs(Transaction.amount_kopeks)), 0).label('total_amount'),
|
||||
)
|
||||
.where(
|
||||
and_(
|
||||
|
||||
@@ -54,7 +54,7 @@ def _build_spending_stats_select():
|
||||
case(
|
||||
(
|
||||
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
|
||||
Transaction.amount_kopeks,
|
||||
func.abs(Transaction.amount_kopeks),
|
||||
),
|
||||
else_=0,
|
||||
)
|
||||
@@ -505,6 +505,7 @@ async def subtract_user_balance(
|
||||
payment_method: PaymentMethod | None = None,
|
||||
*,
|
||||
consume_promo_offer: bool = False,
|
||||
mark_as_paid_subscription: bool = False,
|
||||
) -> bool:
|
||||
user_id_display = user.telegram_id or user.email or f'#{user.id}'
|
||||
logger.info('💸 ОТЛАДКА subtract_user_balance:')
|
||||
@@ -514,7 +515,9 @@ async def subtract_user_balance(
|
||||
logger.info('📝 Описание', description=description)
|
||||
|
||||
# Lock the user row to prevent concurrent balance race conditions
|
||||
locked_result = await db.execute(select(User).where(User.id == user.id).with_for_update())
|
||||
locked_result = await db.execute(
|
||||
select(User).where(User.id == user.id).with_for_update().execution_options(populate_existing=True)
|
||||
)
|
||||
user = locked_result.scalar_one()
|
||||
|
||||
log_context: dict[str, object] | None = None
|
||||
@@ -564,6 +567,9 @@ async def subtract_user_balance(
|
||||
user.promo_offer_discount_source = None
|
||||
user.promo_offer_discount_expires_at = None
|
||||
|
||||
if mark_as_paid_subscription:
|
||||
user.has_had_paid_subscription = True
|
||||
|
||||
user.updated_at = datetime.now(UTC)
|
||||
|
||||
if create_transaction:
|
||||
@@ -1259,7 +1265,9 @@ async def clear_email_change_pending(db: AsyncSession, user: User) -> None:
|
||||
|
||||
# --- OAuth provider functions ---
|
||||
|
||||
_OAUTH_PROVIDER_COLUMNS = {
|
||||
# Single source of truth: provider name → User model column name.
|
||||
# Imported by account_linking.py and account_merge_service.py.
|
||||
OAUTH_PROVIDER_COLUMNS: dict[str, str] = {
|
||||
'google': 'google_id',
|
||||
'yandex': 'yandex_id',
|
||||
'discord': 'discord_id',
|
||||
@@ -1269,8 +1277,9 @@ _OAUTH_PROVIDER_COLUMNS = {
|
||||
|
||||
async def get_user_by_oauth_provider(db: AsyncSession, provider: str, provider_id: str) -> User | None:
|
||||
"""Find a user by OAuth provider ID."""
|
||||
column_name = _OAUTH_PROVIDER_COLUMNS.get(provider)
|
||||
column_name = OAUTH_PROVIDER_COLUMNS.get(provider)
|
||||
if not column_name:
|
||||
logger.warning('Unknown OAuth provider in lookup', provider=provider)
|
||||
return None
|
||||
column = getattr(User, column_name)
|
||||
# VK uses BigInteger, so convert
|
||||
@@ -1281,13 +1290,25 @@ async def get_user_by_oauth_provider(db: AsyncSession, provider: str, provider_i
|
||||
|
||||
async def set_user_oauth_provider_id(db: AsyncSession, user: User, provider: str, provider_id: str) -> None:
|
||||
"""Link an OAuth provider ID to an existing user."""
|
||||
column_name = _OAUTH_PROVIDER_COLUMNS.get(provider)
|
||||
column_name = OAUTH_PROVIDER_COLUMNS.get(provider)
|
||||
if not column_name:
|
||||
logger.warning('Unknown OAuth provider in set', provider=provider, user_id=user.id)
|
||||
return
|
||||
value: str | int = int(provider_id) if provider == 'vk' else provider_id
|
||||
setattr(user, column_name, value)
|
||||
user.updated_at = datetime.now(UTC)
|
||||
logger.info('Linked (id=) to user', provider=provider, provider_id=provider_id, user_id=user.id)
|
||||
logger.info('OAuth provider linked to user', provider=provider, provider_id=provider_id, user_id=user.id)
|
||||
|
||||
|
||||
async def clear_user_oauth_provider_id(db: AsyncSession, user: User, provider: str) -> None:
|
||||
"""Unlink an OAuth provider from an existing user (set column to None)."""
|
||||
column_name = OAUTH_PROVIDER_COLUMNS.get(provider)
|
||||
if not column_name:
|
||||
logger.warning('Unknown OAuth provider in clear', provider=provider, user_id=user.id)
|
||||
return
|
||||
setattr(user, column_name, None)
|
||||
user.updated_at = datetime.now(UTC)
|
||||
logger.info('Unlinked OAuth provider from user', provider=provider, user_id=user.id)
|
||||
|
||||
|
||||
async def create_user_by_oauth(
|
||||
@@ -1307,7 +1328,7 @@ async def create_user_by_oauth(
|
||||
normalized_language = _normalize_language_code(language)
|
||||
default_group = await _get_or_create_default_promo_group(db)
|
||||
|
||||
column_name = _OAUTH_PROVIDER_COLUMNS.get(provider)
|
||||
column_name = OAUTH_PROVIDER_COLUMNS.get(provider)
|
||||
provider_value: str | int = int(provider_id) if provider == 'vk' else provider_id
|
||||
|
||||
user = User(
|
||||
|
||||
@@ -71,6 +71,11 @@ async def get_wata_payment_by_id(
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_wata_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> WataPayment | None:
|
||||
result = await db.execute(select(WataPayment).where(WataPayment.id == payment_id).with_for_update())
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_wata_payment_by_link_id(
|
||||
db: AsyncSession,
|
||||
payment_link_id: str,
|
||||
@@ -143,7 +148,7 @@ async def link_wata_payment_to_transaction(
|
||||
transaction_id: int,
|
||||
) -> WataPayment:
|
||||
await db.execute(update(WataPayment).where(WataPayment.id == payment.id).values(transaction_id=transaction_id))
|
||||
await db.commit()
|
||||
await db.flush()
|
||||
await db.refresh(payment)
|
||||
|
||||
logger.info(
|
||||
|
||||
@@ -127,7 +127,7 @@ async def link_yookassa_payment_to_transaction(
|
||||
.where(YooKassaPayment.yookassa_payment_id == yookassa_payment_id)
|
||||
.values(transaction_id=transaction_id, updated_at=datetime.now(UTC))
|
||||
)
|
||||
await db.commit()
|
||||
await db.flush()
|
||||
|
||||
result = await db.execute(
|
||||
select(YooKassaPayment)
|
||||
|
||||
+156
-23
@@ -28,6 +28,7 @@ from sqlalchemy import (
|
||||
TypeDecorator,
|
||||
UniqueConstraint,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import Mapped, backref, mapped_column, relationship
|
||||
from sqlalchemy.sql import func
|
||||
@@ -190,7 +191,7 @@ class YooKassaPayment(Base):
|
||||
__tablename__ = 'yookassa_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
yookassa_payment_id = Column(String(255), unique=True, nullable=False, index=True)
|
||||
amount_kopeks = Column(Integer, nullable=False)
|
||||
currency = Column(String(3), default='RUB', nullable=False)
|
||||
@@ -239,7 +240,7 @@ class CryptoBotPayment(Base):
|
||||
__tablename__ = 'cryptobot_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
invoice_id = Column(String(255), unique=True, nullable=False, index=True)
|
||||
amount = Column(String(50), nullable=False)
|
||||
@@ -289,7 +290,7 @@ class HeleketPayment(Base):
|
||||
__tablename__ = 'heleket_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
uuid = Column(String(255), unique=True, nullable=False, index=True)
|
||||
order_id = Column(String(128), unique=True, nullable=False, index=True)
|
||||
@@ -348,7 +349,7 @@ class MulenPayPayment(Base):
|
||||
__tablename__ = 'mulenpay_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
mulen_payment_id = Column(Integer, nullable=True, index=True)
|
||||
uuid = Column(String(255), unique=True, nullable=False, index=True)
|
||||
@@ -384,7 +385,7 @@ class Pal24Payment(Base):
|
||||
__tablename__ = 'pal24_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
bill_id = Column(String(255), unique=True, nullable=False, index=True)
|
||||
order_id = Column(String(255), nullable=True, index=True)
|
||||
@@ -441,7 +442,7 @@ class WataPayment(Base):
|
||||
__tablename__ = 'wata_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
payment_link_id = Column(String(64), unique=True, nullable=False, index=True)
|
||||
order_id = Column(String(255), nullable=True, index=True)
|
||||
@@ -484,7 +485,7 @@ class PlategaPayment(Base):
|
||||
__tablename__ = 'platega_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
platega_transaction_id = Column(String(255), unique=True, nullable=True, index=True)
|
||||
correlation_id = Column(String(64), unique=True, nullable=False, index=True)
|
||||
@@ -526,7 +527,7 @@ class CloudPaymentsPayment(Base):
|
||||
__tablename__ = 'cloudpayments_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
# CloudPayments идентификаторы
|
||||
transaction_id_cp = Column(BigInteger, unique=True, nullable=True, index=True) # TransactionId от CloudPayments
|
||||
@@ -595,7 +596,7 @@ class FreekassaPayment(Base):
|
||||
__tablename__ = 'freekassa_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
# Идентификаторы
|
||||
order_id = Column(String(64), unique=True, nullable=False, index=True) # Наш ID заказа
|
||||
@@ -657,7 +658,7 @@ class KassaAiPayment(Base):
|
||||
__tablename__ = 'kassa_ai_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
# Идентификаторы
|
||||
order_id = Column(String(64), unique=True, nullable=False, index=True) # Наш ID заказа
|
||||
@@ -907,6 +908,11 @@ class Tariff(Base):
|
||||
prices = self.period_prices or {}
|
||||
return sorted([int(p) for p in prices.keys()])
|
||||
|
||||
def get_shortest_period(self) -> int | None:
|
||||
"""Возвращает минимальный доступный период в днях (для автопродления)."""
|
||||
periods = self.get_available_periods()
|
||||
return periods[0] if periods else None
|
||||
|
||||
def get_price_rubles(self, period_days: int) -> float | None:
|
||||
"""Возвращает цену в рублях для указанного периода."""
|
||||
price_kopeks = self.get_price_for_period(period_days)
|
||||
@@ -1011,7 +1017,7 @@ class User(Base):
|
||||
balance_kopeks = Column(Integer, default=0)
|
||||
used_promocodes = Column(Integer, default=0)
|
||||
has_had_paid_subscription = Column(Boolean, default=False, nullable=False)
|
||||
referred_by_id = Column(Integer, ForeignKey('users.id'), nullable=True, index=True)
|
||||
referred_by_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
referral_code = Column(String(20), unique=True, nullable=True)
|
||||
created_at = Column(AwareDateTime(), default=func.now())
|
||||
updated_at = Column(AwareDateTime(), default=func.now(), onupdate=func.now())
|
||||
@@ -1060,6 +1066,7 @@ class User(Base):
|
||||
promo_group = relationship('PromoGroup', back_populates='users')
|
||||
user_promo_groups = relationship('UserPromoGroup', back_populates='user', cascade='all, delete-orphan')
|
||||
poll_responses = relationship('PollResponse', back_populates='user')
|
||||
admin_roles_rel = relationship('UserRole', foreign_keys='[UserRole.user_id]', back_populates='user')
|
||||
notification_settings = Column(JSON, nullable=True, default=dict)
|
||||
last_pinned_message_id = Column(Integer, nullable=True)
|
||||
|
||||
@@ -1151,9 +1158,13 @@ class User(Base):
|
||||
|
||||
class Subscription(Base):
|
||||
__tablename__ = 'subscriptions'
|
||||
__table_args__ = (
|
||||
Index('ix_subscriptions_status_trial', 'status', 'is_trial'),
|
||||
Index('ix_subscriptions_trial_created', 'is_trial', 'created_at'),
|
||||
)
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False, unique=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False, unique=True)
|
||||
|
||||
status = Column(String(20), default=SubscriptionStatus.TRIAL.value)
|
||||
is_trial = Column(Boolean, default=True)
|
||||
@@ -1361,6 +1372,7 @@ class TrafficPurchase(Base):
|
||||
"""Докупка трафика с индивидуальной датой истечения."""
|
||||
|
||||
__tablename__ = 'traffic_purchases'
|
||||
__table_args__ = (Index('ix_traffic_purchases_created_at', 'created_at'),)
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
subscription_id = Column(Integer, ForeignKey('subscriptions.id', ondelete='CASCADE'), nullable=False, index=True)
|
||||
@@ -1380,9 +1392,15 @@ class TrafficPurchase(Base):
|
||||
|
||||
class Transaction(Base):
|
||||
__tablename__ = 'transactions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('external_id', 'payment_method', name='uq_transaction_external_id_method'),
|
||||
Index('ix_transactions_type_created_completed', 'type', 'created_at', 'is_completed'),
|
||||
Index('ix_transactions_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_transactions_type_method_created', 'type', 'payment_method', 'created_at'),
|
||||
)
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
type = Column(String(50), nullable=False)
|
||||
amount_kopeks = Column(Integer, nullable=False)
|
||||
@@ -1409,9 +1427,13 @@ class Transaction(Base):
|
||||
|
||||
class SubscriptionConversion(Base):
|
||||
__tablename__ = 'subscription_conversions'
|
||||
__table_args__ = (
|
||||
Index('ix_sub_conversions_converted_at', 'converted_at'),
|
||||
Index('ix_sub_conversions_user_id', 'user_id'),
|
||||
)
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
converted_at = Column(AwareDateTime(), default=func.now())
|
||||
|
||||
@@ -1455,7 +1477,7 @@ class PromoCode(Base):
|
||||
is_active = Column(Boolean, default=True)
|
||||
first_purchase_only = Column(Boolean, default=False) # Только для первой покупки
|
||||
|
||||
created_by = Column(Integer, ForeignKey('users.id'), nullable=True)
|
||||
created_by = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
promo_group_id = Column(Integer, ForeignKey('promo_groups.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
|
||||
created_at = Column(AwareDateTime(), default=func.now())
|
||||
@@ -1481,10 +1503,11 @@ class PromoCode(Base):
|
||||
|
||||
class PromoCodeUse(Base):
|
||||
__tablename__ = 'promocode_uses'
|
||||
__table_args__ = (UniqueConstraint('user_id', 'promocode_id', name='uq_promocode_uses_user_promo'),)
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
promocode_id = Column(Integer, ForeignKey('promocodes.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
|
||||
used_at = Column(AwareDateTime(), default=func.now())
|
||||
|
||||
@@ -1496,8 +1519,8 @@ class ReferralEarning(Base):
|
||||
__tablename__ = 'referral_earnings'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id'), nullable=False, index=True)
|
||||
referral_id = Column(Integer, ForeignKey('users.id'), nullable=False, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False, index=True)
|
||||
referral_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False, index=True)
|
||||
|
||||
amount_kopeks = Column(Integer, nullable=False)
|
||||
reason = Column(String(100), nullable=False)
|
||||
@@ -1535,7 +1558,7 @@ class WithdrawalRequest(Base):
|
||||
__tablename__ = 'withdrawal_requests'
|
||||
|
||||
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='CASCADE'), nullable=False, index=True)
|
||||
|
||||
amount_kopeks = Column(Integer, nullable=False) # Сумма к выводу
|
||||
status = Column(String(50), default=WithdrawalRequestStatus.PENDING.value, nullable=False, index=True)
|
||||
@@ -1548,7 +1571,7 @@ class WithdrawalRequest(Base):
|
||||
risk_analysis = Column(Text, nullable=True) # JSON с деталями анализа
|
||||
|
||||
# Обработка админом
|
||||
processed_by = Column(Integer, ForeignKey('users.id'), nullable=True)
|
||||
processed_by = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
processed_at = Column(AwareDateTime(), nullable=True)
|
||||
admin_comment = Column(Text, nullable=True)
|
||||
|
||||
@@ -1576,6 +1599,7 @@ class PartnerApplication(Base):
|
||||
telegram_channel = Column(String(255), nullable=True)
|
||||
description = Column(Text, nullable=True)
|
||||
expected_monthly_referrals = Column(Integer, nullable=True)
|
||||
desired_commission_percent = Column(Integer, nullable=True)
|
||||
|
||||
status = Column(String(20), default=PartnerStatus.PENDING.value, nullable=False)
|
||||
|
||||
@@ -1977,7 +2001,7 @@ class BroadcastHistory(Base):
|
||||
failed_count = Column(Integer, default=0)
|
||||
blocked_count = Column(Integer, default=0)
|
||||
status = Column(String(50), default='in_progress')
|
||||
admin_id = Column(Integer, ForeignKey('users.id'))
|
||||
admin_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
admin_name = Column(String(255))
|
||||
created_at = Column(AwareDateTime(), server_default=func.now())
|
||||
completed_at = Column(AwareDateTime(), nullable=True)
|
||||
@@ -2193,7 +2217,7 @@ class WelcomeText(Base):
|
||||
text_content = Column(Text, nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_enabled = Column(Boolean, default=True)
|
||||
created_by = Column(Integer, ForeignKey('users.id'), nullable=True)
|
||||
created_by = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
created_at = Column(AwareDateTime(), default=func.now())
|
||||
updated_at = Column(AwareDateTime(), default=func.now(), onupdate=func.now())
|
||||
|
||||
@@ -2241,7 +2265,7 @@ class AdvertisingCampaign(Base):
|
||||
# Привязка к партнёру
|
||||
partner_user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
|
||||
created_by = Column(Integer, ForeignKey('users.id'), nullable=True)
|
||||
created_by = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
created_at = Column(AwareDateTime(), default=func.now())
|
||||
updated_at = Column(AwareDateTime(), default=func.now(), onupdate=func.now())
|
||||
|
||||
@@ -2823,6 +2847,8 @@ class RequiredChannel(Base):
|
||||
title = Column(String(255), nullable=True) # Display name
|
||||
is_active = Column(Boolean, nullable=False, server_default='true')
|
||||
sort_order = Column(Integer, nullable=False, server_default='0')
|
||||
disable_trial_on_leave = Column(Boolean, nullable=False, server_default='true')
|
||||
disable_paid_on_leave = Column(Boolean, nullable=False, server_default='false')
|
||||
created_at = Column(AwareDateTime(), nullable=False, server_default=func.now())
|
||||
updated_at = Column(AwareDateTime(), nullable=True, onupdate=func.now())
|
||||
|
||||
@@ -2855,3 +2881,110 @@ class UserChannelSubscription(Base):
|
||||
f'<UserChannelSubscription telegram_id={self.telegram_id}'
|
||||
f' channel={self.channel_id!r} member={self.is_member}>'
|
||||
)
|
||||
|
||||
|
||||
# ── RBAC / ABAC models ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
class AdminRole(Base):
|
||||
"""Role definition with permission groups for admin cabinet RBAC."""
|
||||
|
||||
__tablename__ = 'admin_roles'
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
name = Column(String(100), unique=True, nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
level = Column(Integer, default=0, nullable=False)
|
||||
permissions = Column(JSONB, default=list, nullable=False)
|
||||
color = Column(String(7), nullable=True)
|
||||
icon = Column(String(50), nullable=True)
|
||||
is_system = Column(Boolean, default=False, nullable=False)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
created_by = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
created_at = Column(AwareDateTime(), server_default=func.now())
|
||||
updated_at = Column(AwareDateTime(), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
creator = relationship('User', foreign_keys=[created_by])
|
||||
user_roles = relationship('UserRole', back_populates='role')
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f'<AdminRole id={self.id} name={self.name!r} level={self.level}>'
|
||||
|
||||
|
||||
class UserRole(Base):
|
||||
"""M2M assignment of users to admin roles."""
|
||||
|
||||
__tablename__ = 'user_roles'
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
role_id = Column(Integer, ForeignKey('admin_roles.id', ondelete='CASCADE'), nullable=False)
|
||||
assigned_by = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
assigned_at = Column(AwareDateTime(), server_default=func.now())
|
||||
expires_at = Column(AwareDateTime(), nullable=True)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
|
||||
__table_args__ = (UniqueConstraint('user_id', 'role_id', name='uq_user_role'),)
|
||||
|
||||
user = relationship('User', foreign_keys=[user_id], back_populates='admin_roles_rel')
|
||||
role = relationship('AdminRole', back_populates='user_roles')
|
||||
assigner = relationship('User', foreign_keys=[assigned_by])
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f'<UserRole id={self.id} user_id={self.user_id} role_id={self.role_id}>'
|
||||
|
||||
|
||||
class AccessPolicy(Base):
|
||||
"""ABAC attribute-based access policy."""
|
||||
|
||||
__tablename__ = 'access_policies'
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
name = Column(String(200), nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
role_id = Column(Integer, ForeignKey('admin_roles.id', ondelete='CASCADE'), nullable=True)
|
||||
priority = Column(Integer, default=0, nullable=False)
|
||||
effect = Column(String(10), nullable=False) # "allow" / "deny"
|
||||
conditions = Column(JSONB, default=dict, nullable=False)
|
||||
resource = Column(String(100), nullable=False)
|
||||
actions = Column(JSONB, default=list, nullable=False)
|
||||
is_active = Column(Boolean, default=True, nullable=False)
|
||||
created_by = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
created_at = Column(AwareDateTime(), server_default=func.now())
|
||||
updated_at = Column(AwareDateTime(), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
role = relationship('AdminRole')
|
||||
creator = relationship('User', foreign_keys=[created_by])
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f'<AccessPolicy id={self.id} name={self.name!r} effect={self.effect!r}>'
|
||||
|
||||
|
||||
class AdminAuditLog(Base):
|
||||
"""Immutable audit log for admin actions."""
|
||||
|
||||
__tablename__ = 'admin_audit_log'
|
||||
|
||||
id = Column(BigInteger, primary_key=True, autoincrement=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), nullable=False)
|
||||
action = Column(String(100), nullable=False)
|
||||
resource_type = Column(String(50), nullable=True)
|
||||
resource_id = Column(String(100), nullable=True)
|
||||
details = Column(JSONB, nullable=True)
|
||||
ip_address = Column(String(45), nullable=True)
|
||||
user_agent = Column(Text, nullable=True)
|
||||
status = Column(String(20), nullable=False)
|
||||
request_method = Column(String(10), nullable=True)
|
||||
request_path = Column(Text, nullable=True)
|
||||
created_at = Column(AwareDateTime(), server_default=func.now())
|
||||
|
||||
__table_args__ = (
|
||||
Index('ix_admin_audit_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_admin_audit_resource', 'resource_type', 'resource_id'),
|
||||
Index('ix_admin_audit_created', 'created_at'),
|
||||
)
|
||||
|
||||
user = relationship('User', foreign_keys=[user_id])
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f'<AdminAuditLog id={self.id} action={self.action!r} status={self.status!r}>'
|
||||
|
||||
Vendored
+11
-1
@@ -461,9 +461,19 @@ class RemnaWaveAPI:
|
||||
if active_internal_squads:
|
||||
data['activeInternalSquads'] = active_internal_squads
|
||||
|
||||
logger.debug('Создание пользователя в панели', data=data)
|
||||
logger.info(
|
||||
'POST /api/users payload',
|
||||
username=data.get('username'),
|
||||
hwidDeviceLimit=data.get('hwidDeviceLimit'),
|
||||
status=data.get('status'),
|
||||
)
|
||||
response = await self._make_request('POST', '/api/users', data)
|
||||
user = self._parse_user(response['response'])
|
||||
logger.info(
|
||||
'POST /api/users response',
|
||||
uuid=user.uuid,
|
||||
response_hwidDeviceLimit=user.hwid_device_limit,
|
||||
)
|
||||
return await self.enrich_user_with_happ_link(user)
|
||||
|
||||
async def get_user_by_uuid(self, uuid: str) -> RemnaWaveUser | None:
|
||||
|
||||
Vendored
+1
-2
@@ -207,7 +207,6 @@ class YooKassaWebhookHandler:
|
||||
async def handle_webhook(self, request: web.Request) -> web.Response:
|
||||
try:
|
||||
logger.info('📥 Получен YooKassa webhook', method=request.method, path=request.path)
|
||||
logger.info('📋 Headers', value=dict(request.headers))
|
||||
|
||||
header_ip_candidates = collect_yookassa_ip_candidates(
|
||||
request.headers.get('X-Forwarded-For'),
|
||||
@@ -242,7 +241,7 @@ class YooKassaWebhookHandler:
|
||||
logger.warning('⚠️ Получен пустой webhook от YooKassa')
|
||||
return web.Response(status=400, text='Empty body')
|
||||
|
||||
logger.info('📄 Body', body=body)
|
||||
logger.debug('📄 Body received', length=len(body))
|
||||
|
||||
signature = request.headers.get('Signature') or request.headers.get('X-YooKassa-Signature')
|
||||
if signature:
|
||||
|
||||
@@ -5,6 +5,7 @@ import time
|
||||
from collections.abc import Iterable
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import structlog
|
||||
from aiogram import Dispatcher, F, types
|
||||
from aiogram.filters import BaseFilter, StateFilter
|
||||
from aiogram.fsm.context import FSMContext
|
||||
@@ -32,6 +33,8 @@ from app.utils.currency_converter import currency_converter
|
||||
from app.utils.decorators import admin_required, error_handler
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
CATEGORY_PAGE_SIZE = 10
|
||||
SETTINGS_PAGE_SIZE = 8
|
||||
SIMPLE_SUBSCRIPTION_SQUADS_PAGE_SIZE = 6
|
||||
|
||||
@@ -3,6 +3,7 @@ import re
|
||||
import structlog
|
||||
from aiogram import Bot, Dispatcher, F, types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from sqlalchemy import inspect as sa_inspect
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
@@ -237,8 +238,10 @@ async def show_campaigns_list(
|
||||
text_lines = ['📋 <b>Список кампаний</b>\n']
|
||||
|
||||
for campaign in campaigns:
|
||||
registrations = len(campaign.registrations or [])
|
||||
total_balance = sum(r.balance_bonus_kopeks or 0 for r in campaign.registrations or [])
|
||||
# Access from instance dict to avoid MissingGreenlet on lazy load
|
||||
regs = sa_inspect(campaign).dict.get('registrations', []) or []
|
||||
registrations = len(regs)
|
||||
total_balance = sum(r.balance_bonus_kopeks or 0 for r in regs)
|
||||
status = '🟢' if campaign.is_active else '⚪'
|
||||
line = (
|
||||
f'{status} <b>{campaign.name}</b> — <code>{campaign.start_parameter}</code>\n'
|
||||
|
||||
@@ -1242,7 +1242,7 @@ async def process_mass_virtual_count(
|
||||
'❌ Введите число от 1 до 50:',
|
||||
reply_markup=types.InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[types.InlineKeyboardButton(text='❌ Отмена', callback_data='admin_contests_ref')],
|
||||
[types.InlineKeyboardButton(text='❌ Отмена', callback_data='admin_contests_referral')],
|
||||
]
|
||||
),
|
||||
)
|
||||
@@ -1252,7 +1252,7 @@ async def process_mass_virtual_count(
|
||||
'❌ Введите корректное число от 1 до 50:',
|
||||
reply_markup=types.InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[types.InlineKeyboardButton(text='❌ Отмена', callback_data='admin_contests_ref')],
|
||||
[types.InlineKeyboardButton(text='❌ Отмена', callback_data='admin_contests_referral')],
|
||||
]
|
||||
),
|
||||
)
|
||||
@@ -1427,13 +1427,15 @@ def register_handlers(dp: Dispatcher):
|
||||
dp.callback_query.register(prompt_edit_summary_times, F.data.startswith('admin_contest_edit_times_'))
|
||||
dp.callback_query.register(delete_contest, F.data.startswith('admin_contest_delete_'))
|
||||
dp.callback_query.register(show_leaderboard, F.data.startswith('admin_contest_leaderboard_'))
|
||||
dp.callback_query.register(show_detailed_stats, F.data.startswith('admin_contest_detailed_stats_'))
|
||||
dp.callback_query.register(show_detailed_stats_page, F.data.startswith('admin_contest_detailed_stats_page_'))
|
||||
dp.callback_query.register(show_detailed_stats, F.data.startswith('admin_contest_detailed_stats_'))
|
||||
dp.callback_query.register(sync_contest, F.data.startswith('admin_contest_sync_'))
|
||||
dp.callback_query.register(debug_contest_transactions, F.data.startswith('admin_contest_debug_'))
|
||||
dp.callback_query.register(start_contest_creation, F.data == 'admin_contests_create')
|
||||
dp.callback_query.register(
|
||||
select_contest_mode, F.data.in_(['admin_contest_mode_paid', 'admin_contest_mode_registered'])
|
||||
select_contest_mode,
|
||||
F.data.in_(['admin_contest_mode_paid', 'admin_contest_mode_registered']),
|
||||
AdminStates.creating_referral_contest_mode,
|
||||
)
|
||||
|
||||
dp.message.register(process_title, AdminStates.creating_referral_contest_title)
|
||||
|
||||
@@ -613,7 +613,9 @@ async def show_messages_history(callback: types.CallbackQuery, db_user: User, db
|
||||
)
|
||||
|
||||
message_preview = (
|
||||
broadcast.message_text[:100] + '...' if len(broadcast.message_text) > 100 else broadcast.message_text
|
||||
broadcast.message_text[:100] + '...'
|
||||
if broadcast.message_text and len(broadcast.message_text) > 100
|
||||
else (broadcast.message_text or '📊 Опрос')
|
||||
)
|
||||
|
||||
import html
|
||||
|
||||
@@ -180,6 +180,13 @@ CORE_PRICING_ENTRIES: tuple[SettingEntry, ...] = (
|
||||
label_en='🔄 Reset traffic on payment',
|
||||
action='toggle',
|
||||
),
|
||||
SettingEntry(
|
||||
key='RESET_TRAFFIC_ON_TARIFF_SWITCH',
|
||||
section='core',
|
||||
label_ru='🔄 Сбрасывать трафик при смене тарифа',
|
||||
label_en='🔄 Reset traffic on tariff switch',
|
||||
action='toggle',
|
||||
),
|
||||
SettingEntry(
|
||||
key='DEFAULT_TRAFFIC_RESET_STRATEGY',
|
||||
section='core',
|
||||
@@ -356,7 +363,7 @@ def _format_core_summary(lang_code: str) -> str:
|
||||
else:
|
||||
traffic_mode = '⚙️ selectable'
|
||||
traffic_label = _format_traffic_label(traffic_limit, lang_code, short=True)
|
||||
return f'{base_price}, {device_limit}📱, {traffic_label}, {traffic_mode}'
|
||||
return f'{base_price}, {device_limit} 📱, {traffic_label}, {traffic_mode}'
|
||||
|
||||
|
||||
def _get_period_items(lang_code: str) -> list[PriceItem]:
|
||||
|
||||
@@ -137,7 +137,7 @@ async def show_revenue_statistics(callback: types.CallbackQuery, db_user: User,
|
||||
month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
month_stats = await get_transactions_statistics(db, month_start, now)
|
||||
all_time_stats = await get_transactions_statistics(db)
|
||||
all_time_stats = await get_transactions_statistics(db, start_date=datetime(2020, 1, 1, tzinfo=UTC), end_date=now)
|
||||
current_time = format_datetime(datetime.now(UTC))
|
||||
|
||||
text = f"""
|
||||
@@ -147,7 +147,7 @@ async def show_revenue_statistics(callback: types.CallbackQuery, db_user: User,
|
||||
- Доходы: {settings.format_price(month_stats['totals']['income_kopeks'])}
|
||||
- Расходы: {settings.format_price(month_stats['totals']['expenses_kopeks'])}
|
||||
- Прибыль: {settings.format_price(month_stats['totals']['profit_kopeks'])}
|
||||
- От подписок: {settings.format_price(month_stats['totals']['subscription_income_kopeks'])}
|
||||
- От подписок: {settings.format_price(abs(month_stats['totals']['subscription_income_kopeks']))}
|
||||
|
||||
<b>Сегодня:</b>
|
||||
- Транзакций: {month_stats['today']['transactions_count']}
|
||||
|
||||
@@ -139,7 +139,7 @@ def get_tariffs_list_keyboard(
|
||||
buttons.append([InlineKeyboardButton(text='➕ Создать тариф', callback_data='admin_tariff_create')])
|
||||
|
||||
# Кнопка назад
|
||||
buttons.append([InlineKeyboardButton(text=texts.BACK, callback_data='admin_submenu_settings')])
|
||||
buttons.append([InlineKeyboardButton(text=texts.BACK, callback_data='admin_panel')])
|
||||
|
||||
return InlineKeyboardMarkup(inline_keyboard=buttons)
|
||||
|
||||
@@ -393,7 +393,7 @@ async def show_tariffs_list(
|
||||
'<code>SALES_MODE=tariffs</code>\n\n'
|
||||
'Текущий режим: <code>classic</code>',
|
||||
reply_markup=InlineKeyboardMarkup(
|
||||
inline_keyboard=[[InlineKeyboardButton(text=texts.BACK, callback_data='admin_submenu_settings')]]
|
||||
inline_keyboard=[[InlineKeyboardButton(text=texts.BACK, callback_data='admin_panel')]]
|
||||
),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
@@ -408,7 +408,7 @@ async def show_tariffs_list(
|
||||
reply_markup=InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[InlineKeyboardButton(text='➕ Создать тариф', callback_data='admin_tariff_create')],
|
||||
[InlineKeyboardButton(text=texts.BACK, callback_data='admin_submenu_settings')],
|
||||
[InlineKeyboardButton(text=texts.BACK, callback_data='admin_panel')],
|
||||
]
|
||||
),
|
||||
parse_mode='HTML',
|
||||
@@ -2238,7 +2238,7 @@ async def delete_tariff_confirmed(
|
||||
reply_markup=InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[InlineKeyboardButton(text='➕ Создать тариф', callback_data='admin_tariff_create')],
|
||||
[InlineKeyboardButton(text=texts.BACK, callback_data='admin_submenu_settings')],
|
||||
[InlineKeyboardButton(text=texts.BACK, callback_data='admin_panel')],
|
||||
]
|
||||
),
|
||||
parse_mode='HTML',
|
||||
|
||||
@@ -3985,7 +3985,11 @@ async def _extend_subscription_by_days(db: AsyncSession, user_id: int, days: int
|
||||
|
||||
async def _add_subscription_traffic(db: AsyncSession, user_id: int, gb: int, admin_id: int) -> bool:
|
||||
try:
|
||||
from app.database.crud.subscription import add_subscription_traffic, get_subscription_by_user_id
|
||||
from app.database.crud.subscription import (
|
||||
add_subscription_traffic,
|
||||
get_subscription_by_user_id,
|
||||
reactivate_subscription,
|
||||
)
|
||||
from app.services.subscription_service import SubscriptionService
|
||||
|
||||
subscription = await get_subscription_by_user_id(db, user_id)
|
||||
@@ -3999,6 +4003,9 @@ async def _add_subscription_traffic(db: AsyncSession, user_id: int, gb: int, adm
|
||||
else:
|
||||
await add_subscription_traffic(db, subscription, gb)
|
||||
|
||||
# Реактивируем подписку если она была DISABLED (например, после LIMITED в RemnaWave)
|
||||
await reactivate_subscription(db, subscription)
|
||||
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.update_remnawave_user(db, subscription)
|
||||
|
||||
@@ -4507,7 +4514,11 @@ async def admin_buy_subscription_execute(callback: types.CallbackQuery, db_user:
|
||||
from app.database.crud.user import subtract_user_balance
|
||||
|
||||
success = await subtract_user_balance(
|
||||
db, target_user, price_kopeks, f'Покупка подписки на {period_days} дней (администратор)'
|
||||
db,
|
||||
target_user,
|
||||
price_kopeks,
|
||||
f'Покупка подписки на {period_days} дней (администратор)',
|
||||
mark_as_paid_subscription=True,
|
||||
)
|
||||
|
||||
if not success:
|
||||
@@ -4736,7 +4747,7 @@ async def admin_buy_tariff(callback: types.CallbackQuery, db_user: User, db: Asy
|
||||
traffic = '♾️' if tariff.traffic_limit_gb == 0 else f'{tariff.traffic_limit_gb} ГБ'
|
||||
prices = tariff.period_prices or {}
|
||||
min_price = min(prices.values()) if prices else 0
|
||||
text += f'<b>{tariff.name}</b> — {traffic}/{tariff.device_limit}📱 от {settings.format_price(min_price)}\n'
|
||||
text += f'<b>{tariff.name}</b> — {traffic} / {tariff.device_limit} 📱 от {settings.format_price(min_price)}\n'
|
||||
|
||||
keyboard = []
|
||||
for tariff in tariffs:
|
||||
@@ -4948,7 +4959,11 @@ async def admin_buy_tariff_execute(callback: types.CallbackQuery, db_user: User,
|
||||
|
||||
# Списываем баланс
|
||||
success = await subtract_user_balance(
|
||||
db, target_user, price_kopeks, f'Покупка тарифа {tariff.name} на {period} дней (администратор)'
|
||||
db,
|
||||
target_user,
|
||||
price_kopeks,
|
||||
f'Покупка тарифа {tariff.name} на {period} дней (администратор)',
|
||||
mark_as_paid_subscription=True,
|
||||
)
|
||||
|
||||
if not success:
|
||||
@@ -5001,7 +5016,7 @@ async def admin_buy_tariff_execute(callback: types.CallbackQuery, db_user: User,
|
||||
db,
|
||||
user_id=target_user.id,
|
||||
type=TransactionType.SUBSCRIPTION_PAYMENT,
|
||||
amount_kopeks=-price_kopeks,
|
||||
amount_kopeks=price_kopeks,
|
||||
description=f'Покупка тарифа {tariff.name} на {period} дней (администратор)',
|
||||
)
|
||||
|
||||
@@ -5110,10 +5125,11 @@ async def _change_subscription_type(db: AsyncSession, user_id: int, new_type: st
|
||||
old_type = 'триальной' if subscription.is_trial else 'платной'
|
||||
new_type_text = 'триальной' if new_is_trial else 'платной'
|
||||
|
||||
was_trial = subscription.is_trial
|
||||
subscription.is_trial = new_is_trial
|
||||
subscription.updated_at = datetime.now(UTC)
|
||||
|
||||
if not new_is_trial and subscription.is_trial:
|
||||
if not new_is_trial and was_trial:
|
||||
user = await get_user_by_id(db, user_id)
|
||||
if user:
|
||||
user.has_had_paid_subscription = True
|
||||
@@ -5326,11 +5342,20 @@ async def confirm_admin_tariff_change(callback: types.CallbackQuery, db_user: Us
|
||||
subscription.purchased_traffic_gb = 0
|
||||
subscription.traffic_reset_at = None
|
||||
|
||||
# Сброс использованного трафика по админ-настройке
|
||||
if settings.RESET_TRAFFIC_ON_TARIFF_SWITCH:
|
||||
subscription.traffic_used_gb = 0.0
|
||||
|
||||
await db.commit()
|
||||
|
||||
# Синхронизируем с RemnaWave
|
||||
# Синхронизируем с RemnaWave (сброс трафика по админ-настройке)
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.update_remnawave_user(db, subscription)
|
||||
await subscription_service.update_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_reason='смена тарифа (админ)',
|
||||
)
|
||||
|
||||
logger.info(
|
||||
'Админ изменил тариф пользователя',
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
"""Handler for Freekassa balance top-up."""
|
||||
|
||||
import html
|
||||
|
||||
import structlog
|
||||
from aiogram import types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
@@ -18,12 +20,29 @@ from app.utils.decorators import error_handler
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
FREEKASSA_SUB_METHODS = {
|
||||
'freekassa_sbp': {'payment_system_id': 44, 'get_name': lambda: settings.get_freekassa_sbp_display_name()},
|
||||
'freekassa_card': {'payment_system_id': 36, 'get_name': lambda: settings.get_freekassa_card_display_name()},
|
||||
}
|
||||
|
||||
|
||||
def _resolve_freekassa_params(
|
||||
payment_method: str | None,
|
||||
) -> tuple[int | None, str]:
|
||||
"""Return (payment_system_id, display_name) for a freekassa sub-method key."""
|
||||
if payment_method and payment_method in FREEKASSA_SUB_METHODS:
|
||||
meta = FREEKASSA_SUB_METHODS[payment_method]
|
||||
return meta['payment_system_id'], meta['get_name']()
|
||||
return None, settings.get_freekassa_display_name()
|
||||
|
||||
|
||||
async def _create_freekassa_payment_and_respond(
|
||||
message_or_callback,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
amount_kopeks: int,
|
||||
edit_message: bool = False,
|
||||
payment_method: str | None = None,
|
||||
):
|
||||
"""
|
||||
Common logic for creating Freekassa payment and sending response.
|
||||
@@ -34,10 +53,13 @@ async def _create_freekassa_payment_and_respond(
|
||||
db: Database session
|
||||
amount_kopeks: Amount in kopeks
|
||||
edit_message: Whether to edit existing message or send new one
|
||||
payment_method: Sub-method key (freekassa_sbp, freekassa_card, or None for default)
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
amount_rub = amount_kopeks / 100
|
||||
|
||||
ps_id, display_name = _resolve_freekassa_params(payment_method)
|
||||
|
||||
# Create payment
|
||||
payment_service = PaymentService()
|
||||
|
||||
@@ -53,6 +75,8 @@ async def _create_freekassa_payment_and_respond(
|
||||
description=description,
|
||||
email=getattr(db_user, 'email', None),
|
||||
language=db_user.language,
|
||||
payment_system_id=ps_id,
|
||||
payment_method=payment_method,
|
||||
)
|
||||
|
||||
if not result:
|
||||
@@ -74,7 +98,6 @@ async def _create_freekassa_payment_and_respond(
|
||||
return
|
||||
|
||||
payment_url = result.get('payment_url')
|
||||
display_name = settings.get_freekassa_display_name()
|
||||
|
||||
# Create keyboard with payment button
|
||||
keyboard = InlineKeyboardMarkup(
|
||||
@@ -103,7 +126,7 @@ async def _create_freekassa_payment_and_respond(
|
||||
'Сумма: <b>{amount}₽</b>\n\n'
|
||||
'Нажмите кнопку ниже для оплаты.\n'
|
||||
'После успешной оплаты баланс будет пополнен автоматически.',
|
||||
).format(name=display_name, amount=f'{amount_rub:.2f}')
|
||||
).format(name=html.escape(display_name), amount=f'{amount_rub:.2f}')
|
||||
|
||||
if edit_message:
|
||||
await message_or_callback.edit_text(
|
||||
@@ -128,9 +151,11 @@ async def process_freekassa_payment_amount(
|
||||
db: AsyncSession,
|
||||
amount_kopeks: int,
|
||||
state: FSMContext,
|
||||
payment_method: str | None = None,
|
||||
):
|
||||
"""
|
||||
Process payment amount directly (called from quick_amount handlers).
|
||||
payment_method: 'freekassa', 'freekassa_sbp', 'freekassa_card'
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
|
||||
@@ -183,21 +208,44 @@ async def process_freekassa_payment_amount(
|
||||
db=db,
|
||||
amount_kopeks=amount_kopeks,
|
||||
edit_message=False,
|
||||
payment_method=payment_method,
|
||||
)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def start_freekassa_topup(
|
||||
async def _start_freekassa_topup_impl(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
payment_method: str,
|
||||
):
|
||||
"""
|
||||
Start Freekassa top-up process - ask for amount.
|
||||
payment_method: 'freekassa', 'freekassa_sbp', 'freekassa_card'
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
|
||||
# Проверка доступности метода
|
||||
if not settings.is_freekassa_enabled():
|
||||
await callback.answer(
|
||||
texts.t('FREEKASSA_NOT_AVAILABLE', 'Freekassa временно недоступен'),
|
||||
show_alert=True,
|
||||
)
|
||||
return
|
||||
|
||||
if payment_method == 'freekassa_sbp' and not settings.is_freekassa_sbp_enabled():
|
||||
await callback.answer(
|
||||
texts.t('FREEKASSA_NOT_AVAILABLE', 'Freekassa временно недоступен'),
|
||||
show_alert=True,
|
||||
)
|
||||
return
|
||||
|
||||
if payment_method == 'freekassa_card' and not settings.is_freekassa_card_enabled():
|
||||
await callback.answer(
|
||||
texts.t('FREEKASSA_NOT_AVAILABLE', 'Freekassa временно недоступен'),
|
||||
show_alert=True,
|
||||
)
|
||||
return
|
||||
|
||||
# Проверка ограничения на пополнение
|
||||
if getattr(db_user, 'restriction_topup', False):
|
||||
reason = getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором'
|
||||
@@ -215,11 +263,11 @@ async def start_freekassa_topup(
|
||||
return
|
||||
|
||||
await state.set_state(BalanceStates.waiting_for_amount)
|
||||
await state.update_data(payment_method='freekassa')
|
||||
await state.update_data(payment_method=payment_method)
|
||||
|
||||
min_amount = settings.FREEKASSA_MIN_AMOUNT_KOPEKS // 100
|
||||
max_amount = settings.FREEKASSA_MAX_AMOUNT_KOPEKS // 100
|
||||
display_name = settings.get_freekassa_display_name()
|
||||
_, display_name = _resolve_freekassa_params(payment_method)
|
||||
|
||||
keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
@@ -249,6 +297,39 @@ async def start_freekassa_topup(
|
||||
)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def start_freekassa_topup(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
):
|
||||
await _start_freekassa_topup_impl(callback, db_user, state, 'freekassa')
|
||||
|
||||
|
||||
@error_handler
|
||||
async def start_freekassa_sbp_topup(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
):
|
||||
await _start_freekassa_topup_impl(callback, db_user, state, 'freekassa_sbp')
|
||||
|
||||
|
||||
@error_handler
|
||||
async def start_freekassa_card_topup(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
):
|
||||
await _start_freekassa_topup_impl(callback, db_user, state, 'freekassa_card')
|
||||
|
||||
|
||||
FREEKASSA_PAYMENT_METHODS = {'freekassa', 'freekassa_sbp', 'freekassa_card'}
|
||||
|
||||
|
||||
@error_handler
|
||||
async def process_freekassa_custom_amount(
|
||||
message: types.Message,
|
||||
@@ -260,7 +341,7 @@ async def process_freekassa_custom_amount(
|
||||
Process custom amount input for Freekassa payment.
|
||||
"""
|
||||
data = await state.get_data()
|
||||
if data.get('payment_method') != 'freekassa':
|
||||
if data.get('payment_method') not in FREEKASSA_PAYMENT_METHODS:
|
||||
return
|
||||
|
||||
texts = get_texts(db_user.language)
|
||||
@@ -285,19 +366,21 @@ async def process_freekassa_custom_amount(
|
||||
db=db,
|
||||
amount_kopeks=amount_kopeks,
|
||||
state=state,
|
||||
payment_method=data.get('payment_method'),
|
||||
)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def process_freekassa_quick_amount(
|
||||
async def _process_freekassa_quick_amount_impl(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
payment_method: str,
|
||||
):
|
||||
"""
|
||||
Process quick amount selection for Freekassa payment.
|
||||
Called when user clicks a predefined amount button.
|
||||
payment_method: 'freekassa', 'freekassa_sbp', 'freekassa_card'
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
|
||||
@@ -308,7 +391,21 @@ async def process_freekassa_quick_amount(
|
||||
)
|
||||
return
|
||||
|
||||
# Extract amount from callback data: topup_amount|freekassa|{amount_kopeks}
|
||||
if payment_method == 'freekassa_sbp' and not settings.is_freekassa_sbp_enabled():
|
||||
await callback.answer(
|
||||
texts.t('FREEKASSA_NOT_AVAILABLE', 'Freekassa временно недоступен'),
|
||||
show_alert=True,
|
||||
)
|
||||
return
|
||||
|
||||
if payment_method == 'freekassa_card' and not settings.is_freekassa_card_enabled():
|
||||
await callback.answer(
|
||||
texts.t('FREEKASSA_NOT_AVAILABLE', 'Freekassa временно недоступен'),
|
||||
show_alert=True,
|
||||
)
|
||||
return
|
||||
|
||||
# Extract amount from callback data: topup_amount|{method}|{amount_kopeks}
|
||||
try:
|
||||
parts = callback.data.split('|')
|
||||
if len(parts) >= 3:
|
||||
@@ -363,4 +460,35 @@ async def process_freekassa_quick_amount(
|
||||
db=db,
|
||||
amount_kopeks=amount_kopeks,
|
||||
edit_message=True,
|
||||
payment_method=payment_method,
|
||||
)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def process_freekassa_quick_amount(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
):
|
||||
await _process_freekassa_quick_amount_impl(callback, db_user, db, state, 'freekassa')
|
||||
|
||||
|
||||
@error_handler
|
||||
async def process_freekassa_sbp_quick_amount(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
):
|
||||
await _process_freekassa_quick_amount_impl(callback, db_user, db, state, 'freekassa_sbp')
|
||||
|
||||
|
||||
@error_handler
|
||||
async def process_freekassa_card_quick_amount(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
):
|
||||
await _process_freekassa_quick_amount_impl(callback, db_user, db, state, 'freekassa_card')
|
||||
|
||||
@@ -24,6 +24,15 @@ logger = structlog.get_logger(__name__)
|
||||
|
||||
TRANSACTIONS_PER_PAGE = 10
|
||||
|
||||
CREDIT_TRANSACTION_TYPES: frozenset[str] = frozenset(
|
||||
{
|
||||
TransactionType.DEPOSIT.value,
|
||||
TransactionType.REFERRAL_REWARD.value,
|
||||
TransactionType.REFUND.value,
|
||||
TransactionType.POLL_REWARD.value,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def route_payment_by_method(
|
||||
message: types.Message, db_user: User, amount_kopeks: int, state: FSMContext, payment_method: str
|
||||
@@ -113,11 +122,13 @@ async def route_payment_by_method(
|
||||
await process_cloudpayments_payment_amount(message, db_user, db, amount_kopeks, state)
|
||||
return True
|
||||
|
||||
if payment_method == 'freekassa':
|
||||
if payment_method in ('freekassa', 'freekassa_sbp', 'freekassa_card'):
|
||||
from .freekassa import process_freekassa_payment_amount
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
await process_freekassa_payment_amount(message, db_user, db, amount_kopeks, state)
|
||||
await process_freekassa_payment_amount(
|
||||
message, db_user, db, amount_kopeks, state, payment_method=payment_method
|
||||
)
|
||||
return True
|
||||
|
||||
if payment_method == 'kassa_ai':
|
||||
@@ -275,10 +286,11 @@ async def show_balance_history(callback: types.CallbackQuery, db_user: User, db:
|
||||
text = '📊 <b>История операций</b>\n\n'
|
||||
|
||||
for transaction in unique_transactions:
|
||||
emoji = '💰' if transaction.type == TransactionType.DEPOSIT.value else '💸'
|
||||
is_credit = transaction.type in CREDIT_TRANSACTION_TYPES
|
||||
emoji = '💰' if is_credit else '💸'
|
||||
amount_text = (
|
||||
f'+{texts.format_price(transaction.amount_kopeks)}'
|
||||
if transaction.type == TransactionType.DEPOSIT.value
|
||||
if is_credit
|
||||
else f'-{texts.format_price(abs(transaction.amount_kopeks))}'
|
||||
)
|
||||
|
||||
@@ -513,15 +525,17 @@ async def handle_successful_topup_with_cart(user_id: int, amount_kopeks: int, bo
|
||||
]
|
||||
)
|
||||
|
||||
if 0 < total_price <= user.balance_kopeks:
|
||||
balance_hint = 'Средств на балансе достаточно для оформления.'
|
||||
else:
|
||||
missing = max(total_price - user.balance_kopeks, 0)
|
||||
balance_hint = f'Не хватает: {texts.format_price(missing)}'
|
||||
|
||||
success_text = (
|
||||
f'✅ Баланс пополнен на {texts.format_price(amount_kopeks)}!\n\n'
|
||||
f'💰 Текущий баланс: {texts.format_price(user.balance_kopeks)}\n\n'
|
||||
f'⚠️ <b>Важно:</b> Пополнение баланса не активирует подписку автоматически. '
|
||||
f'Обязательно активируйте подписку отдельно!\n\n'
|
||||
f'🔄 При наличии сохранённой корзины подписки и включенной автопокупке, '
|
||||
f'подписка будет приобретена автоматически после пополнения баланса.\n\n'
|
||||
f'🛒 У вас есть сохраненная корзина подписки\n'
|
||||
f'Стоимость: {texts.format_price(total_price)}\n\n'
|
||||
f'🛒 У вас есть сохранённая корзина на {texts.format_price(total_price)}\n'
|
||||
f'{balance_hint}\n\n'
|
||||
f'Хотите продолжить оформление?'
|
||||
)
|
||||
|
||||
@@ -838,10 +852,21 @@ def register_balance_handlers(dp: Dispatcher):
|
||||
dp.callback_query.register(start_cloudpayments_payment, F.data == 'topup_cloudpayments')
|
||||
dp.callback_query.register(handle_cloudpayments_quick_amount, F.data.startswith('topup_amount|cloudpayments|'))
|
||||
|
||||
from .freekassa import process_freekassa_quick_amount, start_freekassa_topup
|
||||
from .freekassa import (
|
||||
process_freekassa_card_quick_amount,
|
||||
process_freekassa_quick_amount,
|
||||
process_freekassa_sbp_quick_amount,
|
||||
start_freekassa_card_topup,
|
||||
start_freekassa_sbp_topup,
|
||||
start_freekassa_topup,
|
||||
)
|
||||
|
||||
dp.callback_query.register(start_freekassa_topup, F.data == 'topup_freekassa')
|
||||
dp.callback_query.register(process_freekassa_quick_amount, F.data.startswith('topup_amount|freekassa|'))
|
||||
dp.callback_query.register(start_freekassa_sbp_topup, F.data == 'topup_freekassa_sbp')
|
||||
dp.callback_query.register(process_freekassa_sbp_quick_amount, F.data.startswith('topup_amount|freekassa_sbp|'))
|
||||
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
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ from aiogram.filters import IS_MEMBER, IS_NOT_MEMBER, ChatMemberUpdatedFilter
|
||||
from aiogram.types import ChatMemberUpdated
|
||||
|
||||
from app.config import settings
|
||||
from app.database.crud.subscription import deactivate_subscription, is_active_paid_subscription, reactivate_subscription
|
||||
from app.database.crud.subscription import deactivate_subscription, reactivate_subscription
|
||||
from app.database.crud.user import get_user_by_telegram_id
|
||||
from app.database.database import AsyncSessionLocal
|
||||
from app.database.models import SubscriptionStatus, UserStatus
|
||||
@@ -59,9 +59,6 @@ async def on_user_joined_channel(event: ChatMemberUpdated, bot: Bot) -> None:
|
||||
return # Still missing some channels
|
||||
|
||||
# Reactivate subscription if it was disabled due to channel unsubscribe
|
||||
if not settings.CHANNEL_DISABLE_TRIAL_ON_UNSUBSCRIBE and not settings.CHANNEL_REQUIRED_FOR_ALL:
|
||||
return
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
try:
|
||||
db_user = await get_user_by_telegram_id(db, user.id)
|
||||
@@ -125,7 +122,9 @@ async def on_user_left_channel(event: ChatMemberUpdated, bot: Bot) -> None:
|
||||
if settings.is_admin(user.id):
|
||||
return
|
||||
|
||||
if not settings.CHANNEL_DISABLE_TRIAL_ON_UNSUBSCRIBE and not settings.CHANNEL_REQUIRED_FOR_ALL:
|
||||
# Fetch per-channel settings to decide whether to disable
|
||||
channel_settings = await channel_subscription_service.get_channel_settings(channel_id)
|
||||
if not channel_settings:
|
||||
return
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
@@ -138,15 +137,8 @@ async def on_user_left_channel(event: ChatMemberUpdated, bot: Bot) -> None:
|
||||
if subscription.status != SubscriptionStatus.ACTIVE.value:
|
||||
return
|
||||
|
||||
# CHANNEL_REQUIRED_FOR_ALL: deactivate regardless of trial status
|
||||
# CHANNEL_DISABLE_TRIAL_ON_UNSUBSCRIBE: only deactivate trial subscriptions
|
||||
if settings.CHANNEL_REQUIRED_FOR_ALL:
|
||||
pass # Deactivate any active subscription
|
||||
elif not subscription.is_trial:
|
||||
return # Not a trial -- skip
|
||||
|
||||
# Guard against paid subscriptions (user paid money, don't punish)
|
||||
if is_active_paid_subscription(subscription):
|
||||
# Per-channel settings: check if this channel requires deactivation
|
||||
if not channel_subscription_service.should_disable_subscription(channel_settings, subscription.is_trial):
|
||||
return
|
||||
|
||||
await deactivate_subscription(db, subscription)
|
||||
|
||||
+12
-3
@@ -1337,6 +1337,18 @@ async def handle_activate_button(callback: types.CallbackQuery, db_user: User, d
|
||||
show_alert=True,
|
||||
)
|
||||
else:
|
||||
# Списать баланс ДО создания подписки (чтобы не было orphaned subscription при неудаче)
|
||||
success = await subtract_user_balance(
|
||||
db,
|
||||
db_user,
|
||||
best_price,
|
||||
f'Активация подписки на {best_period} дней',
|
||||
mark_as_paid_subscription=True,
|
||||
)
|
||||
if not success:
|
||||
await callback.answer('❌ Недостаточно средств', show_alert=True)
|
||||
return
|
||||
|
||||
# Создание новой подписки
|
||||
new_subscription = await create_paid_subscription(
|
||||
db,
|
||||
@@ -1348,9 +1360,6 @@ async def handle_activate_button(callback: types.CallbackQuery, db_user: User, d
|
||||
update_server_counters=True,
|
||||
)
|
||||
|
||||
# Списать баланс правильно
|
||||
await subtract_user_balance(db, db_user, best_price, f'Активация подписки на {best_period} дней')
|
||||
|
||||
# Создать пользователя в RemnaWave
|
||||
await subscription_service.create_remnawave_user(db, new_subscription)
|
||||
|
||||
|
||||
@@ -139,6 +139,10 @@ async def process_promocode(message: types.Message, db_user: User, state: FSMCon
|
||||
'PROMOCODE_ACTIVE_DISCOUNT_EXISTS',
|
||||
'❌ У вас уже есть активная скидка. Используйте её перед активацией новой.',
|
||||
),
|
||||
'no_subscription_for_days': texts.t(
|
||||
'PROMOCODE_NO_SUBSCRIPTION',
|
||||
'❌ Для активации этого промокода необходима подписка (активная или просроченная).',
|
||||
),
|
||||
'daily_limit': texts.t(
|
||||
'PROMO_DAILY_LIMIT',
|
||||
'❌ Достигнут лимит активаций промокодов на сегодня. Попробуйте завтра.',
|
||||
|
||||
@@ -433,18 +433,33 @@ async def handle_simple_subscription_pay_with_balance(
|
||||
# Списываем средства с баланса пользователя
|
||||
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,
|
||||
f'Оплата подписки на {subscription_params["period_days"]} дней',
|
||||
purchase_description,
|
||||
consume_promo_offer=False,
|
||||
mark_as_paid_subscription=True,
|
||||
)
|
||||
|
||||
if not success:
|
||||
await callback.answer('❌ Ошибка списания средств с баланса', show_alert=True)
|
||||
return
|
||||
|
||||
# Создаём транзакцию для учёта списания
|
||||
from app.database.crud.transaction import create_transaction
|
||||
from app.database.models import PaymentMethod, TransactionType
|
||||
|
||||
transaction = await create_transaction(
|
||||
db,
|
||||
user_id=db_user.id,
|
||||
type=TransactionType.SUBSCRIPTION_PAYMENT,
|
||||
amount_kopeks=price_kopeks,
|
||||
description=purchase_description,
|
||||
payment_method=PaymentMethod.BALANCE,
|
||||
)
|
||||
|
||||
# Проверяем, есть ли у пользователя уже подписка
|
||||
from app.database.crud.subscription import extend_subscription, get_subscription_by_user_id
|
||||
|
||||
@@ -456,11 +471,13 @@ async def handle_simple_subscription_pay_with_balance(
|
||||
was_trial = getattr(existing_subscription, 'is_trial', False)
|
||||
|
||||
subscription = await extend_subscription(
|
||||
db=db, subscription=existing_subscription, days=subscription_params['period_days']
|
||||
db=db,
|
||||
subscription=existing_subscription,
|
||||
days=subscription_params['period_days'],
|
||||
traffic_limit_gb=subscription_params['traffic_limit_gb'],
|
||||
device_limit=subscription_params['device_limit'],
|
||||
connected_squads=[resolved_squad_uuid] if resolved_squad_uuid else None,
|
||||
)
|
||||
# Обновляем параметры подписки
|
||||
subscription.traffic_limit_gb = subscription_params['traffic_limit_gb']
|
||||
subscription.device_limit = subscription_params['device_limit']
|
||||
|
||||
# Если текущая подписка была пробной, и мы обновляем её
|
||||
# нужно изменить статус подписки
|
||||
@@ -471,10 +488,6 @@ async def handle_simple_subscription_pay_with_balance(
|
||||
subscription.status = SubscriptionStatus.ACTIVE.value
|
||||
subscription.is_trial = False
|
||||
|
||||
# Устанавливаем новый выбранный сквад
|
||||
if resolved_squad_uuid:
|
||||
subscription.connected_squads = [resolved_squad_uuid]
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(subscription)
|
||||
else:
|
||||
@@ -632,7 +645,7 @@ async def handle_simple_subscription_pay_with_balance(
|
||||
db,
|
||||
db_user,
|
||||
subscription,
|
||||
None, # transaction
|
||||
transaction,
|
||||
subscription_params['period_days'],
|
||||
False, # was_trial_conversion
|
||||
amount_kopeks=price_kopeks,
|
||||
@@ -2139,18 +2152,33 @@ async def confirm_simple_subscription_purchase(
|
||||
# Списываем средства с баланса пользователя
|
||||
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,
|
||||
f'Оплата подписки на {subscription_params["period_days"]} дней',
|
||||
purchase_description,
|
||||
consume_promo_offer=False,
|
||||
mark_as_paid_subscription=True,
|
||||
)
|
||||
|
||||
if not success:
|
||||
await callback.answer('❌ Ошибка списания средств с баланса', show_alert=True)
|
||||
return
|
||||
|
||||
# Создаём транзакцию для учёта списания
|
||||
from app.database.crud.transaction import create_transaction
|
||||
from app.database.models import PaymentMethod, TransactionType
|
||||
|
||||
transaction = await create_transaction(
|
||||
db,
|
||||
user_id=db_user.id,
|
||||
type=TransactionType.SUBSCRIPTION_PAYMENT,
|
||||
amount_kopeks=price_kopeks,
|
||||
description=purchase_description,
|
||||
payment_method=PaymentMethod.BALANCE,
|
||||
)
|
||||
|
||||
# Проверяем, есть ли у пользователя уже подписка
|
||||
from app.database.crud.subscription import extend_subscription, get_subscription_by_user_id
|
||||
|
||||
@@ -2162,11 +2190,13 @@ async def confirm_simple_subscription_purchase(
|
||||
was_trial = getattr(existing_subscription, 'is_trial', False)
|
||||
|
||||
subscription = await extend_subscription(
|
||||
db=db, subscription=existing_subscription, days=subscription_params['period_days']
|
||||
db=db,
|
||||
subscription=existing_subscription,
|
||||
days=subscription_params['period_days'],
|
||||
traffic_limit_gb=subscription_params['traffic_limit_gb'],
|
||||
device_limit=subscription_params['device_limit'],
|
||||
connected_squads=[resolved_squad_uuid] if resolved_squad_uuid else None,
|
||||
)
|
||||
# Обновляем параметры подписки
|
||||
subscription.traffic_limit_gb = subscription_params['traffic_limit_gb']
|
||||
subscription.device_limit = subscription_params['device_limit']
|
||||
|
||||
# Если текущая подписка была пробной, и мы обновляем её
|
||||
# нужно изменить статус подписки
|
||||
@@ -2177,10 +2207,6 @@ async def confirm_simple_subscription_purchase(
|
||||
subscription.status = SubscriptionStatus.ACTIVE.value
|
||||
subscription.is_trial = False
|
||||
|
||||
# Устанавливаем новый выбранный сквад
|
||||
if resolved_squad_uuid:
|
||||
subscription.connected_squads = [resolved_squad_uuid]
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(subscription)
|
||||
else:
|
||||
@@ -2338,7 +2364,7 @@ async def confirm_simple_subscription_purchase(
|
||||
db,
|
||||
db_user,
|
||||
subscription,
|
||||
None, # transaction
|
||||
transaction,
|
||||
subscription_params['period_days'],
|
||||
False, # was_trial_conversion
|
||||
amount_kopeks=price_kopeks,
|
||||
|
||||
@@ -37,8 +37,38 @@ async def _handle_wheel_spin_payment(
|
||||
)
|
||||
return False
|
||||
|
||||
# Проверяем наличие активной подписки
|
||||
from app.database.crud.subscription import get_subscription_by_user_id
|
||||
|
||||
subscription = await get_subscription_by_user_id(db, user.id)
|
||||
if not subscription or not subscription.is_active:
|
||||
# Конвертируем Stars в баланс как компенсацию
|
||||
rubles_fallback = TelegramStarsService.calculate_rubles_from_stars(stars_amount)
|
||||
kopeks_fallback = int((rubles_fallback * Decimal(100)).to_integral_value(rounding=ROUND_HALF_UP))
|
||||
from app.database.crud.user import add_user_balance
|
||||
from app.database.models import TransactionType
|
||||
|
||||
await add_user_balance(
|
||||
db,
|
||||
user,
|
||||
kopeks_fallback,
|
||||
f'Возврат за спин колеса без подписки ({stars_amount} Stars)',
|
||||
transaction_type=TransactionType.REFUND,
|
||||
)
|
||||
await db.commit()
|
||||
await message.answer(
|
||||
'❌ Для использования колеса удачи необходима активная подписка.\n'
|
||||
f'💰 {stars_amount} Stars возвращены на баланс в виде {kopeks_fallback / 100:.0f} ₽.',
|
||||
)
|
||||
logger.warning(
|
||||
'Wheel spin without subscription, refunded to balance',
|
||||
user_id=user.id,
|
||||
stars_amount=stars_amount,
|
||||
refund_kopeks=kopeks_fallback,
|
||||
)
|
||||
return False
|
||||
|
||||
# Выполняем спин напрямую (оплата уже прошла через Stars)
|
||||
prizes = await get_or_create_wheel_config(db)
|
||||
prizes = await get_wheel_prizes(db, config.id, active_only=True)
|
||||
|
||||
if not prizes:
|
||||
@@ -64,7 +94,11 @@ async def _handle_wheel_spin_payment(
|
||||
|
||||
promocode_id = None
|
||||
if generated_promocode:
|
||||
result = await db.execute(f"SELECT id FROM promocodes WHERE code = '{generated_promocode}'")
|
||||
from sqlalchemy import text
|
||||
|
||||
result = await db.execute(
|
||||
text('SELECT id FROM promocodes WHERE code = :code'), {'code': generated_promocode}
|
||||
)
|
||||
row = result.fetchone()
|
||||
if row:
|
||||
promocode_id = row[0]
|
||||
@@ -419,10 +453,6 @@ async def handle_successful_payment(message: types.Message, db: AsyncSession, st
|
||||
'⭐ Потрачено звезд: {stars_spent}\n'
|
||||
'💰 Зачислено на баланс: {amount} ₽\n'
|
||||
'🆔 ID транзакции: {transaction_id}...\n\n'
|
||||
'⚠️ <b>Важно:</b> Пополнение баланса не активирует подписку автоматически. '
|
||||
'Обязательно активируйте подписку отдельно!\n\n'
|
||||
'🔄 При наличии сохранённой корзины подписки и включенной автопокупке, '
|
||||
'подписка будет приобретена автоматически после пополнения баланса.\n\n'
|
||||
'Спасибо за пополнение! 🚀',
|
||||
).format(
|
||||
stars_spent=payment.total_amount,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user