Compare commits
131 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1b94d9e700 | |||
| 39a7c92cd4 | |||
| 81ebec676c | |||
| 25ea5c60fd | |||
| 29877fc93b | |||
| 5986c00fab | |||
| ecc4a6147d | |||
| 16bc1d4198 | |||
| 0f814be1b7 | |||
| 97179360c0 | |||
| 2aa5927433 | |||
| 1c696c69e3 | |||
| b531959982 | |||
| ead0fc99d3 | |||
| c09ae7436c | |||
| 1ea76575ce | |||
| 25447edc9e | |||
| a59858227f | |||
| ccc2f4efec | |||
| a18f6caa9b | |||
| 92eaf45311 | |||
| 61cf495fc5 | |||
| 0c545490b6 | |||
| 2d5afe5d75 | |||
| 50dc5a0fd1 | |||
| 4dc8b4c091 | |||
| 4db9e85062 | |||
| fca8d6da97 | |||
| 4fe67a9c74 | |||
| 30a1a31978 | |||
| c2b68e1afa | |||
| cea7260a85 | |||
| e3c0caabcf | |||
| aeaa4f8e0d | |||
| e226ac8637 | |||
| 85403da528 | |||
| bdd873382c | |||
| 9d750d9eb0 | |||
| 87b83f59c6 | |||
| 8ff6f99229 | |||
| 94da3c35b0 | |||
| d35a8bb74c | |||
| c635d88764 | |||
| 5009703676 | |||
| e88a5989b6 | |||
| 02747381dc | |||
| e74fda954c | |||
| 8587f03f67 | |||
| 4707cdf60c | |||
| 0879b8b218 | |||
| 1d91382b8e | |||
| 3768b18a39 | |||
| 1eeeb39779 | |||
| 570af82dfd | |||
| bc3893b934 | |||
| 16d91638bc | |||
| eb18b3a0f9 | |||
| a8e2b62f4b | |||
| fb8d2b3ee4 | |||
| 2321667ecb | |||
| 113304b212 | |||
| 0300044b00 | |||
| 931abfe7a5 | |||
| 1d96f80f60 | |||
| 4e50419171 | |||
| 7208a52c94 | |||
| 63fdfe4a42 | |||
| e0e2edf816 | |||
| 522a8779d6 | |||
| be32010d63 | |||
| 7e920fa30f | |||
| 1b376baeca | |||
| 91a756a33e | |||
| 970dc549df | |||
| 65120f0bad | |||
| 9cb559ff39 | |||
| 8f1882f24c | |||
| 8542a39305 | |||
| 646ac4cfa1 | |||
| abdf296767 | |||
| a1b6d9bb61 | |||
| cf19e4e1f7 | |||
| 35412e9f21 | |||
| 6aed7d355b | |||
| 9c08ce6948 | |||
| 862352139e | |||
| d465ccb3ac | |||
| b57f185258 | |||
| ffbb3fb8be | |||
| f01dbff000 | |||
| 31adcfded4 | |||
| 78f963bf5e | |||
| 357d94d1b0 | |||
| 0fb4a2c235 | |||
| 2f7184627a | |||
| d55e9db62a | |||
| 57adfaf4f3 | |||
| 4165eaea7a | |||
| 3b5d5a18a1 | |||
| eef41c4bca | |||
| 987c3c93c2 | |||
| 7d24e8d704 | |||
| 819f09a68e | |||
| 2f9d00343b | |||
| 9b7ac47f16 | |||
| 0d5638f778 | |||
| 7836720db3 | |||
| dcb90d6139 | |||
| 96c420e917 | |||
| 9d63635502 | |||
| c4c5d330be | |||
| 977950b97f | |||
| 6f6b9fa039 | |||
| 6713921887 | |||
| 2d42152f54 | |||
| 08ca947b2b | |||
| b04157c913 | |||
| f284351c51 | |||
| b607993854 | |||
| 246659032d | |||
| 3dc72b00e7 | |||
| 033d0da5e0 | |||
| 991f0b43e1 | |||
| c9524cb703 | |||
| 76d4a2124c | |||
| 4fa230c07f | |||
| d580a78403 | |||
| 312cc728a9 | |||
| b1820c651d | |||
| 0c284b9e99 | |||
| 72170b35f5 |
+70
-2
@@ -13,11 +13,15 @@ SUPPORT_USERNAME=@support
|
||||
# Имя пользователя бота (опционально, автоопределяется)
|
||||
# BOT_USERNAME=
|
||||
|
||||
# ===== SOCKS5 ПРОКСИ =====
|
||||
# ===== СЕТЬ И ПРОКСИ =====
|
||||
# URL SOCKS5 прокси-сервера для маршрутизации трафика бота к Telegram API
|
||||
# Формат: socks5://user:password@host:port или socks5://host:port
|
||||
# PROXY_URL=socks5://127.0.0.1:1080
|
||||
|
||||
# Альтернативный URL сервера Telegram Bot API (для регионов где api.telegram.org заблокирован)
|
||||
# Примеры: Cloudflare Worker, self-hosted telegram-bot-api (tdlib), любой совместимый прокси
|
||||
# TELEGRAM_API_URL=https://your-telegram-proxy.workers.dev
|
||||
|
||||
# ===== СИСТЕМА ПОДДЕРЖКИ =====
|
||||
# Включить меню поддержки в интерфейсе
|
||||
SUPPORT_MENU_ENABLED=true
|
||||
@@ -614,7 +618,7 @@ PLATEGA_RETURN_URL=
|
||||
PLATEGA_FAILED_URL=
|
||||
PLATEGA_CURRENCY=RUB
|
||||
# Список ID активных методов из кабинета Platega (через запятую)
|
||||
PLATEGA_ACTIVE_METHODS=2,10,11,12,13
|
||||
PLATEGA_ACTIVE_METHODS=2,11,12,13
|
||||
PLATEGA_MIN_AMOUNT_KOPEKS=100
|
||||
PLATEGA_MAX_AMOUNT_KOPEKS=100000000
|
||||
PLATEGA_WEBHOOK_PATH=/platega-webhook
|
||||
@@ -680,6 +684,70 @@ RIOPAY_WEBHOOK_PATH=/riopay-webhook
|
||||
RIOPAY_SUCCESS_URL=
|
||||
RIOPAY_FAIL_URL=
|
||||
|
||||
# ===== SEVERPAY (severpay.io) =====
|
||||
SEVERPAY_ENABLED=false
|
||||
# Merchant ID
|
||||
SEVERPAY_MID=
|
||||
# Секретный токен для HMAC-SHA256
|
||||
SEVERPAY_TOKEN=
|
||||
SEVERPAY_DISPLAY_NAME=SeverPay
|
||||
SEVERPAY_CURRENCY=RUB
|
||||
SEVERPAY_MIN_AMOUNT_KOPEKS=10000
|
||||
SEVERPAY_MAX_AMOUNT_KOPEKS=10000000
|
||||
SEVERPAY_WEBHOOK_PATH=/severpay-webhook
|
||||
# URL возврата после оплаты
|
||||
# SEVERPAY_RETURN_URL=
|
||||
# Время жизни платежа в минутах (30-4320)
|
||||
SEVERPAY_LIFETIME=1440
|
||||
|
||||
# ===== PAYPEAR (api.paypear.ru) =====
|
||||
PAYPEAR_ENABLED=false
|
||||
# Shop ID для HTTP Basic Auth
|
||||
PAYPEAR_SHOP_ID=
|
||||
# Secret Key для HTTP Basic Auth
|
||||
PAYPEAR_SECRET_KEY=
|
||||
PAYPEAR_DISPLAY_NAME=PayPear
|
||||
PAYPEAR_CURRENCY=RUB
|
||||
PAYPEAR_MIN_AMOUNT_KOPEKS=10000
|
||||
PAYPEAR_MAX_AMOUNT_KOPEKS=10000000
|
||||
PAYPEAR_WEBHOOK_PATH=/paypear-webhook
|
||||
# URL возврата после оплаты
|
||||
# PAYPEAR_RETURN_URL=
|
||||
# Время жизни платежа в минутах
|
||||
PAYPEAR_PAYMENT_LIFETIME_MINUTES=60
|
||||
|
||||
# ===== ROLLYPAY (rollypay.io) =====
|
||||
ROLLYPAY_ENABLED=false
|
||||
# API ключ (X-API-Key header)
|
||||
ROLLYPAY_API_KEY=
|
||||
# Секрет для HMAC-SHA256 верификации вебхуков
|
||||
ROLLYPAY_SIGNING_SECRET=
|
||||
ROLLYPAY_DISPLAY_NAME=RollyPay
|
||||
ROLLYPAY_CURRENCY=RUB
|
||||
ROLLYPAY_MIN_AMOUNT_KOPEKS=10000
|
||||
ROLLYPAY_MAX_AMOUNT_KOPEKS=10000000
|
||||
ROLLYPAY_WEBHOOK_PATH=/rollypay-webhook
|
||||
# URL возврата после оплаты
|
||||
# ROLLYPAY_RETURN_URL=
|
||||
|
||||
# ===== AURAPAY (aurapay.tech) =====
|
||||
AURAPAY_ENABLED=false
|
||||
# API ключ (X-ApiKey header)
|
||||
AURAPAY_API_KEY=
|
||||
# UUID магазина (X-ShopId header)
|
||||
AURAPAY_SHOP_ID=
|
||||
# Секретный ключ #2 для HMAC-SHA256 верификации вебхуков
|
||||
AURAPAY_SECRET_KEY=
|
||||
AURAPAY_DISPLAY_NAME=AuraPay
|
||||
AURAPAY_CURRENCY=RUB
|
||||
AURAPAY_MIN_AMOUNT_KOPEKS=10000
|
||||
AURAPAY_MAX_AMOUNT_KOPEKS=10000000
|
||||
AURAPAY_WEBHOOK_PATH=/aurapay-webhook
|
||||
# URL возврата после оплаты
|
||||
# AURAPAY_RETURN_URL=
|
||||
# Время жизни инвойса в минутах
|
||||
AURAPAY_PAYMENT_LIFETIME_MINUTES=60
|
||||
|
||||
# ===== WATA =====
|
||||
WATA_ENABLED=false
|
||||
WATA_BASE_URL=https://api.wata.pro
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 822 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 76 KiB |
@@ -26,36 +26,38 @@ jobs:
|
||||
- name: Get version info
|
||||
id: version
|
||||
run: |
|
||||
echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
|
||||
|
||||
SHORT_SHA=$(git rev-parse --short HEAD)
|
||||
echo "short_sha=$SHORT_SHA" >> $GITHUB_OUTPUT
|
||||
echo "build_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
|
||||
|
||||
# Определяем версию и теги
|
||||
|
||||
# Read base version from release-please manifest (single source of truth)
|
||||
BASE_VERSION=$(jq -r '."."' .release-please-manifest.json)
|
||||
|
||||
if [[ $GITHUB_REF == refs/tags/* ]]; then
|
||||
VERSION=${GITHUB_REF#refs/tags/}
|
||||
TAGS="fr1ngg/remnawave-bedolaga-telegram-bot:latest,fr1ngg/remnawave-bedolaga-telegram-bot:${VERSION}"
|
||||
echo "🏷️ Собираем релизную версию: $VERSION"
|
||||
elif [[ $GITHUB_REF == refs/heads/main ]]; then
|
||||
VERSION="v3.7.0-$(git rev-parse --short HEAD)" # x-release-please-version
|
||||
VERSION="v${BASE_VERSION}-${SHORT_SHA}"
|
||||
TAGS="fr1ngg/remnawave-bedolaga-telegram-bot:latest,fr1ngg/remnawave-bedolaga-telegram-bot:${VERSION}"
|
||||
echo "🚀 Собираем версию из main: $VERSION"
|
||||
elif [[ $GITHUB_REF == refs/heads/dev ]]; then
|
||||
VERSION="v3.7.0-dev-$(git rev-parse --short HEAD)" # x-release-please-version
|
||||
VERSION="v${BASE_VERSION}-dev-${SHORT_SHA}"
|
||||
TAGS="fr1ngg/remnawave-bedolaga-telegram-bot:dev,fr1ngg/remnawave-bedolaga-telegram-bot:${VERSION}"
|
||||
echo "🧪 Собираем dev версию: $VERSION"
|
||||
else
|
||||
VERSION="v3.7.0-pr-$(git rev-parse --short HEAD)" # x-release-please-version
|
||||
TAGS="fr1ngg/remnawave-bedolaga-telegram-bot:pr-$(git rev-parse --short HEAD)"
|
||||
VERSION="v${BASE_VERSION}-pr-${SHORT_SHA}"
|
||||
TAGS="fr1ngg/remnawave-bedolaga-telegram-bot:pr-${SHORT_SHA}"
|
||||
echo "🔀 Собираем PR версию: $VERSION"
|
||||
fi
|
||||
|
||||
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
echo "tags=$TAGS" >> $GITHUB_OUTPUT
|
||||
echo "should_push=${{ github.event_name != 'pull_request' }}" >> $GITHUB_OUTPUT
|
||||
|
||||
|
||||
echo "=== Информация о сборке ==="
|
||||
echo "Версия: $VERSION"
|
||||
echo "Коммит: $(git rev-parse --short HEAD)"
|
||||
echo "Коммит: $SHORT_SHA"
|
||||
echo "Теги: $TAGS"
|
||||
echo "Push: ${{ github.event_name != 'pull_request' }}"
|
||||
echo "==========================="
|
||||
|
||||
@@ -42,25 +42,28 @@ jobs:
|
||||
- name: Get version info
|
||||
id: version
|
||||
run: |
|
||||
echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
|
||||
SHORT_SHA=$(git rev-parse --short HEAD)
|
||||
echo "short_sha=$SHORT_SHA" >> $GITHUB_OUTPUT
|
||||
echo "build_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
|
||||
|
||||
|
||||
# Read base version from release-please manifest (single source of truth)
|
||||
BASE_VERSION=$(jq -r '."."' .release-please-manifest.json)
|
||||
|
||||
if [[ $GITHUB_REF == refs/tags/* ]]; then
|
||||
VERSION=${GITHUB_REF#refs/tags/}
|
||||
echo "🏷️ Building release version: $VERSION"
|
||||
elif [[ $GITHUB_REF == refs/heads/main ]]; then
|
||||
VERSION="v3.7.0-$(git rev-parse --short HEAD)" # x-release-please-version
|
||||
VERSION="v${BASE_VERSION}-${SHORT_SHA}"
|
||||
echo "🚀 Building main version: $VERSION"
|
||||
elif [[ $GITHUB_REF == refs/heads/dev ]]; then
|
||||
VERSION="v3.7.0-dev-$(git rev-parse --short HEAD)" # x-release-please-version
|
||||
VERSION="v${BASE_VERSION}-dev-${SHORT_SHA}"
|
||||
echo "🧪 Building dev version: $VERSION"
|
||||
else
|
||||
VERSION="v3.7.0-pr-$(git rev-parse --short HEAD)" # x-release-please-version
|
||||
VERSION="v${BASE_VERSION}-pr-${SHORT_SHA}"
|
||||
echo "🔀 Building PR version: $VERSION"
|
||||
fi
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
# Определяем, нужно ли пушить образ
|
||||
|
||||
if [[ "${{ github.event_name }}" == "pull_request" ]]; then
|
||||
echo "should_push=false" >> $GITHUB_OUTPUT
|
||||
echo "⚠️ PR - only build without push"
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "3.43.0"
|
||||
".": "3.49.0"
|
||||
}
|
||||
|
||||
+174
@@ -1,5 +1,179 @@
|
||||
# Changelog
|
||||
|
||||
## [3.49.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.48.0...v3.49.0) (2026-04-18)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* integrate AuraPay payment provider ([9717936](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/97179360c0288940b1fa2f6c21a6e1431a27536f))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add missing RollyPay CRUD wrappers and guest payment flow ([0f814be](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0f814be1b7dfaec84dde9acc402b2c1790417611))
|
||||
* align campaign top registrations revenue with period comparison ([16bc1d4](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/16bc1d41989d66e105724ed846fb40ccf03322fd))
|
||||
* handle edge case when all tariffs are daily in legacy renewal ([29877fc](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/29877fc93bc612ee199ccb2438c90e57a3c1e9e0))
|
||||
* rate-limit daily subscription insufficient balance notifications to 6 hours ([ecc4a61](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ecc4a6147dad0c8886acd48f38e567a6c7fc8916))
|
||||
* redirect legacy users without tariff to tariff selection on renewal ([5986c00](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/5986c00fab8c5fe2060d296afca72d28038ff7bd))
|
||||
* register PayPear and RollyPay in admin panel settings ([2aa5927](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2aa59274331610eec3cd84f90ddb49ee59da22ef))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* add AuraPay to README with partner block ([25ea5c6](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/25ea5c60fdaf3cac9294b6df74142c176b1d4d04))
|
||||
* add PayPear and RollyPay to README with partner blocks ([1c696c6](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1c696c69e34e668ff90c915249b7c3dc37bfd89b))
|
||||
* add PayPear and RollyPay to README with partner blocks ([b531959](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b53195998231d34b6e1c7165193e87fee6e5c293))
|
||||
|
||||
## [3.48.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.47.0...v3.48.0) (2026-04-16)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* integrate PayPear payment provider ([a18f6ca](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a18f6caa9bd9c08511c464e6141fb8aa614135b0))
|
||||
* integrate RollyPay payment provider (SBP via USDT) ([ccc2f4e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ccc2f4efecf0a3c1a943971c81a9a7d1985ae14a))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* increase nalogo receipt queue retry window to 12 hours ([92eaf45](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/92eaf4531162e5625b938bafc43eb98abe2632e2))
|
||||
* low balance alerts disabled by default, add quiet hours, expiry filter, top-up button ([2d5afe5](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2d5afe5d75ff65f4d167a853e078943d518a881f))
|
||||
* show menu buttons for limited (traffic exhausted) subscriptions ([0c54549](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0c545490b61baec930f10adc86652a7e5cf5d378))
|
||||
* show menu buttons for limited subscriptions in back-to-menu paths ([61cf495](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/61cf495fc5919e699aba7231f49222722da044b4))
|
||||
* support payment_method selection for RollyPay (sbp/card/crypto) ([a598582](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a59858227f31bd53d0ac54d693288ad52e447687))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* add SEVERPAY, PAYPEAR, ROLLYPAY to .env.example ([25447ed](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/25447edc9eab7c3a76ed94be52c1b341917a40c2))
|
||||
|
||||
## [3.47.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.46.1...v3.47.0) (2026-04-15)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* multi-tariff sync fix, daily discount fix, campaign links, TELEGRAM_API_URL ([4db9e85](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4db9e850629f25cbcb11bb5ba0e0de5c580ca115))
|
||||
|
||||
## [3.46.1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.46.0...v3.46.1) (2026-04-13)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add checkfirst guards to cabinet_refresh_tokens migration ([8587f03](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/8587f03f67d7a451b07a4d9c450bc4524f4ac0e7))
|
||||
* add missing migration for cabinet_refresh_tokens table ([4707cdf](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4707cdf60c9d163c1191719b3b1fc4a17ae993d2))
|
||||
* cabinet_refresh_tokens migration + notification_settings jsonb ([0274738](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/02747381dce2b96af7f97b5f41d6acff5d9d8fd3))
|
||||
* change notification_settings from json to jsonb for DISTINCT compatibility ([e74fda9](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e74fda954ccc63e2ac7a30933d9f9ac26772b25d))
|
||||
|
||||
## [3.46.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.45.2...v3.46.0) (2026-04-13)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* add broadcast category (system/news/promo) + filter recipients by user prefs ([931abfe](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/931abfe7a5a7fb70e9638fbf6b566fa8d1a837e4))
|
||||
* add category field to broadcast API schemas and routes ([0300044](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0300044b009f3e4b3aa3928652dfaf261a387dbc))
|
||||
* add RemnaWave retry queue for failed API calls (BUG-2, BUG-10) ([abdf296](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/abdf2967675975e90f0c4d834f129281c1c28e7b))
|
||||
* add remnawave_resync_service for identity-change sync ([b57f185](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b57f185258be050d945cec5989ad6dc710980a6a))
|
||||
* add traffic % warning check using user's threshold preference ([1d96f80](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1d96f80f60ca445eb5108e7bc54e00d022a4cc9e))
|
||||
* add user notification preferences helper utility ([e0e2edf](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e0e2edf81659fbeea361046d1bb2718c2149d884))
|
||||
* implement low balance alert + respect user notification preferences ([4e50419](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4e50419171176ee452371ff095bdfead3879e554))
|
||||
* respect user subscription_expiry notification preferences ([63fdfe4](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/63fdfe4a421942b26caca35d8bd9b1d65f1fe7e2))
|
||||
* respect user traffic_warning notification preference in webhook handler ([7208a52](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7208a52c9424d39757187fc86eec2c3460a2cdbb))
|
||||
* save campaign_slug during standalone email registration ([a8e2b62](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a8e2b62f4bb0833ca32446b34ad4e0c5615fcd2a))
|
||||
* start RemnaWave retry queue on app startup ([8f1882f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/8f1882f24c7d066e2d0fc756f38ce23bf082687e))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add retry queue to all remaining RemnaWave error handlers ([7e920fa](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7e920fa30fc8e61ed2dd31e7a09151d57b7361ca))
|
||||
* add retry queue to cabinet subscription operation RemnaWave errors ([1b376ba](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1b376baeca120970b1ffcd406b1bbf7d9d43cee0))
|
||||
* add retry queue to classic mode bot purchase handler ([970dc54](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/970dc549dfa06ba9945d5bd861374058acdca86b))
|
||||
* add retry queue to daily subscription service RemnaWave errors ([65120f0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/65120f0badc9a4581ba0a127acdae8a0b23e8501))
|
||||
* add retry queue to payment webhook and renewal service RemnaWave errors ([91a756a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/91a756a33ed4ce685bdf485cdb4e91c3e08799dd))
|
||||
* add TRAFFIC_WARNING_ALERT and LOW_BALANCE_ALERT localization keys to all locales ([2321667](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2321667ecbe76bfe8dd37213e0bb4e45104e0fc5))
|
||||
* always sync squads in auto-purchase renewal (BUG-4) ([8542a39](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/8542a393055a93d320d5c8c6d3aa7cc291cf8def))
|
||||
* default sync_squads=True in update_remnawave_user (BUG-4) ([6aed7d3](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/6aed7d355bc47c4dbd2aa761d78a5e5421c32edf))
|
||||
* enforce max_attempts limit in NaloGO receipt queue ([16d9163](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/16d91638bc149c5eee8f4cdd266cbd195c411030))
|
||||
* enqueue retry on RemnaWave API failure in all purchase flows (BUG-2, BUG-10) ([9cb559f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9cb559ff3994c0f1c6ba48a4ec09dec9b391e48b))
|
||||
* exclude users with active subscriptions from expired broadcast ([1eeeb39](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1eeeb39779982ebb2700cb7523760631229407da))
|
||||
* handle TelegramBadRequest when deleting old ticket notifications ([eb18b3a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/eb18b3a0f9ac3a617a1b21d3293e1619980a2a71))
|
||||
* match tariff_id when creating subscriptions from panel sync (BUG-11) ([646ac4c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/646ac4cfa18f738040fbc6498c5d86c1546e2b9a))
|
||||
* protect OAuth users with remnawave_uuid from sync deactivation (BUG-6) ([cf19e4e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/cf19e4e1f7148b21d9a8072f7a0b4ae97fd04e8a))
|
||||
* raise MAX_BUTTONS_PER_ROW to 8 and allow tg:// deep links in menu editor ([570af82](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/570af82dfdec980f42be96c8f816e1677f896f81))
|
||||
* resync RemnaWave after account merge (BUG-7) ([9c08ce6](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9c08ce69485b78f8fe818500e05ab6995115166a))
|
||||
* resync RemnaWave after Telegram account linking (BUG-1) ([d465ccb](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/d465ccb3ac3a86add6313d6bb61d53d0fe143d5e))
|
||||
* sync connected_squads from panel during sync (BUG-5) ([35412e9](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/35412e9f215680c0fdf1c55b5bf23496f662935c))
|
||||
* trial activation fallback to trial-eligible servers when tariff has no squads (BUG-12) + fix misleading button text ([be32010](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/be32010d63966498bc6216823a75d328346d9a37))
|
||||
* upsert refresh tokens (ON CONFLICT) + periodic cleanup of expired/revoked tokens ([fb8d2b3](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/fb8d2b3ee4566823840100b96fe2f3bc7d41edb7))
|
||||
* use 'is not None' for telegram_id in create_user API (BUG-9) ([8623521](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/862352139e8a3545e144b0618fed5011470a9a67))
|
||||
* use MAX_DEVICES_LIMIT instead of hardcoded 10 for device buttons ([bc3893b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/bc3893b934f0d4e5059eedbd03cdfbc628852ac1))
|
||||
* use update_remnawave_user when UUID exists in tariff_purchase (BUG-3) ([a1b6d9b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a1b6d9bb619ec3de038647fe6f2e5d38979298a8))
|
||||
|
||||
## [3.45.2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.45.1...v3.45.2) (2026-04-08)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* batch bug fixes from user complaints ([31adcfd](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/31adcfded4b161bf515d4d6b25b4395e543208f4))
|
||||
* batch bug fixes from user complaints ([78f963b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/78f963bf5e7b3439d7614584c4041f88be5beb4a))
|
||||
* исправление парсинга черного списка (поддержка '#' и извлечение username) ([357d94d](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/357d94d1b0d7fc8036b00cbb6b75175c29821751))
|
||||
* исправление парсинга черного списка (поддержка '#' и извлечение username) ([2f71846](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2f7184627a0fb598a8c0208905cdecf0e4bb04a7))
|
||||
|
||||
## [3.45.1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.45.0...v3.45.1) (2026-04-03)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* add missing WEBHOOK_TORRENT_DETECTED mapping + dedup before uniq… ([4165eae](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4165eaea7adfdaf683b1ece16c8c93a9c4ed216d))
|
||||
* add missing WEBHOOK_TORRENT_DETECTED mapping + dedup before unique index in migration 0053 ([3b5d5a1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3b5d5a18a1122ef50868fd038a09109d17795a74))
|
||||
|
||||
## [3.45.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.44.0...v3.45.0) (2026-04-03)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* send torrent blocker notification to user (not just admin) ([2f9d003](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2f9d00343bee2980cc89bd24361259073b97127a))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* resolve multiple subscription bugs — LIMITED status, trial tariff blocking, traffic reset strategy, classic mode pricing, 100% discount support ([9b7ac47](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9b7ac47f16076e546da62062ff7ce18d7c308988))
|
||||
* restore missing import + rewrite user.deleted webhook to properly deactivate all subscriptions ([819f09a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/819f09a68ec95237294bae97f31c644044a3623f))
|
||||
* subscription system bugfixes + torrent notifications + user deletion cleanup ([7d24e8d](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7d24e8d7047c7a3a1c417e655a6fbccbe5ae577d))
|
||||
|
||||
## [3.44.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.43.1...v3.44.0) (2026-04-02)
|
||||
|
||||
|
||||
### New Features
|
||||
|
||||
* add SberPay as KassaAI sub-method (payment_system_id=43) ([9d63635](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9d636355026ad1e50d045e78ffa21e76cfef0774))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* address review issues in PR [#2829](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/issues/2829) webhook intentional deletion guard ([977950b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/977950b97f07eecf089152d3f4e678fda373e1e6))
|
||||
* autopay failure notifications ignoring 6h cooldown ([991f0b4](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/991f0b43e1e73446690a4fbec7c5c5642ac8c406))
|
||||
* middleware disables panel VPN for all subs ignoring per-channel settings ([f284351](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/f284351c51a6843db0771a92338ec770d5f0d8d2))
|
||||
* NameError in SeverPay guest payment flow ([2d42152](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2d42152f5491b14cc45388e0ffccf8a61848a2f6))
|
||||
* notification sent for non-deactivated subs + webhook race condition ([b04157c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b04157c91327d9031e9f603a6ad33c708e27d753))
|
||||
* Pal24 card/sbp option not passed to API in cabinet balance topup ([6713921](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/67139218878dca3e75974eb5b5a2ce91d5b1438e))
|
||||
* prevent nested state saves and None state loss in promo handler ([b607993](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b607993854d1374e7d7c2afbb7fe5cc8824732f5))
|
||||
* promo code activation destroys balance input FSM state ([2466590](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/246659032de812f1d4502029ab139f3104237d5c))
|
||||
* remove non-existent Platega method code 10, rename 11 to Карты (RUB) ([033d0da](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/033d0da5e0033a2310431586a291b529e3ccb89a))
|
||||
* send telegram_id@telegram.org as email to Kassa AI ([3dc72b0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3dc72b00e751a69966d2d5830492c82e055b72e6))
|
||||
* send telegram_id@telegram.org as email to SeverPay ([08ca947](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/08ca947b2b2bb29782c86e7b5d6bea71e2811751))
|
||||
|
||||
## [3.43.1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.43.0...v3.43.1) (2026-03-31)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* prevent MissingGreenlet on subscription.tariff lazy load in webhook handlers ([72170b3](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/72170b35f5d2af56aa7dcb579a70ecf6af2da3f6))
|
||||
* use subscription-level remnawave_uuid in multi-tariff mode for sync and detail pages ([0c284b9](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0c284b9e9941b516170fc68a3f63551096cb5a7b))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* add Platega partnership to README, highlight partner payment providers ([312cc72](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/312cc728a9321fe9ac90cf1f5201e38465f67f16))
|
||||
|
||||
## [3.43.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.42.0...v3.43.0) (2026-03-29)
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@ RUN --mount=type=cache,target=/root/.cache/uv \
|
||||
|
||||
FROM python:3.13-slim
|
||||
|
||||
ARG VERSION="v3.43.0" # x-release-please-version
|
||||
ARG VERSION="v3.49.0" # x-release-please-version
|
||||
ARG BUILD_DATE
|
||||
ARG VCS_REF
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ Bedolaga — полнофункциональная платформа для п
|
||||
|
||||
### 💳 Платежи
|
||||
|
||||
- 🏦 **15 платёжных провайдеров** одновременно
|
||||
- 🏦 **18 платёжных провайдеров** одновременно
|
||||
- 💰 Единый баланс: пополнение любым способом → покупка с баланса
|
||||
- ⚡ Автопокупка подписки после пополнения
|
||||
- 💾 Рекуррентные платежи (сохранённые карты)
|
||||
@@ -118,15 +118,20 @@ Bedolaga — полнофункциональная платформа для п
|
||||
| 💳 | **Freekassa** | NSPK СБП, карты | RUB |
|
||||
| 💳 | **Kassa AI** | СБП, карты, SberPay | RUB |
|
||||
| 💳 | **PayPalych (Pal24)** | Карты, СБП | RUB |
|
||||
| 💳 | **Platega** | Карты, СБП, крипто | RUB |
|
||||
| 💳 | **WATA** | СБП, Карты | RUB |
|
||||
| 🤝 | **[Platega](https://t.me/ArstanPlatega)** 🔸 | Карты, СБП, крипто | RUB |
|
||||
| 🤝 | **[WATA](https://t.me/wyrz_wata)** 🔸 | СБП, Карты | RUB |
|
||||
| 💳 | **MulenPay** | Карты | RUB |
|
||||
| 💳 | **RioPay** | Карты | RUB |
|
||||
| 💳 | **SeverPay** | СБП, карты | RUB |
|
||||
| 🤝 | **[PayPear](https://t.me/Paymen1_Manager)** 🔸 | Карты, СБП, SberPay, T-Pay | RUB |
|
||||
| 🤝 | **[RollyPay](https://rollypay.io/?utm_source=bedolaga&utm_medium=community&utm_campaign=integration)** 🔸 | СБП, карты, крипто | RUB → USDT |
|
||||
| 🤝 | **[AuraPay](https://aurapay.tech/)** 🔸 | Карты, СБП | RUB |
|
||||
| 📲 | **Tribute** | Telegram-платежи | RUB |
|
||||
|
||||
</div>
|
||||
|
||||
> 🔸 — официальный партнёр Bedolaga (особые условия по кодовому слову **`bedolaga`**)
|
||||
>
|
||||
> Все провайдеры работают параллельно через единый веб-сервер на порту 8080. Подробная настройка — в [документации](https://docs.bedolagam.ru/bot/payments).
|
||||
|
||||
<div align="center">
|
||||
@@ -134,6 +139,18 @@ Bedolaga — полнофункциональная платформа для п
|
||||
<tr>
|
||||
<td align="center">
|
||||
|
||||
<img src=".github/assets/platega-logo.jpg" alt="Platega" width="60" />
|
||||
|
||||
**🤝 Официальный партнёр Platega**
|
||||
|
||||
Bedolaga — официальный партнёр платёжной системы **Platega**.<br>
|
||||
Пользователи бота получают **особые условия** при подключении по кодовому слову **`bedolaga`**
|
||||
|
||||
📩 По вопросам: [@ArstanPlatega](https://t.me/ArstanPlatega)
|
||||
|
||||
</td>
|
||||
<td align="center">
|
||||
|
||||
<img src=".github/assets/wata-logo.jpg" alt="WATA" width="60" />
|
||||
|
||||
**🤝 Официальный партнёр WATA**
|
||||
@@ -143,6 +160,44 @@ Bedolaga — официальный партнёр платёжной систе
|
||||
|
||||
📩 По вопросам: [@wyrz_wata](https://t.me/wyrz_wata)
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
|
||||
**🤝 Официальный партнёр PayPear**
|
||||
|
||||
Bedolaga — официальный партнёр платёжной системы **[PayPear](https://paypear.ru)**.<br>
|
||||
Банковские карты, СБП, SberPay и T-Pay — всё через единый API.<br>
|
||||
Подключение по **спец. условиям** через кодовое слово **`БЕДОЛАГА`**
|
||||
|
||||
📩 Менеджер: [@Paymen1_Manager](https://t.me/Paymen1_Manager)
|
||||
|
||||
</td>
|
||||
<td align="center">
|
||||
|
||||
**🤝 Официальный партнёр RollyPay**
|
||||
|
||||
Bedolaga — официальный партнёр платёжного шлюза **[RollyPay](https://rollypay.io/?utm_source=bedolaga&utm_medium=community&utm_campaign=integration)**.<br>
|
||||
СБП (от 5%), банковские карты РФ, крипто, вывод в USDT.<br>
|
||||
Универсальная форма оплаты, высокая проходимость, стабильная работа в каскаде.<br>
|
||||
Подключение по кодовому слову **`БЕДОЛАГА`** — **спец. условия**
|
||||
|
||||
📩 Менеджер: [@rollypay_manager](https://t.me/rollypay_manager) | 🌐 [rollypay.io](https://rollypay.io/?utm_source=bedolaga&utm_medium=community&utm_campaign=integration)
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center">
|
||||
|
||||
**🤝 Официальный партнёр AuraPay**
|
||||
|
||||
Bedolaga — официальный партнёр платёжной системы **[AuraPay](https://aurapay.tech/)**.<br>
|
||||
Банковские карты и СБП через единый API с быстрой интеграцией.<br>
|
||||
Подключение по кодовому слову **`БЕДОЛАГА`** — **спец. условия**
|
||||
|
||||
📩 Менеджер: [@kickdownm](https://t.me/kickdownm) | 🌐 [aurapay.tech](https://aurapay.tech/)
|
||||
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -208,7 +263,7 @@ docker compose up -d
|
||||
| | Раздел | Описание |
|
||||
|:---:|:---|:---|
|
||||
| 🚀 | [Быстрый старт](https://docs.bedolagam.ru/getting-started/quickstart) | Развёртывание за 5 минут |
|
||||
| 💳 | [Настройка платежей](https://docs.bedolagam.ru/bot/payments) | 14 провайдеров, webhook, фискализация |
|
||||
| 💳 | [Настройка платежей](https://docs.bedolagam.ru/bot/payments) | 18 провайдеров, webhook, фискализация |
|
||||
| 📦 | [Подписки и тарифы](https://docs.bedolagam.ru/bot/subscriptions) | Конфигурация планов и трафика |
|
||||
| 👥 | [Реферальная программа](https://docs.bedolagam.ru/bot/referral-program) | Партнёрка и вывод средств |
|
||||
| 🖥 | [Cabinet](https://docs.bedolagam.ru/cabinet/overview) | Настройка веб-кабинета |
|
||||
|
||||
+16
@@ -280,12 +280,28 @@ async def setup_bot() -> tuple[Bot, Dispatcher]:
|
||||
except Exception as e:
|
||||
logger.warning('Failed to load menu layout cache', error=e)
|
||||
|
||||
try:
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
await remnawave_retry_queue.start()
|
||||
logger.info('RemnaWave retry queue запущен')
|
||||
except Exception as e:
|
||||
logger.error('Ошибка запуска RemnaWave retry queue', error=e)
|
||||
|
||||
logger.info('Бот успешно настроен')
|
||||
|
||||
return bot, dp
|
||||
|
||||
|
||||
async def shutdown_bot():
|
||||
try:
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
await remnawave_retry_queue.stop()
|
||||
logger.info('RemnaWave retry queue остановлен')
|
||||
except Exception as e:
|
||||
logger.error('Ошибка остановки RemnaWave retry queue', error=e)
|
||||
|
||||
try:
|
||||
await maintenance_service.stop_monitoring()
|
||||
logger.info('Мониторинг техработ остановлен')
|
||||
|
||||
+12
-4
@@ -1,4 +1,4 @@
|
||||
"""Factory for creating Bot instances with proxy support."""
|
||||
"""Factory for creating Bot instances with proxy and custom API server support."""
|
||||
|
||||
from aiogram import Bot
|
||||
from aiogram.client.default import DefaultBotProperties
|
||||
@@ -8,13 +8,21 @@ from app.config import settings
|
||||
|
||||
|
||||
def create_bot(token: str | None = None, **kwargs) -> Bot:
|
||||
"""Create a Bot instance with SOCKS5 proxy session if PROXY_URL is configured."""
|
||||
"""Create a Bot instance with SOCKS5 proxy and/or custom Telegram API server."""
|
||||
proxy_url = settings.get_proxy_url()
|
||||
telegram_api_url = settings.get_telegram_api_url()
|
||||
session = None
|
||||
if proxy_url:
|
||||
if proxy_url or telegram_api_url:
|
||||
from aiogram.client.session.aiohttp import AiohttpSession
|
||||
from aiogram.client.telegram import TelegramAPIServer
|
||||
|
||||
session = AiohttpSession(proxy=proxy_url)
|
||||
session_kwargs: dict = {}
|
||||
if proxy_url:
|
||||
session_kwargs['proxy'] = proxy_url
|
||||
if telegram_api_url:
|
||||
session_kwargs['api'] = TelegramAPIServer.from_base(telegram_api_url)
|
||||
|
||||
session = AiohttpSession(**session_kwargs)
|
||||
|
||||
kwargs.setdefault('default', DefaultBotProperties(parse_mode=ParseMode.HTML))
|
||||
return Bot(token=token or settings.BOT_TOKEN, session=session, **kwargs)
|
||||
|
||||
@@ -195,7 +195,8 @@ async def _get_jwks(force: bool = False) -> dict[str, Any]:
|
||||
if not force and _jwks_cache and _jwks_cache_expiry and now < _jwks_cache_expiry:
|
||||
return _jwks_cache
|
||||
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
proxy = settings.PROXY_URL if hasattr(settings, 'PROXY_URL') and settings.PROXY_URL else None
|
||||
async with httpx.AsyncClient(timeout=10, proxy=proxy) as client:
|
||||
response = await client.get(_JWKS_URL)
|
||||
response.raise_for_status()
|
||||
_jwks_cache = response.json()
|
||||
|
||||
@@ -622,6 +622,24 @@ async def link_telegram(
|
||||
telegram_id=telegram_id,
|
||||
user_id=user.id,
|
||||
)
|
||||
# BUG-1 fix: Sync all subscriptions with RemnaWave panel so it knows the new telegram_id
|
||||
try:
|
||||
from app.services.remnawave_resync_service import resync_user_subscriptions_with_panel
|
||||
|
||||
resync_result = await resync_user_subscriptions_with_panel(db, user)
|
||||
logger.info(
|
||||
'Post-TG-link resync completed',
|
||||
user_id=user.id,
|
||||
telegram_id=telegram_id,
|
||||
synced=resync_result['synced'],
|
||||
failed=resync_result['failed'],
|
||||
)
|
||||
except Exception as resync_error:
|
||||
logger.error(
|
||||
'Post-TG-link resync failed (non-fatal)',
|
||||
user_id=user.id,
|
||||
error=resync_error,
|
||||
)
|
||||
return LinkCallbackResponse(success=True, message='linked')
|
||||
|
||||
|
||||
@@ -867,6 +885,25 @@ async def execute_merge_endpoint(
|
||||
detail='Failed to load merged user',
|
||||
)
|
||||
|
||||
# BUG-7 fix: Resync merged user's subscriptions with RemnaWave panel
|
||||
try:
|
||||
from app.services.remnawave_resync_service import resync_user_subscriptions_with_panel
|
||||
|
||||
resync_result = await resync_user_subscriptions_with_panel(db, merged_user)
|
||||
logger.info(
|
||||
'Post-merge resync completed',
|
||||
primary_user_id=primary_user_id,
|
||||
secondary_user_id=secondary_user_id,
|
||||
synced=resync_result['synced'],
|
||||
failed=resync_result['failed'],
|
||||
)
|
||||
except Exception as resync_error:
|
||||
logger.error(
|
||||
'Post-merge resync failed (non-fatal)',
|
||||
primary_user_id=primary_user_id,
|
||||
error=resync_error,
|
||||
)
|
||||
|
||||
# 5. Create auth tokens for the merged user
|
||||
try:
|
||||
auth_response = await _create_auth_response(merged_user, db)
|
||||
|
||||
@@ -141,6 +141,7 @@ def _serialize_broadcast(broadcast: BroadcastHistory) -> BroadcastResponse:
|
||||
created_at=broadcast.created_at,
|
||||
completed_at=broadcast.completed_at,
|
||||
progress_percent=progress,
|
||||
category=getattr(broadcast, 'category', 'system') or 'system',
|
||||
channel=getattr(broadcast, 'channel', 'telegram') or 'telegram',
|
||||
email_subject=getattr(broadcast, 'email_subject', None),
|
||||
email_html_content=getattr(broadcast, 'email_html_content', None),
|
||||
@@ -432,6 +433,7 @@ async def create_broadcast(
|
||||
status='queued',
|
||||
admin_id=admin.id,
|
||||
admin_name=admin.username or f'Admin #{admin.id}',
|
||||
category=request.category,
|
||||
)
|
||||
db.add(broadcast)
|
||||
await db.commit()
|
||||
@@ -454,6 +456,7 @@ async def create_broadcast(
|
||||
media=media_config,
|
||||
initiator_name=admin.username or f'Admin #{admin.id}',
|
||||
custom_buttons=[btn.model_dump() for btn in request.custom_buttons] if request.custom_buttons else None,
|
||||
category=request.category,
|
||||
)
|
||||
|
||||
# Start broadcast
|
||||
@@ -626,6 +629,7 @@ async def create_combined_broadcast(
|
||||
status='queued',
|
||||
admin_id=admin.id,
|
||||
admin_name=admin_name,
|
||||
category=request.category,
|
||||
channel=request.channel,
|
||||
email_subject=request.email_subject.strip() if request.email_subject else None,
|
||||
email_html_content=request.email_html_content.strip() if request.email_html_content else None,
|
||||
@@ -653,6 +657,7 @@ async def create_combined_broadcast(
|
||||
media=media_config,
|
||||
initiator_name=admin_name,
|
||||
custom_buttons=[btn.model_dump() for btn in request.custom_buttons] if request.custom_buttons else None,
|
||||
category=request.category,
|
||||
)
|
||||
|
||||
await broadcast_service.start_broadcast(broadcast.id, telegram_config)
|
||||
|
||||
@@ -42,9 +42,9 @@ router = APIRouter(prefix='/admin/menu-layout', tags=['Admin Menu Layout'])
|
||||
# ---- Constants ---------------------------------------------------------------
|
||||
|
||||
MAX_ROWS = 20
|
||||
MAX_BUTTONS_PER_ROW = 3
|
||||
MAX_BUTTONS_PER_ROW = 8 # Telegram inline keyboard limit
|
||||
MAX_LABEL_LENGTH = 100
|
||||
URL_PATTERN = re.compile(r'^https?://')
|
||||
URL_PATTERN = re.compile(r'^(https?://|tg://)')
|
||||
|
||||
|
||||
# ---- Schemas -----------------------------------------------------------------
|
||||
@@ -275,7 +275,7 @@ def _validate_update_payload(rows: list[RowConfig]) -> None:
|
||||
if not btn.url or not URL_PATTERN.match(btn.url):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f'Custom button "{btn.id}" must have a URL starting with http:// or https://.',
|
||||
detail=f'Custom button "{btn.id}" must have a URL starting with http://, https://, or tg://.',
|
||||
)
|
||||
if btn.open_in == 'webapp' and not btn.url.startswith('https://'):
|
||||
raise HTTPException(
|
||||
|
||||
@@ -4,14 +4,14 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import structlog
|
||||
from aiogram import Bot
|
||||
from aiogram.exceptions import TelegramBadRequest, TelegramForbiddenError
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, Field, validator
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.bot_factory import create_bot
|
||||
@@ -128,6 +128,20 @@ class PromoOfferBroadcastRequest(BaseModel):
|
||||
message_text: str | None = Field(None, description='Custom message text (HTML)')
|
||||
button_text: str | None = Field(None, description='Button text')
|
||||
|
||||
_TARGET_ALIASES: ClassVar[dict[str, str]] = {
|
||||
'no_sub': 'no',
|
||||
'all_users': 'all',
|
||||
'active_subscribers': 'active',
|
||||
'trial_users': 'trial',
|
||||
}
|
||||
|
||||
@validator('target')
|
||||
def normalize_target(cls, value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = value.strip().lower()
|
||||
return cls._TARGET_ALIASES.get(normalized, normalized)
|
||||
|
||||
|
||||
class PromoOfferBroadcastResponse(BaseModel):
|
||||
created_offers: int
|
||||
|
||||
@@ -236,8 +236,9 @@ async def _sync_subscription_to_panel(
|
||||
"""
|
||||
try:
|
||||
from app.config import settings
|
||||
from app.external.remnawave_api import TrafficLimitStrategy, UserStatus as PanelUserStatus
|
||||
from app.external.remnawave_api import UserStatus as PanelUserStatus
|
||||
from app.services.remnawave_service import RemnaWaveService
|
||||
from app.services.subscription_service import get_traffic_reset_strategy
|
||||
from app.utils.subscription_utils import resolve_hwid_device_limit_for_payload
|
||||
|
||||
service = RemnaWaveService()
|
||||
@@ -323,7 +324,7 @@ async def _sync_subscription_to_panel(
|
||||
'uuid': panel_uuid,
|
||||
'status': panel_status,
|
||||
'traffic_limit_bytes': traffic_limit_bytes,
|
||||
'traffic_limit_strategy': TrafficLimitStrategy.MONTH,
|
||||
'traffic_limit_strategy': get_traffic_reset_strategy(subscription.tariff),
|
||||
'description': description,
|
||||
}
|
||||
if expire_at:
|
||||
@@ -358,7 +359,7 @@ async def _sync_subscription_to_panel(
|
||||
'expire_at': expire_at or (datetime.now(UTC) + timedelta(days=30)),
|
||||
'status': panel_status,
|
||||
'traffic_limit_bytes': traffic_limit_bytes,
|
||||
'traffic_limit_strategy': TrafficLimitStrategy.MONTH,
|
||||
'traffic_limit_strategy': get_traffic_reset_strategy(subscription.tariff),
|
||||
'telegram_id': user.telegram_id,
|
||||
'email': user.email,
|
||||
'description': description,
|
||||
@@ -709,7 +710,11 @@ async def get_user_detail(
|
||||
promo_offer_discount_source=user.promo_offer_discount_source,
|
||||
promo_offer_discount_expires_at=user.promo_offer_discount_expires_at,
|
||||
recent_transactions=recent_transactions,
|
||||
remnawave_uuid=user.remnawave_uuid,
|
||||
remnawave_uuid=(
|
||||
primary_sub.remnawave_uuid
|
||||
if settings.is_multi_tariff_enabled() and primary_sub and primary_sub.remnawave_uuid
|
||||
else user.remnawave_uuid
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -2681,6 +2686,13 @@ async def get_user_sync_status(
|
||||
bot_device_limit = active_sub.device_limit or 0
|
||||
bot_squads = active_sub.connected_squads or []
|
||||
|
||||
# In multi-tariff mode, UUID lives on subscription, not user
|
||||
effective_uuid = (
|
||||
active_sub.remnawave_uuid
|
||||
if settings.is_multi_tariff_enabled() and active_sub and active_sub.remnawave_uuid
|
||||
else user.remnawave_uuid
|
||||
)
|
||||
|
||||
# Panel data
|
||||
panel_found = False
|
||||
panel_status = None
|
||||
@@ -2699,16 +2711,9 @@ async def get_user_sync_status(
|
||||
async with service.get_api_client() as api:
|
||||
panel_user = None
|
||||
|
||||
# In multi-tariff mode, UUID lives on subscription, not user
|
||||
sync_uuid = (
|
||||
active_sub.remnawave_uuid
|
||||
if settings.is_multi_tariff_enabled() and active_sub and active_sub.remnawave_uuid
|
||||
else user.remnawave_uuid
|
||||
)
|
||||
|
||||
# Try by UUID first (works for all users including OAuth)
|
||||
if sync_uuid:
|
||||
panel_user = await api.get_user_by_uuid(sync_uuid)
|
||||
if effective_uuid:
|
||||
panel_user = await api.get_user_by_uuid(effective_uuid)
|
||||
|
||||
# Fallback: search by telegram_id
|
||||
if not panel_user and user.telegram_id:
|
||||
@@ -2800,7 +2805,7 @@ async def get_user_sync_status(
|
||||
return PanelSyncStatusResponse(
|
||||
user_id=user.id,
|
||||
telegram_id=user.telegram_id,
|
||||
remnawave_uuid=user.remnawave_uuid,
|
||||
remnawave_uuid=effective_uuid,
|
||||
last_sync=user.last_remnawave_sync,
|
||||
subscription_id=active_sub.id if active_sub else None,
|
||||
subscription_tariff_name=sub_tariff_name,
|
||||
@@ -3018,6 +3023,11 @@ async def sync_user_from_panel(
|
||||
changes['remnawave_short_uuid'] = {'old': sub.remnawave_short_uuid, 'new': panel_user.short_uuid}
|
||||
sub.remnawave_short_uuid = panel_user.short_uuid
|
||||
|
||||
# Update crypto link
|
||||
if panel_user.happ_crypto_link and sub.subscription_crypto_link != panel_user.happ_crypto_link:
|
||||
changes['subscription_crypto_link'] = {'old': sub.subscription_crypto_link, 'new': '***'}
|
||||
sub.subscription_crypto_link = panel_user.happ_crypto_link
|
||||
|
||||
# Update traffic usage if requested
|
||||
if request.update_traffic and sync_sub:
|
||||
panel_traffic_used = panel_user.used_traffic_bytes / (1024**3) if panel_user.used_traffic_bytes else 0
|
||||
@@ -3114,8 +3124,9 @@ async def sync_user_to_panel(
|
||||
|
||||
try:
|
||||
from app.config import settings
|
||||
from app.external.remnawave_api import TrafficLimitStrategy, UserStatus as PanelUserStatus
|
||||
from app.external.remnawave_api import UserStatus as PanelUserStatus
|
||||
from app.services.remnawave_service import RemnaWaveService
|
||||
from app.services.subscription_service import get_traffic_reset_strategy
|
||||
from app.utils.subscription_utils import resolve_hwid_device_limit_for_payload
|
||||
|
||||
service = RemnaWaveService()
|
||||
@@ -3214,7 +3225,7 @@ async def sync_user_to_panel(
|
||||
|
||||
if request.update_traffic_limit:
|
||||
update_kwargs['traffic_limit_bytes'] = traffic_limit_bytes
|
||||
update_kwargs['traffic_limit_strategy'] = TrafficLimitStrategy.MONTH
|
||||
update_kwargs['traffic_limit_strategy'] = get_traffic_reset_strategy(sub.tariff)
|
||||
changes['traffic_limit_gb'] = sub.traffic_limit_gb
|
||||
|
||||
if request.update_squads and sub.connected_squads:
|
||||
@@ -3248,7 +3259,7 @@ async def sync_user_to_panel(
|
||||
'expire_at': expire_at or (datetime.now(UTC) + timedelta(days=30)),
|
||||
'status': panel_status,
|
||||
'traffic_limit_bytes': traffic_limit_bytes,
|
||||
'traffic_limit_strategy': TrafficLimitStrategy.MONTH,
|
||||
'traffic_limit_strategy': get_traffic_reset_strategy(sub.tariff),
|
||||
'telegram_id': user.telegram_id,
|
||||
'email': user.email,
|
||||
'description': description,
|
||||
|
||||
+29
-10
@@ -144,22 +144,28 @@ async def _store_refresh_token(
|
||||
refresh_token: str,
|
||||
device_info: str | None = None,
|
||||
) -> None:
|
||||
"""Store refresh token hash in database."""
|
||||
"""Store refresh token hash in database using upsert to avoid duplicate key errors."""
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
token_hash = hashlib.sha256(refresh_token.encode()).hexdigest()
|
||||
expires_at = get_refresh_token_expires_at()
|
||||
|
||||
token_record = CabinetRefreshToken(
|
||||
stmt = pg_insert(CabinetRefreshToken).values(
|
||||
user_id=user_id,
|
||||
token_hash=token_hash,
|
||||
device_info=device_info,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
db.add(token_record)
|
||||
try:
|
||||
await db.commit()
|
||||
except IntegrityError:
|
||||
await db.rollback()
|
||||
logger.debug('Refresh token already exists (duplicate)', user_id=user_id)
|
||||
stmt = stmt.on_conflict_do_update(
|
||||
index_elements=['token_hash'],
|
||||
set_={
|
||||
'expires_at': expires_at,
|
||||
'device_info': device_info,
|
||||
'revoked_at': None,
|
||||
},
|
||||
)
|
||||
await db.execute(stmt)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def _process_campaign_bonus(
|
||||
@@ -1052,6 +1058,10 @@ async def register_email_standalone(
|
||||
referred_by_id=referrer.id if referrer else None,
|
||||
)
|
||||
|
||||
# Сохранить campaign_slug для обработки при верификации email
|
||||
if request.campaign_slug:
|
||||
user.pending_campaign_slug = request.campaign_slug
|
||||
|
||||
# Для тестового email или отключённой верификации - автоматически верифицировать
|
||||
if is_test_email or not settings.is_cabinet_email_verification_enabled():
|
||||
user.email_verified = True
|
||||
@@ -1063,6 +1073,11 @@ async def register_email_standalone(
|
||||
await _sync_subscription_from_panel_by_email(db, user)
|
||||
except Exception:
|
||||
logger.warning('Failed to sync panel subscription after auto-verify', user_id=user.id, exc_info=True)
|
||||
# Process campaign bonus immediately for auto-verified users
|
||||
if request.campaign_slug:
|
||||
await _process_campaign_bonus(db, user, request.campaign_slug)
|
||||
user.pending_campaign_slug = None
|
||||
await db.commit()
|
||||
else:
|
||||
# Сгенерировать токен верификации
|
||||
verification_token = generate_verification_token()
|
||||
@@ -1173,8 +1188,12 @@ async def verify_email(
|
||||
response = await _create_auth_response(user, db)
|
||||
await _store_refresh_token(db, user.id, response.refresh_token)
|
||||
|
||||
# Process campaign bonus
|
||||
response.campaign_bonus = await _process_campaign_bonus(db, user, request.campaign_slug)
|
||||
# Process campaign bonus (prefer request param, fallback to saved slug from registration)
|
||||
effective_campaign_slug = request.campaign_slug or user.pending_campaign_slug
|
||||
response.campaign_bonus = await _process_campaign_bonus(db, user, effective_campaign_slug)
|
||||
if user.pending_campaign_slug:
|
||||
user.pending_campaign_slug = None
|
||||
await db.commit()
|
||||
if response.campaign_bonus:
|
||||
response.user = _user_to_response(user)
|
||||
|
||||
|
||||
@@ -578,6 +578,7 @@ async def create_topup(
|
||||
request.amount_kopeks, telegram_user_id=user.telegram_id, user_db_id=user.id
|
||||
),
|
||||
language=getattr(user, 'language', None) or settings.DEFAULT_LANGUAGE,
|
||||
payment_method=option,
|
||||
)
|
||||
|
||||
if result:
|
||||
@@ -698,7 +699,7 @@ async def create_topup(
|
||||
)
|
||||
|
||||
# Use payment_option to select sbp or card
|
||||
KASSA_AI_OPTION_MAP = {'sbp': 44, 'card': 36}
|
||||
KASSA_AI_OPTION_MAP = {'sbp': 44, 'card': 36, 'sberpay': 43}
|
||||
option = (request.payment_option or '').strip().lower()
|
||||
ps_id = KASSA_AI_OPTION_MAP.get(option) # None = use env default
|
||||
|
||||
@@ -793,6 +794,97 @@ async def create_topup(
|
||||
detail='Failed to create SeverPay payment',
|
||||
)
|
||||
|
||||
elif request.payment_method == 'paypear':
|
||||
if not settings.is_paypear_enabled():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='PayPear payment method is unavailable',
|
||||
)
|
||||
|
||||
payment_service = PaymentService()
|
||||
result = await payment_service.create_paypear_payment(
|
||||
db=db,
|
||||
user_id=user.id,
|
||||
amount_kopeks=request.amount_kopeks,
|
||||
description=settings.get_balance_payment_description(
|
||||
request.amount_kopeks, telegram_user_id=user.telegram_id, user_db_id=user.id
|
||||
),
|
||||
email=getattr(user, 'email', None),
|
||||
language=getattr(user, 'language', None) or settings.DEFAULT_LANGUAGE,
|
||||
return_url=cabinet_success_url,
|
||||
)
|
||||
|
||||
if result and result.get('payment_url'):
|
||||
payment_url = result.get('payment_url')
|
||||
payment_id = str(result.get('local_payment_id') or result.get('order_id') or 'pending')
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to create PayPear payment',
|
||||
)
|
||||
|
||||
elif request.payment_method == 'rollypay':
|
||||
if not settings.is_rollypay_enabled():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='RollyPay payment method is unavailable',
|
||||
)
|
||||
|
||||
payment_service = PaymentService()
|
||||
payment_method_type = request.payment_option or None
|
||||
result = await payment_service.create_rollypay_payment(
|
||||
db=db,
|
||||
user_id=user.id,
|
||||
amount_kopeks=request.amount_kopeks,
|
||||
description=settings.get_balance_payment_description(
|
||||
request.amount_kopeks, telegram_user_id=user.telegram_id, user_db_id=user.id
|
||||
),
|
||||
email=getattr(user, 'email', None),
|
||||
language=getattr(user, 'language', None) or settings.DEFAULT_LANGUAGE,
|
||||
payment_method_type=payment_method_type,
|
||||
return_url=cabinet_success_url,
|
||||
)
|
||||
|
||||
if result and result.get('payment_url'):
|
||||
payment_url = result.get('payment_url')
|
||||
payment_id = str(result.get('local_payment_id') or result.get('order_id') or 'pending')
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to create RollyPay payment',
|
||||
)
|
||||
|
||||
elif request.payment_method == 'aurapay':
|
||||
if not settings.is_aurapay_enabled():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='AuraPay payment method is unavailable',
|
||||
)
|
||||
|
||||
payment_service = PaymentService()
|
||||
payment_method_type = request.payment_option or None
|
||||
result = await payment_service.create_aurapay_payment(
|
||||
db=db,
|
||||
user_id=user.id,
|
||||
amount_kopeks=request.amount_kopeks,
|
||||
description=settings.get_balance_payment_description(
|
||||
request.amount_kopeks, telegram_user_id=user.telegram_id, user_db_id=user.id
|
||||
),
|
||||
email=getattr(user, 'email', None),
|
||||
language=getattr(user, 'language', None) or settings.DEFAULT_LANGUAGE,
|
||||
payment_method_type=payment_method_type,
|
||||
return_url=cabinet_success_url,
|
||||
)
|
||||
|
||||
if result and result.get('payment_url'):
|
||||
payment_url = result.get('payment_url')
|
||||
payment_id = str(result.get('local_payment_id') or result.get('order_id') or 'pending')
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail='Failed to create AuraPay payment',
|
||||
)
|
||||
|
||||
else:
|
||||
# For other payment methods, redirect to bot
|
||||
raise HTTPException(
|
||||
|
||||
@@ -425,8 +425,8 @@ async def create_gift_purchase(
|
||||
warning=recipient_warning,
|
||||
)
|
||||
|
||||
# Balance mode
|
||||
if user.balance_kopeks < price_kopeks:
|
||||
# Balance mode (skip for 100% discount)
|
||||
if price_kopeks > 0 and user.balance_kopeks < price_kopeks:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Insufficient balance',
|
||||
|
||||
@@ -28,7 +28,7 @@ class NotificationSettingsResponse(BaseModel):
|
||||
subscription_expiry_days: int = 3
|
||||
traffic_warning_enabled: bool = True
|
||||
traffic_warning_percent: int = 80
|
||||
balance_low_enabled: bool = True
|
||||
balance_low_enabled: bool = False
|
||||
balance_low_threshold: int = 100 # kopeks
|
||||
news_enabled: bool = True
|
||||
promo_offers_enabled: bool = True
|
||||
@@ -60,7 +60,7 @@ def _get_notification_settings(user: User) -> dict[str, Any]:
|
||||
'subscription_expiry_days': settings_data.get('subscription_expiry_days', 3),
|
||||
'traffic_warning_enabled': settings_data.get('traffic_warning_enabled', True),
|
||||
'traffic_warning_percent': settings_data.get('traffic_warning_percent', 80),
|
||||
'balance_low_enabled': settings_data.get('balance_low_enabled', True),
|
||||
'balance_low_enabled': settings_data.get('balance_low_enabled', False),
|
||||
'balance_low_threshold': settings_data.get('balance_low_threshold', 100),
|
||||
'news_enabled': settings_data.get('news_enabled', True),
|
||||
'promo_offers_enabled': settings_data.get('promo_offers_enabled', True),
|
||||
|
||||
@@ -79,6 +79,8 @@ async def activate_promocode(
|
||||
error_messages = {
|
||||
'not_found': 'Promo code not found',
|
||||
'expired': 'Promo code has expired',
|
||||
'inactive': 'Promo code is deactivated',
|
||||
'not_yet_valid': 'Promo code is not yet active',
|
||||
'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',
|
||||
|
||||
@@ -168,6 +168,13 @@ async def toggle_subscription_pause(
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Error syncing RemnaWave user on resume', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
if new_paused_state:
|
||||
message = 'Daily subscription paused'
|
||||
|
||||
@@ -134,8 +134,8 @@ async def purchase_devices_legacy(
|
||||
detail=f'Максимальное количество устройств: {max_device_limit}',
|
||||
)
|
||||
|
||||
# Check balance
|
||||
if user.balance_kopeks < total_price:
|
||||
# Check balance (skip for 100% discount)
|
||||
if total_price > 0 and user.balance_kopeks < total_price:
|
||||
missing = total_price - user.balance_kopeks
|
||||
|
||||
# Сохраняем корзину для автопокупки после пополнения
|
||||
@@ -228,12 +228,24 @@ async def purchase_devices_legacy(
|
||||
# Sync with RemnaWave
|
||||
try:
|
||||
service = SubscriptionService()
|
||||
if _resolve_panel_uuid(subscription, user):
|
||||
await service.update_remnawave_user(db, subscription)
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await service.create_remnawave_user(db, subscription)
|
||||
else:
|
||||
await service.update_remnawave_user(db, subscription)
|
||||
except Exception as e:
|
||||
logger.error('Failed to sync devices with RemnaWave (legacy endpoint)', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
action='create' if _should_create else 'update',
|
||||
)
|
||||
|
||||
# Отправляем уведомление админам
|
||||
try:
|
||||
@@ -375,8 +387,8 @@ async def purchase_devices(
|
||||
if devices_discount_percent < 100:
|
||||
price_kopeks = max(100, price_kopeks)
|
||||
|
||||
# Check balance
|
||||
if user.balance_kopeks < price_kopeks:
|
||||
# Check balance (skip for 100% discount)
|
||||
if price_kopeks > 0 and user.balance_kopeks < price_kopeks:
|
||||
missing = price_kopeks - user.balance_kopeks
|
||||
|
||||
# Сохраняем корзину для автопокупки после пополнения
|
||||
@@ -469,12 +481,24 @@ async def purchase_devices(
|
||||
# Sync with RemnaWave
|
||||
service = SubscriptionService()
|
||||
try:
|
||||
if _resolve_panel_uuid(subscription, user):
|
||||
await service.update_remnawave_user(db, subscription)
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await service.create_remnawave_user(db, subscription)
|
||||
else:
|
||||
await service.update_remnawave_user(db, subscription)
|
||||
except Exception as e:
|
||||
logger.error('Failed to sync devices with RemnaWave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
action='create' if _should_create else 'update',
|
||||
)
|
||||
|
||||
await db.refresh(user)
|
||||
|
||||
|
||||
@@ -304,9 +304,7 @@ async def get_purchase_options(
|
||||
from app.database.crud.subscription import get_active_subscriptions_by_user_id
|
||||
|
||||
active_subs = await get_active_subscriptions_by_user_id(db, user.id)
|
||||
purchased_tariff_ids = {
|
||||
s.tariff_id for s in active_subs if s.tariff_id and s.status in ('active', 'trial')
|
||||
}
|
||||
purchased_tariff_ids = {s.tariff_id for s in active_subs if s.tariff_id and not s.is_trial}
|
||||
|
||||
if subscription_id:
|
||||
from app.database.crud.subscription import get_subscription_by_id_for_user
|
||||
@@ -678,15 +676,17 @@ async def purchase_tariff(
|
||||
promo_offer_discount_value = result.promo_offer_discount
|
||||
price_before_promo_offer = price_kopeks + promo_offer_discount_value
|
||||
|
||||
# Safety guard: reject zero-price purchases for non-daily tariffs (defense in depth)
|
||||
if price_kopeks <= 0 and result.base_price <= 0 and not is_daily_tariff:
|
||||
# Safety guard: reject zero-price purchases for non-daily tariffs (defense in depth).
|
||||
# Use original_total (pre-discount price) — base_price is already discounted,
|
||||
# so a 100% group discount legitimately makes it 0.
|
||||
if price_kopeks <= 0 and result.original_total <= 0 and not is_daily_tariff:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Invalid tariff period or pricing configuration',
|
||||
)
|
||||
|
||||
# Check balance
|
||||
if user.balance_kopeks < price_kopeks:
|
||||
if price_kopeks > 0 and user.balance_kopeks < price_kopeks:
|
||||
missing = price_kopeks - user.balance_kopeks
|
||||
|
||||
# Save cart for auto-purchase after balance top-up
|
||||
@@ -911,6 +911,13 @@ async def purchase_tariff(
|
||||
)
|
||||
except Exception as remnawave_error:
|
||||
logger.error('Failed to sync subscription with RemnaWave', remnawave_error=remnawave_error)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
action='create' if not subscription.remnawave_uuid else 'update',
|
||||
)
|
||||
|
||||
# Save cart for auto-renewal (not for daily tariffs - they have their own charging)
|
||||
if not is_daily_tariff:
|
||||
@@ -1158,7 +1165,7 @@ async def activate_trial(
|
||||
from app.database.crud.user import subtract_user_balance
|
||||
|
||||
price_kopeks = settings.TRIAL_ACTIVATION_PRICE
|
||||
if user.balance_kopeks < price_kopeks:
|
||||
if price_kopeks > 0 and user.balance_kopeks < price_kopeks:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f'Insufficient balance. Need {price_kopeks / 100:.2f} RUB',
|
||||
@@ -1228,6 +1235,13 @@ async def activate_trial(
|
||||
except Exception as e:
|
||||
logger.error('Error getting trial tariff', error=e)
|
||||
|
||||
# BUG-12 fix: If no squads from tariff, fallback to trial-eligible servers
|
||||
if not trial_squads:
|
||||
from app.database.crud.server_squad import get_random_trial_squad_uuid
|
||||
|
||||
trial_squad_uuid = await get_random_trial_squad_uuid(db)
|
||||
trial_squads = [trial_squad_uuid] if trial_squad_uuid else []
|
||||
|
||||
# Create trial subscription
|
||||
subscription = await create_trial_subscription(
|
||||
db=db,
|
||||
@@ -1249,6 +1263,13 @@ async def activate_trial(
|
||||
await db.refresh(subscription)
|
||||
except Exception as e:
|
||||
logger.error('Failed to create RemnaWave user for trial', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Send admin notification about trial activation
|
||||
try:
|
||||
|
||||
@@ -67,7 +67,7 @@ async def get_renewal_options(
|
||||
for period in periods:
|
||||
pricing = await pricing_engine.calculate_renewal_price(db, subscription, period, user=user)
|
||||
|
||||
if pricing.final_total <= 0 and pricing.base_price <= 0:
|
||||
if pricing.final_total <= 0 and pricing.original_total <= 0:
|
||||
continue
|
||||
|
||||
original_price = pricing.original_total
|
||||
@@ -155,7 +155,7 @@ async def renew_subscription(
|
||||
promo_offer_discount_value = pricing.promo_offer_discount
|
||||
promo_offer_discount_percent = pricing.breakdown.get('offer_discount_pct', 0)
|
||||
|
||||
if price_kopeks <= 0 and pricing.base_price <= 0:
|
||||
if price_kopeks <= 0 and pricing.original_total <= 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail='Invalid renewal period',
|
||||
@@ -168,8 +168,8 @@ async def renew_subscription(
|
||||
|
||||
tariff = subscription.tariff if subscription.tariff_id else None
|
||||
|
||||
# Check balance
|
||||
if user.balance_kopeks < price_kopeks:
|
||||
# Check balance (skip for 100% discount)
|
||||
if price_kopeks > 0 and user.balance_kopeks < price_kopeks:
|
||||
missing = price_kopeks - user.balance_kopeks
|
||||
|
||||
# Get tariff info for cart
|
||||
|
||||
@@ -249,6 +249,13 @@ async def update_countries(
|
||||
await subscription_service.create_remnawave_user(db, subscription)
|
||||
except Exception as e:
|
||||
logger.error('Failed to sync countries with RemnaWave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
action='update' if _has_panel else 'create',
|
||||
)
|
||||
|
||||
await db.refresh(subscription)
|
||||
|
||||
|
||||
@@ -428,6 +428,13 @@ async def switch_tariff(
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Failed to sync tariff switch with RemnaWave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
action='update' if _has_panel else 'create',
|
||||
)
|
||||
|
||||
# Reset all devices on tariff switch
|
||||
devices_reset = False
|
||||
|
||||
@@ -254,7 +254,7 @@ async def purchase_traffic(
|
||||
final_price = max(100, final_price)
|
||||
|
||||
# Проверяем баланс
|
||||
if user.balance_kopeks < final_price:
|
||||
if final_price > 0 and user.balance_kopeks < final_price:
|
||||
missing = final_price - user.balance_kopeks
|
||||
|
||||
# Save cart for auto-purchase after balance top-up
|
||||
@@ -316,19 +316,32 @@ async def purchase_traffic(
|
||||
# Синхронизируем с RemnaWave
|
||||
try:
|
||||
subscription_service = SubscriptionService()
|
||||
_panel_uuid = (
|
||||
subscription.remnawave_uuid
|
||||
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
|
||||
else getattr(user, 'remnawave_uuid', None)
|
||||
)
|
||||
if _panel_uuid:
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await subscription_service.create_remnawave_user(db, subscription)
|
||||
else:
|
||||
await subscription_service.update_remnawave_user(db, subscription)
|
||||
if subscription.status == 'active':
|
||||
await subscription_service.enable_remnawave_user(_panel_uuid)
|
||||
else:
|
||||
await subscription_service.create_remnawave_user(db, subscription)
|
||||
_enable_uuid = (
|
||||
subscription.remnawave_uuid
|
||||
if settings.is_multi_tariff_enabled()
|
||||
else getattr(user, 'remnawave_uuid', None)
|
||||
)
|
||||
if _enable_uuid:
|
||||
await subscription_service.enable_remnawave_user(_enable_uuid)
|
||||
except Exception as e:
|
||||
logger.error('Failed to sync traffic with RemnaWave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
action='create' if _should_create else 'update',
|
||||
)
|
||||
|
||||
# Создаём транзакцию
|
||||
await create_transaction(
|
||||
@@ -560,7 +573,7 @@ async def switch_traffic_package(
|
||||
# Prorated calculation
|
||||
final_price, days_charged = calculate_prorated_price(price_diff, subscription.end_date)
|
||||
|
||||
if user.balance_kopeks < final_price:
|
||||
if final_price > 0 and user.balance_kopeks < final_price:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_402_PAYMENT_REQUIRED,
|
||||
detail=f'Insufficient balance. Need {final_price / 100:.2f} RUB',
|
||||
@@ -604,17 +617,25 @@ async def switch_traffic_package(
|
||||
# Sync with RemnaWave
|
||||
try:
|
||||
subscription_service = SubscriptionService()
|
||||
_panel_uuid2 = (
|
||||
subscription.remnawave_uuid
|
||||
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
|
||||
else getattr(user, 'remnawave_uuid', None)
|
||||
)
|
||||
if _panel_uuid2:
|
||||
await subscription_service.update_remnawave_user(db, subscription)
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await subscription_service.create_remnawave_user(db, subscription)
|
||||
else:
|
||||
await subscription_service.update_remnawave_user(db, subscription)
|
||||
except Exception as e:
|
||||
logger.error('Failed to sync traffic switch with RemnaWave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
if hasattr(subscription, 'id') and hasattr(subscription, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='create' if _should_create else 'update',
|
||||
)
|
||||
|
||||
await db.refresh(user)
|
||||
await db.refresh(subscription)
|
||||
|
||||
@@ -138,6 +138,9 @@ class EmailRegisterStandaloneRequest(BaseModel):
|
||||
referral_code: str | None = Field(
|
||||
None, max_length=32, pattern=r'^[a-zA-Z0-9_-]+$', description='Referral code of inviter'
|
||||
)
|
||||
campaign_slug: str | None = Field(
|
||||
None, min_length=1, max_length=64, pattern=r'^[a-zA-Z0-9_-]+$', description='Campaign slug from web link'
|
||||
)
|
||||
|
||||
|
||||
class CampaignBonusInfo(BaseModel):
|
||||
|
||||
@@ -118,6 +118,7 @@ class BroadcastCreateRequest(BaseModel):
|
||||
selected_buttons: list[str] = Field(default_factory=lambda: ['home'])
|
||||
custom_buttons: list[CustomBroadcastButton] = Field(default_factory=list, max_length=10)
|
||||
media: BroadcastMediaRequest | None = None
|
||||
category: str = Field(default='system', pattern='^(system|news|promo)$')
|
||||
|
||||
|
||||
# ============ Response ============
|
||||
@@ -144,6 +145,9 @@ class BroadcastResponse(BaseModel):
|
||||
completed_at: datetime | None = None
|
||||
progress_percent: float = 0.0
|
||||
|
||||
# Category for user notification preference filtering
|
||||
category: str = 'system' # system|news|promo
|
||||
|
||||
# Email/channel fields
|
||||
channel: str = 'telegram' # telegram|email|both
|
||||
email_subject: str | None = None
|
||||
@@ -212,6 +216,9 @@ class CombinedBroadcastCreateRequest(BaseModel):
|
||||
custom_buttons: list[CustomBroadcastButton] = Field(default_factory=list, max_length=10)
|
||||
media: BroadcastMediaRequest | None = None
|
||||
|
||||
# Broadcast category for user notification preference filtering
|
||||
category: str = Field(default='system', pattern='^(system|news|promo)$')
|
||||
|
||||
# Email-specific fields
|
||||
email_subject: str | None = Field(default=None, max_length=255)
|
||||
email_html_content: str | None = Field(default=None, max_length=100000)
|
||||
|
||||
@@ -12,7 +12,16 @@ def get_campaign_deep_link(start_parameter: str) -> str:
|
||||
|
||||
|
||||
def get_campaign_web_link(start_parameter: str) -> str | None:
|
||||
"""Generate a web app link for a campaign."""
|
||||
"""Generate a web app link for a campaign.
|
||||
|
||||
Prefers CABINET_URL (where the auth flow captures ?campaign= param),
|
||||
falls back to MINIAPP_CUSTOM_URL for backwards compatibility.
|
||||
"""
|
||||
cabinet_url = settings._normalized_cabinet_url()
|
||||
if cabinet_url:
|
||||
sep = '&' if '?' in cabinet_url else '?'
|
||||
return f'{cabinet_url}{sep}campaign={start_parameter}'
|
||||
|
||||
base_url = (settings.MINIAPP_CUSTOM_URL or '').rstrip('/')
|
||||
if base_url:
|
||||
return f'{base_url}/?campaign={start_parameter}'
|
||||
|
||||
+99
-6
@@ -68,9 +68,9 @@ class Settings(BaseSettings):
|
||||
ADMIN_NOTIFICATIONS_PARTNERS_TOPIC_ID: int | None = None # Партнёрки, выводы, админ-действия
|
||||
|
||||
# Настройки очереди чеков NaloGO
|
||||
NALOGO_QUEUE_CHECK_INTERVAL: int = 300 # Интервал проверки очереди (секунды)
|
||||
NALOGO_QUEUE_CHECK_INTERVAL: int = 600 # Интервал проверки очереди (секунды, 10 мин)
|
||||
NALOGO_QUEUE_RECEIPT_DELAY: int = 3 # Задержка между отправкой чеков (секунды)
|
||||
NALOGO_QUEUE_MAX_ATTEMPTS: int = 10 # Максимум попыток отправки чека
|
||||
NALOGO_QUEUE_MAX_ATTEMPTS: int = 72 # Максимум попыток отправки чека (72 × 10мин = 12 часов)
|
||||
|
||||
ADMIN_REPORTS_ENABLED: bool = False
|
||||
ADMIN_REPORTS_CHAT_ID: str | None = None
|
||||
@@ -133,6 +133,7 @@ class Settings(BaseSettings):
|
||||
WEBHOOK_NOTIFY_NOT_CONNECTED: bool = True
|
||||
WEBHOOK_NOTIFY_BANDWIDTH_THRESHOLD: bool = True
|
||||
WEBHOOK_NOTIFY_DEVICES: bool = True
|
||||
WEBHOOK_NOTIFY_TORRENT_DETECTED: bool = True
|
||||
|
||||
TRIAL_DURATION_DAYS: int = 3
|
||||
TRIAL_TRAFFIC_LIMIT_GB: int = 10
|
||||
@@ -323,6 +324,7 @@ class Settings(BaseSettings):
|
||||
SUBSCRIPTION_RENEWAL_BALANCE_THRESHOLD_KOPEKS: int = 20000
|
||||
|
||||
MONITORING_INTERVAL: int = 60
|
||||
LOW_BALANCE_ALERT_EXPIRY_DAYS: int = 3 # Only alert when subscription expires within N days
|
||||
INACTIVE_USER_DELETE_MONTHS: int = 3
|
||||
|
||||
MAINTENANCE_MODE: bool = False
|
||||
@@ -435,6 +437,7 @@ class Settings(BaseSettings):
|
||||
MULENPAY_LANGUAGE: str = 'ru'
|
||||
MULENPAY_VAT_CODE: int = 0
|
||||
|
||||
DISPLAY_NAME_RESTRICTION_ENABLED: bool = True
|
||||
DISPLAY_NAME_BANNED_KEYWORDS: str = '\n'.join(DEFAULT_DISPLAY_NAME_BANNED_KEYWORDS)
|
||||
MULENPAY_PAYMENT_SUBJECT: int = 4
|
||||
MULENPAY_PAYMENT_MODE: int = 4
|
||||
@@ -467,7 +470,7 @@ class Settings(BaseSettings):
|
||||
PLATEGA_RETURN_URL: str | None = None
|
||||
PLATEGA_FAILED_URL: str | None = None
|
||||
PLATEGA_CURRENCY: str = 'RUB'
|
||||
PLATEGA_ACTIVE_METHODS: str = '2,10,11,12,13'
|
||||
PLATEGA_ACTIVE_METHODS: str = '2,11,12,13'
|
||||
PLATEGA_INLINE_METHODS: bool = True
|
||||
PLATEGA_MIN_AMOUNT_KOPEKS: int = 10000
|
||||
PLATEGA_MAX_AMOUNT_KOPEKS: int = 100000000
|
||||
@@ -558,6 +561,8 @@ class Settings(BaseSettings):
|
||||
KASSA_AI_SBP_DISPLAY_NAME: str = 'СБП (KassaAI)'
|
||||
KASSA_AI_CARD_ENABLED: bool = False # Карты РФ — payment_system_id=36
|
||||
KASSA_AI_CARD_DISPLAY_NAME: str = 'Карта (KassaAI)'
|
||||
KASSA_AI_SBERPAY_ENABLED: bool = False # SberPay — payment_system_id=43
|
||||
KASSA_AI_SBERPAY_DISPLAY_NAME: str = 'SberPay (KassaAI)'
|
||||
|
||||
# RioPay (api.riopay.online) v2.0.1
|
||||
RIOPAY_ENABLED: bool = False
|
||||
@@ -583,6 +588,42 @@ class Settings(BaseSettings):
|
||||
SEVERPAY_RETURN_URL: str | None = None
|
||||
SEVERPAY_LIFETIME: int = 1440 # minutes, 30-4320
|
||||
|
||||
# PayPear (paypear.ru)
|
||||
PAYPEAR_ENABLED: bool = False
|
||||
PAYPEAR_SHOP_ID: str | None = None
|
||||
PAYPEAR_SECRET_KEY: str | None = None
|
||||
PAYPEAR_DISPLAY_NAME: str = 'PayPear'
|
||||
PAYPEAR_CURRENCY: str = 'RUB'
|
||||
PAYPEAR_MIN_AMOUNT_KOPEKS: int = 10000 # 100₽
|
||||
PAYPEAR_MAX_AMOUNT_KOPEKS: int = 10000000 # 100 000₽
|
||||
PAYPEAR_WEBHOOK_PATH: str = '/paypear-webhook'
|
||||
PAYPEAR_RETURN_URL: str | None = None
|
||||
PAYPEAR_PAYMENT_METHOD: str = 'sbp' # bank_card, sbp, sberpay, tpay
|
||||
|
||||
# RollyPay (rollypay.io)
|
||||
ROLLYPAY_ENABLED: bool = False
|
||||
ROLLYPAY_API_KEY: str | None = None # X-API-Key header
|
||||
ROLLYPAY_SIGNING_SECRET: str | None = None # HMAC webhook verification
|
||||
ROLLYPAY_DISPLAY_NAME: str = 'RollyPay'
|
||||
ROLLYPAY_CURRENCY: str = 'RUB'
|
||||
ROLLYPAY_MIN_AMOUNT_KOPEKS: int = 10000 # 100₽
|
||||
ROLLYPAY_MAX_AMOUNT_KOPEKS: int = 10000000 # 100 000₽
|
||||
ROLLYPAY_WEBHOOK_PATH: str = '/rollypay-webhook'
|
||||
ROLLYPAY_RETURN_URL: str | None = None
|
||||
|
||||
# AuraPay (aurapay.tech)
|
||||
AURAPAY_ENABLED: bool = False
|
||||
AURAPAY_API_KEY: str | None = None # X-ApiKey header
|
||||
AURAPAY_SHOP_ID: str | None = None # X-ShopId header (UUID)
|
||||
AURAPAY_SECRET_KEY: str | None = None # Secret key #2 for webhook HMAC
|
||||
AURAPAY_DISPLAY_NAME: str = 'AuraPay'
|
||||
AURAPAY_CURRENCY: str = 'RUB'
|
||||
AURAPAY_MIN_AMOUNT_KOPEKS: int = 10000 # 100₽
|
||||
AURAPAY_MAX_AMOUNT_KOPEKS: int = 10000000 # 100 000₽
|
||||
AURAPAY_WEBHOOK_PATH: str = '/aurapay-webhook'
|
||||
AURAPAY_RETURN_URL: str | None = None
|
||||
AURAPAY_PAYMENT_LIFETIME_MINUTES: int = 60
|
||||
|
||||
MAIN_MENU_MODE: str = 'default' # 'default' | 'cabinet'
|
||||
# Стиль кнопок Cabinet: primary (синий), success (зелёный), danger (красный), '' (по умолчанию для каждой секции)
|
||||
CABINET_BUTTON_STYLE: str = ''
|
||||
@@ -822,6 +863,10 @@ class Settings(BaseSettings):
|
||||
# Format: socks5://user:password@host:port or socks5://host:port
|
||||
PROXY_URL: str | None = None
|
||||
|
||||
# Custom Telegram Bot API server URL (for regions where api.telegram.org is blocked)
|
||||
# Examples: Cloudflare Worker proxy, self-hosted telegram-bot-api (tdlib), nginx reverse proxy
|
||||
TELEGRAM_API_URL: str | None = None
|
||||
|
||||
@field_validator('PROXY_URL', 'NALOGO_PROXY_URL', mode='before')
|
||||
@classmethod
|
||||
def validate_proxy_url(cls, value: str | None) -> str | None:
|
||||
@@ -969,6 +1014,10 @@ class Settings(BaseSettings):
|
||||
"""Return SOCKS5 proxy URL or None."""
|
||||
return self.PROXY_URL if self.PROXY_URL else None
|
||||
|
||||
def get_telegram_api_url(self) -> str | None:
|
||||
"""Return custom Telegram Bot API server URL or None."""
|
||||
return self.TELEGRAM_API_URL if self.TELEGRAM_API_URL else None
|
||||
|
||||
def get_nalogo_proxy_url(self) -> str | None:
|
||||
"""Return SOCKS proxy URL for nalogo or None.
|
||||
|
||||
@@ -1839,7 +1888,7 @@ class Settings(BaseSettings):
|
||||
except ValueError:
|
||||
logger.warning('Некорректный код метода Platega', part=part)
|
||||
continue
|
||||
if method_code in {2, 10, 11, 12, 13} and method_code not in seen:
|
||||
if method_code in {2, 11, 12, 13} and method_code not in seen:
|
||||
methods.append(method_code)
|
||||
seen.add(method_code)
|
||||
|
||||
@@ -1852,8 +1901,7 @@ class Settings(BaseSettings):
|
||||
def get_platega_method_definitions() -> dict[int, dict[str, str]]:
|
||||
return {
|
||||
2: {'name': 'СБП (QR)', 'title': '🏦 СБП (QR)'},
|
||||
10: {'name': 'Банковские карты (RUB)', 'title': '💳 Карты (RUB)'},
|
||||
11: {'name': 'Банковские карты', 'title': '💳 Банковские карты'},
|
||||
11: {'name': 'Карты (RUB)', 'title': '💳 Карты (RUB)'},
|
||||
12: {'name': 'Международные карты', 'title': '🌍 Международные карты'},
|
||||
13: {'name': 'Криптовалюта', 'title': '🪙 Криптовалюта'},
|
||||
}
|
||||
@@ -1961,6 +2009,41 @@ class Settings(BaseSettings):
|
||||
def get_severpay_display_name_html(self) -> str:
|
||||
return html.escape(self.get_severpay_display_name())
|
||||
|
||||
def is_paypear_enabled(self) -> bool:
|
||||
return self.PAYPEAR_ENABLED and self.PAYPEAR_SHOP_ID is not None and self.PAYPEAR_SECRET_KEY is not None
|
||||
|
||||
def get_paypear_display_name(self) -> str:
|
||||
name = (self.PAYPEAR_DISPLAY_NAME or '').strip()
|
||||
return name if name else 'PayPear'
|
||||
|
||||
def get_paypear_display_name_html(self) -> str:
|
||||
return html.escape(self.get_paypear_display_name())
|
||||
|
||||
def is_rollypay_enabled(self) -> bool:
|
||||
return self.ROLLYPAY_ENABLED and self.ROLLYPAY_API_KEY is not None and self.ROLLYPAY_SIGNING_SECRET is not None
|
||||
|
||||
def get_rollypay_display_name(self) -> str:
|
||||
name = (self.ROLLYPAY_DISPLAY_NAME or '').strip()
|
||||
return name if name else 'RollyPay'
|
||||
|
||||
def get_rollypay_display_name_html(self) -> str:
|
||||
return html.escape(self.get_rollypay_display_name())
|
||||
|
||||
def is_aurapay_enabled(self) -> bool:
|
||||
return (
|
||||
self.AURAPAY_ENABLED
|
||||
and self.AURAPAY_API_KEY is not None
|
||||
and self.AURAPAY_SHOP_ID is not None
|
||||
and self.AURAPAY_SECRET_KEY is not None
|
||||
)
|
||||
|
||||
def get_aurapay_display_name(self) -> str:
|
||||
name = (self.AURAPAY_DISPLAY_NAME or '').strip()
|
||||
return name if name else 'AuraPay'
|
||||
|
||||
def get_aurapay_display_name_html(self) -> str:
|
||||
return html.escape(self.get_aurapay_display_name())
|
||||
|
||||
def is_kassa_ai_sbp_enabled(self) -> bool:
|
||||
return self.KASSA_AI_SBP_ENABLED and self.is_kassa_ai_enabled()
|
||||
|
||||
@@ -1981,6 +2064,16 @@ class Settings(BaseSettings):
|
||||
def get_kassa_ai_card_display_name_html(self) -> str:
|
||||
return html.escape(self.get_kassa_ai_card_display_name())
|
||||
|
||||
def is_kassa_ai_sberpay_enabled(self) -> bool:
|
||||
return self.KASSA_AI_SBERPAY_ENABLED and self.is_kassa_ai_enabled()
|
||||
|
||||
def get_kassa_ai_sberpay_display_name(self) -> str:
|
||||
name = (self.KASSA_AI_SBERPAY_DISPLAY_NAME or '').strip()
|
||||
return name if name else 'SberPay (KassaAI)'
|
||||
|
||||
def get_kassa_ai_sberpay_display_name_html(self) -> str:
|
||||
return html.escape(self.get_kassa_ai_sberpay_display_name())
|
||||
|
||||
def is_payment_verification_auto_check_enabled(self) -> bool:
|
||||
return self.PAYMENT_VERIFICATION_AUTO_CHECK_ENABLED
|
||||
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""CRUD операции для платежей AuraPay."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import structlog
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.models import AuraPayPayment
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
async def create_aurapay_payment(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: int | None,
|
||||
order_id: str,
|
||||
amount_kopeks: int,
|
||||
currency: str = 'RUB',
|
||||
description: str | None = None,
|
||||
payment_url: str | None = None,
|
||||
payment_method: str | None = None,
|
||||
aurapay_invoice_id: str | None = None,
|
||||
expires_at: datetime | None = None,
|
||||
metadata_json: dict | None = None,
|
||||
) -> AuraPayPayment:
|
||||
"""Создает запись о платеже AuraPay."""
|
||||
payment = AuraPayPayment(
|
||||
user_id=user_id,
|
||||
order_id=order_id,
|
||||
amount_kopeks=amount_kopeks,
|
||||
currency=currency,
|
||||
description=description,
|
||||
payment_url=payment_url,
|
||||
payment_method=payment_method,
|
||||
aurapay_invoice_id=aurapay_invoice_id,
|
||||
expires_at=expires_at,
|
||||
metadata_json=metadata_json,
|
||||
status='pending',
|
||||
is_paid=False,
|
||||
)
|
||||
db.add(payment)
|
||||
await db.commit()
|
||||
await db.refresh(payment)
|
||||
logger.info('Создан платеж AuraPay', order_id=order_id, user_id=user_id)
|
||||
return payment
|
||||
|
||||
|
||||
async def get_aurapay_payment_by_order_id(db: AsyncSession, order_id: str) -> AuraPayPayment | None:
|
||||
"""Получает платеж по order_id (internal)."""
|
||||
result = await db.execute(select(AuraPayPayment).where(AuraPayPayment.order_id == order_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_aurapay_payment_by_invoice_id(db: AsyncSession, aurapay_invoice_id: str) -> AuraPayPayment | None:
|
||||
"""Получает платеж по UUID от AuraPay."""
|
||||
result = await db.execute(select(AuraPayPayment).where(AuraPayPayment.aurapay_invoice_id == aurapay_invoice_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_aurapay_payment_by_id(db: AsyncSession, payment_id: int) -> AuraPayPayment | None:
|
||||
"""Получает платеж по ID."""
|
||||
result = await db.execute(select(AuraPayPayment).where(AuraPayPayment.id == payment_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_aurapay_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> AuraPayPayment | None:
|
||||
"""Получает платеж по ID с блокировкой FOR UPDATE."""
|
||||
result = await db.execute(
|
||||
select(AuraPayPayment)
|
||||
.where(AuraPayPayment.id == payment_id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def update_aurapay_payment_status(
|
||||
db: AsyncSession,
|
||||
payment: AuraPayPayment,
|
||||
*,
|
||||
status: str,
|
||||
is_paid: bool | None = None,
|
||||
aurapay_invoice_id: str | None = None,
|
||||
payment_method: str | None = None,
|
||||
callback_payload: dict | None = None,
|
||||
transaction_id: int | None = None,
|
||||
) -> AuraPayPayment:
|
||||
"""Обновляет статус платежа."""
|
||||
payment.status = status
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
|
||||
if is_paid is not None:
|
||||
payment.is_paid = is_paid
|
||||
if is_paid:
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
if aurapay_invoice_id is not None:
|
||||
payment.aurapay_invoice_id = aurapay_invoice_id
|
||||
if payment_method is not None:
|
||||
payment.payment_method = payment_method
|
||||
if callback_payload is not None:
|
||||
payment.callback_payload = callback_payload
|
||||
if transaction_id is not None:
|
||||
payment.transaction_id = transaction_id
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(payment)
|
||||
logger.info(
|
||||
'Обновлен статус платежа AuraPay',
|
||||
order_id=payment.order_id,
|
||||
status=status,
|
||||
is_paid=payment.is_paid,
|
||||
)
|
||||
return payment
|
||||
|
||||
|
||||
async def get_pending_aurapay_payments(db: AsyncSession, user_id: int) -> list[AuraPayPayment]:
|
||||
"""Получает незавершенные платежи пользователя."""
|
||||
result = await db.execute(
|
||||
select(AuraPayPayment).where(
|
||||
AuraPayPayment.user_id == user_id,
|
||||
AuraPayPayment.status == 'pending',
|
||||
AuraPayPayment.is_paid == False,
|
||||
)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def get_expired_pending_aurapay_payments(
|
||||
db: AsyncSession,
|
||||
) -> list[AuraPayPayment]:
|
||||
"""Получает просроченные платежи в статусе pending."""
|
||||
now = datetime.now(UTC)
|
||||
result = await db.execute(
|
||||
select(AuraPayPayment).where(
|
||||
AuraPayPayment.status == 'pending',
|
||||
AuraPayPayment.is_paid == False,
|
||||
AuraPayPayment.expires_at < now,
|
||||
)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def link_aurapay_payment_to_transaction(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
payment: AuraPayPayment,
|
||||
transaction_id: int,
|
||||
) -> AuraPayPayment:
|
||||
"""Связывает платеж с транзакцией."""
|
||||
payment.transaction_id = transaction_id
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
await db.refresh(payment)
|
||||
return payment
|
||||
@@ -0,0 +1,157 @@
|
||||
"""CRUD операции для платежей PayPear."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import structlog
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.models import PayPearPayment
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
async def create_paypear_payment(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: int | None,
|
||||
order_id: str,
|
||||
amount_kopeks: int,
|
||||
currency: str = 'RUB',
|
||||
description: str | None = None,
|
||||
payment_url: str | None = None,
|
||||
payment_method: str | None = None,
|
||||
paypear_id: str | None = None,
|
||||
expires_at: datetime | None = None,
|
||||
metadata_json: dict | None = None,
|
||||
) -> PayPearPayment:
|
||||
"""Создает запись о платеже PayPear."""
|
||||
payment = PayPearPayment(
|
||||
user_id=user_id,
|
||||
order_id=order_id,
|
||||
amount_kopeks=amount_kopeks,
|
||||
currency=currency,
|
||||
description=description,
|
||||
payment_url=payment_url,
|
||||
payment_method=payment_method,
|
||||
paypear_id=paypear_id,
|
||||
expires_at=expires_at,
|
||||
metadata_json=metadata_json,
|
||||
status='pending',
|
||||
is_paid=False,
|
||||
)
|
||||
db.add(payment)
|
||||
await db.commit()
|
||||
await db.refresh(payment)
|
||||
logger.info('Создан платеж PayPear', order_id=order_id, user_id=user_id)
|
||||
return payment
|
||||
|
||||
|
||||
async def get_paypear_payment_by_order_id(db: AsyncSession, order_id: str) -> PayPearPayment | None:
|
||||
"""Получает платеж по order_id (internal)."""
|
||||
result = await db.execute(select(PayPearPayment).where(PayPearPayment.order_id == order_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_paypear_payment_by_paypear_id(db: AsyncSession, paypear_id: str) -> PayPearPayment | None:
|
||||
"""Получает платеж по ID от PayPear."""
|
||||
result = await db.execute(select(PayPearPayment).where(PayPearPayment.paypear_id == paypear_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_paypear_payment_by_id(db: AsyncSession, payment_id: int) -> PayPearPayment | None:
|
||||
"""Получает платеж по ID."""
|
||||
result = await db.execute(select(PayPearPayment).where(PayPearPayment.id == payment_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_paypear_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> PayPearPayment | None:
|
||||
"""Получает платеж по ID с блокировкой FOR UPDATE."""
|
||||
result = await db.execute(
|
||||
select(PayPearPayment)
|
||||
.where(PayPearPayment.id == payment_id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def update_paypear_payment_status(
|
||||
db: AsyncSession,
|
||||
payment: PayPearPayment,
|
||||
*,
|
||||
status: str,
|
||||
is_paid: bool | None = None,
|
||||
paypear_id: str | None = None,
|
||||
payment_method: str | None = None,
|
||||
callback_payload: dict | None = None,
|
||||
transaction_id: int | None = None,
|
||||
) -> PayPearPayment:
|
||||
"""Обновляет статус платежа."""
|
||||
payment.status = status
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
|
||||
if is_paid is not None:
|
||||
payment.is_paid = is_paid
|
||||
if is_paid:
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
if paypear_id is not None:
|
||||
payment.paypear_id = paypear_id
|
||||
if payment_method is not None:
|
||||
payment.payment_method = payment_method
|
||||
if callback_payload is not None:
|
||||
payment.callback_payload = callback_payload
|
||||
if transaction_id is not None:
|
||||
payment.transaction_id = transaction_id
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(payment)
|
||||
logger.info(
|
||||
'Обновлен статус платежа PayPear',
|
||||
order_id=payment.order_id,
|
||||
status=status,
|
||||
is_paid=payment.is_paid,
|
||||
)
|
||||
return payment
|
||||
|
||||
|
||||
async def get_pending_paypear_payments(db: AsyncSession, user_id: int) -> list[PayPearPayment]:
|
||||
"""Получает незавершенные платежи пользователя."""
|
||||
result = await db.execute(
|
||||
select(PayPearPayment).where(
|
||||
PayPearPayment.user_id == user_id,
|
||||
PayPearPayment.status == 'pending',
|
||||
PayPearPayment.is_paid == False,
|
||||
)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def get_expired_pending_paypear_payments(
|
||||
db: AsyncSession,
|
||||
) -> list[PayPearPayment]:
|
||||
"""Получает просроченные платежи в статусе pending."""
|
||||
now = datetime.now(UTC)
|
||||
result = await db.execute(
|
||||
select(PayPearPayment).where(
|
||||
PayPearPayment.status == 'pending',
|
||||
PayPearPayment.is_paid == False,
|
||||
PayPearPayment.expires_at < now,
|
||||
)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def link_paypear_payment_to_transaction(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
payment: PayPearPayment,
|
||||
transaction_id: int,
|
||||
) -> PayPearPayment:
|
||||
"""Связывает платеж с транзакцией."""
|
||||
payment.transaction_id = transaction_id
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
await db.refresh(payment)
|
||||
return payment
|
||||
@@ -166,7 +166,7 @@ async def update_promo_group(
|
||||
group.device_discount_percent = max(0, min(100, device_discount_percent))
|
||||
if period_discounts is not None:
|
||||
normalized_period_discounts = _normalize_period_discounts(period_discounts)
|
||||
group.period_discounts = normalized_period_discounts or None
|
||||
group.period_discounts = normalized_period_discounts if normalized_period_discounts else None
|
||||
if auto_assign_total_spent_kopeks is not None:
|
||||
value = max(0, auto_assign_total_spent_kopeks)
|
||||
group.auto_assign_total_spent_kopeks = value if value > 0 else None
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""CRUD операции для платежей RollyPay."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import structlog
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database.models import RollyPayPayment
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
async def create_rollypay_payment(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: int | None,
|
||||
order_id: str,
|
||||
amount_kopeks: int,
|
||||
currency: str = 'RUB',
|
||||
description: str | None = None,
|
||||
payment_url: str | None = None,
|
||||
payment_method: str | None = None,
|
||||
rollypay_payment_id: str | None = None,
|
||||
expires_at: datetime | None = None,
|
||||
metadata_json: dict | None = None,
|
||||
) -> RollyPayPayment:
|
||||
"""Создает запись о платеже RollyPay."""
|
||||
payment = RollyPayPayment(
|
||||
user_id=user_id,
|
||||
order_id=order_id,
|
||||
amount_kopeks=amount_kopeks,
|
||||
currency=currency,
|
||||
description=description,
|
||||
payment_url=payment_url,
|
||||
payment_method=payment_method,
|
||||
rollypay_payment_id=rollypay_payment_id,
|
||||
expires_at=expires_at,
|
||||
metadata_json=metadata_json,
|
||||
status='pending',
|
||||
is_paid=False,
|
||||
)
|
||||
db.add(payment)
|
||||
await db.commit()
|
||||
await db.refresh(payment)
|
||||
logger.info('Создан платеж RollyPay', order_id=order_id, user_id=user_id)
|
||||
return payment
|
||||
|
||||
|
||||
async def get_rollypay_payment_by_order_id(db: AsyncSession, order_id: str) -> RollyPayPayment | None:
|
||||
"""Получает платеж по order_id (internal)."""
|
||||
result = await db.execute(select(RollyPayPayment).where(RollyPayPayment.order_id == order_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_rollypay_payment_by_rollypay_id(db: AsyncSession, rollypay_payment_id: str) -> RollyPayPayment | None:
|
||||
"""Получает платеж по ID от RollyPay."""
|
||||
result = await db.execute(select(RollyPayPayment).where(RollyPayPayment.rollypay_payment_id == rollypay_payment_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_rollypay_payment_by_id(db: AsyncSession, payment_id: int) -> RollyPayPayment | None:
|
||||
"""Получает платеж по ID."""
|
||||
result = await db.execute(select(RollyPayPayment).where(RollyPayPayment.id == payment_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_rollypay_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> RollyPayPayment | None:
|
||||
"""Получает платеж по ID с блокировкой FOR UPDATE."""
|
||||
result = await db.execute(
|
||||
select(RollyPayPayment)
|
||||
.where(RollyPayPayment.id == payment_id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def update_rollypay_payment_status(
|
||||
db: AsyncSession,
|
||||
payment: RollyPayPayment,
|
||||
*,
|
||||
status: str,
|
||||
is_paid: bool | None = None,
|
||||
rollypay_payment_id: str | None = None,
|
||||
payment_method: str | None = None,
|
||||
callback_payload: dict | None = None,
|
||||
transaction_id: int | None = None,
|
||||
) -> RollyPayPayment:
|
||||
"""Обновляет статус платежа."""
|
||||
payment.status = status
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
|
||||
if is_paid is not None:
|
||||
payment.is_paid = is_paid
|
||||
if is_paid:
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
if rollypay_payment_id is not None:
|
||||
payment.rollypay_payment_id = rollypay_payment_id
|
||||
if payment_method is not None:
|
||||
payment.payment_method = payment_method
|
||||
if callback_payload is not None:
|
||||
payment.callback_payload = callback_payload
|
||||
if transaction_id is not None:
|
||||
payment.transaction_id = transaction_id
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(payment)
|
||||
logger.info(
|
||||
'Обновлен статус платежа RollyPay',
|
||||
order_id=payment.order_id,
|
||||
status=status,
|
||||
is_paid=payment.is_paid,
|
||||
)
|
||||
return payment
|
||||
|
||||
|
||||
async def get_pending_rollypay_payments(db: AsyncSession, user_id: int) -> list[RollyPayPayment]:
|
||||
"""Получает незавершенные платежи пользователя."""
|
||||
result = await db.execute(
|
||||
select(RollyPayPayment).where(
|
||||
RollyPayPayment.user_id == user_id,
|
||||
RollyPayPayment.status == 'pending',
|
||||
RollyPayPayment.is_paid == False,
|
||||
)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def get_expired_pending_rollypay_payments(
|
||||
db: AsyncSession,
|
||||
) -> list[RollyPayPayment]:
|
||||
"""Получает просроченные платежи в статусе pending."""
|
||||
now = datetime.now(UTC)
|
||||
result = await db.execute(
|
||||
select(RollyPayPayment).where(
|
||||
RollyPayPayment.status == 'pending',
|
||||
RollyPayPayment.is_paid == False,
|
||||
RollyPayPayment.expires_at < now,
|
||||
)
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def link_rollypay_payment_to_transaction(
|
||||
db: AsyncSession,
|
||||
*,
|
||||
payment: RollyPayPayment,
|
||||
transaction_id: int,
|
||||
) -> RollyPayPayment:
|
||||
"""Связывает платеж с транзакцией."""
|
||||
payment.transaction_id = transaction_id
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
await db.refresh(payment)
|
||||
return payment
|
||||
@@ -96,12 +96,13 @@ async def get_subscription_by_user_id(db: AsyncSession, user_id: int) -> Subscri
|
||||
)
|
||||
.where(Subscription.user_id == user_id)
|
||||
.order_by(
|
||||
# Active/trial subscriptions first, then by creation date
|
||||
# Active/trial subscriptions first, then by end_date (most remaining time)
|
||||
case(
|
||||
(Subscription.status == SubscriptionStatus.ACTIVE.value, 0),
|
||||
(Subscription.status == SubscriptionStatus.TRIAL.value, 1),
|
||||
else_=2,
|
||||
),
|
||||
Subscription.end_date.desc().nulls_last(),
|
||||
Subscription.created_at.desc(),
|
||||
)
|
||||
.limit(1)
|
||||
@@ -2075,7 +2076,12 @@ async def toggle_daily_subscription_pause(
|
||||
|
||||
|
||||
async def get_active_subscriptions_by_user_id(db: AsyncSession, user_id: int) -> list[Subscription]:
|
||||
"""Get all active/trial subscriptions for a user."""
|
||||
"""Get all active/trial/limited subscriptions for a user.
|
||||
|
||||
Includes LIMITED status because those subscriptions still have time remaining
|
||||
(just ran out of traffic) and should be treated as "alive" for renewal,
|
||||
duplicate prevention, and display purposes.
|
||||
"""
|
||||
result = await db.execute(
|
||||
select(Subscription)
|
||||
.options(
|
||||
@@ -2084,7 +2090,13 @@ async def get_active_subscriptions_by_user_id(db: AsyncSession, user_id: int) ->
|
||||
)
|
||||
.where(
|
||||
Subscription.user_id == user_id,
|
||||
Subscription.status.in_([SubscriptionStatus.ACTIVE.value, SubscriptionStatus.TRIAL.value]),
|
||||
Subscription.status.in_(
|
||||
[
|
||||
SubscriptionStatus.ACTIVE.value,
|
||||
SubscriptionStatus.TRIAL.value,
|
||||
SubscriptionStatus.LIMITED.value,
|
||||
]
|
||||
),
|
||||
)
|
||||
.order_by(Subscription.created_at.desc())
|
||||
)
|
||||
@@ -2121,7 +2133,11 @@ async def get_subscription_by_id(db: AsyncSession, subscription_id: int) -> Subs
|
||||
|
||||
|
||||
async def get_subscription_by_user_and_tariff(db: AsyncSession, user_id: int, tariff_id: int) -> Subscription | None:
|
||||
"""Get active/trial subscription for a specific user+tariff combination."""
|
||||
"""Get active/trial/limited subscription for a specific user+tariff combination.
|
||||
|
||||
Includes LIMITED status because those subscriptions still have time remaining
|
||||
(just ran out of traffic) and should be extended rather than duplicated.
|
||||
"""
|
||||
result = await db.execute(
|
||||
select(Subscription)
|
||||
.options(
|
||||
@@ -2131,7 +2147,13 @@ async def get_subscription_by_user_and_tariff(db: AsyncSession, user_id: int, ta
|
||||
.where(
|
||||
Subscription.user_id == user_id,
|
||||
Subscription.tariff_id == tariff_id,
|
||||
Subscription.status.in_([SubscriptionStatus.ACTIVE.value, SubscriptionStatus.TRIAL.value]),
|
||||
Subscription.status.in_(
|
||||
[
|
||||
SubscriptionStatus.ACTIVE.value,
|
||||
SubscriptionStatus.TRIAL.value,
|
||||
SubscriptionStatus.LIMITED.value,
|
||||
]
|
||||
),
|
||||
)
|
||||
.order_by(Subscription.created_at.desc())
|
||||
.limit(1)
|
||||
|
||||
@@ -122,6 +122,12 @@ async def clear_trial_tariff(db: AsyncSession) -> None:
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def get_all_active_tariffs(db: AsyncSession) -> list[Tariff]:
|
||||
"""Get all active tariffs."""
|
||||
result = await db.execute(select(Tariff).where(Tariff.is_active.is_(True)).order_by(Tariff.tier_level))
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def get_tariffs_for_user(
|
||||
db: AsyncSession,
|
||||
promo_group_id: int | None = None,
|
||||
|
||||
@@ -235,7 +235,12 @@ async def get_user_total_spent_kopeks(db: AsyncSession, user_id: int) -> int:
|
||||
and_(
|
||||
Transaction.user_id == user_id,
|
||||
Transaction.is_completed.is_(True),
|
||||
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
|
||||
Transaction.type.in_(
|
||||
[
|
||||
TransactionType.SUBSCRIPTION_PAYMENT.value,
|
||||
TransactionType.GIFT_PAYMENT.value,
|
||||
]
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
+196
-2
@@ -162,6 +162,9 @@ class PaymentMethod(Enum):
|
||||
KASSA_AI = 'kassa_ai'
|
||||
RIOPAY = 'riopay'
|
||||
SEVERPAY = 'severpay'
|
||||
PAYPEAR = 'paypear'
|
||||
ROLLYPAY = 'rollypay'
|
||||
AURAPAY = 'aurapay'
|
||||
MANUAL = 'manual'
|
||||
BALANCE = 'balance'
|
||||
|
||||
@@ -878,6 +881,192 @@ class SeverPayPayment(Base):
|
||||
return f'<SeverPayPayment(id={self.id}, order_id={self.order_id}, amount={self.amount_rubles}₽, status={self.status})>'
|
||||
|
||||
|
||||
class PayPearPayment(Base):
|
||||
"""Платежи через PayPear (paypear.ru)."""
|
||||
|
||||
__tablename__ = 'paypear_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
|
||||
# Идентификаторы
|
||||
order_id = Column(String(64), unique=True, nullable=False, index=True) # Наш internal ID
|
||||
paypear_id = Column(String(64), unique=True, nullable=True, index=True) # ID от PayPear
|
||||
|
||||
# Суммы
|
||||
amount_kopeks = Column(Integer, nullable=False)
|
||||
currency = Column(String(10), nullable=False, default='RUB')
|
||||
description = Column(Text, nullable=True)
|
||||
|
||||
# Статусы
|
||||
status = Column(String(32), nullable=False, default='pending')
|
||||
is_paid = Column(Boolean, default=False)
|
||||
|
||||
# Данные платежа
|
||||
payment_url = Column(Text, nullable=True)
|
||||
payment_method = Column(String(32), nullable=True)
|
||||
|
||||
# Метаданные
|
||||
metadata_json = Column(JSON, nullable=True)
|
||||
callback_payload = Column(JSON, nullable=True)
|
||||
|
||||
# Временные метки
|
||||
paid_at = Column(AwareDateTime(), nullable=True)
|
||||
expires_at = Column(AwareDateTime(), nullable=True)
|
||||
created_at = Column(AwareDateTime(), default=func.now())
|
||||
updated_at = Column(AwareDateTime(), default=func.now(), onupdate=func.now())
|
||||
|
||||
# Связь с транзакцией
|
||||
transaction_id = Column(Integer, ForeignKey('transactions.id'), nullable=True)
|
||||
|
||||
# Relationships
|
||||
user = relationship('User', backref='paypear_payments')
|
||||
transaction = relationship('Transaction', backref='paypear_payment')
|
||||
|
||||
@property
|
||||
def amount_rubles(self) -> float:
|
||||
return self.amount_kopeks / 100
|
||||
|
||||
@property
|
||||
def is_pending(self) -> bool:
|
||||
return self.status == 'pending'
|
||||
|
||||
@property
|
||||
def is_success(self) -> bool:
|
||||
return self.status == 'success' and self.is_paid
|
||||
|
||||
@property
|
||||
def is_failed(self) -> bool:
|
||||
return self.status in ['failed', 'expired', 'canceled', 'amount_mismatch']
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debug helper
|
||||
return f'<PayPearPayment(id={self.id}, order_id={self.order_id}, amount={self.amount_rubles}₽, status={self.status})>'
|
||||
|
||||
|
||||
class RollyPayPayment(Base):
|
||||
"""Платежи через RollyPay (rollypay.io)."""
|
||||
|
||||
__tablename__ = 'rollypay_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
|
||||
# Идентификаторы
|
||||
order_id = Column(String(64), unique=True, nullable=False, index=True) # Наш internal ID
|
||||
rollypay_payment_id = Column(String(128), unique=True, nullable=True, index=True) # pay_uuid от RollyPay
|
||||
|
||||
# Суммы
|
||||
amount_kopeks = Column(Integer, nullable=False)
|
||||
currency = Column(String(10), nullable=False, default='RUB')
|
||||
description = Column(Text, nullable=True)
|
||||
|
||||
# Статусы
|
||||
status = Column(String(32), nullable=False, default='pending')
|
||||
is_paid = Column(Boolean, default=False)
|
||||
|
||||
# Данные платежа
|
||||
payment_url = Column(Text, nullable=True)
|
||||
payment_method = Column(String(32), nullable=True)
|
||||
|
||||
# Метаданные
|
||||
metadata_json = Column(JSON, nullable=True)
|
||||
callback_payload = Column(JSON, nullable=True)
|
||||
|
||||
# Временные метки
|
||||
paid_at = Column(AwareDateTime(), nullable=True)
|
||||
expires_at = Column(AwareDateTime(), nullable=True)
|
||||
created_at = Column(AwareDateTime(), default=func.now())
|
||||
updated_at = Column(AwareDateTime(), default=func.now(), onupdate=func.now())
|
||||
|
||||
# Связь с транзакцией
|
||||
transaction_id = Column(Integer, ForeignKey('transactions.id'), nullable=True)
|
||||
|
||||
# Relationships
|
||||
user = relationship('User', backref='rollypay_payments')
|
||||
transaction = relationship('Transaction', backref='rollypay_payment')
|
||||
|
||||
@property
|
||||
def amount_rubles(self) -> float:
|
||||
return self.amount_kopeks / 100
|
||||
|
||||
@property
|
||||
def is_pending(self) -> bool:
|
||||
return self.status == 'pending'
|
||||
|
||||
@property
|
||||
def is_success(self) -> bool:
|
||||
return self.status == 'success' and self.is_paid
|
||||
|
||||
@property
|
||||
def is_failed(self) -> bool:
|
||||
return self.status in ['failed', 'expired', 'canceled', 'chargeback', 'amount_mismatch']
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debug helper
|
||||
return f'<RollyPayPayment(id={self.id}, order_id={self.order_id}, amount={self.amount_rubles}₽, status={self.status})>'
|
||||
|
||||
|
||||
class AuraPayPayment(Base):
|
||||
"""Платежи через AuraPay (aurapay.tech)."""
|
||||
|
||||
__tablename__ = 'aurapay_payments'
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
|
||||
# Идентификаторы
|
||||
order_id = Column(String(64), unique=True, nullable=False, index=True) # Наш internal ID
|
||||
aurapay_invoice_id = Column(String(128), unique=True, nullable=True, index=True) # UUID от AuraPay
|
||||
|
||||
# Суммы
|
||||
amount_kopeks = Column(Integer, nullable=False)
|
||||
currency = Column(String(10), nullable=False, default='RUB')
|
||||
description = Column(Text, nullable=True)
|
||||
|
||||
# Статусы
|
||||
status = Column(String(32), nullable=False, default='pending')
|
||||
is_paid = Column(Boolean, default=False)
|
||||
|
||||
# Данные платежа
|
||||
payment_url = Column(Text, nullable=True)
|
||||
payment_method = Column(String(32), nullable=True)
|
||||
|
||||
# Метаданные
|
||||
metadata_json = Column(JSON, nullable=True)
|
||||
callback_payload = Column(JSON, nullable=True)
|
||||
|
||||
# Временные метки
|
||||
paid_at = Column(AwareDateTime(), nullable=True)
|
||||
expires_at = Column(AwareDateTime(), nullable=True)
|
||||
created_at = Column(AwareDateTime(), default=func.now())
|
||||
updated_at = Column(AwareDateTime(), default=func.now(), onupdate=func.now())
|
||||
|
||||
# Связь с транзакцией
|
||||
transaction_id = Column(Integer, ForeignKey('transactions.id'), nullable=True)
|
||||
|
||||
# Relationships
|
||||
user = relationship('User', backref='aurapay_payments')
|
||||
transaction = relationship('Transaction', backref='aurapay_payment')
|
||||
|
||||
@property
|
||||
def amount_rubles(self) -> float:
|
||||
return self.amount_kopeks / 100
|
||||
|
||||
@property
|
||||
def is_pending(self) -> bool:
|
||||
return self.status == 'pending'
|
||||
|
||||
@property
|
||||
def is_success(self) -> bool:
|
||||
return self.status == 'success' and self.is_paid
|
||||
|
||||
@property
|
||||
def is_failed(self) -> bool:
|
||||
return self.status in ['failed', 'expired', 'canceled', 'amount_mismatch']
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debug helper
|
||||
return f'<AuraPayPayment(id={self.id}, order_id={self.order_id}, amount={self.amount_rubles}₽, status={self.status})>'
|
||||
|
||||
|
||||
class PromoGroup(Base):
|
||||
__tablename__ = 'promo_groups'
|
||||
|
||||
@@ -1204,6 +1393,8 @@ class User(Base):
|
||||
password_reset_token = Column(String(255), nullable=True)
|
||||
password_reset_expires = Column(AwareDateTime(), nullable=True)
|
||||
cabinet_last_login = Column(AwareDateTime(), nullable=True)
|
||||
# Campaign slug saved at registration, consumed at email verification
|
||||
pending_campaign_slug = Column(String(64), nullable=True)
|
||||
# Email change fields
|
||||
email_change_new = Column(String(255), nullable=True) # New email pending verification
|
||||
email_change_code = Column(String(6), nullable=True) # 6-digit verification code
|
||||
@@ -1255,7 +1446,7 @@ class User(Base):
|
||||
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)
|
||||
notification_settings = Column(JSONB, nullable=True, default=dict)
|
||||
last_pinned_message_id = Column(Integer, nullable=True)
|
||||
|
||||
# Ограничения пользователя
|
||||
@@ -1357,7 +1548,7 @@ class Subscription(Base):
|
||||
'user_id',
|
||||
'tariff_id',
|
||||
unique=True,
|
||||
postgresql_where=text("tariff_id IS NOT NULL AND status IN ('active', 'trial')"),
|
||||
postgresql_where=text("tariff_id IS NOT NULL AND status IN ('active', 'trial', 'limited')"),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -2238,6 +2429,9 @@ class BroadcastHistory(Base):
|
||||
created_at = Column(AwareDateTime(), server_default=func.now())
|
||||
completed_at = Column(AwareDateTime(), nullable=True)
|
||||
|
||||
# Broadcast category for user notification preferences filtering
|
||||
category = Column(String(20), default='system', nullable=False) # system|news|promo
|
||||
|
||||
# Email broadcast fields
|
||||
channel = Column(String(20), default='telegram', nullable=False) # telegram|email|both
|
||||
email_subject = Column(String(255), nullable=True)
|
||||
|
||||
Vendored
+9
-8
@@ -376,15 +376,16 @@ class RemnaWaveAPI:
|
||||
except json.JSONDecodeError:
|
||||
response_data = {'raw_response': response_text}
|
||||
|
||||
if response.status == 429 and attempt < max_retries:
|
||||
if response.status in (429, 502, 503, 504) and attempt < max_retries:
|
||||
retry_after = float(response.headers.get('Retry-After', base_delay * (2**attempt)))
|
||||
logger.warning(
|
||||
'Rate limited (429) on , retry / after s',
|
||||
method=method,
|
||||
endpoint=endpoint,
|
||||
attempt=attempt + 1,
|
||||
max_retries=max_retries,
|
||||
retry_after=retry_after,
|
||||
'Retryable %s on %s %s, retry %s/%s after %ss',
|
||||
response.status,
|
||||
method,
|
||||
endpoint,
|
||||
attempt + 1,
|
||||
max_retries,
|
||||
retry_after,
|
||||
)
|
||||
await asyncio.sleep(retry_after)
|
||||
continue
|
||||
@@ -445,7 +446,7 @@ class RemnaWaveAPI:
|
||||
'trafficLimitStrategy': traffic_limit_strategy.value,
|
||||
}
|
||||
|
||||
if telegram_id:
|
||||
if telegram_id is not None:
|
||||
data['telegramId'] = telegram_id
|
||||
if email:
|
||||
data['email'] = email
|
||||
|
||||
@@ -63,7 +63,7 @@ CATEGORY_GROUP_METADATA: dict[str, dict[str, object]] = {
|
||||
},
|
||||
'payments': {
|
||||
'title': '💳 Платежные системы',
|
||||
'description': 'YooKassa, CryptoBot, Heleket, CloudPayments, Freekassa, MulenPay, PAL24, Wata, Platega, Tribute, Kassa AI, RioPay, SeverPay и Telegram Stars.',
|
||||
'description': 'YooKassa, CryptoBot, Heleket, CloudPayments, Freekassa, MulenPay, PAL24, Wata, Platega, Tribute, Kassa AI, RioPay, SeverPay, PayPear, RollyPay и Telegram Stars.',
|
||||
'icon': '💳',
|
||||
'categories': (
|
||||
'PAYMENT',
|
||||
@@ -76,6 +76,9 @@ CATEGORY_GROUP_METADATA: dict[str, dict[str, object]] = {
|
||||
'KASSA_AI',
|
||||
'RIOPAY',
|
||||
'SEVERPAY',
|
||||
'PAYPEAR',
|
||||
'ROLLYPAY',
|
||||
'AURAPAY',
|
||||
'MULENPAY',
|
||||
'PAL24',
|
||||
'WATA',
|
||||
@@ -1260,6 +1263,15 @@ def _build_settings_keyboard(
|
||||
elif category_key == 'SEVERPAY':
|
||||
label = texts.t('PAYMENT_SEVERPAY', f'💳 {settings.get_severpay_display_name()}')
|
||||
test_payment_buttons.append([_test_button(f'{label} · тест', 'severpay')])
|
||||
elif category_key == 'PAYPEAR':
|
||||
label = texts.t('PAYMENT_PAYPEAR', f'💳 {settings.get_paypear_display_name()}')
|
||||
test_payment_buttons.append([_test_button(f'{label} · тест', 'paypear')])
|
||||
elif category_key == 'ROLLYPAY':
|
||||
label = texts.t('PAYMENT_ROLLYPAY', f'💳 {settings.get_rollypay_display_name()}')
|
||||
test_payment_buttons.append([_test_button(f'{label} · тест', 'rollypay')])
|
||||
elif category_key == 'AURAPAY':
|
||||
label = texts.t('PAYMENT_AURAPAY', f'💳 {settings.get_aurapay_display_name()}')
|
||||
test_payment_buttons.append([_test_button(f'{label} · тест', 'aurapay')])
|
||||
|
||||
if test_payment_buttons:
|
||||
rows.extend(test_payment_buttons)
|
||||
|
||||
@@ -1599,42 +1599,28 @@ async def get_target_users_count(db: AsyncSession, target: str) -> int:
|
||||
result = await db.execute(query)
|
||||
return result.scalar() or 0
|
||||
|
||||
if target == 'expired':
|
||||
# Истекшие подписки
|
||||
if target in ('expired', 'expired_subscribers'):
|
||||
# Истекшие подписки — исключаем юзеров с хотя бы одной активной
|
||||
now = datetime.now(UTC)
|
||||
expired_statuses = [
|
||||
SubscriptionStatus.EXPIRED.value,
|
||||
SubscriptionStatus.DISABLED.value,
|
||||
SubscriptionStatus.LIMITED.value,
|
||||
]
|
||||
query = (
|
||||
select(sql_func.count(distinct(User.id)))
|
||||
.outerjoin(Subscription, User.id == Subscription.user_id)
|
||||
has_active_sub = (
|
||||
select(Subscription.id)
|
||||
.where(
|
||||
base_filter,
|
||||
or_(
|
||||
Subscription.status.in_(expired_statuses),
|
||||
and_(Subscription.end_date <= now, Subscription.status != SubscriptionStatus.ACTIVE.value),
|
||||
and_(Subscription.id == None, User.has_had_paid_subscription == True),
|
||||
),
|
||||
Subscription.user_id == User.id,
|
||||
Subscription.status == SubscriptionStatus.ACTIVE.value,
|
||||
)
|
||||
.exists()
|
||||
)
|
||||
result = await db.execute(query)
|
||||
return result.scalar() or 0
|
||||
|
||||
if target == 'expired_subscribers':
|
||||
# То же что и expired
|
||||
now = datetime.now(UTC)
|
||||
expired_statuses = [
|
||||
SubscriptionStatus.EXPIRED.value,
|
||||
SubscriptionStatus.DISABLED.value,
|
||||
SubscriptionStatus.LIMITED.value,
|
||||
]
|
||||
query = (
|
||||
select(sql_func.count(distinct(User.id)))
|
||||
.outerjoin(Subscription, User.id == Subscription.user_id)
|
||||
.where(
|
||||
base_filter,
|
||||
~has_active_sub,
|
||||
or_(
|
||||
Subscription.status.in_(expired_statuses),
|
||||
and_(Subscription.end_date <= now, Subscription.status != SubscriptionStatus.ACTIVE.value),
|
||||
@@ -1785,6 +1771,9 @@ async def get_target_users(db: AsyncSession, target: str) -> list:
|
||||
for user in users:
|
||||
subs = getattr(user, 'subscriptions', None) or []
|
||||
if subs:
|
||||
has_active = any(s.is_active for s in subs)
|
||||
if has_active:
|
||||
continue # Skip users who have at least one active subscription
|
||||
has_expired = any(s.status in expired_statuses or (s.end_date <= now and not s.is_active) for s in subs)
|
||||
if has_expired:
|
||||
expired_users.append(user)
|
||||
@@ -1833,6 +1822,9 @@ async def get_target_users(db: AsyncSession, target: str) -> list:
|
||||
for user in users:
|
||||
subs = getattr(user, 'subscriptions', None) or []
|
||||
if subs:
|
||||
has_active = any(s.is_active for s in subs)
|
||||
if has_active:
|
||||
continue # Skip users who have at least one active subscription
|
||||
has_expired = any(s.status in expired_statuses or (s.end_date <= now and not s.is_active) for s in subs)
|
||||
if has_expired:
|
||||
expired_users.append(user)
|
||||
|
||||
@@ -77,7 +77,7 @@ def _build_server_edit_view(server):
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text='🎁 Выдавать сквад' if not server.is_trial_eligible else '🚫 Не выдавать сквад',
|
||||
text='🎁 Выдавать в триал' if not server.is_trial_eligible else '🚫 Не выдавать в триал',
|
||||
callback_data=f'admin_server_trial_{server.id}',
|
||||
),
|
||||
],
|
||||
|
||||
+122
-31
@@ -990,13 +990,14 @@ async def _render_user_subscription_overview(
|
||||
]
|
||||
)
|
||||
else:
|
||||
keyboard.append(
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text='✅ Активировать', callback_data=f'admin_sub_activate_{user_id}{_sid}'
|
||||
)
|
||||
]
|
||||
)
|
||||
row = [
|
||||
types.InlineKeyboardButton(text='✅ Активировать', callback_data=f'admin_sub_activate_{user_id}{_sid}'),
|
||||
]
|
||||
if settings.is_multi_tariff_enabled() and subscription_id:
|
||||
row.append(
|
||||
types.InlineKeyboardButton(text='🗑 Удалить', callback_data=f'admin_sub_delete_{user_id}{_sid}')
|
||||
)
|
||||
keyboard.append(row)
|
||||
else:
|
||||
text += '❌ <b>Подписка отсутствует</b>\n\n'
|
||||
text += 'Пользователь еще не активировал подписку.'
|
||||
@@ -3302,6 +3303,76 @@ async def confirm_subscription_deactivation(callback: types.CallbackQuery, db_us
|
||||
await callback.answer()
|
||||
|
||||
|
||||
@admin_required
|
||||
@error_handler
|
||||
async def delete_user_subscription(callback: types.CallbackQuery, db_user: User, db: AsyncSession):
|
||||
"""Show confirmation for deleting a subscription (multi-tariff only)."""
|
||||
user_id, subscription_id = _extract_admin_sub_context(callback.data)
|
||||
|
||||
if not subscription_id or not settings.is_multi_tariff_enabled():
|
||||
await callback.answer('Удаление доступно только в мультитарифном режиме', show_alert=True)
|
||||
return
|
||||
|
||||
back_cb = f'admin_user_sub_select_{user_id}_{subscription_id}'
|
||||
_sid = f'_s{subscription_id}'
|
||||
|
||||
await callback.message.edit_text(
|
||||
'🗑 <b>Удаление подписки</b>\n\n⚠️ Подписка будет полностью удалена из системы.\nЭто действие необратимо!',
|
||||
reply_markup=get_confirmation_keyboard(f'admin_sub_delete_confirm_{user_id}{_sid}', back_cb, db_user.language),
|
||||
)
|
||||
await callback.answer()
|
||||
|
||||
|
||||
@admin_required
|
||||
@error_handler
|
||||
async def confirm_subscription_deletion(callback: types.CallbackQuery, db_user: User, db: AsyncSession):
|
||||
"""Delete a subscription permanently (multi-tariff only)."""
|
||||
user_id, subscription_id = _extract_admin_sub_context(callback.data)
|
||||
|
||||
if not subscription_id or not settings.is_multi_tariff_enabled():
|
||||
await callback.answer('Удаление доступно только в мультитарифном режиме', show_alert=True)
|
||||
return
|
||||
|
||||
from app.database.crud.subscription import get_subscription_by_id_for_user
|
||||
|
||||
subscription = await get_subscription_by_id_for_user(db, subscription_id, user_id)
|
||||
if not subscription:
|
||||
await callback.answer('Подписка не найдена', show_alert=True)
|
||||
return
|
||||
|
||||
# Disable on Remnawave side first
|
||||
_uuid = getattr(subscription, 'remnawave_uuid', None)
|
||||
if _uuid:
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.disable_remnawave_user(_uuid)
|
||||
|
||||
# Delete traffic purchases
|
||||
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.delete(subscription)
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Админ удалил подписку пользователя',
|
||||
admin_id=db_user.id,
|
||||
user_id=user_id,
|
||||
subscription_id=subscription_id,
|
||||
)
|
||||
|
||||
back_cb = f'admin_user_subscription_{user_id}'
|
||||
await callback.message.edit_text(
|
||||
'✅ Подписка удалена',
|
||||
reply_markup=types.InlineKeyboardMarkup(
|
||||
inline_keyboard=[[types.InlineKeyboardButton(text='📱 К подпискам', callback_data=back_cb)]]
|
||||
),
|
||||
)
|
||||
await callback.answer()
|
||||
|
||||
|
||||
@admin_required
|
||||
@error_handler
|
||||
async def activate_user_subscription(callback: types.CallbackQuery, db_user: User, db: AsyncSession):
|
||||
@@ -3750,26 +3821,38 @@ async def start_devices_edit(callback: types.CallbackQuery, db_user: User, state
|
||||
else f'admin_user_subscription_{user_id}'
|
||||
)
|
||||
|
||||
await callback.message.edit_text(
|
||||
'📱 <b>Изменение количества устройств</b>\n\n'
|
||||
'Введите новое количество устройств (от 1 до 10):\n'
|
||||
'• Текущее значение будет заменено\n'
|
||||
'• Примеры: 1, 2, 5, 10\n\n'
|
||||
'Или нажмите /cancel для отмены',
|
||||
reply_markup=types.InlineKeyboardMarkup(
|
||||
max_dev = settings.MAX_DEVICES_LIMIT
|
||||
# Build device buttons dynamically: rows of 4, respect Telegram 100 button limit (99 + cancel)
|
||||
if max_dev <= 99:
|
||||
device_buttons: list[list[types.InlineKeyboardButton]] = []
|
||||
row: list[types.InlineKeyboardButton] = []
|
||||
for i in range(1, max_dev + 1):
|
||||
row.append(
|
||||
types.InlineKeyboardButton(
|
||||
text=str(i),
|
||||
callback_data=f'admin_user_devices_set_{user_id}{_sid}_{i}',
|
||||
)
|
||||
)
|
||||
if len(row) == 4:
|
||||
device_buttons.append(row)
|
||||
row = []
|
||||
if row:
|
||||
device_buttons.append(row)
|
||||
device_buttons.append([types.InlineKeyboardButton(text='❌ Отмена', callback_data=back_cb)])
|
||||
markup = types.InlineKeyboardMarkup(inline_keyboard=device_buttons)
|
||||
else:
|
||||
markup = types.InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[
|
||||
types.InlineKeyboardButton(text='1', callback_data=f'admin_user_devices_set_{user_id}{_sid}_1'),
|
||||
types.InlineKeyboardButton(text='2', callback_data=f'admin_user_devices_set_{user_id}{_sid}_2'),
|
||||
types.InlineKeyboardButton(text='3', callback_data=f'admin_user_devices_set_{user_id}{_sid}_3'),
|
||||
],
|
||||
[
|
||||
types.InlineKeyboardButton(text='5', callback_data=f'admin_user_devices_set_{user_id}{_sid}_5'),
|
||||
types.InlineKeyboardButton(text='10', callback_data=f'admin_user_devices_set_{user_id}{_sid}_10'),
|
||||
],
|
||||
[types.InlineKeyboardButton(text='❌ Отмена', callback_data=back_cb)],
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
await callback.message.edit_text(
|
||||
'📱 <b>Изменение количества устройств</b>\n\n'
|
||||
f'Введите новое количество устройств (от 1 до {max_dev}):\n'
|
||||
'• Текущее значение будет заменено\n\n'
|
||||
'Или нажмите /cancel для отмены',
|
||||
reply_markup=markup,
|
||||
)
|
||||
|
||||
await state.set_state(AdminStates.editing_user_devices)
|
||||
@@ -3839,8 +3922,8 @@ async def process_devices_edit_text(message: types.Message, db_user: User, state
|
||||
try:
|
||||
devices = int(message.text.strip())
|
||||
|
||||
if devices <= 0 or devices > 10:
|
||||
await message.answer('❌ Количество устройств должно быть от 1 до 10')
|
||||
if devices <= 0 or devices > settings.MAX_DEVICES_LIMIT:
|
||||
await message.answer(f'❌ Количество устройств должно быть от 1 до {settings.MAX_DEVICES_LIMIT}')
|
||||
return
|
||||
|
||||
success = await _update_user_devices(db, user_id, devices, db_user.id, subscription_id=subscription_id)
|
||||
@@ -4162,14 +4245,16 @@ async def _update_user_traffic(
|
||||
) or getattr(user, 'remnawave_uuid', None)
|
||||
if _uuid:
|
||||
try:
|
||||
from app.external.remnawave_api import TrafficLimitStrategy
|
||||
from app.services.subscription_service import get_traffic_reset_strategy
|
||||
|
||||
remnawave_service = RemnaWaveService()
|
||||
async with remnawave_service.get_api_client() as api:
|
||||
await api.update_user(
|
||||
uuid=_uuid,
|
||||
traffic_limit_bytes=traffic_gb * (1024**3) if traffic_gb > 0 else 0,
|
||||
traffic_limit_strategy=TrafficLimitStrategy.MONTH,
|
||||
traffic_limit_strategy=get_traffic_reset_strategy(
|
||||
subscription.tariff if subscription else None
|
||||
),
|
||||
description=settings.format_remnawave_user_description(
|
||||
full_name=user.full_name, username=user.username, telegram_id=user.telegram_id
|
||||
),
|
||||
@@ -4877,8 +4962,9 @@ async def admin_buy_subscription_execute(callback: types.CallbackQuery, db_user:
|
||||
)
|
||||
|
||||
try:
|
||||
from app.external.remnawave_api import TrafficLimitStrategy, UserStatus
|
||||
from app.external.remnawave_api import UserStatus
|
||||
from app.services.remnawave_service import RemnaWaveService
|
||||
from app.services.subscription_service import get_traffic_reset_strategy
|
||||
|
||||
remnawave_service = RemnaWaveService()
|
||||
|
||||
@@ -4903,7 +4989,7 @@ async def admin_buy_subscription_execute(callback: types.CallbackQuery, db_user:
|
||||
traffic_limit_bytes=subscription.traffic_limit_gb * (1024**3)
|
||||
if subscription.traffic_limit_gb > 0
|
||||
else 0,
|
||||
traffic_limit_strategy=TrafficLimitStrategy.MONTH,
|
||||
traffic_limit_strategy=get_traffic_reset_strategy(subscription.tariff),
|
||||
description=settings.format_remnawave_user_description(
|
||||
full_name=target_user.full_name,
|
||||
username=target_user.username,
|
||||
@@ -4939,7 +5025,7 @@ async def admin_buy_subscription_execute(callback: types.CallbackQuery, db_user:
|
||||
traffic_limit_bytes=subscription.traffic_limit_gb * (1024**3)
|
||||
if subscription.traffic_limit_gb > 0
|
||||
else 0,
|
||||
traffic_limit_strategy=TrafficLimitStrategy.MONTH,
|
||||
traffic_limit_strategy=get_traffic_reset_strategy(subscription.tariff),
|
||||
telegram_id=target_user.telegram_id,
|
||||
email=target_user.email,
|
||||
description=settings.format_remnawave_user_description(
|
||||
@@ -5939,6 +6025,11 @@ def register_handlers(dp: Dispatcher):
|
||||
|
||||
dp.callback_query.register(activate_user_subscription, F.data.startswith('admin_sub_activate_'))
|
||||
|
||||
dp.callback_query.register(
|
||||
delete_user_subscription, F.data.startswith('admin_sub_delete_') & ~F.data.contains('confirm')
|
||||
)
|
||||
dp.callback_query.register(confirm_subscription_deletion, F.data.startswith('admin_sub_delete_confirm_'))
|
||||
|
||||
dp.callback_query.register(grant_trial_subscription, F.data.startswith('admin_sub_grant_trial_'))
|
||||
|
||||
dp.callback_query.register(
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Handler for AuraPay balance top-up."""
|
||||
|
||||
import html
|
||||
|
||||
import structlog
|
||||
from aiogram import types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database.models import User
|
||||
from app.keyboards.inline import get_back_keyboard
|
||||
from app.localization.texts import get_texts
|
||||
from app.services.payment_service import PaymentService
|
||||
from app.states import BalanceStates
|
||||
from app.utils.decorators import error_handler
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
def _check_topup_restriction(db_user: User, texts) -> InlineKeyboardMarkup | None:
|
||||
"""Проверяет ограничение на пополнение. Возвращает клавиатуру если ограничен, иначе None."""
|
||||
if not getattr(db_user, 'restriction_topup', False):
|
||||
return None
|
||||
|
||||
keyboard = []
|
||||
support_url = settings.get_support_contact_url()
|
||||
if support_url:
|
||||
keyboard.append([InlineKeyboardButton(text='\U0001f198 Обжаловать', url=support_url)])
|
||||
keyboard.append([InlineKeyboardButton(text=texts.BACK, callback_data='menu_balance')])
|
||||
return InlineKeyboardMarkup(inline_keyboard=keyboard)
|
||||
|
||||
|
||||
async def _create_aurapay_payment_and_respond(
|
||||
message_or_callback,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
amount_kopeks: int,
|
||||
edit_message: bool = False,
|
||||
):
|
||||
"""
|
||||
Common logic for creating AuraPay payment and sending response.
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
amount_rub = amount_kopeks / 100
|
||||
|
||||
# Create payment
|
||||
payment_service = PaymentService()
|
||||
|
||||
description = settings.PAYMENT_BALANCE_TEMPLATE.format(
|
||||
service_name=settings.PAYMENT_SERVICE_NAME,
|
||||
description='Пополнение баланса',
|
||||
)
|
||||
|
||||
result = await payment_service.create_aurapay_payment(
|
||||
db=db,
|
||||
user_id=db_user.id,
|
||||
amount_kopeks=amount_kopeks,
|
||||
description=description,
|
||||
email=getattr(db_user, 'email', None),
|
||||
language=db_user.language,
|
||||
)
|
||||
|
||||
if not result:
|
||||
error_text = texts.t(
|
||||
'PAYMENT_CREATE_ERROR',
|
||||
'Не удалось создать платёж. Попробуйте позже.',
|
||||
)
|
||||
if edit_message:
|
||||
await message_or_callback.edit_text(
|
||||
error_text,
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
else:
|
||||
await message_or_callback.answer(
|
||||
error_text,
|
||||
parse_mode='HTML',
|
||||
)
|
||||
return
|
||||
|
||||
payment_url = result.get('payment_url')
|
||||
display_name = settings.get_aurapay_display_name()
|
||||
|
||||
# Create keyboard with payment button
|
||||
keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t(
|
||||
'PAY_BUTTON',
|
||||
'\U0001f4b3 Оплатить {amount}\u20bd',
|
||||
).format(amount=f'{amount_rub:.0f}'),
|
||||
url=payment_url,
|
||||
)
|
||||
],
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
|
||||
callback_data='menu_balance',
|
||||
)
|
||||
],
|
||||
]
|
||||
)
|
||||
|
||||
response_text = texts.t(
|
||||
'AURAPAY_PAYMENT_CREATED',
|
||||
'\U0001f4b3 <b>Оплата через {name}</b>\n\n'
|
||||
'Сумма: <b>{amount}\u20bd</b>\n\n'
|
||||
'Нажмите кнопку ниже для оплаты.\n'
|
||||
'После успешной оплаты баланс будет пополнен автоматически.',
|
||||
).format(name=display_name, amount=f'{amount_rub:.2f}')
|
||||
|
||||
if edit_message:
|
||||
await message_or_callback.edit_text(
|
||||
response_text,
|
||||
reply_markup=keyboard,
|
||||
parse_mode='HTML',
|
||||
)
|
||||
else:
|
||||
await message_or_callback.answer(
|
||||
response_text,
|
||||
reply_markup=keyboard,
|
||||
parse_mode='HTML',
|
||||
)
|
||||
|
||||
logger.info('AuraPay payment created', telegram_id=db_user.telegram_id, amount_rub=amount_rub)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def process_aurapay_payment_amount(
|
||||
message: types.Message,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
amount_kopeks: int,
|
||||
state: FSMContext,
|
||||
):
|
||||
"""
|
||||
Process payment amount directly.
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
|
||||
restriction_kb = _check_topup_restriction(db_user, texts)
|
||||
if restriction_kb:
|
||||
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
|
||||
await message.answer(
|
||||
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
|
||||
parse_mode='HTML',
|
||||
reply_markup=restriction_kb,
|
||||
)
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
# Validate amount
|
||||
min_amount = settings.AURAPAY_MIN_AMOUNT_KOPEKS
|
||||
max_amount = settings.AURAPAY_MAX_AMOUNT_KOPEKS
|
||||
|
||||
if amount_kopeks < min_amount:
|
||||
await message.answer(
|
||||
texts.t(
|
||||
'PAYMENT_AMOUNT_TOO_LOW',
|
||||
'Минимальная сумма пополнения: {min_amount}\u20bd',
|
||||
).format(min_amount=min_amount // 100),
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
return
|
||||
|
||||
if amount_kopeks > max_amount:
|
||||
await message.answer(
|
||||
texts.t(
|
||||
'PAYMENT_AMOUNT_TOO_HIGH',
|
||||
'Максимальная сумма пополнения: {max_amount}\u20bd',
|
||||
).format(max_amount=max_amount // 100),
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
return
|
||||
|
||||
await state.clear()
|
||||
|
||||
await _create_aurapay_payment_and_respond(
|
||||
message_or_callback=message,
|
||||
db_user=db_user,
|
||||
db=db,
|
||||
amount_kopeks=amount_kopeks,
|
||||
edit_message=False,
|
||||
)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def start_aurapay_topup(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
):
|
||||
"""
|
||||
Start AuraPay top-up process - ask for amount.
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
|
||||
restriction_kb = _check_topup_restriction(db_user, texts)
|
||||
if restriction_kb:
|
||||
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
|
||||
await callback.message.edit_text(
|
||||
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
|
||||
parse_mode='HTML',
|
||||
reply_markup=restriction_kb,
|
||||
)
|
||||
return
|
||||
|
||||
await state.set_state(BalanceStates.waiting_for_amount)
|
||||
await state.update_data(payment_method='aurapay')
|
||||
|
||||
min_amount = settings.AURAPAY_MIN_AMOUNT_KOPEKS // 100
|
||||
max_amount = settings.AURAPAY_MAX_AMOUNT_KOPEKS // 100
|
||||
display_name = settings.get_aurapay_display_name()
|
||||
|
||||
keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
|
||||
callback_data='menu_balance',
|
||||
)
|
||||
]
|
||||
]
|
||||
)
|
||||
|
||||
await callback.message.edit_text(
|
||||
texts.t(
|
||||
'AURAPAY_ENTER_AMOUNT',
|
||||
'\U0001f4b3 <b>Пополнение через {name}</b>\n\n'
|
||||
'Введите сумму пополнения в рублях.\n\n'
|
||||
'Минимум: {min_amount}\u20bd\n'
|
||||
'Максимум: {max_amount}\u20bd',
|
||||
).format(
|
||||
name=display_name,
|
||||
min_amount=min_amount,
|
||||
max_amount=f'{max_amount:,}'.replace(',', ' '),
|
||||
),
|
||||
parse_mode='HTML',
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
@@ -39,6 +39,11 @@ _KASSA_AI_METHOD_CONFIG = {
|
||||
'display_name': settings.get_kassa_ai_card_display_name,
|
||||
'unavailable_text': 'KassaAI Карта временно недоступна',
|
||||
},
|
||||
'kassa_ai_sberpay': {
|
||||
'is_enabled': settings.is_kassa_ai_sberpay_enabled,
|
||||
'display_name': settings.get_kassa_ai_sberpay_display_name,
|
||||
'unavailable_text': 'KassaAI SberPay временно недоступен',
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -350,3 +355,14 @@ async def start_kassa_ai_card_topup(
|
||||
):
|
||||
"""Start KassaAI Card top-up process."""
|
||||
await _start_kassa_ai_sub_topup(callback, db_user, db, state, 'kassa_ai_card')
|
||||
|
||||
|
||||
@error_handler
|
||||
async def start_kassa_ai_sberpay_topup(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
):
|
||||
"""Start KassaAI SberPay top-up process."""
|
||||
await _start_kassa_ai_sub_topup(callback, db_user, db, state, 'kassa_ai_sberpay')
|
||||
|
||||
@@ -133,7 +133,7 @@ async def route_payment_by_method(
|
||||
)
|
||||
return True
|
||||
|
||||
if payment_method in ('kassa_ai', 'kassa_ai_sbp', 'kassa_ai_card'):
|
||||
if payment_method in ('kassa_ai', 'kassa_ai_sbp', 'kassa_ai_card', 'kassa_ai_sberpay'):
|
||||
from .kassa_ai import process_kassa_ai_payment_amount
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
@@ -149,6 +149,27 @@ async def route_payment_by_method(
|
||||
await process_severpay_payment_amount(message, db_user, db, amount_kopeks, state)
|
||||
return True
|
||||
|
||||
if payment_method == 'paypear':
|
||||
from .paypear import process_paypear_payment_amount
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
await process_paypear_payment_amount(message, db_user, db, amount_kopeks, state)
|
||||
return True
|
||||
|
||||
if payment_method == 'rollypay':
|
||||
from .rollypay import process_rollypay_payment_amount
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
await process_rollypay_payment_amount(message, db_user, db, amount_kopeks, state)
|
||||
return True
|
||||
|
||||
if payment_method == 'aurapay':
|
||||
from .aurapay import process_aurapay_payment_amount
|
||||
|
||||
async with AsyncSessionLocal() as db:
|
||||
await process_aurapay_payment_amount(message, db_user, db, amount_kopeks, state)
|
||||
return True
|
||||
|
||||
if payment_method == 'riopay':
|
||||
from .riopay import process_riopay_payment_amount
|
||||
|
||||
@@ -701,6 +722,7 @@ def register_balance_handlers(dp: Dispatcher):
|
||||
|
||||
from .kassa_ai import (
|
||||
start_kassa_ai_card_topup,
|
||||
start_kassa_ai_sberpay_topup,
|
||||
start_kassa_ai_sbp_topup,
|
||||
start_kassa_ai_topup,
|
||||
)
|
||||
@@ -708,6 +730,7 @@ def register_balance_handlers(dp: Dispatcher):
|
||||
dp.callback_query.register(start_kassa_ai_topup, F.data == 'topup_kassa_ai')
|
||||
dp.callback_query.register(start_kassa_ai_sbp_topup, F.data == 'topup_kassa_ai_sbp')
|
||||
dp.callback_query.register(start_kassa_ai_card_topup, F.data == 'topup_kassa_ai_card')
|
||||
dp.callback_query.register(start_kassa_ai_sberpay_topup, F.data == 'topup_kassa_ai_sberpay')
|
||||
|
||||
from .riopay import start_riopay_topup
|
||||
|
||||
@@ -717,6 +740,18 @@ def register_balance_handlers(dp: Dispatcher):
|
||||
|
||||
dp.callback_query.register(start_severpay_topup, F.data == 'topup_severpay')
|
||||
|
||||
from .paypear import start_paypear_topup
|
||||
|
||||
dp.callback_query.register(start_paypear_topup, F.data == 'topup_paypear')
|
||||
|
||||
from .rollypay import start_rollypay_topup
|
||||
|
||||
dp.callback_query.register(start_rollypay_topup, F.data == 'topup_rollypay')
|
||||
|
||||
from .aurapay import start_aurapay_topup
|
||||
|
||||
dp.callback_query.register(start_aurapay_topup, F.data == 'topup_aurapay')
|
||||
|
||||
from .mulenpay import check_mulenpay_payment_status
|
||||
|
||||
dp.callback_query.register(check_mulenpay_payment_status, F.data.startswith('check_mulenpay_'))
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Handler for PayPear balance top-up."""
|
||||
|
||||
import html
|
||||
|
||||
import structlog
|
||||
from aiogram import types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database.models import User
|
||||
from app.keyboards.inline import get_back_keyboard
|
||||
from app.localization.texts import get_texts
|
||||
from app.services.payment_service import PaymentService
|
||||
from app.states import BalanceStates
|
||||
from app.utils.decorators import error_handler
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
def _check_topup_restriction(db_user: User, texts) -> InlineKeyboardMarkup | None:
|
||||
"""Проверяет ограничение на пополнение. Возвращает клавиатуру если ограничен, иначе None."""
|
||||
if not getattr(db_user, 'restriction_topup', False):
|
||||
return None
|
||||
|
||||
keyboard = []
|
||||
support_url = settings.get_support_contact_url()
|
||||
if support_url:
|
||||
keyboard.append([InlineKeyboardButton(text='\U0001f198 Обжаловать', url=support_url)])
|
||||
keyboard.append([InlineKeyboardButton(text=texts.BACK, callback_data='menu_balance')])
|
||||
return InlineKeyboardMarkup(inline_keyboard=keyboard)
|
||||
|
||||
|
||||
async def _create_paypear_payment_and_respond(
|
||||
message_or_callback,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
amount_kopeks: int,
|
||||
edit_message: bool = False,
|
||||
):
|
||||
"""
|
||||
Common logic for creating PayPear payment and sending response.
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
amount_rub = amount_kopeks / 100
|
||||
|
||||
# Create payment
|
||||
payment_service = PaymentService()
|
||||
|
||||
description = settings.PAYMENT_BALANCE_TEMPLATE.format(
|
||||
service_name=settings.PAYMENT_SERVICE_NAME,
|
||||
description='Пополнение баланса',
|
||||
)
|
||||
|
||||
result = await payment_service.create_paypear_payment(
|
||||
db=db,
|
||||
user_id=db_user.id,
|
||||
amount_kopeks=amount_kopeks,
|
||||
description=description,
|
||||
email=getattr(db_user, 'email', None),
|
||||
language=db_user.language,
|
||||
)
|
||||
|
||||
if not result:
|
||||
error_text = texts.t(
|
||||
'PAYMENT_CREATE_ERROR',
|
||||
'Не удалось создать платёж. Попробуйте позже.',
|
||||
)
|
||||
if edit_message:
|
||||
await message_or_callback.edit_text(
|
||||
error_text,
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
else:
|
||||
await message_or_callback.answer(
|
||||
error_text,
|
||||
parse_mode='HTML',
|
||||
)
|
||||
return
|
||||
|
||||
payment_url = result.get('payment_url')
|
||||
display_name = settings.get_paypear_display_name()
|
||||
|
||||
# Create keyboard with payment button
|
||||
keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t(
|
||||
'PAY_BUTTON',
|
||||
'\U0001f4b3 Оплатить {amount}\u20bd',
|
||||
).format(amount=f'{amount_rub:.0f}'),
|
||||
url=payment_url,
|
||||
)
|
||||
],
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
|
||||
callback_data='menu_balance',
|
||||
)
|
||||
],
|
||||
]
|
||||
)
|
||||
|
||||
response_text = texts.t(
|
||||
'PAYPEAR_PAYMENT_CREATED',
|
||||
'\U0001f4b3 <b>Оплата через {name}</b>\n\n'
|
||||
'Сумма: <b>{amount}\u20bd</b>\n\n'
|
||||
'Нажмите кнопку ниже для оплаты.\n'
|
||||
'После успешной оплаты баланс будет пополнен автоматически.',
|
||||
).format(name=display_name, amount=f'{amount_rub:.2f}')
|
||||
|
||||
if edit_message:
|
||||
await message_or_callback.edit_text(
|
||||
response_text,
|
||||
reply_markup=keyboard,
|
||||
parse_mode='HTML',
|
||||
)
|
||||
else:
|
||||
await message_or_callback.answer(
|
||||
response_text,
|
||||
reply_markup=keyboard,
|
||||
parse_mode='HTML',
|
||||
)
|
||||
|
||||
logger.info('PayPear payment created', telegram_id=db_user.telegram_id, amount_rub=amount_rub)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def process_paypear_payment_amount(
|
||||
message: types.Message,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
amount_kopeks: int,
|
||||
state: FSMContext,
|
||||
):
|
||||
"""
|
||||
Process payment amount directly.
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
|
||||
restriction_kb = _check_topup_restriction(db_user, texts)
|
||||
if restriction_kb:
|
||||
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
|
||||
await message.answer(
|
||||
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
|
||||
parse_mode='HTML',
|
||||
reply_markup=restriction_kb,
|
||||
)
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
# Validate amount
|
||||
min_amount = settings.PAYPEAR_MIN_AMOUNT_KOPEKS
|
||||
max_amount = settings.PAYPEAR_MAX_AMOUNT_KOPEKS
|
||||
|
||||
if amount_kopeks < min_amount:
|
||||
await message.answer(
|
||||
texts.t(
|
||||
'PAYMENT_AMOUNT_TOO_LOW',
|
||||
'Минимальная сумма пополнения: {min_amount}\u20bd',
|
||||
).format(min_amount=min_amount // 100),
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
return
|
||||
|
||||
if amount_kopeks > max_amount:
|
||||
await message.answer(
|
||||
texts.t(
|
||||
'PAYMENT_AMOUNT_TOO_HIGH',
|
||||
'Максимальная сумма пополнения: {max_amount}\u20bd',
|
||||
).format(max_amount=max_amount // 100),
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
return
|
||||
|
||||
await state.clear()
|
||||
|
||||
await _create_paypear_payment_and_respond(
|
||||
message_or_callback=message,
|
||||
db_user=db_user,
|
||||
db=db,
|
||||
amount_kopeks=amount_kopeks,
|
||||
edit_message=False,
|
||||
)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def start_paypear_topup(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
):
|
||||
"""
|
||||
Start PayPear top-up process - ask for amount.
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
|
||||
restriction_kb = _check_topup_restriction(db_user, texts)
|
||||
if restriction_kb:
|
||||
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
|
||||
await callback.message.edit_text(
|
||||
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
|
||||
parse_mode='HTML',
|
||||
reply_markup=restriction_kb,
|
||||
)
|
||||
return
|
||||
|
||||
await state.set_state(BalanceStates.waiting_for_amount)
|
||||
await state.update_data(payment_method='paypear')
|
||||
|
||||
min_amount = settings.PAYPEAR_MIN_AMOUNT_KOPEKS // 100
|
||||
max_amount = settings.PAYPEAR_MAX_AMOUNT_KOPEKS // 100
|
||||
display_name = settings.get_paypear_display_name()
|
||||
|
||||
keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
|
||||
callback_data='menu_balance',
|
||||
)
|
||||
]
|
||||
]
|
||||
)
|
||||
|
||||
await callback.message.edit_text(
|
||||
texts.t(
|
||||
'PAYPEAR_ENTER_AMOUNT',
|
||||
'\U0001f4b3 <b>Пополнение через {name}</b>\n\n'
|
||||
'Введите сумму пополнения в рублях.\n\n'
|
||||
'Минимум: {min_amount}\u20bd\n'
|
||||
'Максимум: {max_amount}\u20bd',
|
||||
).format(
|
||||
name=display_name,
|
||||
min_amount=min_amount,
|
||||
max_amount=f'{max_amount:,}'.replace(',', ' '),
|
||||
),
|
||||
parse_mode='HTML',
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
@@ -20,8 +20,7 @@ logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
def _get_active_methods() -> list[int]:
|
||||
methods = settings.get_platega_active_methods()
|
||||
return [code for code in methods if code in {2, 10, 11, 12, 13}]
|
||||
return settings.get_platega_active_methods()
|
||||
|
||||
|
||||
async def _prompt_amount(
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Handler for RollyPay balance top-up."""
|
||||
|
||||
import html
|
||||
|
||||
import structlog
|
||||
from aiogram import types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database.models import User
|
||||
from app.keyboards.inline import get_back_keyboard
|
||||
from app.localization.texts import get_texts
|
||||
from app.services.payment_service import PaymentService
|
||||
from app.states import BalanceStates
|
||||
from app.utils.decorators import error_handler
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
def _check_topup_restriction(db_user: User, texts) -> InlineKeyboardMarkup | None:
|
||||
"""Проверяет ограничение на пополнение. Возвращает клавиатуру если ограничен, иначе None."""
|
||||
if not getattr(db_user, 'restriction_topup', False):
|
||||
return None
|
||||
|
||||
keyboard = []
|
||||
support_url = settings.get_support_contact_url()
|
||||
if support_url:
|
||||
keyboard.append([InlineKeyboardButton(text='\U0001f198 Обжаловать', url=support_url)])
|
||||
keyboard.append([InlineKeyboardButton(text=texts.BACK, callback_data='menu_balance')])
|
||||
return InlineKeyboardMarkup(inline_keyboard=keyboard)
|
||||
|
||||
|
||||
async def _create_rollypay_payment_and_respond(
|
||||
message_or_callback,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
amount_kopeks: int,
|
||||
edit_message: bool = False,
|
||||
):
|
||||
"""
|
||||
Common logic for creating RollyPay payment and sending response.
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
amount_rub = amount_kopeks / 100
|
||||
|
||||
# Create payment
|
||||
payment_service = PaymentService()
|
||||
|
||||
description = settings.PAYMENT_BALANCE_TEMPLATE.format(
|
||||
service_name=settings.PAYMENT_SERVICE_NAME,
|
||||
description='Пополнение баланса',
|
||||
)
|
||||
|
||||
result = await payment_service.create_rollypay_payment(
|
||||
db=db,
|
||||
user_id=db_user.id,
|
||||
amount_kopeks=amount_kopeks,
|
||||
description=description,
|
||||
email=getattr(db_user, 'email', None),
|
||||
language=db_user.language,
|
||||
)
|
||||
|
||||
if not result:
|
||||
error_text = texts.t(
|
||||
'PAYMENT_CREATE_ERROR',
|
||||
'Не удалось создать платёж. Попробуйте позже.',
|
||||
)
|
||||
if edit_message:
|
||||
await message_or_callback.edit_text(
|
||||
error_text,
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
else:
|
||||
await message_or_callback.answer(
|
||||
error_text,
|
||||
parse_mode='HTML',
|
||||
)
|
||||
return
|
||||
|
||||
payment_url = result.get('payment_url')
|
||||
display_name = settings.get_rollypay_display_name()
|
||||
|
||||
# Create keyboard with payment button
|
||||
keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t(
|
||||
'PAY_BUTTON',
|
||||
'\U0001f4b3 Оплатить {amount}\u20bd',
|
||||
).format(amount=f'{amount_rub:.0f}'),
|
||||
url=payment_url,
|
||||
)
|
||||
],
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
|
||||
callback_data='menu_balance',
|
||||
)
|
||||
],
|
||||
]
|
||||
)
|
||||
|
||||
response_text = texts.t(
|
||||
'ROLLYPAY_PAYMENT_CREATED',
|
||||
'\U0001f4b3 <b>Оплата через {name}</b>\n\n'
|
||||
'Сумма: <b>{amount}\u20bd</b>\n\n'
|
||||
'Нажмите кнопку ниже для оплаты.\n'
|
||||
'После успешной оплаты баланс будет пополнен автоматически.',
|
||||
).format(name=display_name, amount=f'{amount_rub:.2f}')
|
||||
|
||||
if edit_message:
|
||||
await message_or_callback.edit_text(
|
||||
response_text,
|
||||
reply_markup=keyboard,
|
||||
parse_mode='HTML',
|
||||
)
|
||||
else:
|
||||
await message_or_callback.answer(
|
||||
response_text,
|
||||
reply_markup=keyboard,
|
||||
parse_mode='HTML',
|
||||
)
|
||||
|
||||
logger.info('RollyPay payment created', telegram_id=db_user.telegram_id, amount_rub=amount_rub)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def process_rollypay_payment_amount(
|
||||
message: types.Message,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
amount_kopeks: int,
|
||||
state: FSMContext,
|
||||
):
|
||||
"""
|
||||
Process payment amount directly.
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
|
||||
restriction_kb = _check_topup_restriction(db_user, texts)
|
||||
if restriction_kb:
|
||||
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
|
||||
await message.answer(
|
||||
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
|
||||
parse_mode='HTML',
|
||||
reply_markup=restriction_kb,
|
||||
)
|
||||
await state.clear()
|
||||
return
|
||||
|
||||
# Validate amount
|
||||
min_amount = settings.ROLLYPAY_MIN_AMOUNT_KOPEKS
|
||||
max_amount = settings.ROLLYPAY_MAX_AMOUNT_KOPEKS
|
||||
|
||||
if amount_kopeks < min_amount:
|
||||
await message.answer(
|
||||
texts.t(
|
||||
'PAYMENT_AMOUNT_TOO_LOW',
|
||||
'Минимальная сумма пополнения: {min_amount}\u20bd',
|
||||
).format(min_amount=min_amount // 100),
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
return
|
||||
|
||||
if amount_kopeks > max_amount:
|
||||
await message.answer(
|
||||
texts.t(
|
||||
'PAYMENT_AMOUNT_TOO_HIGH',
|
||||
'Максимальная сумма пополнения: {max_amount}\u20bd',
|
||||
).format(max_amount=max_amount // 100),
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
return
|
||||
|
||||
await state.clear()
|
||||
|
||||
await _create_rollypay_payment_and_respond(
|
||||
message_or_callback=message,
|
||||
db_user=db_user,
|
||||
db=db,
|
||||
amount_kopeks=amount_kopeks,
|
||||
edit_message=False,
|
||||
)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def start_rollypay_topup(
|
||||
callback: types.CallbackQuery,
|
||||
db_user: User,
|
||||
db: AsyncSession,
|
||||
state: FSMContext,
|
||||
):
|
||||
"""
|
||||
Start RollyPay top-up process - ask for amount.
|
||||
"""
|
||||
texts = get_texts(db_user.language)
|
||||
|
||||
restriction_kb = _check_topup_restriction(db_user, texts)
|
||||
if restriction_kb:
|
||||
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
|
||||
await callback.message.edit_text(
|
||||
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
|
||||
parse_mode='HTML',
|
||||
reply_markup=restriction_kb,
|
||||
)
|
||||
return
|
||||
|
||||
await state.set_state(BalanceStates.waiting_for_amount)
|
||||
await state.update_data(payment_method='rollypay')
|
||||
|
||||
min_amount = settings.ROLLYPAY_MIN_AMOUNT_KOPEKS // 100
|
||||
max_amount = settings.ROLLYPAY_MAX_AMOUNT_KOPEKS // 100
|
||||
display_name = settings.get_rollypay_display_name()
|
||||
|
||||
keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
|
||||
callback_data='menu_balance',
|
||||
)
|
||||
]
|
||||
]
|
||||
)
|
||||
|
||||
await callback.message.edit_text(
|
||||
texts.t(
|
||||
'ROLLYPAY_ENTER_AMOUNT',
|
||||
'\U0001f4b3 <b>Пополнение через {name}</b>\n\n'
|
||||
'Введите сумму пополнения в рублях.\n\n'
|
||||
'Минимум: {min_amount}\u20bd\n'
|
||||
'Максимум: {max_amount}\u20bd',
|
||||
).format(
|
||||
name=display_name,
|
||||
min_amount=min_amount,
|
||||
max_amount=f'{max_amount:,}'.replace(',', ' '),
|
||||
),
|
||||
parse_mode='HTML',
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
@@ -78,6 +78,9 @@ async def on_user_joined_channel(event: ChatMemberUpdated, bot: Bot) -> None:
|
||||
|
||||
for subscription in disabled_subs:
|
||||
await reactivate_subscription(db, subscription)
|
||||
# Ставим штамп чтобы webhook user.disabled (echo от нашего disable)
|
||||
# не переотключил подписку при быстрой реподписке
|
||||
subscription.last_webhook_update_at = datetime.now(UTC)
|
||||
logger.info(
|
||||
'Subscriptions reactivated via channel event',
|
||||
telegram_id=user.id,
|
||||
|
||||
@@ -169,7 +169,9 @@ async def show_main_menu(
|
||||
await db.commit()
|
||||
|
||||
# Multi-tariff aware: check if user has ANY active subscription
|
||||
has_active_subscription = any(sub.is_active for sub in (getattr(db_user, 'subscriptions', None) or []))
|
||||
# 'limited' (traffic exhausted) subscriptions are still active for UI purposes
|
||||
_subs = getattr(db_user, 'subscriptions', None) or []
|
||||
has_active_subscription = any(sub.is_active or getattr(sub, 'actual_status', None) == 'limited' for sub in _subs)
|
||||
subscription_is_active = has_active_subscription
|
||||
|
||||
menu_text = await get_main_menu_text(db_user, texts, db)
|
||||
@@ -1013,7 +1015,9 @@ async def handle_back_to_menu(callback: types.CallbackQuery, state: FSMContext,
|
||||
texts = get_texts(db_user.language)
|
||||
|
||||
# Multi-tariff aware: check if user has ANY active subscription
|
||||
has_active_subscription = any(sub.is_active for sub in (getattr(db_user, 'subscriptions', None) or []))
|
||||
# 'limited' (traffic exhausted) subscriptions are still active for UI purposes
|
||||
_subs = getattr(db_user, 'subscriptions', None) or []
|
||||
has_active_subscription = any(sub.is_active or getattr(sub, 'actual_status', None) == 'limited' for sub in _subs)
|
||||
subscription_is_active = has_active_subscription
|
||||
|
||||
menu_text = await get_main_menu_text(db_user, texts, db)
|
||||
|
||||
@@ -34,7 +34,21 @@ async def show_promocode_menu(callback: types.CallbackQuery, db_user: User, stat
|
||||
else:
|
||||
raise
|
||||
|
||||
# Сохраняем предыдущее состояние, чтобы восстановить после промокода
|
||||
previous_state = await state.get_state()
|
||||
previous_data = await state.get_data()
|
||||
|
||||
# Не перезаписываем сохранённое состояние при повторном входе в промо-флоу
|
||||
if previous_state == PromoCodeStates.waiting_for_code.state:
|
||||
await callback.answer()
|
||||
return
|
||||
|
||||
# Убираем мета-ключи чтобы не создавать вложенность
|
||||
previous_data.pop('_prev_state', None)
|
||||
previous_data.pop('_prev_data', None)
|
||||
|
||||
await state.set_state(PromoCodeStates.waiting_for_code)
|
||||
await state.update_data(_prev_state=previous_state, _prev_data=previous_data)
|
||||
await callback.answer()
|
||||
|
||||
|
||||
@@ -75,6 +89,23 @@ async def activate_promocode_for_registration(
|
||||
return result
|
||||
|
||||
|
||||
_NO_SAVED_STATE = object()
|
||||
|
||||
|
||||
async def _restore_previous_state(state: FSMContext) -> None:
|
||||
"""Восстанавливает FSM-состояние, которое было до входа в промокод-флоу."""
|
||||
data = await state.get_data()
|
||||
prev_state = data.get('_prev_state', _NO_SAVED_STATE)
|
||||
prev_data = data.get('_prev_data') or {}
|
||||
if prev_state is _NO_SAVED_STATE:
|
||||
# Не было сохранённого состояния — defensive clear
|
||||
await state.clear()
|
||||
else:
|
||||
# Восстанавливаем предыдущее состояние (включая None = меню без FSM)
|
||||
await state.set_state(prev_state)
|
||||
await state.set_data(prev_data)
|
||||
|
||||
|
||||
@error_handler
|
||||
async def process_promocode(message: types.Message, db_user: User, state: FSMContext, db: AsyncSession):
|
||||
texts = get_texts(db_user.language)
|
||||
@@ -108,7 +139,7 @@ async def process_promocode(message: types.Message, db_user: User, state: FSMCon
|
||||
).format(cooldown=cooldown),
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
)
|
||||
await state.clear()
|
||||
await _restore_previous_state(state)
|
||||
return
|
||||
|
||||
# Лимит на стакинг (макс активаций в день)
|
||||
@@ -120,7 +151,7 @@ async def process_promocode(message: types.Message, db_user: User, state: FSMCon
|
||||
),
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
)
|
||||
await state.clear()
|
||||
await _restore_previous_state(state)
|
||||
return
|
||||
|
||||
result = await activate_promocode_for_registration(db, db_user.id, code, message.bot)
|
||||
@@ -131,7 +162,7 @@ async def process_promocode(message: types.Message, db_user: User, state: FSMCon
|
||||
texts.PROMOCODE_SUCCESS.format(description=result['description']),
|
||||
reply_markup=get_back_keyboard(db_user.language),
|
||||
)
|
||||
await state.clear()
|
||||
await _restore_previous_state(state)
|
||||
elif result.get('error') == 'select_subscription':
|
||||
# Multi-tariff: user needs to choose which subscription to apply days to
|
||||
eligible = result.get('eligible_subscriptions', [])
|
||||
@@ -156,7 +187,7 @@ async def process_promocode(message: types.Message, db_user: User, state: FSMCon
|
||||
),
|
||||
reply_markup=types.InlineKeyboardMarkup(inline_keyboard=buttons),
|
||||
)
|
||||
await state.clear()
|
||||
await _restore_previous_state(state)
|
||||
else:
|
||||
# Записываем неудачную попытку только для not_found (перебор)
|
||||
if result['error'] == 'not_found':
|
||||
@@ -166,6 +197,8 @@ async def process_promocode(message: types.Message, db_user: User, state: FSMCon
|
||||
error_messages = {
|
||||
'not_found': texts.PROMOCODE_INVALID,
|
||||
'expired': texts.PROMOCODE_EXPIRED,
|
||||
'inactive': texts.t('PROMOCODE_INACTIVE', '❌ Промокод деактивирован'),
|
||||
'not_yet_valid': texts.t('PROMOCODE_NOT_YET_VALID', '❌ Промокод ещё не начал действовать'),
|
||||
'used': texts.PROMOCODE_USED,
|
||||
'already_used_by_user': texts.PROMOCODE_USED,
|
||||
'not_first_purchase': texts.t(
|
||||
@@ -188,7 +221,7 @@ async def process_promocode(message: types.Message, db_user: User, state: FSMCon
|
||||
|
||||
error_text = error_messages.get(result['error'], texts.PROMOCODE_INVALID)
|
||||
await message.answer(error_text, reply_markup=get_back_keyboard(db_user.language))
|
||||
await state.clear()
|
||||
await _restore_previous_state(state)
|
||||
|
||||
|
||||
async def handle_promo_subscription_select(
|
||||
|
||||
@@ -441,7 +441,7 @@ async def handle_simple_subscription_pay_with_balance(
|
||||
# Проверяем баланс пользователя
|
||||
user_balance_kopeks = getattr(db_user, 'balance_kopeks', 0)
|
||||
|
||||
if user_balance_kopeks < total_required:
|
||||
if total_required > 0 and user_balance_kopeks < total_required:
|
||||
await callback.answer('❌ Недостаточно средств на балансе для оплаты подписки', show_alert=True)
|
||||
return
|
||||
|
||||
@@ -549,6 +549,14 @@ async def handle_simple_subscription_pay_with_balance(
|
||||
sync_error=sync_error,
|
||||
exc_info=True,
|
||||
)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
if hasattr(subscription, 'id') and hasattr(subscription, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Отправляем уведомление об успешной покупке
|
||||
server_label = _get_simple_subscription_server_label(
|
||||
@@ -2181,7 +2189,7 @@ async def confirm_simple_subscription_purchase(
|
||||
# Проверяем баланс пользователя
|
||||
user_balance_kopeks = getattr(db_user, 'balance_kopeks', 0)
|
||||
|
||||
if user_balance_kopeks < total_required:
|
||||
if total_required > 0 and user_balance_kopeks < total_required:
|
||||
await callback.answer('❌ Недостаточно средств на балансе для оплаты подписки', show_alert=True)
|
||||
return
|
||||
|
||||
@@ -2289,6 +2297,14 @@ async def confirm_simple_subscription_purchase(
|
||||
sync_error=sync_error,
|
||||
exc_info=True,
|
||||
)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
if hasattr(subscription, 'id') and hasattr(subscription, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Отправляем уведомление об успешной покупке
|
||||
server_label = _get_simple_subscription_server_label(
|
||||
|
||||
@@ -253,6 +253,14 @@ async def _handle_trial_payment(
|
||||
except Exception as rw_error:
|
||||
logger.error('Ошибка создания пользователя RemnaWave для триала', rw_error=rw_error)
|
||||
# Не откатываем подписку, просто логируем - RemnaWave может быть временно недоступен
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
if hasattr(subscription, 'id') and hasattr(subscription, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
+23
-2
@@ -234,6 +234,14 @@ async def _claim_phantom_user(
|
||||
subscription_id=phantom_sub.id,
|
||||
error=str(exc),
|
||||
)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
if hasattr(phantom_sub, 'id') and hasattr(phantom_sub, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=phantom_sub.id,
|
||||
user_id=phantom_sub.user_id,
|
||||
action='update',
|
||||
)
|
||||
|
||||
return True, phantom
|
||||
|
||||
@@ -336,8 +344,9 @@ def _calculate_subscription_flags(subscription):
|
||||
return False, False
|
||||
|
||||
actual_status = getattr(subscription, 'actual_status', None)
|
||||
has_active_subscription = actual_status in {'active', 'trial'}
|
||||
subscription_is_active = bool(getattr(subscription, 'is_active', False))
|
||||
# 'limited' subscriptions are still active (traffic exhausted, but subscription not expired)
|
||||
has_active_subscription = actual_status in {'active', 'trial', 'limited'}
|
||||
subscription_is_active = bool(getattr(subscription, 'is_active', False)) or actual_status == 'limited'
|
||||
|
||||
return has_active_subscription, subscription_is_active
|
||||
|
||||
@@ -2443,6 +2452,18 @@ async def required_sub_channel_check(
|
||||
telegram_id=user.telegram_id if user else query.from_user.id,
|
||||
api_error=api_error,
|
||||
)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
for sub in _subs:
|
||||
if sub.is_trial and sub.status == SubscriptionStatus.ACTIVE.value:
|
||||
if hasattr(sub, 'id') and hasattr(sub, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=sub.id,
|
||||
user_id=sub.user_id,
|
||||
action='update'
|
||||
if (getattr(sub, 'remnawave_uuid', None) or user.remnawave_uuid)
|
||||
else 'create',
|
||||
)
|
||||
|
||||
await query.answer(
|
||||
texts.t('CHANNEL_SUBSCRIBE_THANKS', '✅ Спасибо за подписку'),
|
||||
|
||||
@@ -412,7 +412,18 @@ async def apply_countries_changes(callback: types.CallbackQuery, db_user: User,
|
||||
await db.commit()
|
||||
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.update_remnawave_user(db, subscription, sync_squads=True)
|
||||
try:
|
||||
await subscription_service.update_remnawave_user(db, subscription, sync_squads=True)
|
||||
except Exception as rw_err:
|
||||
logger.error('Ошибка синхронизации с RemnaWave при смене стран', error=rw_err)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
if hasattr(subscription, 'id') and hasattr(subscription, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='update',
|
||||
)
|
||||
|
||||
await db.refresh(subscription)
|
||||
|
||||
@@ -861,7 +872,7 @@ async def confirm_add_countries_to_subscription(
|
||||
if country['uuid'] in removed_countries:
|
||||
removed_countries_names.append(html.escape(country['name']))
|
||||
|
||||
if new_countries and db_user.balance_kopeks < total_price:
|
||||
if new_countries and total_price > 0 and db_user.balance_kopeks < total_price:
|
||||
missing_kopeks = total_price - db_user.balance_kopeks
|
||||
message_text = texts.t(
|
||||
'ADDON_INSUFFICIENT_FUNDS_MESSAGE',
|
||||
|
||||
@@ -1273,7 +1273,7 @@ async def confirm_add_devices(callback: types.CallbackQuery, db_user: User, db:
|
||||
total_discount=total_discount / 100,
|
||||
)
|
||||
|
||||
if db_user.balance_kopeks < price:
|
||||
if price > 0 and db_user.balance_kopeks < price:
|
||||
missing_kopeks = price - db_user.balance_kopeks
|
||||
required_text = f'{texts.format_price(price)} (за {period_label})'
|
||||
message_text = texts.t(
|
||||
|
||||
@@ -937,6 +937,13 @@ async def activate_trial(callback: types.CallbackQuery, db_user: User, db: Async
|
||||
except Exception as e:
|
||||
logger.error('Ошибка получения триального тарифа', error=e)
|
||||
|
||||
# BUG-12 fix: If no squads from tariff, fallback to trial-eligible servers
|
||||
if not trial_squads:
|
||||
from app.database.crud.server_squad import get_random_trial_squad_uuid
|
||||
|
||||
trial_squad_uuid = await get_random_trial_squad_uuid(db)
|
||||
trial_squads = [trial_squad_uuid] if trial_squad_uuid else []
|
||||
|
||||
subscription = await create_trial_subscription(
|
||||
db,
|
||||
db_user.id,
|
||||
@@ -1537,7 +1544,7 @@ async def return_to_saved_cart(callback: types.CallbackQuery, state: FSMContext,
|
||||
|
||||
total_price = prepared_cart_data.get('total_price', 0)
|
||||
|
||||
if db_user.balance_kopeks < total_price:
|
||||
if total_price > 0 and db_user.balance_kopeks < total_price:
|
||||
missing_amount = total_price - db_user.balance_kopeks
|
||||
insufficient_keyboard = get_insufficient_balance_keyboard_with_cart(
|
||||
db_user.language,
|
||||
@@ -1635,7 +1642,7 @@ async def handle_extend_subscription(
|
||||
else:
|
||||
subscription = db_user.subscription
|
||||
|
||||
if not subscription or subscription.is_trial:
|
||||
if not subscription:
|
||||
await callback.message.edit_text(
|
||||
'🎯 <b>Пробный период заканчивается</b>\n\nЧтобы продолжить пользоваться VPN, выберите подходящий тариф.',
|
||||
reply_markup=types.InlineKeyboardMarkup(
|
||||
@@ -1654,24 +1661,53 @@ async def handle_extend_subscription(
|
||||
await callback.answer()
|
||||
return
|
||||
|
||||
# В режиме тарифов проверяем наличие tariff_id
|
||||
if settings.is_tariffs_mode():
|
||||
if subscription.tariff_id:
|
||||
# Проверяем, суточный ли тариф — у суточных нет period_prices, продление через resume
|
||||
from app.database.crud.tariff import get_tariff_by_id
|
||||
# Триальная подписка с тарифом — направляем на покупку этого тарифа
|
||||
if subscription.is_trial:
|
||||
if subscription.tariff_id and settings.is_tariffs_mode():
|
||||
from .tariff_purchase import show_tariff_extend
|
||||
|
||||
tariff = await get_tariff_by_id(db, subscription.tariff_id)
|
||||
if tariff and getattr(tariff, 'is_daily', False):
|
||||
# Суточный тариф: перенаправляем на страницу подписки (там кнопка «Возобновить»)
|
||||
await show_subscription_info(callback, db_user, db)
|
||||
return
|
||||
await show_tariff_extend(callback, db_user, db)
|
||||
return
|
||||
# Триал без тарифа — предлагаем выбрать
|
||||
await callback.message.edit_text(
|
||||
'🎯 <b>Пробный период заканчивается</b>\n\nЧтобы продолжить пользоваться VPN, выберите подходящий тариф.',
|
||||
reply_markup=types.InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[types.InlineKeyboardButton(text=texts.MENU_BUY_SUBSCRIPTION, callback_data='menu_buy')],
|
||||
[
|
||||
types.InlineKeyboardButton(
|
||||
text=texts.t('WEBHOOK_CLOSE_BUTTON', '✖️ Закрыть'),
|
||||
callback_data='webhook:close',
|
||||
)
|
||||
],
|
||||
]
|
||||
),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
await callback.answer()
|
||||
return
|
||||
|
||||
# Подписка с тарифом — всегда используем тарифный flow,
|
||||
# даже если бот в классическом режиме (подписка могла быть куплена через кабинет)
|
||||
if subscription.tariff_id:
|
||||
# Проверяем, суточный ли тариф — у суточных нет period_prices, продление через resume
|
||||
from app.database.crud.tariff import get_tariff_by_id
|
||||
|
||||
tariff = await get_tariff_by_id(db, subscription.tariff_id)
|
||||
if tariff and getattr(tariff, 'is_daily', False):
|
||||
# Суточный тариф: перенаправляем на страницу подписки (там кнопка «Возобновить»)
|
||||
await show_subscription_info(callback, db_user, db)
|
||||
return
|
||||
|
||||
if tariff:
|
||||
# У подписки есть тариф - перенаправляем на продление по тарифу
|
||||
from .tariff_purchase import show_tariff_extend
|
||||
|
||||
await show_tariff_extend(callback, db_user, db)
|
||||
return
|
||||
# У подписки нет тарифа - предлагаем выбрать тариф
|
||||
|
||||
if settings.is_tariffs_mode():
|
||||
# У подписки нет тарифа, но режим тарифов включён - предлагаем выбрать тариф
|
||||
await callback.message.edit_text(
|
||||
'📦 <b>Выберите тариф для продления</b>\n\n'
|
||||
'Ваша текущая подписка была создана до введения тарифов.\n'
|
||||
@@ -1706,6 +1742,10 @@ async def handle_extend_subscription(
|
||||
# original = price before ALL discounts, final = price with all discounts
|
||||
total_original_price = pricing.original_total
|
||||
|
||||
# Пропускаем периоды с нулевой ценой (если оригинальная цена тоже 0 — не настроен)
|
||||
if pricing.final_total <= 0 and pricing.original_total <= 0:
|
||||
continue
|
||||
|
||||
renewal_prices[days] = {
|
||||
'final': pricing.final_total,
|
||||
'original': total_original_price,
|
||||
@@ -1899,7 +1939,7 @@ async def confirm_extend_subscription(
|
||||
await callback.answer('⚠ Ошибка расчета стоимости', show_alert=True)
|
||||
return
|
||||
|
||||
if db_user.balance_kopeks < price:
|
||||
if price > 0 and db_user.balance_kopeks < price:
|
||||
missing_kopeks = price - db_user.balance_kopeks
|
||||
required_text = texts.format_price(price)
|
||||
message_text = texts.t(
|
||||
@@ -2307,7 +2347,7 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
|
||||
)
|
||||
logger.info('ИТОГО: ₽', final_price=final_price / 100)
|
||||
|
||||
if db_user.balance_kopeks < final_price:
|
||||
if final_price > 0 and db_user.balance_kopeks < final_price:
|
||||
missing_kopeks = final_price - db_user.balance_kopeks
|
||||
message_text = texts.t(
|
||||
'ADDON_INSUFFICIENT_FUNDS_MESSAGE',
|
||||
@@ -2546,17 +2586,19 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
|
||||
|
||||
subscription_service = SubscriptionService()
|
||||
# При покупке подписки ВСЕГДА сбрасываем трафик в панели
|
||||
_purchase_uuid = (
|
||||
subscription.remnawave_uuid
|
||||
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
|
||||
else db_user.remnawave_uuid
|
||||
)
|
||||
if settings.is_multi_tariff_enabled() and not getattr(subscription, 'remnawave_uuid', None):
|
||||
logger.warning(
|
||||
'Multi-tariff: subscription missing remnawave_uuid, using user fallback',
|
||||
subscription_id=getattr(subscription, 'id', None),
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(db_user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
remnawave_user = await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка подписки',
|
||||
)
|
||||
if _purchase_uuid:
|
||||
else:
|
||||
remnawave_user = await subscription_service.update_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
@@ -2564,22 +2606,25 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
|
||||
reset_reason='покупка подписки',
|
||||
sync_squads=True,
|
||||
)
|
||||
else:
|
||||
remnawave_user = await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка подписки',
|
||||
)
|
||||
|
||||
if not remnawave_user:
|
||||
logger.error('Не удалось создать/обновить RemnaWave пользователя для', telegram_id=db_user.telegram_id)
|
||||
remnawave_user = await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка подписки (повторная попытка)',
|
||||
)
|
||||
logger.error('Не удалось создать/обновить RemnaWave пользователя', telegram_id=db_user.telegram_id)
|
||||
try:
|
||||
remnawave_user = await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка подписки (повторная попытка)',
|
||||
)
|
||||
except Exception as retry_error:
|
||||
logger.error('Повторная попытка создания RemnaWave пользователя не удалась', error=retry_error)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=db_user.id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
transaction = await create_transaction(
|
||||
db=db,
|
||||
@@ -3129,6 +3174,13 @@ async def handle_toggle_daily_subscription_pause(callback: types.CallbackQuery,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Ошибка синхронизации с Remnawave при возобновлении', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=db_user.id,
|
||||
action='update',
|
||||
)
|
||||
|
||||
# Отправляем уведомление администраторам о возобновлении суточной подписки
|
||||
if resume_transaction is not None:
|
||||
@@ -3270,6 +3322,13 @@ async def handle_trial_pay_with_balance(callback: types.CallbackQuery, db_user:
|
||||
except Exception as e:
|
||||
logger.error('Ошибка получения триального тарифа для платного триала', error=e)
|
||||
|
||||
# BUG-12 fix: If no squads from tariff, fallback to trial-eligible servers
|
||||
if not trial_squads:
|
||||
from app.database.crud.server_squad import get_random_trial_squad_uuid
|
||||
|
||||
trial_squad_uuid = await get_random_trial_squad_uuid(db)
|
||||
trial_squads = [trial_squad_uuid] if trial_squad_uuid else []
|
||||
|
||||
subscription = await create_trial_subscription(
|
||||
db,
|
||||
db_user.id,
|
||||
@@ -4415,8 +4474,8 @@ async def _extend_existing_subscription(
|
||||
device_limit=device_limit,
|
||||
)
|
||||
|
||||
# Проверяем баланс пользователя
|
||||
if db_user.balance_kopeks < price_kopeks:
|
||||
# Проверяем баланс пользователя (при 100% скидке — пропускаем)
|
||||
if price_kopeks > 0 and db_user.balance_kopeks < price_kopeks:
|
||||
missing_kopeks = price_kopeks - db_user.balance_kopeks
|
||||
message_text = texts.t(
|
||||
'ADDON_INSUFFICIENT_FUNDS_MESSAGE',
|
||||
@@ -4561,6 +4620,13 @@ async def _extend_existing_subscription(
|
||||
logger.error('⚠ ОШИБКА ОБНОВЛЕНИЯ REMNAWAVE')
|
||||
except Exception as e:
|
||||
logger.error('⚠ ИСКЛЮЧЕНИЕ ПРИ ОБНОВЛЕНИИ REMNAWAVE', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=current_subscription.id,
|
||||
user_id=db_user.id,
|
||||
action='update',
|
||||
)
|
||||
|
||||
# Создаём транзакцию
|
||||
transaction = await create_transaction(
|
||||
|
||||
@@ -576,7 +576,7 @@ async def show_tariffs_list(
|
||||
from app.database.crud.subscription import get_active_subscriptions_by_user_id
|
||||
|
||||
active_subs = await get_active_subscriptions_by_user_id(db, db_user.id)
|
||||
purchased_tariff_ids = {s.tariff_id for s in active_subs if s.tariff_id and s.status in ('active', 'trial')}
|
||||
purchased_tariff_ids = {s.tariff_id for s in active_subs if s.tariff_id and not s.is_trial}
|
||||
|
||||
# Проверяем есть ли у пользователя скидки по периодам
|
||||
promo_group = db_user.get_primary_promo_group() if hasattr(db_user, 'get_primary_promo_group') else None
|
||||
@@ -619,7 +619,7 @@ async def select_tariff(
|
||||
from app.database.crud.subscription import get_active_subscriptions_by_user_id
|
||||
|
||||
_active = await get_active_subscriptions_by_user_id(db, db_user.id)
|
||||
_existing = next((s for s in _active if s.tariff_id == tariff_id and s.status in ('active', 'trial')), None)
|
||||
_existing = next((s for s in _active if s.tariff_id == tariff_id and not s.is_trial), None)
|
||||
if _existing:
|
||||
days_left = max(0, (_existing.end_date - datetime.now(UTC)).days) if _existing.end_date else 0
|
||||
await callback.answer(
|
||||
@@ -928,14 +928,14 @@ async def handle_custom_confirm(
|
||||
)
|
||||
total_price = result.final_total
|
||||
|
||||
# Проверяем, что цена за период валидна
|
||||
if result.base_price == 0 and not tariff.can_purchase_custom_days():
|
||||
# Проверяем, что цена за период валидна (original_total — цена до скидок)
|
||||
if result.original_total == 0 and not tariff.can_purchase_custom_days():
|
||||
await callback.answer('Выбранный период недоступен для этого тарифа', show_alert=True)
|
||||
return
|
||||
|
||||
# Проверяем баланс (user already locked, balance is fresh)
|
||||
# Проверяем баланс (при 100% скидке — пропускаем)
|
||||
user_balance = db_user.balance_kopeks or 0
|
||||
if user_balance < total_price:
|
||||
if total_price > 0 and user_balance < total_price:
|
||||
await callback.answer('Недостаточно средств на балансе', show_alert=True)
|
||||
return
|
||||
|
||||
@@ -1057,14 +1057,34 @@ async def handle_custom_confirm(
|
||||
# При покупке тарифа ВСЕГДА сбрасываем трафик в панели
|
||||
try:
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка тарифа',
|
||||
)
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(db_user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка тарифа',
|
||||
)
|
||||
else:
|
||||
await subscription_service.update_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка тарифа',
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Ошибка обновления Remnawave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=db_user.id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Создаем транзакцию
|
||||
await create_transaction(
|
||||
@@ -1353,7 +1373,7 @@ async def confirm_tariff_purchase(
|
||||
|
||||
# Проверяем баланс (user already locked, balance is fresh)
|
||||
user_balance = db_user.balance_kopeks or 0
|
||||
if user_balance < final_price:
|
||||
if final_price > 0 and user_balance < final_price:
|
||||
await callback.answer('Недостаточно средств на балансе', show_alert=True)
|
||||
return
|
||||
|
||||
@@ -1568,14 +1588,37 @@ async def confirm_tariff_purchase(
|
||||
# При покупке тарифа ВСЕГДА сбрасываем трафик в панели
|
||||
try:
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка тарифа',
|
||||
)
|
||||
# In multi-tariff mode, each subscription has its own panel user.
|
||||
# A new subscription has no remnawave_uuid yet, so always CREATE.
|
||||
# In single-tariff mode, reuse the user-level UUID if available.
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(db_user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка тарифа',
|
||||
)
|
||||
else:
|
||||
await subscription_service.update_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка тарифа',
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Ошибка обновления Remnawave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=db_user.id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Создаем транзакцию
|
||||
try:
|
||||
@@ -1694,7 +1737,7 @@ async def confirm_daily_tariff_purchase(
|
||||
|
||||
# Проверяем баланс (user already locked, balance is fresh)
|
||||
user_balance = db_user.balance_kopeks or 0
|
||||
if user_balance < final_daily_price:
|
||||
if final_daily_price > 0 and user_balance < final_daily_price:
|
||||
await callback.answer('Недостаточно средств на балансе', show_alert=True)
|
||||
return
|
||||
|
||||
@@ -1828,14 +1871,34 @@ async def confirm_daily_tariff_purchase(
|
||||
# При покупке тарифа ВСЕГДА сбрасываем трафик в панели
|
||||
try:
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка суточного тарифа',
|
||||
)
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(db_user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка суточного тарифа',
|
||||
)
|
||||
else:
|
||||
await subscription_service.update_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=True,
|
||||
reset_reason='покупка суточного тарифа',
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Ошибка обновления Remnawave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=db_user.id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Создаем транзакцию
|
||||
await create_transaction(
|
||||
@@ -2013,8 +2076,6 @@ async def show_tariff_extend(
|
||||
# Show subscription picker for extending
|
||||
keyboard = []
|
||||
for sub in sorted(active_subs, key=lambda s: s.id):
|
||||
if sub.is_trial:
|
||||
continue
|
||||
tariff_name = ''
|
||||
if sub.tariff_id:
|
||||
_t = await get_tariff_by_id(db, sub.tariff_id)
|
||||
@@ -2044,8 +2105,36 @@ async def show_tariff_extend(
|
||||
subscription = None
|
||||
else:
|
||||
subscription = await get_subscription_by_user_id(db, db_user.id)
|
||||
if not subscription or not subscription.tariff_id:
|
||||
await callback.answer('Тариф не найден', show_alert=True)
|
||||
if not subscription:
|
||||
await callback.answer('Подписка не найдена', show_alert=True)
|
||||
return
|
||||
|
||||
if not subscription.tariff_id:
|
||||
# Legacy user without tariff — show tariff selection for upgrade
|
||||
promo_group_id = getattr(db_user, 'promo_group_id', None)
|
||||
tariffs = await get_tariffs_for_user(db, promo_group_id)
|
||||
if not tariffs:
|
||||
await callback.answer('Нет доступных тарифов', show_alert=True)
|
||||
return
|
||||
|
||||
keyboard = []
|
||||
for t in tariffs:
|
||||
if t.is_daily:
|
||||
continue
|
||||
keyboard.append([InlineKeyboardButton(text=f'📦 {t.name}', callback_data=f'tariff_select:{t.id}')])
|
||||
if not keyboard:
|
||||
await callback.answer('Нет доступных тарифов для продления', show_alert=True)
|
||||
return
|
||||
keyboard.append([InlineKeyboardButton(text='◀️ Назад', callback_data='back_to_menu')])
|
||||
|
||||
await callback.message.edit_text(
|
||||
'🔄 <b>Выберите тариф для продления</b>\n\n'
|
||||
'Для продления подписки необходимо выбрать тариф.\n'
|
||||
'Подписка будет обновлена с параметрами выбранного тарифа.',
|
||||
reply_markup=InlineKeyboardMarkup(inline_keyboard=keyboard),
|
||||
parse_mode='HTML',
|
||||
)
|
||||
await callback.answer()
|
||||
return
|
||||
|
||||
tariff = await get_tariff_by_id(db, subscription.tariff_id)
|
||||
@@ -2246,7 +2335,7 @@ async def confirm_tariff_extend(
|
||||
|
||||
# Проверяем баланс
|
||||
user_balance = db_user.balance_kopeks or 0
|
||||
if user_balance < final_price:
|
||||
if final_price > 0 and user_balance < final_price:
|
||||
await callback.answer('Недостаточно средств на балансе', show_alert=True)
|
||||
return
|
||||
|
||||
@@ -2266,24 +2355,50 @@ async def confirm_tariff_extend(
|
||||
await callback.answer('Ошибка списания баланса', show_alert=True)
|
||||
return
|
||||
|
||||
# Продлеваем подписку (параметры тарифа не меняются, только добавляется время)
|
||||
# Запоминаем, был ли триал ДО продления
|
||||
was_trial = subscription.is_trial
|
||||
|
||||
# Продлеваем подписку; для триала передаём tariff_id чтобы сбросить is_trial
|
||||
subscription = await extend_subscription(
|
||||
db,
|
||||
subscription,
|
||||
days=period,
|
||||
tariff_id=tariff.id if was_trial else None,
|
||||
traffic_limit_gb=tariff.traffic_limit_gb if was_trial else None,
|
||||
device_limit=actual_device_limit if was_trial else None,
|
||||
)
|
||||
|
||||
# Обновляем пользователя в Remnawave
|
||||
try:
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_PAYMENT,
|
||||
reset_reason='продление тарифа',
|
||||
)
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(db_user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_PAYMENT or was_trial,
|
||||
reset_reason='конвертация триала' if was_trial else 'продление тарифа',
|
||||
)
|
||||
else:
|
||||
await subscription_service.update_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_PAYMENT or was_trial,
|
||||
reset_reason='конвертация триала' if was_trial else 'продление тарифа',
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Ошибка обновления Remnawave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=db_user.id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Создаем транзакцию
|
||||
await create_transaction(
|
||||
@@ -2303,7 +2418,7 @@ async def confirm_tariff_extend(
|
||||
subscription,
|
||||
None, # Транзакция отсутствует, оплата с баланса
|
||||
period,
|
||||
was_trial_conversion=False,
|
||||
was_trial_conversion=was_trial,
|
||||
amount_kopeks=final_price,
|
||||
purchase_type='renewal',
|
||||
)
|
||||
@@ -2836,7 +2951,7 @@ async def confirm_tariff_switch(
|
||||
|
||||
# Проверяем баланс
|
||||
user_balance = db_user.balance_kopeks or 0
|
||||
if user_balance < final_price:
|
||||
if final_price > 0 and user_balance < final_price:
|
||||
await callback.answer('Недостаточно средств на балансе', show_alert=True)
|
||||
return
|
||||
|
||||
@@ -2889,14 +3004,34 @@ async def confirm_tariff_switch(
|
||||
# Обновляем пользователя в Remnawave
|
||||
try:
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_reason='переключение тарифа',
|
||||
)
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(db_user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_reason='переключение тарифа',
|
||||
)
|
||||
else:
|
||||
await subscription_service.update_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_reason='переключение тарифа',
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Ошибка обновления Remnawave при переключении тарифа', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=db_user.id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Гарантированный сброс устройств при смене тарифа
|
||||
await db.refresh(db_user)
|
||||
@@ -3042,7 +3177,7 @@ async def confirm_daily_tariff_switch(
|
||||
|
||||
# Проверяем баланс (user already locked, balance is fresh)
|
||||
user_balance = db_user.balance_kopeks or 0
|
||||
if user_balance < final_daily_price:
|
||||
if final_daily_price > 0 and user_balance < final_daily_price:
|
||||
await callback.answer('Недостаточно средств на балансе', show_alert=True)
|
||||
return
|
||||
|
||||
@@ -3117,14 +3252,34 @@ async def confirm_daily_tariff_switch(
|
||||
# Обновляем пользователя в Remnawave (сброс трафика по админ-настройке)
|
||||
try:
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_reason='смена на суточный тариф',
|
||||
)
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(db_user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_reason='смена на суточный тариф',
|
||||
)
|
||||
else:
|
||||
await subscription_service.update_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_reason='смена на суточный тариф',
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Ошибка обновления Remnawave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=db_user.id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Гарантированный сброс устройств при смене тарифа
|
||||
await db.refresh(db_user)
|
||||
@@ -3791,14 +3946,34 @@ async def confirm_instant_switch(
|
||||
# Обновляем пользователя в Remnawave (сброс трафика по админ-настройке)
|
||||
try:
|
||||
subscription_service = SubscriptionService()
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_reason='мгновенное переключение тарифа',
|
||||
)
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(db_user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
await subscription_service.create_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_reason='мгновенное переключение тарифа',
|
||||
)
|
||||
else:
|
||||
await subscription_service.update_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
|
||||
reset_reason='мгновенное переключение тарифа',
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error('Ошибка обновления Remnawave при мгновенном переключении', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=db_user.id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Гарантированный сброс устройств при смене тарифа
|
||||
await db.refresh(db_user)
|
||||
@@ -3946,8 +4121,8 @@ async def return_to_saved_tariff_cart(
|
||||
user_balance = db_user.balance_kopeks or 0
|
||||
traffic = format_traffic(tariff.traffic_limit_gb)
|
||||
|
||||
# Проверяем баланс
|
||||
if user_balance < total_price:
|
||||
# Проверяем баланс (при 100% скидке — пропускаем)
|
||||
if total_price > 0 and user_balance < total_price:
|
||||
missing = total_price - user_balance
|
||||
|
||||
if cart_mode == 'daily_tariff_purchase':
|
||||
|
||||
@@ -332,7 +332,7 @@ async def confirm_reset_traffic(
|
||||
|
||||
reset_price = _calculate_traffic_reset_price(subscription)
|
||||
|
||||
if db_user.balance_kopeks < reset_price:
|
||||
if reset_price > 0 and db_user.balance_kopeks < reset_price:
|
||||
missing_kopeks = reset_price - db_user.balance_kopeks
|
||||
message_text = texts.t(
|
||||
'ADDON_INSUFFICIENT_FUNDS_MESSAGE',
|
||||
@@ -574,7 +574,7 @@ async def add_traffic(callback: types.CallbackQuery, db_user: User, db: AsyncSes
|
||||
|
||||
total_discount_value = int(discount_per_month * charged_days / 30)
|
||||
|
||||
if db_user.balance_kopeks < price:
|
||||
if price > 0 and db_user.balance_kopeks < price:
|
||||
missing_kopeks = price - db_user.balance_kopeks
|
||||
|
||||
# Save cart for auto-purchase after balance top-up
|
||||
@@ -830,7 +830,7 @@ async def confirm_switch_traffic(
|
||||
total_price_difference = int(price_difference_per_month * days_remaining / 30)
|
||||
total_price_difference = max(100, total_price_difference)
|
||||
|
||||
if db_user.balance_kopeks < total_price_difference:
|
||||
if total_price_difference > 0 and db_user.balance_kopeks < total_price_difference:
|
||||
missing_kopeks = total_price_difference - db_user.balance_kopeks
|
||||
message_text = texts.t(
|
||||
'ADDON_INSUFFICIENT_FUNDS_MESSAGE',
|
||||
|
||||
@@ -983,7 +983,14 @@ async def close_ticket_notification(callback: types.CallbackQuery, db_user: User
|
||||
await callback.answer()
|
||||
return
|
||||
|
||||
await callback.message.delete()
|
||||
try:
|
||||
await callback.message.delete()
|
||||
except TelegramBadRequest:
|
||||
# Message is too old to delete (>48h) — edit it instead
|
||||
try:
|
||||
await callback.message.edit_text(texts.t('NOTIFICATION_CLOSED', 'Уведомление закрыто.'))
|
||||
except TelegramBadRequest:
|
||||
pass
|
||||
await callback.answer(texts.t('NOTIFICATION_CLOSED', 'Уведомление закрыто.'))
|
||||
|
||||
|
||||
|
||||
@@ -1755,10 +1755,23 @@ def get_payment_methods_keyboard(amount_kopeks: int, language: str = DEFAULT_LAN
|
||||
)
|
||||
has_direct_payment_methods = True
|
||||
|
||||
if settings.is_kassa_ai_sberpay_enabled():
|
||||
sberpay_name = settings.get_kassa_ai_sberpay_display_name()
|
||||
keyboard.append(
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t('PAYMENT_KASSA_AI_SBERPAY', f'💳 {sberpay_name}'),
|
||||
callback_data=_build_callback('kassa_ai_sberpay'),
|
||||
)
|
||||
]
|
||||
)
|
||||
has_direct_payment_methods = True
|
||||
|
||||
if (
|
||||
settings.is_kassa_ai_enabled()
|
||||
and not settings.is_kassa_ai_sbp_enabled()
|
||||
and not settings.is_kassa_ai_card_enabled()
|
||||
and not settings.is_kassa_ai_sberpay_enabled()
|
||||
):
|
||||
kassa_ai_name = settings.get_kassa_ai_display_name()
|
||||
keyboard.append(
|
||||
@@ -1794,6 +1807,42 @@ def get_payment_methods_keyboard(amount_kopeks: int, language: str = DEFAULT_LAN
|
||||
)
|
||||
has_direct_payment_methods = True
|
||||
|
||||
if settings.is_paypear_enabled():
|
||||
paypear_name = settings.get_paypear_display_name()
|
||||
keyboard.append(
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t('PAYMENT_PAYPEAR', f'💳 Оплата ({paypear_name})'),
|
||||
callback_data=_build_callback('paypear'),
|
||||
)
|
||||
]
|
||||
)
|
||||
has_direct_payment_methods = True
|
||||
|
||||
if settings.is_rollypay_enabled():
|
||||
rollypay_name = settings.get_rollypay_display_name()
|
||||
keyboard.append(
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t('PAYMENT_ROLLYPAY', f'💳 {rollypay_name}'),
|
||||
callback_data=_build_callback('rollypay'),
|
||||
)
|
||||
]
|
||||
)
|
||||
has_direct_payment_methods = True
|
||||
|
||||
if settings.is_aurapay_enabled():
|
||||
aurapay_name = settings.get_aurapay_display_name()
|
||||
keyboard.append(
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=texts.t('PAYMENT_AURAPAY', f'💳 {aurapay_name}'),
|
||||
callback_data=_build_callback('aurapay'),
|
||||
)
|
||||
]
|
||||
)
|
||||
has_direct_payment_methods = True
|
||||
|
||||
if settings.is_support_topup_enabled():
|
||||
keyboard.append(
|
||||
[
|
||||
|
||||
@@ -1755,5 +1755,8 @@
|
||||
"WEBHOOK_USER_NOT_CONNECTED": "📡 <b>Not connected yet</b>\n\nYour subscription{tariff_label} is active but no VPN connection has been made. Connect to start using the service.",
|
||||
"WEBHOOK_DEVICE_ADDED": "📱 <b>New device</b>\n\nA new device has been added to your subscription{tariff_label}: <code>{device}</code>",
|
||||
"WEBHOOK_DEVICE_DELETED": "📱 <b>Device removed</b>\n\nA device has been removed from your subscription{tariff_label}: <code>{device}</code>",
|
||||
"WEBHOOK_CLOSE_BUTTON": "✖️ Close"
|
||||
"WEBHOOK_TORRENT_DETECTED": "🚫 <b>Torrent detected</b>\n\nTorrent traffic was detected on your connection{tariff_label}. Using torrents may result in subscription restrictions.",
|
||||
"WEBHOOK_CLOSE_BUTTON": "✖️ Close",
|
||||
"TRAFFIC_WARNING_ALERT": "⚠️ <b>Traffic Warning</b>\n\nUsed: {used:.1f} / {limit} GB ({percent:.0f}%)\n\nYour traffic limit is almost reached.",
|
||||
"LOW_BALANCE_ALERT": "⚠️ <b>Low Balance</b>\n\nYour balance: {balance} ₽\nNotification threshold: {threshold} ₽\n\nTop up your balance to ensure automatic subscription renewal."
|
||||
}
|
||||
+1781
-1778
File diff suppressed because it is too large
Load Diff
@@ -1749,19 +1749,16 @@
|
||||
"MODEM_PRICE_WITH_DISCOUNT": "Стоимость: <s>{base_price}</s> <b>{final_price}</b> (за {months} мес)\n🎁 Скидка {discount}%: -{discount_amount}",
|
||||
"MODEM_PRICE_NO_DISCOUNT": "Стоимость: {price} (за {months} мес)",
|
||||
"MODEM_CONFIRM_ENABLE_BASE": "📡 <b>Подтверждение подключения модема</b>\n\n{price_text}\n\nПри подключении модема:\n• К подписке добавится дополнительное устройство\n• Ежемесячная плата увеличится на {monthly_price}\n\nПодтвердить подключение?",
|
||||
|
||||
"ADMIN_USER_RESTRICTIONS": "⚠️ Ограничить",
|
||||
"USER_RESTRICTION_TOPUP_BLOCKED": "🚫 <b>Пополнение ограничено</b>\n\n{reason}\n\nЕсли вы считаете это ошибкой, вы можете обжаловать решение.",
|
||||
"USER_RESTRICTION_SUBSCRIPTION_BLOCKED": "🚫 <b>Покупка/продление подписки ограничено</b>\n\n{reason}\n\nЕсли вы считаете это ошибкой, вы можете обжаловать решение.",
|
||||
"USER_RESTRICTION_APPEAL_BUTTON": "🆘 Обжаловать",
|
||||
|
||||
"PAUSE_DAILY_BUTTON": "⏸️ Приостановить подписку",
|
||||
"RESUME_DAILY_BUTTON": "▶️ Возобновить подписку",
|
||||
"DAILY_SWITCH_WARNING": "⚠️ <b>Внимание!</b> У вас осталось {days} дн. подписки.\nПри смене на суточный тариф они будут утеряны!",
|
||||
"DAILY_SUBSCRIPTION_PAUSED": "⏸️ Подписка приостановлена",
|
||||
"DAILY_SUBSCRIPTION_RESUMED": "▶️ Подписка возобновлена!",
|
||||
"DAILY_SUBSCRIPTION_RESUMED_AFTER_TOPUP": "✅ <b>Подписка возобновлена!</b>\n\nВаш суточный тариф «{tariff_name}» возобновлён после пополнения баланса.\n\n💳 Списано: {amount}\n💰 Остаток: {balance}",
|
||||
|
||||
"WEBHOOK_SUB_EXPIRED": "❌ <b>Подписка{tariff_label} истекла</b>\n\nВаша подписка завершена. Продлите подписку, чтобы восстановить доступ к VPN.",
|
||||
"WEBHOOK_SUB_DISABLED": "🚫 <b>Подписка{tariff_label} отключена</b>\n\nВаша подписка была отключена администратором.",
|
||||
"WEBHOOK_SUB_ENABLED": "✅ <b>Подписка{tariff_label} активирована</b>\n\nВаша подписка снова активна. Приятного использования!",
|
||||
@@ -1779,5 +1776,8 @@
|
||||
"WEBHOOK_USER_NOT_CONNECTED": "📡 <b>Вы ещё не подключились</b>\n\nВаша подписка{tariff_label} активна, но VPN-соединение не было установлено. Подключитесь, чтобы начать пользоваться.",
|
||||
"WEBHOOK_DEVICE_ADDED": "📱 <b>Новое устройство</b>\n\nК подписке{tariff_label} подключено новое устройство: <code>{device}</code>",
|
||||
"WEBHOOK_DEVICE_DELETED": "📱 <b>Устройство удалено</b>\n\nУстройство отключено от подписки{tariff_label}: <code>{device}</code>",
|
||||
"WEBHOOK_CLOSE_BUTTON": "✖️ Закрыть"
|
||||
}
|
||||
"WEBHOOK_TORRENT_DETECTED": "🚫 <b>Обнаружен торрент</b>\n\nВ вашем подключении{tariff_label} обнаружен торрент-трафик. Использование торрентов может привести к ограничению подписки.",
|
||||
"WEBHOOK_CLOSE_BUTTON": "✖️ Закрыть",
|
||||
"TRAFFIC_WARNING_ALERT": "⚠️ <b>Предупреждение о трафике</b>\n\nИспользовано: {used:.1f} / {limit} ГБ ({percent:.0f}%)\n\nВаш лимит трафика почти исчерпан.",
|
||||
"LOW_BALANCE_ALERT": "⚠️ <b>Низкий баланс</b>\n\nВаш баланс: {balance} ₽\nПорог уведомления: {threshold} ₽\n\nПополните баланс, чтобы автопродление подписки прошло успешно."
|
||||
}
|
||||
+1529
-1526
File diff suppressed because it is too large
Load Diff
+1651
-1648
File diff suppressed because it is too large
Load Diff
@@ -370,6 +370,7 @@ class ChannelCheckerMiddleware(BaseMiddleware):
|
||||
# Per-channel settings: check if any unsubscribed channel requires deactivation
|
||||
unsubscribed = [ch for ch in channels if not ch.get('is_subscribed', False)]
|
||||
|
||||
deactivated_subs = []
|
||||
for subscription in active_subs:
|
||||
should_disable = any(
|
||||
channel_subscription_service.should_disable_subscription(ch, subscription.is_trial)
|
||||
@@ -379,6 +380,7 @@ class ChannelCheckerMiddleware(BaseMiddleware):
|
||||
continue
|
||||
|
||||
await deactivate_subscription(db, subscription)
|
||||
deactivated_subs.append(subscription)
|
||||
sub_type = 'trial' if subscription.is_trial else 'paid'
|
||||
logger.info(
|
||||
'Subscription deactivated after channel unsubscribe',
|
||||
@@ -387,7 +389,7 @@ class ChannelCheckerMiddleware(BaseMiddleware):
|
||||
)
|
||||
|
||||
service = SubscriptionService()
|
||||
for subscription in active_subs:
|
||||
for subscription in deactivated_subs:
|
||||
panel_uuid = (
|
||||
subscription.remnawave_uuid
|
||||
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
|
||||
@@ -404,29 +406,30 @@ class ChannelCheckerMiddleware(BaseMiddleware):
|
||||
)
|
||||
|
||||
# Notify user about deactivation
|
||||
try:
|
||||
normalized = _normalize_channels(channels)
|
||||
texts = get_texts(user.language or DEFAULT_LANGUAGE)
|
||||
if settings.is_multi_tariff_enabled() and len(active_subs) > 1:
|
||||
notification_text = texts.t(
|
||||
'SUBSCRIPTION_DEACTIVATED_CHANNEL_UNSUBSCRIBE_MULTI',
|
||||
'🚫 Ваши подписки приостановлены, так как вы отписались от обязательного канала.\n\n'
|
||||
'Подпишитесь на все каналы для восстановления доступа к VPN.',
|
||||
if deactivated_subs:
|
||||
try:
|
||||
normalized = _normalize_channels(channels)
|
||||
texts = get_texts(user.language or DEFAULT_LANGUAGE)
|
||||
if settings.is_multi_tariff_enabled() and len(deactivated_subs) > 1:
|
||||
notification_text = texts.t(
|
||||
'SUBSCRIPTION_DEACTIVATED_CHANNEL_UNSUBSCRIBE_MULTI',
|
||||
'🚫 Ваши подписки приостановлены, так как вы отписались от обязательного канала.\n\n'
|
||||
'Подпишитесь на все каналы для восстановления доступа к VPN.',
|
||||
)
|
||||
else:
|
||||
notification_text = texts.t(
|
||||
'SUBSCRIPTION_DEACTIVATED_CHANNEL_UNSUBSCRIBE',
|
||||
'🚫 Ваша подписка приостановлена, так как вы отписались от канала.\n\n'
|
||||
'Подпишитесь на канал снова, чтобы восстановить доступ к VPN.',
|
||||
)
|
||||
channel_kb = get_channel_sub_keyboard(normalized, language=user.language)
|
||||
await bot.send_message(telegram_id, notification_text, reply_markup=channel_kb)
|
||||
except Exception as notify_error:
|
||||
logger.error(
|
||||
'Failed to send deactivation notification to user',
|
||||
telegram_id=telegram_id,
|
||||
notify_error=notify_error,
|
||||
)
|
||||
else:
|
||||
notification_text = texts.t(
|
||||
'SUBSCRIPTION_DEACTIVATED_CHANNEL_UNSUBSCRIBE',
|
||||
'🚫 Ваша подписка приостановлена, так как вы отписались от канала.\n\n'
|
||||
'Подпишитесь на канал снова, чтобы восстановить доступ к VPN.',
|
||||
)
|
||||
channel_kb = get_channel_sub_keyboard(normalized, language=user.language)
|
||||
await bot.send_message(telegram_id, notification_text, reply_markup=channel_kb)
|
||||
except Exception as notify_error:
|
||||
logger.error(
|
||||
'Failed to send deactivation notification to user',
|
||||
telegram_id=telegram_id,
|
||||
notify_error=notify_error,
|
||||
)
|
||||
await db.commit()
|
||||
except Exception as db_error:
|
||||
logger.error(
|
||||
@@ -463,6 +466,8 @@ class ChannelCheckerMiddleware(BaseMiddleware):
|
||||
|
||||
for subscription in disabled_subs:
|
||||
await reactivate_subscription(db, subscription)
|
||||
# Штамп для защиты от echo-webhook user.disabled
|
||||
subscription.last_webhook_update_at = datetime.now(UTC)
|
||||
sub_type = 'trial' if subscription.is_trial else 'paid'
|
||||
logger.info(
|
||||
'Subscription reactivated after channel subscribe',
|
||||
|
||||
@@ -85,6 +85,9 @@ class DisplayNameRestrictionMiddleware(BaseMiddleware):
|
||||
if not user or user.is_bot:
|
||||
return await handler(event, data)
|
||||
|
||||
if not settings.DISPLAY_NAME_RESTRICTION_ENABLED:
|
||||
return await handler(event, data)
|
||||
|
||||
display_name = self._build_display_name(user)
|
||||
username = user.username or ''
|
||||
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Сервис для работы с API AuraPay (aurapay.tech)."""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
import structlog
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
API_BASE_URL = 'https://app.aurapay.tech'
|
||||
|
||||
|
||||
class AuraPayAPIError(Exception):
|
||||
"""Ошибка API AuraPay."""
|
||||
|
||||
def __init__(self, status_code: int, message: str):
|
||||
self.status_code = status_code
|
||||
self.message = message
|
||||
super().__init__(f'AuraPay API error ({status_code}): {message}')
|
||||
|
||||
|
||||
class AuraPayService:
|
||||
"""Сервис для работы с API AuraPay."""
|
||||
|
||||
def __init__(self):
|
||||
self._session: aiohttp.ClientSession | None = None
|
||||
|
||||
@property
|
||||
def api_key(self) -> str:
|
||||
return settings.AURAPAY_API_KEY or ''
|
||||
|
||||
@property
|
||||
def shop_id(self) -> str:
|
||||
return settings.AURAPAY_SHOP_ID or ''
|
||||
|
||||
@property
|
||||
def secret_key(self) -> str:
|
||||
return settings.AURAPAY_SECRET_KEY or ''
|
||||
|
||||
async def _get_session(self) -> aiohttp.ClientSession:
|
||||
"""Возвращает переиспользуемую HTTP-сессию."""
|
||||
if self._session is None or self._session.closed:
|
||||
self._session = aiohttp.ClientSession(
|
||||
timeout=aiohttp.ClientTimeout(total=30),
|
||||
)
|
||||
return self._session
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Закрывает HTTP-сессию."""
|
||||
if self._session and not self._session.closed:
|
||||
await self._session.close()
|
||||
self._session = None
|
||||
|
||||
def _build_headers(self) -> dict[str, str]:
|
||||
"""Строит заголовки запроса с X-ApiKey и X-ShopId."""
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
'X-ApiKey': self.api_key,
|
||||
'X-ShopId': self.shop_id,
|
||||
}
|
||||
|
||||
async def create_invoice(
|
||||
self,
|
||||
*,
|
||||
amount: float,
|
||||
order_id: str,
|
||||
comment: str = '',
|
||||
service: str | None = None,
|
||||
success_url: str | None = None,
|
||||
fail_url: str | None = None,
|
||||
callback_url: str | None = None,
|
||||
custom_fields: str | None = None,
|
||||
lifetime: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Создает инвойс через API AuraPay.
|
||||
POST /invoice/create
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
'amount': amount,
|
||||
'order_id': order_id,
|
||||
}
|
||||
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
if service:
|
||||
payload['service'] = service
|
||||
if success_url:
|
||||
payload['success_url'] = success_url
|
||||
if fail_url:
|
||||
payload['fail_url'] = fail_url
|
||||
if callback_url:
|
||||
payload['callback_url'] = callback_url
|
||||
if custom_fields:
|
||||
payload['custom_fields'] = custom_fields
|
||||
if lifetime is not None:
|
||||
payload['lifetime'] = lifetime
|
||||
|
||||
logger.info(
|
||||
'AuraPay API create_invoice',
|
||||
order_id=order_id,
|
||||
amount=amount,
|
||||
service=service,
|
||||
)
|
||||
|
||||
try:
|
||||
session = await self._get_session()
|
||||
async with session.post(
|
||||
f'{API_BASE_URL}/invoice/create',
|
||||
json=payload,
|
||||
headers=self._build_headers(),
|
||||
) as response:
|
||||
data = await response.json(content_type=None)
|
||||
|
||||
if response.status == 200:
|
||||
logger.info(
|
||||
'AuraPay API invoice created',
|
||||
order_id=order_id,
|
||||
invoice_id=data.get('id'),
|
||||
status=data.get('status'),
|
||||
)
|
||||
return data
|
||||
|
||||
error_msg = data.get('message') or data.get('error') or str(data)
|
||||
logger.error(
|
||||
'AuraPay create_invoice error',
|
||||
status_code=response.status,
|
||||
error_msg=error_msg,
|
||||
response_data=data,
|
||||
)
|
||||
raise AuraPayAPIError(response.status, error_msg)
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.exception('AuraPay API connection error', error=e)
|
||||
raise
|
||||
|
||||
async def get_invoice_status(
|
||||
self,
|
||||
*,
|
||||
order_id: str | None = None,
|
||||
invoice_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Получает статус инвойса.
|
||||
POST /invoice/status
|
||||
"""
|
||||
if not order_id and not invoice_id:
|
||||
raise ValueError('Either order_id or invoice_id must be provided')
|
||||
|
||||
payload: dict[str, str] = {}
|
||||
if order_id:
|
||||
payload['order_id'] = order_id
|
||||
if invoice_id:
|
||||
payload['id'] = invoice_id
|
||||
|
||||
logger.info('AuraPay get_invoice_status', order_id=order_id, invoice_id=invoice_id)
|
||||
|
||||
try:
|
||||
session = await self._get_session()
|
||||
async with session.post(
|
||||
f'{API_BASE_URL}/invoice/status',
|
||||
json=payload,
|
||||
headers=self._build_headers(),
|
||||
) as response:
|
||||
data = await response.json(content_type=None)
|
||||
|
||||
if response.status == 200:
|
||||
return data
|
||||
|
||||
error_msg = data.get('message') or data.get('error') or str(data)
|
||||
logger.error(
|
||||
'AuraPay get_invoice_status error',
|
||||
status_code=response.status,
|
||||
error_msg=error_msg,
|
||||
)
|
||||
raise AuraPayAPIError(response.status, error_msg)
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.exception('AuraPay API connection error', error=e)
|
||||
raise
|
||||
|
||||
def verify_webhook_signature(self, payload: dict[str, Any], received_signature: str) -> bool:
|
||||
"""Верификация подписи webhook AuraPay через HMAC-SHA256.
|
||||
|
||||
Algorithm: sort JSON keys alphabetically, concatenate all VALUES
|
||||
(converted to str) into one string, HMAC-SHA256 with secret key #2.
|
||||
Header: X-SIGNATURE
|
||||
"""
|
||||
try:
|
||||
if not received_signature:
|
||||
logger.warning('AuraPay webhook: отсутствует X-SIGNATURE')
|
||||
return False
|
||||
|
||||
# Сортируем ключи по алфавиту и конкатенируем значения
|
||||
sorted_keys = sorted(payload.keys())
|
||||
concatenated_values = ''.join(str(payload[key]) for key in sorted_keys)
|
||||
|
||||
expected = hmac.new(
|
||||
self.secret_key.encode('utf-8'),
|
||||
concatenated_values.encode('utf-8'),
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
|
||||
return hmac.compare_digest(expected, received_signature)
|
||||
except Exception as e:
|
||||
logger.error('AuraPay webhook verify error', error=e)
|
||||
return False
|
||||
|
||||
|
||||
# Singleton instance
|
||||
aurapay_service = AuraPayService()
|
||||
@@ -86,33 +86,38 @@ class BlacklistService:
|
||||
if not line or line.startswith('#'):
|
||||
continue # Пропускаем пустые строки и комментарии
|
||||
|
||||
# В формате '7021477105 #@MAMYT_PAXAL2016, перепродажа подписок'
|
||||
# В формате '7021477105 # @MAMYT_PAXAL2016, перепродажа подписок'
|
||||
# только первая часть до пробела - это Telegram ID, всё остальное комментарий
|
||||
parts = line.split()
|
||||
if not parts:
|
||||
continue
|
||||
|
||||
try:
|
||||
telegram_id = int(parts[0]) # Первое число - это Telegram ID
|
||||
# Всё остальное - просто комментарий, не используем его для логики
|
||||
# Но можем использовать первую часть после ID как username для отображения
|
||||
username = ''
|
||||
if len(parts) > 1:
|
||||
# Берем вторую часть как username (если начинается с @)
|
||||
if parts[1].startswith('@'):
|
||||
username = parts[1]
|
||||
# 1. Разделяем строку на ID и всё остальное по символу '#'
|
||||
if '#' in line:
|
||||
id_part, content_part = line.split('#', 1)
|
||||
telegram_id = int(id_part.strip())
|
||||
content = content_part.strip()
|
||||
else:
|
||||
# Если решётки нет, пробуем просто взять первое число
|
||||
parts = line.split(maxsplit=1)
|
||||
telegram_id = int(parts[0])
|
||||
content = parts[1].strip() if len(parts) > 1 else ''
|
||||
|
||||
# По умолчанию используем "Занесен в черный список", если нет другой информации
|
||||
# 2. Обрабатываем контент: вычленяем username, если он есть в начале
|
||||
username = ''
|
||||
reason = 'Занесен в черный список'
|
||||
|
||||
# Если есть запятая в строке, можем использовать часть после нее как причину
|
||||
full_line_after_id = line[len(str(telegram_id)) :].strip()
|
||||
if ',' in full_line_after_id:
|
||||
# Извлекаем причину после запятой
|
||||
after_comma = full_line_after_id.split(',', 1)[1].strip()
|
||||
reason = after_comma
|
||||
if content:
|
||||
if content.startswith('@'):
|
||||
# Разбиваем контент только по первому пробелу
|
||||
# content_parts[0] будет юзернеймом, content_parts[1] — причиной
|
||||
content_parts = content.split(maxsplit=1)
|
||||
username = content_parts[0]
|
||||
if len(content_parts) > 1:
|
||||
reason = content_parts[1].strip()
|
||||
else:
|
||||
# Если собачки нет, значит весь контент — это причина
|
||||
reason = content
|
||||
|
||||
blacklist_data.append((telegram_id, username, reason))
|
||||
|
||||
except ValueError:
|
||||
# Если не удается преобразовать в число, это не ID
|
||||
logger.warning(
|
||||
|
||||
@@ -62,6 +62,7 @@ class BroadcastConfig:
|
||||
media: BroadcastMediaConfig | None = None
|
||||
initiator_name: str | None = None
|
||||
custom_buttons: list[dict] | None = None
|
||||
category: str = 'system' # system|news|promo
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -160,7 +161,7 @@ class BroadcastService:
|
||||
await session.commit()
|
||||
|
||||
# _fetch_recipients теперь возвращает list[int] (telegram_id), а не ORM-объекты
|
||||
recipient_ids: list[int] = await self._fetch_recipients(config.target)
|
||||
recipient_ids: list[int] = await self._fetch_recipients(config.target, config.category)
|
||||
|
||||
async with AsyncSessionLocal() as session:
|
||||
broadcast = await session.get(BroadcastHistory, broadcast_id)
|
||||
@@ -226,8 +227,13 @@ class BroadcastService:
|
||||
logger.exception('Критическая ошибка при выполнении рассылки', broadcast_id=broadcast_id, exc=exc)
|
||||
await self._mark_failed(broadcast_id, sent_count, failed_count, blocked_count)
|
||||
|
||||
async def _fetch_recipients(self, target: str) -> list[int]:
|
||||
"""Загружает получателей и возвращает список telegram_id (скаляры, не ORM-объекты)."""
|
||||
async def _fetch_recipients(self, target: str, category: str = 'system') -> list[int]:
|
||||
"""Загружает получателей и возвращает список telegram_id (скаляры, не ORM-объекты).
|
||||
|
||||
Filters out users who disabled the given broadcast category in their
|
||||
notification preferences (news_enabled, promo_offers_enabled).
|
||||
Category 'system' is never filtered — system notifications reach everyone.
|
||||
"""
|
||||
async with AsyncSessionLocal() as session:
|
||||
if target.startswith('custom_'):
|
||||
criteria = target[len('custom_') :]
|
||||
@@ -235,6 +241,17 @@ class BroadcastService:
|
||||
else:
|
||||
users_orm = await get_target_users(session, target)
|
||||
|
||||
# Filter by user notification preferences based on broadcast category
|
||||
if category == 'news':
|
||||
from app.utils.notification_prefs import is_news_enabled
|
||||
|
||||
users_orm = [u for u in users_orm if is_news_enabled(u)]
|
||||
elif category == 'promo':
|
||||
from app.utils.notification_prefs import is_promo_offers_enabled
|
||||
|
||||
users_orm = [u for u in users_orm if is_promo_offers_enabled(u)]
|
||||
# category == 'system' → no filtering, sent to everyone
|
||||
|
||||
# Извлекаем telegram_id сразу, пока сессия жива.
|
||||
# После выхода из блока ORM-объекты станут detached.
|
||||
return [u.telegram_id for u in users_orm if u.telegram_id is not None]
|
||||
|
||||
@@ -141,14 +141,27 @@ class DailySubscriptionService:
|
||||
PricingEngine.apply_discount(raw_daily_price, daily_group_pct) if daily_group_pct > 0 else raw_daily_price
|
||||
)
|
||||
|
||||
# Проверяем баланс
|
||||
if user.balance_kopeks < daily_price:
|
||||
# Проверяем баланс (при 100% скидке — пропускаем)
|
||||
if daily_price > 0 and user.balance_kopeks < daily_price:
|
||||
# Недостаточно средств - приостанавливаем подписку
|
||||
await suspend_daily_subscription_insufficient_balance(db, subscription)
|
||||
|
||||
# Уведомляем пользователя
|
||||
# Уведомляем пользователя (rate-limit: 1 раз в 6 часов)
|
||||
if self._bot:
|
||||
await self._notify_insufficient_balance(user, subscription, daily_price)
|
||||
from app.utils.cache import cache
|
||||
|
||||
cache_key = f'daily_insuf_notify:{subscription.id}'
|
||||
try:
|
||||
already_notified = await cache.get(cache_key)
|
||||
except Exception:
|
||||
already_notified = None
|
||||
|
||||
if not already_notified:
|
||||
await self._notify_insufficient_balance(user, subscription, daily_price)
|
||||
try:
|
||||
await cache.set(cache_key, '1', expire=21600) # 6 hours
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
logger.info(
|
||||
'Подписка приостановлена: недостаточно средств (баланс: требуется: )',
|
||||
@@ -264,6 +277,14 @@ class DailySubscriptionService:
|
||||
logger.warning('Не удалось синхронизировать сквады после создания', error=patch_err)
|
||||
except Exception as e:
|
||||
logger.warning('Не удалось обновить Remnawave', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
if hasattr(subscription, 'id') and hasattr(subscription, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='update' if _has_panel_user else 'create',
|
||||
)
|
||||
|
||||
# Отправляем уведомление администраторам
|
||||
try:
|
||||
@@ -539,6 +560,14 @@ class DailySubscriptionService:
|
||||
await subscription_service.update_remnawave_user(db, subscription)
|
||||
except Exception as e:
|
||||
logger.warning('Не удалось синхронизировать с RemnaWave после сброса трафика', error=e)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
if hasattr(subscription, 'id') and hasattr(subscription, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='update',
|
||||
)
|
||||
|
||||
# Уведомляем пользователя
|
||||
if self._bot and subscription.user_id:
|
||||
|
||||
@@ -15,7 +15,12 @@ from app.cabinet.auth.jwt_handler import create_auto_login_token
|
||||
from app.cabinet.auth.password_utils import hash_password
|
||||
from app.config import settings
|
||||
from app.database.crud.landing import create_guest_purchase
|
||||
from app.database.crud.subscription import create_paid_subscription, get_subscription_by_user_id, replace_subscription
|
||||
from app.database.crud.subscription import (
|
||||
create_paid_subscription,
|
||||
extend_subscription,
|
||||
get_subscription_by_user_id,
|
||||
replace_subscription,
|
||||
)
|
||||
from app.database.crud.tariff import get_tariff_by_id
|
||||
from app.database.crud.transaction import create_transaction
|
||||
from app.database.crud.user import _get_or_create_default_promo_group
|
||||
@@ -28,6 +33,7 @@ from app.database.models import (
|
||||
Transaction,
|
||||
TransactionType,
|
||||
User,
|
||||
_aware,
|
||||
)
|
||||
from app.services.subscription_service import SubscriptionService
|
||||
|
||||
@@ -1039,7 +1045,24 @@ async def activate_purchase(db: AsyncSession, purchase_token: str, *, skip_notif
|
||||
from app.database.crud.subscription import get_subscription_by_user_and_tariff
|
||||
|
||||
existing_for_tariff = await get_subscription_by_user_and_tariff(db, user.id, tariff.id)
|
||||
if existing_for_tariff:
|
||||
_has_time = (
|
||||
existing_for_tariff is not None
|
||||
and existing_for_tariff.end_date is not None
|
||||
and _aware(existing_for_tariff.end_date) > datetime.now(UTC)
|
||||
)
|
||||
if existing_for_tariff and _has_time:
|
||||
# Extend existing active/trial subscription instead of replacing (preserve remaining days)
|
||||
subscription = await extend_subscription(
|
||||
db,
|
||||
existing_for_tariff,
|
||||
purchase.period_days,
|
||||
traffic_limit_gb=tariff.traffic_limit_gb,
|
||||
device_limit=tariff.device_limit,
|
||||
connected_squads=squads,
|
||||
commit=False,
|
||||
)
|
||||
elif existing_for_tariff:
|
||||
# Expired subscription — replace with fresh dates
|
||||
subscription = await replace_subscription(
|
||||
db,
|
||||
existing_for_tariff,
|
||||
@@ -1066,7 +1089,25 @@ async def activate_purchase(db: AsyncSession, purchase_token: str, *, skip_notif
|
||||
)
|
||||
else:
|
||||
existing_subscription = await get_subscription_by_user_id(db, user.id)
|
||||
if existing_subscription is not None:
|
||||
_sub_has_time = (
|
||||
existing_subscription is not None
|
||||
and existing_subscription.end_date is not None
|
||||
and _aware(existing_subscription.end_date) > datetime.now(UTC)
|
||||
)
|
||||
if existing_subscription is not None and _sub_has_time:
|
||||
# Extend existing active subscription (preserve remaining days)
|
||||
subscription = await extend_subscription(
|
||||
db,
|
||||
existing_subscription,
|
||||
purchase.period_days,
|
||||
tariff_id=tariff.id,
|
||||
traffic_limit_gb=tariff.traffic_limit_gb,
|
||||
device_limit=tariff.device_limit,
|
||||
connected_squads=squads,
|
||||
commit=False,
|
||||
)
|
||||
elif existing_subscription is not None:
|
||||
# Expired subscription — replace with fresh dates
|
||||
subscription = await replace_subscription(
|
||||
db,
|
||||
existing_subscription,
|
||||
|
||||
@@ -18,6 +18,7 @@ logger = structlog.get_logger(__name__)
|
||||
KASSA_AI_SUB_METHODS = {
|
||||
'kassa_ai_sbp': {'payment_system_id': 44},
|
||||
'kassa_ai_card': {'payment_system_id': 36},
|
||||
'kassa_ai_sberpay': {'payment_system_id': 43},
|
||||
}
|
||||
|
||||
# Кэш для публичного IP
|
||||
|
||||
@@ -49,7 +49,6 @@ from app.database.models import (
|
||||
from app.external.remnawave_api import (
|
||||
RemnaWaveAPIError,
|
||||
RemnaWaveUser,
|
||||
TrafficLimitStrategy,
|
||||
UserStatus as RemnaWaveUserStatus,
|
||||
)
|
||||
from app.localization.texts import get_texts
|
||||
@@ -58,7 +57,7 @@ from app.services.notification_delivery_service import (
|
||||
)
|
||||
from app.services.notification_settings_service import NotificationSettingsService
|
||||
from app.services.promo_offer_service import promo_offer_service
|
||||
from app.services.subscription_service import SubscriptionService
|
||||
from app.services.subscription_service import SubscriptionService, get_traffic_reset_strategy
|
||||
from app.utils.cache import cache
|
||||
from app.utils.message_patch import caption_exceeds_telegram_limit
|
||||
from app.utils.miniapp_buttons import build_miniapp_or_callback_button
|
||||
@@ -90,6 +89,8 @@ class MonitoringService:
|
||||
self._notified_users: set[str] = set()
|
||||
self._last_cleanup = datetime.now(UTC)
|
||||
self._sla_task = None
|
||||
# In-memory fallback для cooldown автоплатежей (на случай недоступности Redis)
|
||||
self._autopay_fail_notified_at: dict[int, datetime] = {}
|
||||
|
||||
async def _send_message_with_logo(
|
||||
self,
|
||||
@@ -244,7 +245,10 @@ class MonitoringService:
|
||||
await self._check_trial_expiring_soon(db)
|
||||
await self._check_trial_channel_subscriptions(db)
|
||||
await self._check_expired_subscription_followups(db)
|
||||
await self._check_traffic_warnings(db)
|
||||
await self._check_low_balance_alerts(db)
|
||||
await self._retry_stuck_guest_purchases(db)
|
||||
await self._cleanup_expired_refresh_tokens(db)
|
||||
await self._cleanup_inactive_users(db)
|
||||
await self._sync_with_remnawave(db)
|
||||
|
||||
@@ -276,8 +280,76 @@ class MonitoringService:
|
||||
if (current_time - self._last_cleanup).total_seconds() >= 3600:
|
||||
old_count = len(self._notified_users)
|
||||
self._notified_users.clear()
|
||||
|
||||
# Чистим просроченные записи cooldown автоплатежей
|
||||
cutoff = current_time - timedelta(seconds=AUTOPAY_INSUFFICIENT_BALANCE_COOLDOWN_SECONDS)
|
||||
expired_ids = [uid for uid, ts in self._autopay_fail_notified_at.items() if ts < cutoff]
|
||||
for uid in expired_ids:
|
||||
del self._autopay_fail_notified_at[uid]
|
||||
|
||||
self._last_cleanup = current_time
|
||||
logger.info('🧹 Очищен кеш уведомлений ( записей)', old_count=old_count)
|
||||
logger.info(
|
||||
'🧹 Очищен кеш уведомлений',
|
||||
old_count=old_count,
|
||||
autopay_cooldown_evicted=len(expired_ids),
|
||||
autopay_cooldown_remaining=len(self._autopay_fail_notified_at),
|
||||
)
|
||||
|
||||
async def _check_autopay_fail_cooldown(self, user_id: int, user_identifier: str) -> bool:
|
||||
"""Проверяет, можно ли отправить уведомление об ошибке автоплатежа.
|
||||
|
||||
Использует Redis как primary хранилище cooldown, с in-memory fallback.
|
||||
Returns True если уведомление можно отправить.
|
||||
"""
|
||||
# 1. In-memory fallback (работает даже без Redis)
|
||||
last_notified = self._autopay_fail_notified_at.get(user_id)
|
||||
if last_notified:
|
||||
elapsed = (datetime.now(UTC) - last_notified).total_seconds()
|
||||
if elapsed < AUTOPAY_INSUFFICIENT_BALANCE_COOLDOWN_SECONDS:
|
||||
logger.debug(
|
||||
'Пропуск уведомления об ошибке автоплатежа — in-memory cooldown активен',
|
||||
user_identifier=user_identifier,
|
||||
elapsed_seconds=int(elapsed),
|
||||
)
|
||||
return False
|
||||
|
||||
# 2. Redis check (если доступен)
|
||||
cooldown_key = f'autopay_insufficient_balance_notified:{user_id}'
|
||||
try:
|
||||
if await cache.exists(cooldown_key):
|
||||
logger.debug(
|
||||
'Пропуск уведомления об ошибке автоплатежа — Redis cooldown активен',
|
||||
user_identifier=user_identifier,
|
||||
)
|
||||
return False
|
||||
except Exception as redis_err:
|
||||
logger.warning(
|
||||
'Ошибка проверки cooldown в Redis, используем in-memory fallback',
|
||||
user_identifier=user_identifier,
|
||||
redis_err=redis_err,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
async def _set_autopay_fail_cooldown(self, user_id: int, user_identifier: str) -> None:
|
||||
"""Устанавливает cooldown после отправки уведомления об ошибке автоплатежа."""
|
||||
# In-memory (всегда)
|
||||
self._autopay_fail_notified_at[user_id] = datetime.now(UTC)
|
||||
|
||||
# Redis (если доступен)
|
||||
cooldown_key = f'autopay_insufficient_balance_notified:{user_id}'
|
||||
try:
|
||||
await cache.set(
|
||||
cooldown_key,
|
||||
1,
|
||||
expire=AUTOPAY_INSUFFICIENT_BALANCE_COOLDOWN_SECONDS,
|
||||
)
|
||||
except Exception as redis_err:
|
||||
logger.warning(
|
||||
'Не удалось установить cooldown в Redis, in-memory fallback активен',
|
||||
user_identifier=user_identifier,
|
||||
redis_err=redis_err,
|
||||
)
|
||||
|
||||
async def _check_expired_subscriptions(self, db: AsyncSession):
|
||||
try:
|
||||
@@ -394,7 +466,7 @@ class MonitoringService:
|
||||
if is_active
|
||||
else max(subscription.end_date, current_time + timedelta(minutes=1)),
|
||||
traffic_limit_bytes=self._gb_to_bytes(subscription.traffic_limit_gb),
|
||||
traffic_limit_strategy=TrafficLimitStrategy.MONTH,
|
||||
traffic_limit_strategy=get_traffic_reset_strategy(subscription.tariff),
|
||||
description=settings.format_remnawave_user_description(
|
||||
full_name=user.full_name, username=user.username, telegram_id=user.telegram_id
|
||||
),
|
||||
@@ -448,11 +520,25 @@ class MonitoringService:
|
||||
|
||||
users_with_cards = await get_user_ids_with_active_payment_methods(db, autopay_user_ids)
|
||||
|
||||
from app.utils.notification_prefs import (
|
||||
get_subscription_expiry_days,
|
||||
is_subscription_expiry_enabled,
|
||||
)
|
||||
|
||||
for subscription in expiring_subscriptions:
|
||||
user = await get_user_by_id(db, subscription.user_id)
|
||||
if not user:
|
||||
continue
|
||||
|
||||
# Respect user notification preferences
|
||||
if not is_subscription_expiry_enabled(user):
|
||||
continue
|
||||
|
||||
# Check if user's preferred days threshold matches this check
|
||||
user_expiry_days = get_subscription_expiry_days(user)
|
||||
if days > user_expiry_days:
|
||||
continue
|
||||
|
||||
# Use user.id + subscription.id for key to support multiple subscriptions per user
|
||||
sub_key = f'user_{user.id}_sub_{subscription.id}_today'
|
||||
user_identifier = user.telegram_id or f'email:{user.id}'
|
||||
@@ -815,18 +901,24 @@ class MonitoringService:
|
||||
)
|
||||
|
||||
try:
|
||||
panel_uuid_restore = (
|
||||
subscription.remnawave_uuid
|
||||
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
|
||||
else user.remnawave_uuid
|
||||
)
|
||||
if panel_uuid_restore:
|
||||
await self.subscription_service.enable_remnawave_user(panel_uuid_restore)
|
||||
if settings.is_multi_tariff_enabled():
|
||||
_should_create = not subscription.remnawave_uuid
|
||||
else:
|
||||
_should_create = not getattr(user, 'remnawave_uuid', None)
|
||||
|
||||
if _should_create:
|
||||
# create_remnawave_user calls db.commit() internally --
|
||||
# flush accumulated batch state first to preserve atomicity.
|
||||
await batch_db.commit()
|
||||
await self.subscription_service.create_remnawave_user(batch_db, subscription)
|
||||
else:
|
||||
_enable_uuid = (
|
||||
subscription.remnawave_uuid
|
||||
if settings.is_multi_tariff_enabled()
|
||||
else user.remnawave_uuid
|
||||
)
|
||||
if _enable_uuid:
|
||||
await self.subscription_service.enable_remnawave_user(_enable_uuid)
|
||||
except Exception as api_error:
|
||||
logger.error(
|
||||
'Failed to update RemnaWave user',
|
||||
@@ -1264,42 +1356,24 @@ class MonitoringService:
|
||||
)
|
||||
else:
|
||||
failed_count += 1
|
||||
if user.telegram_id and self.bot:
|
||||
await self._send_autopay_failed_notification(
|
||||
user, user.balance_kopeks, charge_amount, subscription=subscription
|
||||
)
|
||||
elif not user.telegram_id:
|
||||
await notification_delivery_service.notify_autopay_failed(
|
||||
user=user,
|
||||
reason='Ошибка списания средств',
|
||||
)
|
||||
if await self._check_autopay_fail_cooldown(user.id, user_identifier):
|
||||
if user.telegram_id and self.bot:
|
||||
await self._send_autopay_failed_notification(
|
||||
user, user.balance_kopeks, charge_amount, subscription=subscription
|
||||
)
|
||||
elif not user.telegram_id:
|
||||
await notification_delivery_service.notify_autopay_failed(
|
||||
user=user,
|
||||
reason='Ошибка списания средств',
|
||||
)
|
||||
await self._set_autopay_fail_cooldown(user.id, user_identifier)
|
||||
logger.warning(
|
||||
'💳 Ошибка списания средств для автопродления пользователя', user_identifier=user_identifier
|
||||
)
|
||||
else:
|
||||
failed_count += 1
|
||||
|
||||
# Проверяем кулдаун уведомления через Redis, чтобы не спамить
|
||||
# при каждом срабатывании мониторинга
|
||||
cooldown_key = f'autopay_insufficient_balance_notified:{user.id}'
|
||||
should_notify = True
|
||||
|
||||
try:
|
||||
if await cache.exists(cooldown_key):
|
||||
should_notify = False
|
||||
logger.debug(
|
||||
'💳 Пропуск уведомления о недостаточном балансе для пользователя — кулдаун активен',
|
||||
user_identifier=user_identifier,
|
||||
)
|
||||
except Exception as redis_err:
|
||||
# Fallback: если Redis недоступен — отправляем уведомление
|
||||
logger.warning(
|
||||
'⚠️ Ошибка проверки кулдауна в Redis для пользователя : . Отправляем уведомление.',
|
||||
user_identifier=user_identifier,
|
||||
redis_err=redis_err,
|
||||
)
|
||||
|
||||
if should_notify:
|
||||
if await self._check_autopay_fail_cooldown(user.id, user_identifier):
|
||||
if user.telegram_id and self.bot:
|
||||
await self._send_autopay_failed_notification(
|
||||
user, user.balance_kopeks, charge_amount, subscription=subscription
|
||||
@@ -1309,20 +1383,7 @@ class MonitoringService:
|
||||
user=user,
|
||||
reason='Недостаточно средств на балансе',
|
||||
)
|
||||
|
||||
# Ставим ключ кулдауна после отправки
|
||||
try:
|
||||
await cache.set(
|
||||
cooldown_key,
|
||||
1,
|
||||
expire=AUTOPAY_INSUFFICIENT_BALANCE_COOLDOWN_SECONDS,
|
||||
)
|
||||
except Exception as redis_err:
|
||||
logger.warning(
|
||||
'⚠️ Не удалось установить кулдаун в Redis для пользователя',
|
||||
user_identifier=user_identifier,
|
||||
redis_err=redis_err,
|
||||
)
|
||||
await self._set_autopay_fail_cooldown(user.id, user_identifier)
|
||||
|
||||
logger.warning(
|
||||
'💳 Недостаточно средств для автопродления у пользователя', user_identifier=user_identifier
|
||||
@@ -1922,6 +1983,239 @@ class MonitoringService:
|
||||
except Exception:
|
||||
logger.error('Error retrying stuck PENDING_ACTIVATION guest purchases', exc_info=True)
|
||||
|
||||
async def _check_traffic_warnings(self, db: AsyncSession):
|
||||
"""Check subscriptions approaching traffic limit and notify users."""
|
||||
if not self.bot:
|
||||
return
|
||||
|
||||
try:
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
from app.database.models import Subscription
|
||||
from app.utils.notification_prefs import get_traffic_warning_percent, is_traffic_warning_enabled
|
||||
|
||||
# Get active subscriptions with traffic limits (not unlimited)
|
||||
result = await db.execute(
|
||||
select(Subscription)
|
||||
.options(selectinload(Subscription.user))
|
||||
.where(
|
||||
Subscription.status.in_(['active', 'trial']),
|
||||
Subscription.traffic_limit_gb > 0,
|
||||
)
|
||||
)
|
||||
subscriptions = result.scalars().all()
|
||||
|
||||
sent_count = 0
|
||||
for subscription in subscriptions:
|
||||
user = subscription.user
|
||||
if not user or not user.telegram_id:
|
||||
continue
|
||||
|
||||
if not is_traffic_warning_enabled(user):
|
||||
continue
|
||||
|
||||
traffic_limit = subscription.traffic_limit_gb or 0
|
||||
traffic_used = subscription.traffic_used_gb or 0.0
|
||||
|
||||
if traffic_limit <= 0:
|
||||
continue
|
||||
|
||||
current_percent = (traffic_used / traffic_limit) * 100
|
||||
user_threshold = get_traffic_warning_percent(user)
|
||||
|
||||
if current_percent < user_threshold:
|
||||
continue
|
||||
|
||||
# Rate-limit: 1 notification per subscription per 24 hours
|
||||
cache_key_str = f'traffic_warn:{subscription.id}'
|
||||
try:
|
||||
already_sent = await cache.get(cache_key_str)
|
||||
if already_sent:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
language = getattr(user, 'language', 'ru') or 'ru'
|
||||
texts = get_texts(language)
|
||||
message = texts.get(
|
||||
'TRAFFIC_WARNING_ALERT',
|
||||
'⚠️ <b>Предупреждение о трафике</b>\n\n'
|
||||
'Использовано: {used:.1f} / {limit} ГБ ({percent:.0f}%)\n\n'
|
||||
'Ваш лимит трафика почти исчерпан.',
|
||||
)
|
||||
message = message.format(
|
||||
used=traffic_used,
|
||||
limit=traffic_limit,
|
||||
percent=current_percent,
|
||||
)
|
||||
await self.bot.send_message(
|
||||
user.telegram_id,
|
||||
message,
|
||||
parse_mode='HTML',
|
||||
)
|
||||
try:
|
||||
await cache.set(cache_key_str, '1', expire=86400)
|
||||
except Exception:
|
||||
pass
|
||||
sent_count += 1
|
||||
except Exception as send_error:
|
||||
logger.debug(
|
||||
'Failed to send traffic warning',
|
||||
user_id=user.id,
|
||||
subscription_id=subscription.id,
|
||||
error=send_error,
|
||||
)
|
||||
|
||||
if sent_count > 0:
|
||||
logger.info('Traffic warnings sent', sent_count=sent_count)
|
||||
|
||||
except Exception as error:
|
||||
logger.error('Error checking traffic warnings', error=error)
|
||||
|
||||
async def _check_low_balance_alerts(self, db: AsyncSession):
|
||||
"""Check users with autopay enabled who have low balance and notify them.
|
||||
|
||||
Guards:
|
||||
- Disabled by default; users opt-in via cabinet notification settings
|
||||
- Only alerts when subscription expires within LOW_BALANCE_ALERT_EXPIRY_DAYS (default 3)
|
||||
- Quiet hours: skips sending between 22:00 and 09:00 server time
|
||||
- Rate-limited: max 1 alert per 24 hours per user
|
||||
"""
|
||||
if not self.bot:
|
||||
return
|
||||
|
||||
try:
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.database.models import Subscription, User
|
||||
from app.utils.notification_prefs import get_balance_low_threshold, is_balance_low_enabled
|
||||
|
||||
# Quiet hours: don't disturb users at night (22:00-09:00 UTC)
|
||||
current_hour = datetime.now(UTC).hour
|
||||
if current_hour >= 22 or current_hour < 9:
|
||||
return
|
||||
|
||||
# Only alert for subscriptions expiring soon (default 3 days)
|
||||
expiry_days = getattr(settings, 'LOW_BALANCE_ALERT_EXPIRY_DAYS', 3)
|
||||
expiry_threshold = datetime.now(UTC) + timedelta(days=expiry_days)
|
||||
|
||||
result = await db.execute(
|
||||
select(User)
|
||||
.join(Subscription, Subscription.user_id == User.id)
|
||||
.where(
|
||||
Subscription.status.in_(['active', 'trial']),
|
||||
Subscription.autopay_enabled.is_(True),
|
||||
Subscription.end_date.isnot(None),
|
||||
Subscription.end_date <= expiry_threshold,
|
||||
User.telegram_id.isnot(None),
|
||||
)
|
||||
.distinct()
|
||||
)
|
||||
users = result.scalars().all()
|
||||
|
||||
sent_count = 0
|
||||
for user in users:
|
||||
if not is_balance_low_enabled(user):
|
||||
continue
|
||||
|
||||
threshold = get_balance_low_threshold(user)
|
||||
balance = int(getattr(user, 'balance_kopeks', 0) or 0)
|
||||
|
||||
if balance >= threshold:
|
||||
continue
|
||||
|
||||
# Rate-limit via Redis: max 1 notification per 24 hours per user
|
||||
cache_key_str = f'low_balance_alert:{user.id}'
|
||||
try:
|
||||
already_sent = await cache.get(cache_key_str)
|
||||
if already_sent:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
language = getattr(user, 'language', 'ru') or 'ru'
|
||||
texts = get_texts(language)
|
||||
threshold_rub = threshold / 100
|
||||
balance_rub = balance / 100
|
||||
message = texts.get(
|
||||
'LOW_BALANCE_ALERT',
|
||||
'⚠️ <b>Низкий баланс</b>\n\n'
|
||||
'Ваш баланс: {balance} ₽\n'
|
||||
'Порог уведомления: {threshold} ₽\n\n'
|
||||
'Пополните баланс, чтобы автопродление подписки прошло успешно.',
|
||||
)
|
||||
message = message.format(
|
||||
balance=f'{balance_rub:.0f}',
|
||||
threshold=f'{threshold_rub:.0f}',
|
||||
)
|
||||
|
||||
# Build inline keyboard with cabinet top-up button
|
||||
keyboard = None
|
||||
miniapp_url = settings.get_main_menu_miniapp_url()
|
||||
if miniapp_url:
|
||||
topup_label = texts.get('LOW_BALANCE_TOPUP_BUTTON', '💳 Пополнить баланс')
|
||||
keyboard = InlineKeyboardMarkup(
|
||||
inline_keyboard=[
|
||||
[
|
||||
InlineKeyboardButton(
|
||||
text=topup_label,
|
||||
web_app=WebAppInfo(url=miniapp_url),
|
||||
)
|
||||
]
|
||||
]
|
||||
)
|
||||
|
||||
await self.bot.send_message(
|
||||
user.telegram_id,
|
||||
message,
|
||||
parse_mode='HTML',
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
# Mark as sent for 24 hours
|
||||
try:
|
||||
await cache.set(cache_key_str, '1', expire=86400)
|
||||
except Exception:
|
||||
pass
|
||||
sent_count += 1
|
||||
except Exception as send_error:
|
||||
logger.debug('Failed to send low balance alert', user_id=user.id, error=send_error)
|
||||
|
||||
if sent_count > 0:
|
||||
logger.info('Low balance alerts sent', sent_count=sent_count)
|
||||
|
||||
except Exception as error:
|
||||
logger.error('Error checking low balance alerts', error=error)
|
||||
|
||||
async def _cleanup_expired_refresh_tokens(self, db: AsyncSession):
|
||||
"""Delete expired and revoked refresh tokens to prevent table bloat."""
|
||||
try:
|
||||
from sqlalchemy import delete
|
||||
|
||||
from app.database.models import CabinetRefreshToken
|
||||
|
||||
now = datetime.now(UTC)
|
||||
# Delete tokens that are either expired or revoked more than 24h ago
|
||||
stmt = delete(CabinetRefreshToken).where(
|
||||
(CabinetRefreshToken.expires_at < now) | (CabinetRefreshToken.revoked_at < now - timedelta(hours=24))
|
||||
)
|
||||
result = await db.execute(stmt)
|
||||
deleted = result.rowcount
|
||||
if deleted > 0:
|
||||
await db.commit()
|
||||
logger.info('Cleaned up expired/revoked refresh tokens', deleted_count=deleted)
|
||||
except Exception as error:
|
||||
logger.error('Error cleaning up refresh tokens', error=error)
|
||||
try:
|
||||
await db.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
async def _cleanup_inactive_users(self, db: AsyncSession):
|
||||
try:
|
||||
now = datetime.now(UTC)
|
||||
|
||||
@@ -156,11 +156,20 @@ class NalogoQueueService:
|
||||
payment_id = receipt_data.get('payment_id', 'unknown')
|
||||
amount = receipt_data.get('amount', 0)
|
||||
|
||||
# Логируем количество попыток (чек никогда не удаляется из очереди)
|
||||
if attempts >= 10:
|
||||
logger.warning(
|
||||
'Чек уже много попыток, продолжаем пытаться...', payment_id=payment_id, attempts=attempts
|
||||
# Проверяем лимит попыток
|
||||
if attempts >= self._max_attempts:
|
||||
logger.error(
|
||||
'Чек превысил максимальное количество попыток, удалён из очереди',
|
||||
payment_id=payment_id,
|
||||
attempts=attempts,
|
||||
max_attempts=self._max_attempts,
|
||||
)
|
||||
# Удаляем метку "в очереди" — чек больше не будет обрабатываться
|
||||
if payment_id and payment_id != 'unknown':
|
||||
queued_key = f'nalogo:queued:{payment_id}'
|
||||
await cache.delete(queued_key)
|
||||
failed += 1
|
||||
continue
|
||||
|
||||
# Пытаемся отправить чек
|
||||
try:
|
||||
|
||||
@@ -79,6 +79,7 @@ class NotificationType(Enum):
|
||||
WEBHOOK_USER_NOT_CONNECTED = 'webhook_user_not_connected'
|
||||
WEBHOOK_DEVICE_ADDED = 'webhook_device_added'
|
||||
WEBHOOK_DEVICE_DELETED = 'webhook_device_deleted'
|
||||
WEBHOOK_TORRENT_DETECTED = 'webhook_torrent_detected'
|
||||
|
||||
# Other
|
||||
BROADCAST = 'broadcast'
|
||||
|
||||
@@ -1121,10 +1121,6 @@ class PartnerStatsService:
|
||||
),
|
||||
Transaction.amount_kopeks,
|
||||
),
|
||||
(
|
||||
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
|
||||
func.abs(Transaction.amount_kopeks),
|
||||
),
|
||||
else_=0,
|
||||
)
|
||||
),
|
||||
@@ -1137,12 +1133,8 @@ class PartnerStatsService:
|
||||
and_(
|
||||
Transaction.user_id == User.id,
|
||||
Transaction.is_completed.is_(True),
|
||||
Transaction.type.in_(
|
||||
[
|
||||
TransactionType.DEPOSIT.value,
|
||||
TransactionType.SUBSCRIPTION_PAYMENT.value,
|
||||
]
|
||||
),
|
||||
Transaction.type == TransactionType.DEPOSIT.value,
|
||||
Transaction.payment_method.in_(REAL_PAYMENT_METHODS),
|
||||
),
|
||||
)
|
||||
.where(AdvertisingCampaignRegistration.campaign_id == campaign_id)
|
||||
@@ -1159,10 +1151,6 @@ class PartnerStatsService:
|
||||
),
|
||||
Transaction.amount_kopeks,
|
||||
),
|
||||
(
|
||||
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
|
||||
func.abs(Transaction.amount_kopeks),
|
||||
),
|
||||
else_=0,
|
||||
)
|
||||
),
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
оставался компактным и импортировал только нужные компоненты.
|
||||
"""
|
||||
|
||||
from .aurapay import AuraPayPaymentMixin
|
||||
from .cloudpayments import CloudPaymentsPaymentMixin
|
||||
from .common import PaymentCommonMixin
|
||||
from .cryptobot import CryptoBotPaymentMixin
|
||||
@@ -12,8 +13,10 @@ from .heleket import HeleketPaymentMixin
|
||||
from .kassa_ai import KassaAiPaymentMixin
|
||||
from .mulenpay import MulenPayPaymentMixin
|
||||
from .pal24 import Pal24PaymentMixin
|
||||
from .paypear import PayPearPaymentMixin
|
||||
from .platega import PlategaPaymentMixin
|
||||
from .riopay import RioPayPaymentMixin
|
||||
from .rollypay import RollyPayPaymentMixin
|
||||
from .severpay import SeverPayPaymentMixin
|
||||
from .stars import TelegramStarsMixin
|
||||
from .tribute import TributePaymentMixin
|
||||
@@ -22,6 +25,7 @@ from .yookassa import YooKassaPaymentMixin
|
||||
|
||||
|
||||
__all__ = [
|
||||
'AuraPayPaymentMixin',
|
||||
'CloudPaymentsPaymentMixin',
|
||||
'CryptoBotPaymentMixin',
|
||||
'FreekassaPaymentMixin',
|
||||
@@ -29,9 +33,11 @@ __all__ = [
|
||||
'KassaAiPaymentMixin',
|
||||
'MulenPayPaymentMixin',
|
||||
'Pal24PaymentMixin',
|
||||
'PayPearPaymentMixin',
|
||||
'PaymentCommonMixin',
|
||||
'PlategaPaymentMixin',
|
||||
'RioPayPaymentMixin',
|
||||
'RollyPayPaymentMixin',
|
||||
'SeverPayPaymentMixin',
|
||||
'TelegramStarsMixin',
|
||||
'TributePaymentMixin',
|
||||
|
||||
@@ -0,0 +1,636 @@
|
||||
"""Mixin для интеграции с AuraPay (aurapay.tech)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from importlib import import_module
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database.models import PaymentMethod, TransactionType
|
||||
from app.services.aurapay_service import aurapay_service
|
||||
from app.utils.payment_logger import payment_logger as logger
|
||||
from app.utils.user_utils import format_referrer_info
|
||||
|
||||
|
||||
# Маппинг статусов AuraPay -> internal
|
||||
AURAPAY_STATUS_MAP: dict[str, tuple[str, bool]] = {
|
||||
'PENDING': ('pending', False),
|
||||
'PAID': ('success', True),
|
||||
'EXPIRED': ('expired', False),
|
||||
}
|
||||
|
||||
|
||||
class AuraPayPaymentMixin:
|
||||
"""Mixin для работы с платежами AuraPay."""
|
||||
|
||||
async def create_aurapay_payment(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: int | None,
|
||||
amount_kopeks: int,
|
||||
description: str = 'Пополнение баланса',
|
||||
email: str | None = None,
|
||||
language: str = 'ru',
|
||||
payment_method_type: str | None = None,
|
||||
return_url: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
Создает платеж AuraPay.
|
||||
|
||||
Returns:
|
||||
Словарь с данными платежа или None при ошибке
|
||||
"""
|
||||
if not settings.is_aurapay_enabled():
|
||||
logger.error('AuraPay не настроен')
|
||||
return None
|
||||
|
||||
# Валидация лимитов
|
||||
if amount_kopeks < settings.AURAPAY_MIN_AMOUNT_KOPEKS:
|
||||
logger.warning(
|
||||
'AuraPay: сумма меньше минимальной',
|
||||
amount_kopeks=amount_kopeks,
|
||||
AURAPAY_MIN_AMOUNT_KOPEKS=settings.AURAPAY_MIN_AMOUNT_KOPEKS,
|
||||
)
|
||||
return None
|
||||
|
||||
if amount_kopeks > settings.AURAPAY_MAX_AMOUNT_KOPEKS:
|
||||
logger.warning(
|
||||
'AuraPay: сумма больше максимальной',
|
||||
amount_kopeks=amount_kopeks,
|
||||
AURAPAY_MAX_AMOUNT_KOPEKS=settings.AURAPAY_MAX_AMOUNT_KOPEKS,
|
||||
)
|
||||
return None
|
||||
|
||||
# Получаем telegram_id пользователя для order_id
|
||||
payment_module = import_module('app.services.payment_service')
|
||||
if user_id is not None:
|
||||
user = await payment_module.get_user_by_id(db, user_id)
|
||||
tg_id = user.telegram_id if user else user_id
|
||||
else:
|
||||
user = None
|
||||
tg_id = 'guest'
|
||||
|
||||
# Генерируем уникальный order_id с telegram_id для удобного поиска
|
||||
order_id = f'ap{tg_id}_{uuid.uuid4().hex[:6]}'
|
||||
amount_rubles = amount_kopeks / 100
|
||||
currency = settings.AURAPAY_CURRENCY
|
||||
|
||||
# Метаданные
|
||||
metadata = {
|
||||
'user_id': user_id,
|
||||
'amount_kopeks': amount_kopeks,
|
||||
'description': description,
|
||||
'language': language,
|
||||
'type': 'balance_topup',
|
||||
}
|
||||
|
||||
try:
|
||||
# Формируем webhook URL
|
||||
webhook_url = None
|
||||
if settings.WEBHOOK_URL:
|
||||
webhook_url = f'{settings.WEBHOOK_URL.rstrip("/")}{settings.AURAPAY_WEBHOOK_PATH}'
|
||||
|
||||
lifetime = settings.AURAPAY_PAYMENT_LIFETIME_MINUTES
|
||||
|
||||
# Используем API для создания инвойса
|
||||
result = await aurapay_service.create_invoice(
|
||||
amount=amount_rubles,
|
||||
order_id=order_id,
|
||||
comment=description,
|
||||
service=payment_method_type,
|
||||
success_url=return_url or settings.AURAPAY_RETURN_URL,
|
||||
fail_url=return_url or settings.AURAPAY_RETURN_URL,
|
||||
callback_url=webhook_url,
|
||||
custom_fields=f'user_id={user_id}' if user_id else None,
|
||||
lifetime=lifetime,
|
||||
)
|
||||
|
||||
payment_data = result.get('payment_data', {})
|
||||
payment_url = payment_data.get('url') if isinstance(payment_data, dict) else None
|
||||
aurapay_invoice_id = result.get('id')
|
||||
|
||||
if not payment_url:
|
||||
logger.error('AuraPay API не вернул URL платежа', result=result)
|
||||
return None
|
||||
|
||||
logger.info(
|
||||
'AuraPay API: создан инвойс',
|
||||
order_id=order_id,
|
||||
aurapay_invoice_id=aurapay_invoice_id,
|
||||
payment_url=payment_url,
|
||||
)
|
||||
|
||||
# Срок действия из expires_at ответа или lifetime минут по умолчанию
|
||||
expires_at_str = result.get('expires_at')
|
||||
if expires_at_str:
|
||||
try:
|
||||
expires_at = datetime.fromisoformat(expires_at_str)
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=UTC)
|
||||
except (ValueError, TypeError):
|
||||
expires_at = datetime.now(UTC) + timedelta(minutes=lifetime)
|
||||
else:
|
||||
expires_at = datetime.now(UTC) + timedelta(minutes=lifetime)
|
||||
|
||||
# Сохраняем в БД
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
local_payment = await aurapay_crud.create_aurapay_payment(
|
||||
db=db,
|
||||
user_id=user_id,
|
||||
order_id=order_id,
|
||||
amount_kopeks=amount_kopeks,
|
||||
currency=currency,
|
||||
description=description,
|
||||
payment_url=payment_url,
|
||||
payment_method=payment_method_type,
|
||||
aurapay_invoice_id=aurapay_invoice_id,
|
||||
expires_at=expires_at,
|
||||
metadata_json=metadata,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
'AuraPay: создан платеж',
|
||||
order_id=order_id,
|
||||
user_id=user_id,
|
||||
amount_rubles=amount_rubles,
|
||||
currency=currency,
|
||||
)
|
||||
|
||||
return {
|
||||
'order_id': order_id,
|
||||
'aurapay_invoice_id': aurapay_invoice_id,
|
||||
'amount_kopeks': amount_kopeks,
|
||||
'amount_rubles': amount_rubles,
|
||||
'currency': currency,
|
||||
'payment_url': payment_url,
|
||||
'expires_at': expires_at.isoformat(),
|
||||
'local_payment_id': local_payment.id,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.exception('AuraPay: ошибка создания платежа', error=e)
|
||||
return None
|
||||
|
||||
async def process_aurapay_webhook(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
payload: dict[str, Any],
|
||||
) -> bool:
|
||||
"""
|
||||
Обрабатывает webhook от AuraPay.
|
||||
|
||||
Подпись проверяется в webserver/payments.py до вызова этого метода.
|
||||
|
||||
Args:
|
||||
db: Сессия БД
|
||||
payload: JSON тело webhook (signature проверена в webserver)
|
||||
|
||||
Returns:
|
||||
True если платеж успешно обработан
|
||||
"""
|
||||
try:
|
||||
aurapay_invoice_id = payload.get('id')
|
||||
order_id = payload.get('order_id')
|
||||
aurapay_status = payload.get('status')
|
||||
|
||||
if not aurapay_invoice_id or not aurapay_status:
|
||||
logger.warning('AuraPay webhook: отсутствуют обязательные поля', payload=payload)
|
||||
return False
|
||||
|
||||
# Определяем is_paid по статусу
|
||||
is_confirmed = aurapay_status == 'PAID'
|
||||
|
||||
# Ищем платеж по order_id (наш) или aurapay_invoice_id
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
payment = None
|
||||
if order_id:
|
||||
payment = await aurapay_crud.get_aurapay_payment_by_order_id(db, str(order_id))
|
||||
if not payment and aurapay_invoice_id:
|
||||
payment = await aurapay_crud.get_aurapay_payment_by_invoice_id(db, aurapay_invoice_id)
|
||||
|
||||
if not payment:
|
||||
logger.warning(
|
||||
'AuraPay webhook: платеж не найден',
|
||||
order_id=order_id,
|
||||
aurapay_invoice_id=aurapay_invoice_id,
|
||||
)
|
||||
return False
|
||||
|
||||
# Lock payment row immediately to prevent concurrent webhook processing (TOCTOU race)
|
||||
locked = await aurapay_crud.get_aurapay_payment_by_id_for_update(db, payment.id)
|
||||
if not locked:
|
||||
logger.error('AuraPay: не удалось заблокировать платёж', payment_id=payment.id)
|
||||
return False
|
||||
payment = locked
|
||||
|
||||
# Проверка дублирования (re-check from locked row)
|
||||
if payment.is_paid:
|
||||
logger.info('AuraPay webhook: платеж уже обработан', order_id=payment.order_id)
|
||||
return True
|
||||
|
||||
# Маппинг статуса
|
||||
status_info = AURAPAY_STATUS_MAP.get(aurapay_status, ('pending', False))
|
||||
internal_status, is_paid = status_info
|
||||
|
||||
# Если статус PAID, принудительно считаем оплаченным
|
||||
if is_confirmed:
|
||||
is_paid = True
|
||||
internal_status = 'success'
|
||||
|
||||
callback_payload = {
|
||||
'aurapay_invoice_id': aurapay_invoice_id,
|
||||
'order_id': order_id,
|
||||
'status': aurapay_status,
|
||||
'amount': payload.get('amount'),
|
||||
'service': payload.get('service'),
|
||||
'payer_details': payload.get('payer_details'),
|
||||
}
|
||||
|
||||
# Проверка суммы ДО обновления статуса
|
||||
# AuraPay отправляет amount как строку "1250.00"
|
||||
if is_paid:
|
||||
amount_value = payload.get('amount')
|
||||
if amount_value is not None:
|
||||
received_kopeks = round(float(amount_value) * 100)
|
||||
if abs(received_kopeks - payment.amount_kopeks) > 1:
|
||||
logger.error(
|
||||
'AuraPay amount mismatch',
|
||||
expected_kopeks=payment.amount_kopeks,
|
||||
received_kopeks=received_kopeks,
|
||||
order_id=payment.order_id,
|
||||
)
|
||||
await aurapay_crud.update_aurapay_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status='amount_mismatch',
|
||||
is_paid=False,
|
||||
aurapay_invoice_id=aurapay_invoice_id,
|
||||
callback_payload=callback_payload,
|
||||
)
|
||||
return False
|
||||
|
||||
# Финализируем платеж если оплачен — без промежуточного commit
|
||||
if is_paid:
|
||||
# Inline field assignments to keep FOR UPDATE lock intact
|
||||
payment.status = internal_status
|
||||
payment.is_paid = True
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
payment.aurapay_invoice_id = aurapay_invoice_id or payment.aurapay_invoice_id
|
||||
payment.callback_payload = callback_payload
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
return await self._finalize_aurapay_payment(
|
||||
db, payment, aurapay_invoice_id=aurapay_invoice_id, trigger='webhook'
|
||||
)
|
||||
|
||||
# Для не-success статусов можно безопасно коммитить
|
||||
payment = await aurapay_crud.update_aurapay_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status=internal_status,
|
||||
is_paid=False,
|
||||
aurapay_invoice_id=aurapay_invoice_id,
|
||||
callback_payload=callback_payload,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.exception('AuraPay webhook: ошибка обработки', error=e)
|
||||
return False
|
||||
|
||||
async def _finalize_aurapay_payment(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
payment: Any,
|
||||
*,
|
||||
aurapay_invoice_id: str | None,
|
||||
trigger: str,
|
||||
) -> bool:
|
||||
"""Создаёт транзакцию, начисляет баланс и отправляет уведомления.
|
||||
|
||||
FOR UPDATE lock must be acquired by the caller before invoking this method.
|
||||
"""
|
||||
payment_module = import_module('app.services.payment_service')
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
|
||||
# FOR UPDATE lock already acquired by caller — just check idempotency
|
||||
if payment.transaction_id:
|
||||
logger.info(
|
||||
'AuraPay платеж уже связан с транзакцией',
|
||||
order_id=payment.order_id,
|
||||
transaction_id=payment.transaction_id,
|
||||
trigger=trigger,
|
||||
)
|
||||
return True
|
||||
|
||||
# Read fresh metadata AFTER lock to avoid stale data
|
||||
metadata = dict(getattr(payment, 'metadata_json', {}) or {})
|
||||
|
||||
# --- Guest purchase flow ---
|
||||
from app.services.payment.common import try_fulfill_guest_purchase
|
||||
|
||||
guest_result = await try_fulfill_guest_purchase(
|
||||
db,
|
||||
metadata=metadata,
|
||||
payment_amount_kopeks=payment.amount_kopeks,
|
||||
provider_payment_id=str(aurapay_invoice_id) if aurapay_invoice_id else payment.order_id,
|
||||
provider_name='aurapay',
|
||||
)
|
||||
if guest_result is not None:
|
||||
return True
|
||||
|
||||
# Ensure paid fields are set (idempotent — caller may have already set them)
|
||||
if not payment.is_paid:
|
||||
payment.status = 'success'
|
||||
payment.is_paid = True
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
|
||||
balance_already_credited = bool(metadata.get('balance_credited'))
|
||||
|
||||
user = await payment_module.get_user_by_id(db, payment.user_id)
|
||||
if not user:
|
||||
logger.error('Пользователь не найден для AuraPay', user_id=payment.user_id)
|
||||
return False
|
||||
|
||||
# Загружаем промогруппы в асинхронном контексте
|
||||
await db.refresh(user, attribute_names=['promo_group', 'user_promo_groups'])
|
||||
for user_promo_group in getattr(user, 'user_promo_groups', []):
|
||||
await db.refresh(user_promo_group, attribute_names=['promo_group'])
|
||||
|
||||
promo_group = user.get_primary_promo_group()
|
||||
subscription = getattr(user, 'subscription', None)
|
||||
referrer_info = format_referrer_info(user)
|
||||
|
||||
transaction_external_id = str(aurapay_invoice_id) if aurapay_invoice_id else payment.order_id
|
||||
|
||||
# Проверяем дупликат транзакции
|
||||
existing_transaction = None
|
||||
if transaction_external_id:
|
||||
existing_transaction = await payment_module.get_transaction_by_external_id(
|
||||
db,
|
||||
transaction_external_id,
|
||||
PaymentMethod.AURAPAY,
|
||||
)
|
||||
|
||||
display_name = settings.get_aurapay_display_name()
|
||||
description = f'Пополнение через {display_name}'
|
||||
|
||||
transaction = existing_transaction
|
||||
created_transaction = False
|
||||
|
||||
if not transaction:
|
||||
transaction = await payment_module.create_transaction(
|
||||
db,
|
||||
user_id=payment.user_id,
|
||||
type=TransactionType.DEPOSIT,
|
||||
amount_kopeks=payment.amount_kopeks,
|
||||
description=description,
|
||||
payment_method=PaymentMethod.AURAPAY,
|
||||
external_id=transaction_external_id,
|
||||
is_completed=True,
|
||||
created_at=getattr(payment, 'created_at', None),
|
||||
commit=False,
|
||||
)
|
||||
created_transaction = True
|
||||
|
||||
await aurapay_crud.link_aurapay_payment_to_transaction(db, payment=payment, transaction_id=transaction.id)
|
||||
|
||||
should_credit_balance = created_transaction or not balance_already_credited
|
||||
|
||||
if not should_credit_balance:
|
||||
logger.info('AuraPay платеж уже зачислил баланс ранее', order_id=payment.order_id)
|
||||
return True
|
||||
|
||||
# Lock user row to prevent concurrent balance race conditions
|
||||
from app.database.crud.user import lock_user_for_update
|
||||
|
||||
user = await lock_user_for_update(db, user)
|
||||
|
||||
old_balance = user.balance_kopeks
|
||||
was_first_topup = not user.has_made_first_topup
|
||||
|
||||
user.balance_kopeks += payment.amount_kopeks
|
||||
user.updated_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
# Emit deferred side-effects after atomic commit
|
||||
from app.database.crud.transaction import emit_transaction_side_effects
|
||||
|
||||
await emit_transaction_side_effects(
|
||||
db,
|
||||
transaction,
|
||||
amount_kopeks=payment.amount_kopeks,
|
||||
user_id=payment.user_id,
|
||||
type=TransactionType.DEPOSIT,
|
||||
payment_method=PaymentMethod.AURAPAY,
|
||||
external_id=transaction_external_id,
|
||||
)
|
||||
|
||||
topup_status = '\U0001f195 Первое пополнение' if was_first_topup else '\U0001f504 Пополнение'
|
||||
|
||||
try:
|
||||
from app.services.referral_service import process_referral_topup
|
||||
|
||||
await process_referral_topup(
|
||||
db,
|
||||
user.id,
|
||||
payment.amount_kopeks,
|
||||
getattr(self, 'bot', None),
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error('Ошибка обработки реферального пополнения AuraPay', error=error)
|
||||
|
||||
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
|
||||
user.has_made_first_topup = True
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
if getattr(self, 'bot', None):
|
||||
try:
|
||||
from app.services.admin_notification_service import AdminNotificationService
|
||||
|
||||
notification_service = AdminNotificationService(self.bot)
|
||||
await notification_service.send_balance_topup_notification(
|
||||
user,
|
||||
transaction,
|
||||
old_balance,
|
||||
topup_status=topup_status,
|
||||
referrer_info=referrer_info,
|
||||
subscription=subscription,
|
||||
promo_group=promo_group,
|
||||
db=db,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error('Ошибка отправки админ уведомления AuraPay', error=error)
|
||||
|
||||
if getattr(self, 'bot', None) and user.telegram_id:
|
||||
try:
|
||||
keyboard = await self.build_topup_success_keyboard(user)
|
||||
await self.bot.send_message(
|
||||
user.telegram_id,
|
||||
(
|
||||
'\u2705 <b>Пополнение успешно!</b>\n\n'
|
||||
f'\U0001f4b0 Сумма: {settings.format_price(payment.amount_kopeks)}\n'
|
||||
f'\U0001f4b3 Способ: {display_name}\n'
|
||||
f'\U0001f194 Транзакция: {transaction.id}\n\n'
|
||||
'Баланс пополнен автоматически!'
|
||||
),
|
||||
parse_mode='HTML',
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error('Ошибка отправки уведомления пользователю AuraPay', error=error)
|
||||
|
||||
try:
|
||||
from app.services.payment.common import send_cart_notification_after_topup
|
||||
|
||||
await send_cart_notification_after_topup(user, payment.amount_kopeks, db, getattr(self, 'bot', None))
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
'Ошибка при работе с сохраненной корзиной для пользователя',
|
||||
user_id=payment.user_id,
|
||||
error=error,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
metadata['balance_change'] = {
|
||||
'old_balance': old_balance,
|
||||
'new_balance': user.balance_kopeks,
|
||||
'credited_at': datetime.now(UTC).isoformat(),
|
||||
}
|
||||
metadata['balance_credited'] = True
|
||||
payment.metadata_json = metadata
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Обработан AuraPay платеж',
|
||||
order_id=payment.order_id,
|
||||
user_id=payment.user_id,
|
||||
trigger=trigger,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
async def check_aurapay_payment_status(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
order_id: str,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Проверяет статус платежа через API."""
|
||||
try:
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
payment = await aurapay_crud.get_aurapay_payment_by_order_id(db, order_id)
|
||||
if not payment:
|
||||
logger.warning('AuraPay payment not found', order_id=order_id)
|
||||
return None
|
||||
|
||||
if payment.is_paid:
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': 'success',
|
||||
'is_paid': True,
|
||||
}
|
||||
|
||||
# Проверяем через API по aurapay_invoice_id или order_id
|
||||
try:
|
||||
order_data = await aurapay_service.get_invoice_status(
|
||||
order_id=payment.order_id,
|
||||
invoice_id=payment.aurapay_invoice_id,
|
||||
)
|
||||
aurapay_status = order_data.get('status')
|
||||
|
||||
if aurapay_status:
|
||||
status_info = AURAPAY_STATUS_MAP.get(aurapay_status, ('pending', False))
|
||||
internal_status, is_paid = status_info
|
||||
|
||||
if is_paid:
|
||||
# Проверка суммы — AuraPay возвращает amount как число
|
||||
api_amount = order_data.get('amount')
|
||||
if api_amount is not None:
|
||||
received_kopeks = round(float(api_amount) * 100)
|
||||
if abs(received_kopeks - payment.amount_kopeks) > 1:
|
||||
logger.error(
|
||||
'AuraPay amount mismatch (API check)',
|
||||
expected_kopeks=payment.amount_kopeks,
|
||||
received_kopeks=received_kopeks,
|
||||
order_id=payment.order_id,
|
||||
)
|
||||
await aurapay_crud.update_aurapay_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status='amount_mismatch',
|
||||
is_paid=False,
|
||||
aurapay_invoice_id=payment.aurapay_invoice_id,
|
||||
callback_payload={
|
||||
'check_source': 'api',
|
||||
'aurapay_order_data': order_data,
|
||||
},
|
||||
)
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': 'amount_mismatch',
|
||||
'is_paid': False,
|
||||
}
|
||||
|
||||
# Acquire FOR UPDATE lock before finalization
|
||||
locked = await aurapay_crud.get_aurapay_payment_by_id_for_update(db, payment.id)
|
||||
if not locked:
|
||||
logger.error('AuraPay: не удалось заблокировать платёж', payment_id=payment.id)
|
||||
return None
|
||||
payment = locked
|
||||
|
||||
if payment.is_paid:
|
||||
logger.info('AuraPay платеж уже обработан (api_check)', order_id=payment.order_id)
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': 'success',
|
||||
'is_paid': True,
|
||||
}
|
||||
|
||||
logger.info('AuraPay payment confirmed via API', order_id=payment.order_id)
|
||||
|
||||
# Inline field updates — NO intermediate commit that would release FOR UPDATE lock
|
||||
payment.status = 'success'
|
||||
payment.is_paid = True
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
payment.callback_payload = {
|
||||
'check_source': 'api',
|
||||
'aurapay_order_data': order_data,
|
||||
}
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
|
||||
await self._finalize_aurapay_payment(
|
||||
db,
|
||||
payment,
|
||||
aurapay_invoice_id=payment.aurapay_invoice_id,
|
||||
trigger='api_check',
|
||||
)
|
||||
elif internal_status != payment.status:
|
||||
# Обновляем статус если изменился
|
||||
payment = await aurapay_crud.update_aurapay_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status=internal_status,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error('Error checking AuraPay payment status via API', error=e)
|
||||
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': payment.status or 'pending',
|
||||
'is_paid': payment.is_paid,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.exception('AuraPay: ошибка проверки статуса', error=e)
|
||||
return None
|
||||
@@ -58,6 +58,7 @@ class HeleketPaymentMixin:
|
||||
'currency': 'RUB',
|
||||
'order_id': order_id,
|
||||
'lifetime': settings.get_heleket_lifetime(),
|
||||
'from_referral_code': 'wZ7QrW',
|
||||
}
|
||||
|
||||
to_currency = (settings.HELEKET_DEFAULT_CURRENCY or '').strip()
|
||||
|
||||
@@ -92,11 +92,14 @@ class KassaAiPaymentMixin:
|
||||
|
||||
try:
|
||||
# Используем API для создания заказа
|
||||
# KassaAI требует email в формате {telegram_id}@telegram.org
|
||||
target_email = email or (f'{user.telegram_id}@telegram.org' if user and user.telegram_id else None)
|
||||
|
||||
result = await kassa_ai_service.create_order(
|
||||
order_id=order_id,
|
||||
amount=amount_rubles,
|
||||
currency=currency,
|
||||
email=email,
|
||||
email=target_email,
|
||||
payment_system_id=payment_system_id
|
||||
if payment_system_id is not None
|
||||
else settings.KASSA_AI_PAYMENT_SYSTEM_ID,
|
||||
|
||||
@@ -0,0 +1,624 @@
|
||||
"""Mixin для интеграции с PayPear (paypear.ru)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from importlib import import_module
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database.models import PaymentMethod, TransactionType
|
||||
from app.services.paypear_service import paypear_service
|
||||
from app.utils.payment_logger import payment_logger as logger
|
||||
from app.utils.user_utils import format_referrer_info
|
||||
|
||||
|
||||
# Маппинг статусов PayPear -> internal
|
||||
PAYPEAR_STATUS_MAP: dict[str, tuple[str, bool]] = {
|
||||
'NEW': ('pending', False),
|
||||
'PROCESS': ('processing', False),
|
||||
'CONFIRMED': ('success', True),
|
||||
'CANCELED': ('canceled', False),
|
||||
'REFUNDED': ('refunded', False),
|
||||
'EXPIRED': ('expired', False),
|
||||
}
|
||||
|
||||
|
||||
class PayPearPaymentMixin:
|
||||
"""Mixin для работы с платежами PayPear."""
|
||||
|
||||
async def create_paypear_payment(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: int | None,
|
||||
amount_kopeks: int,
|
||||
description: str = 'Пополнение баланса',
|
||||
email: str | None = None,
|
||||
language: str = 'ru',
|
||||
return_url: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
Создает платеж PayPear.
|
||||
|
||||
Returns:
|
||||
Словарь с данными платежа или None при ошибке
|
||||
"""
|
||||
if not settings.is_paypear_enabled():
|
||||
logger.error('PayPear не настроен')
|
||||
return None
|
||||
|
||||
# Валидация лимитов
|
||||
if amount_kopeks < settings.PAYPEAR_MIN_AMOUNT_KOPEKS:
|
||||
logger.warning(
|
||||
'PayPear: сумма меньше минимальной',
|
||||
amount_kopeks=amount_kopeks,
|
||||
PAYPEAR_MIN_AMOUNT_KOPEKS=settings.PAYPEAR_MIN_AMOUNT_KOPEKS,
|
||||
)
|
||||
return None
|
||||
|
||||
if amount_kopeks > settings.PAYPEAR_MAX_AMOUNT_KOPEKS:
|
||||
logger.warning(
|
||||
'PayPear: сумма больше максимальной',
|
||||
amount_kopeks=amount_kopeks,
|
||||
PAYPEAR_MAX_AMOUNT_KOPEKS=settings.PAYPEAR_MAX_AMOUNT_KOPEKS,
|
||||
)
|
||||
return None
|
||||
|
||||
# Получаем telegram_id пользователя для order_id
|
||||
payment_module = import_module('app.services.payment_service')
|
||||
if user_id is not None:
|
||||
user = await payment_module.get_user_by_id(db, user_id)
|
||||
tg_id = user.telegram_id if user else user_id
|
||||
else:
|
||||
user = None
|
||||
tg_id = 'guest'
|
||||
|
||||
# Генерируем уникальный order_id с telegram_id для удобного поиска
|
||||
order_id = f'pp{tg_id}_{uuid.uuid4().hex[:6]}'
|
||||
amount_rubles = amount_kopeks / 100
|
||||
currency = settings.PAYPEAR_CURRENCY
|
||||
|
||||
# Метаданные
|
||||
metadata = {
|
||||
'user_id': user_id,
|
||||
'amount_kopeks': amount_kopeks,
|
||||
'description': description,
|
||||
'language': language,
|
||||
'type': 'balance_topup',
|
||||
}
|
||||
|
||||
try:
|
||||
payment_method_type = settings.PAYPEAR_PAYMENT_METHOD
|
||||
|
||||
# Используем API для создания платежа
|
||||
result = await paypear_service.create_payment(
|
||||
order_id=order_id,
|
||||
amount_rubles=amount_rubles,
|
||||
currency=currency,
|
||||
payment_method_type=payment_method_type,
|
||||
description=description,
|
||||
return_url=return_url or settings.PAYPEAR_RETURN_URL,
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
confirmation = result.get('confirmation', {})
|
||||
payment_url = confirmation.get('url') if isinstance(confirmation, dict) else None
|
||||
paypear_id = result.get('id')
|
||||
|
||||
if not payment_url:
|
||||
logger.error('PayPear API не вернул URL платежа', result=result)
|
||||
return None
|
||||
|
||||
logger.info(
|
||||
'PayPear API: создан платеж',
|
||||
order_id=order_id,
|
||||
paypear_id=paypear_id,
|
||||
payment_url=payment_url,
|
||||
)
|
||||
|
||||
# Срок действия — 30 минут по умолчанию
|
||||
expires_at = datetime.now(UTC) + timedelta(minutes=30)
|
||||
|
||||
# Сохраняем в БД
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
local_payment = await paypear_crud.create_paypear_payment(
|
||||
db=db,
|
||||
user_id=user_id,
|
||||
order_id=order_id,
|
||||
amount_kopeks=amount_kopeks,
|
||||
currency=currency,
|
||||
description=description,
|
||||
payment_url=payment_url,
|
||||
payment_method=payment_method_type,
|
||||
paypear_id=paypear_id,
|
||||
expires_at=expires_at,
|
||||
metadata_json=metadata,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
'PayPear: создан платеж',
|
||||
order_id=order_id,
|
||||
user_id=user_id,
|
||||
amount_rubles=amount_rubles,
|
||||
currency=currency,
|
||||
)
|
||||
|
||||
return {
|
||||
'order_id': order_id,
|
||||
'paypear_id': paypear_id,
|
||||
'amount_kopeks': amount_kopeks,
|
||||
'amount_rubles': amount_rubles,
|
||||
'currency': currency,
|
||||
'payment_url': payment_url,
|
||||
'expires_at': expires_at.isoformat(),
|
||||
'local_payment_id': local_payment.id,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.exception('PayPear: ошибка создания платежа', error=e)
|
||||
return None
|
||||
|
||||
async def process_paypear_webhook(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
payload: dict[str, Any],
|
||||
) -> bool:
|
||||
"""
|
||||
Обрабатывает webhook от PayPear.
|
||||
|
||||
Подпись проверяется в webserver/payments.py до вызова этого метода.
|
||||
|
||||
Args:
|
||||
db: Сессия БД
|
||||
payload: JSON тело webhook (signature проверена в webserver)
|
||||
|
||||
Returns:
|
||||
True если платеж успешно обработан
|
||||
"""
|
||||
try:
|
||||
event = payload.get('event')
|
||||
obj = payload.get('object', {})
|
||||
paypear_id = obj.get('id')
|
||||
order_id = obj.get('order_id')
|
||||
paypear_status = obj.get('status')
|
||||
|
||||
if not paypear_id or not paypear_status:
|
||||
logger.warning('PayPear webhook: отсутствуют обязательные поля', payload=payload)
|
||||
return False
|
||||
|
||||
# Определяем is_paid по event
|
||||
is_confirmed = event == 'payment.confirmed'
|
||||
|
||||
# Ищем платеж по order_id (наш) или paypear_id
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
payment = None
|
||||
if order_id:
|
||||
payment = await paypear_crud.get_paypear_payment_by_order_id(db, order_id)
|
||||
if not payment and paypear_id:
|
||||
payment = await paypear_crud.get_paypear_payment_by_paypear_id(db, paypear_id)
|
||||
|
||||
if not payment:
|
||||
logger.warning(
|
||||
'PayPear webhook: платеж не найден',
|
||||
order_id=order_id,
|
||||
paypear_id=paypear_id,
|
||||
)
|
||||
return False
|
||||
|
||||
# Lock payment row immediately to prevent concurrent webhook processing (TOCTOU race)
|
||||
locked = await paypear_crud.get_paypear_payment_by_id_for_update(db, payment.id)
|
||||
if not locked:
|
||||
logger.error('PayPear: не удалось заблокировать платёж', payment_id=payment.id)
|
||||
return False
|
||||
payment = locked
|
||||
|
||||
# Проверка дублирования (re-check from locked row)
|
||||
if payment.is_paid:
|
||||
logger.info('PayPear webhook: платеж уже обработан', order_id=payment.order_id)
|
||||
return True
|
||||
|
||||
# Маппинг статуса
|
||||
status_info = PAYPEAR_STATUS_MAP.get(paypear_status, ('pending', False))
|
||||
internal_status, is_paid = status_info
|
||||
|
||||
# Если event = payment.confirmed, принудительно считаем оплаченным
|
||||
if is_confirmed:
|
||||
is_paid = True
|
||||
internal_status = 'success'
|
||||
|
||||
callback_payload = {
|
||||
'paypear_id': paypear_id,
|
||||
'order_id': order_id,
|
||||
'status': paypear_status,
|
||||
'event': event,
|
||||
'amount': obj.get('amount'),
|
||||
}
|
||||
|
||||
# Проверка суммы ДО обновления статуса
|
||||
if is_paid:
|
||||
amount_info = obj.get('amount', {})
|
||||
if isinstance(amount_info, dict):
|
||||
amount_value = amount_info.get('value')
|
||||
else:
|
||||
amount_value = amount_info
|
||||
|
||||
if amount_value is not None:
|
||||
received_kopeks = round(float(amount_value) * 100)
|
||||
if abs(received_kopeks - payment.amount_kopeks) > 1:
|
||||
logger.error(
|
||||
'PayPear amount mismatch',
|
||||
expected_kopeks=payment.amount_kopeks,
|
||||
received_kopeks=received_kopeks,
|
||||
order_id=payment.order_id,
|
||||
)
|
||||
await paypear_crud.update_paypear_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status='amount_mismatch',
|
||||
is_paid=False,
|
||||
paypear_id=paypear_id,
|
||||
callback_payload=callback_payload,
|
||||
)
|
||||
return False
|
||||
|
||||
# Финализируем платеж если оплачен — без промежуточного commit
|
||||
if is_paid:
|
||||
# Inline field assignments to keep FOR UPDATE lock intact
|
||||
payment.status = internal_status
|
||||
payment.is_paid = True
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
payment.paypear_id = paypear_id or payment.paypear_id
|
||||
payment.callback_payload = callback_payload
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
return await self._finalize_paypear_payment(db, payment, paypear_id=paypear_id, trigger='webhook')
|
||||
|
||||
# Для не-success статусов можно безопасно коммитить
|
||||
payment = await paypear_crud.update_paypear_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status=internal_status,
|
||||
is_paid=False,
|
||||
paypear_id=paypear_id,
|
||||
callback_payload=callback_payload,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.exception('PayPear webhook: ошибка обработки', error=e)
|
||||
return False
|
||||
|
||||
async def _finalize_paypear_payment(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
payment: Any,
|
||||
*,
|
||||
paypear_id: str | None,
|
||||
trigger: str,
|
||||
) -> bool:
|
||||
"""Создаёт транзакцию, начисляет баланс и отправляет уведомления.
|
||||
|
||||
FOR UPDATE lock must be acquired by the caller before invoking this method.
|
||||
"""
|
||||
payment_module = import_module('app.services.payment_service')
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
|
||||
# FOR UPDATE lock already acquired by caller — just check idempotency
|
||||
if payment.transaction_id:
|
||||
logger.info(
|
||||
'PayPear платеж уже связан с транзакцией',
|
||||
order_id=payment.order_id,
|
||||
transaction_id=payment.transaction_id,
|
||||
trigger=trigger,
|
||||
)
|
||||
return True
|
||||
|
||||
# Read fresh metadata AFTER lock to avoid stale data
|
||||
metadata = dict(getattr(payment, 'metadata_json', {}) or {})
|
||||
|
||||
# --- Guest purchase flow ---
|
||||
from app.services.payment.common import try_fulfill_guest_purchase
|
||||
|
||||
guest_result = await try_fulfill_guest_purchase(
|
||||
db,
|
||||
metadata=metadata,
|
||||
payment_amount_kopeks=payment.amount_kopeks,
|
||||
provider_payment_id=str(paypear_id) if paypear_id else payment.order_id,
|
||||
provider_name='paypear',
|
||||
)
|
||||
if guest_result is not None:
|
||||
return True
|
||||
|
||||
# Ensure paid fields are set (idempotent — caller may have already set them)
|
||||
if not payment.is_paid:
|
||||
payment.status = 'success'
|
||||
payment.is_paid = True
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
|
||||
balance_already_credited = bool(metadata.get('balance_credited'))
|
||||
|
||||
user = await payment_module.get_user_by_id(db, payment.user_id)
|
||||
if not user:
|
||||
logger.error('Пользователь не найден для PayPear', user_id=payment.user_id)
|
||||
return False
|
||||
|
||||
# Загружаем промогруппы в асинхронном контексте
|
||||
await db.refresh(user, attribute_names=['promo_group', 'user_promo_groups'])
|
||||
for user_promo_group in getattr(user, 'user_promo_groups', []):
|
||||
await db.refresh(user_promo_group, attribute_names=['promo_group'])
|
||||
|
||||
promo_group = user.get_primary_promo_group()
|
||||
subscription = getattr(user, 'subscription', None)
|
||||
referrer_info = format_referrer_info(user)
|
||||
|
||||
transaction_external_id = str(paypear_id) if paypear_id else payment.order_id
|
||||
|
||||
# Проверяем дупликат транзакции
|
||||
existing_transaction = None
|
||||
if transaction_external_id:
|
||||
existing_transaction = await payment_module.get_transaction_by_external_id(
|
||||
db,
|
||||
transaction_external_id,
|
||||
PaymentMethod.PAYPEAR,
|
||||
)
|
||||
|
||||
display_name = settings.get_paypear_display_name()
|
||||
description = f'Пополнение через {display_name}'
|
||||
|
||||
transaction = existing_transaction
|
||||
created_transaction = False
|
||||
|
||||
if not transaction:
|
||||
transaction = await payment_module.create_transaction(
|
||||
db,
|
||||
user_id=payment.user_id,
|
||||
type=TransactionType.DEPOSIT,
|
||||
amount_kopeks=payment.amount_kopeks,
|
||||
description=description,
|
||||
payment_method=PaymentMethod.PAYPEAR,
|
||||
external_id=transaction_external_id,
|
||||
is_completed=True,
|
||||
created_at=getattr(payment, 'created_at', None),
|
||||
commit=False,
|
||||
)
|
||||
created_transaction = True
|
||||
|
||||
await paypear_crud.link_paypear_payment_to_transaction(db, payment=payment, transaction_id=transaction.id)
|
||||
|
||||
should_credit_balance = created_transaction or not balance_already_credited
|
||||
|
||||
if not should_credit_balance:
|
||||
logger.info('PayPear платеж уже зачислил баланс ранее', order_id=payment.order_id)
|
||||
return True
|
||||
|
||||
# Lock user row to prevent concurrent balance race conditions
|
||||
from app.database.crud.user import lock_user_for_update
|
||||
|
||||
user = await lock_user_for_update(db, user)
|
||||
|
||||
old_balance = user.balance_kopeks
|
||||
was_first_topup = not user.has_made_first_topup
|
||||
|
||||
user.balance_kopeks += payment.amount_kopeks
|
||||
user.updated_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
# Emit deferred side-effects after atomic commit
|
||||
from app.database.crud.transaction import emit_transaction_side_effects
|
||||
|
||||
await emit_transaction_side_effects(
|
||||
db,
|
||||
transaction,
|
||||
amount_kopeks=payment.amount_kopeks,
|
||||
user_id=payment.user_id,
|
||||
type=TransactionType.DEPOSIT,
|
||||
payment_method=PaymentMethod.PAYPEAR,
|
||||
external_id=transaction_external_id,
|
||||
)
|
||||
|
||||
topup_status = '\U0001f195 Первое пополнение' if was_first_topup else '\U0001f504 Пополнение'
|
||||
|
||||
try:
|
||||
from app.services.referral_service import process_referral_topup
|
||||
|
||||
await process_referral_topup(
|
||||
db,
|
||||
user.id,
|
||||
payment.amount_kopeks,
|
||||
getattr(self, 'bot', None),
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error('Ошибка обработки реферального пополнения PayPear', error=error)
|
||||
|
||||
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
|
||||
user.has_made_first_topup = True
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
if getattr(self, 'bot', None):
|
||||
try:
|
||||
from app.services.admin_notification_service import AdminNotificationService
|
||||
|
||||
notification_service = AdminNotificationService(self.bot)
|
||||
await notification_service.send_balance_topup_notification(
|
||||
user,
|
||||
transaction,
|
||||
old_balance,
|
||||
topup_status=topup_status,
|
||||
referrer_info=referrer_info,
|
||||
subscription=subscription,
|
||||
promo_group=promo_group,
|
||||
db=db,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error('Ошибка отправки админ уведомления PayPear', error=error)
|
||||
|
||||
if getattr(self, 'bot', None) and user.telegram_id:
|
||||
try:
|
||||
keyboard = await self.build_topup_success_keyboard(user)
|
||||
await self.bot.send_message(
|
||||
user.telegram_id,
|
||||
(
|
||||
'\u2705 <b>Пополнение успешно!</b>\n\n'
|
||||
f'\U0001f4b0 Сумма: {settings.format_price(payment.amount_kopeks)}\n'
|
||||
f'\U0001f4b3 Способ: {display_name}\n'
|
||||
f'\U0001f194 Транзакция: {transaction.id}\n\n'
|
||||
'Баланс пополнен автоматически!'
|
||||
),
|
||||
parse_mode='HTML',
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error('Ошибка отправки уведомления пользователю PayPear', error=error)
|
||||
|
||||
try:
|
||||
from app.services.payment.common import send_cart_notification_after_topup
|
||||
|
||||
await send_cart_notification_after_topup(user, payment.amount_kopeks, db, getattr(self, 'bot', None))
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
'Ошибка при работе с сохраненной корзиной для пользователя',
|
||||
user_id=payment.user_id,
|
||||
error=error,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
metadata['balance_change'] = {
|
||||
'old_balance': old_balance,
|
||||
'new_balance': user.balance_kopeks,
|
||||
'credited_at': datetime.now(UTC).isoformat(),
|
||||
}
|
||||
metadata['balance_credited'] = True
|
||||
payment.metadata_json = metadata
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Обработан PayPear платеж',
|
||||
order_id=payment.order_id,
|
||||
user_id=payment.user_id,
|
||||
trigger=trigger,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
async def check_paypear_payment_status(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
order_id: str,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Проверяет статус платежа через API."""
|
||||
try:
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
payment = await paypear_crud.get_paypear_payment_by_order_id(db, order_id)
|
||||
if not payment:
|
||||
logger.warning('PayPear payment not found', order_id=order_id)
|
||||
return None
|
||||
|
||||
if payment.is_paid:
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': 'success',
|
||||
'is_paid': True,
|
||||
}
|
||||
|
||||
# Проверяем через API по paypear_id
|
||||
if payment.paypear_id:
|
||||
try:
|
||||
order_data = await paypear_service.get_payment(payment.paypear_id)
|
||||
paypear_status = order_data.get('status')
|
||||
|
||||
if paypear_status:
|
||||
status_info = PAYPEAR_STATUS_MAP.get(paypear_status, ('pending', False))
|
||||
internal_status, is_paid = status_info
|
||||
|
||||
if is_paid:
|
||||
# Проверка суммы
|
||||
amount_info = order_data.get('amount', {})
|
||||
api_amount = amount_info.get('value') if isinstance(amount_info, dict) else amount_info
|
||||
if api_amount is not None:
|
||||
received_kopeks = round(float(api_amount) * 100)
|
||||
if abs(received_kopeks - payment.amount_kopeks) > 1:
|
||||
logger.error(
|
||||
'PayPear amount mismatch (API check)',
|
||||
expected_kopeks=payment.amount_kopeks,
|
||||
received_kopeks=received_kopeks,
|
||||
order_id=payment.order_id,
|
||||
)
|
||||
await paypear_crud.update_paypear_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status='amount_mismatch',
|
||||
is_paid=False,
|
||||
paypear_id=payment.paypear_id,
|
||||
callback_payload={
|
||||
'check_source': 'api',
|
||||
'paypear_order_data': order_data,
|
||||
},
|
||||
)
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': 'amount_mismatch',
|
||||
'is_paid': False,
|
||||
}
|
||||
|
||||
# Acquire FOR UPDATE lock before finalization
|
||||
locked = await paypear_crud.get_paypear_payment_by_id_for_update(db, payment.id)
|
||||
if not locked:
|
||||
logger.error('PayPear: не удалось заблокировать платёж', payment_id=payment.id)
|
||||
return None
|
||||
payment = locked
|
||||
|
||||
if payment.is_paid:
|
||||
logger.info('PayPear платеж уже обработан (api_check)', order_id=payment.order_id)
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': 'success',
|
||||
'is_paid': True,
|
||||
}
|
||||
|
||||
logger.info('PayPear payment confirmed via API', order_id=payment.order_id)
|
||||
|
||||
# Inline field updates — NO intermediate commit that would release FOR UPDATE lock
|
||||
payment.status = 'success'
|
||||
payment.is_paid = True
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
payment.callback_payload = {
|
||||
'check_source': 'api',
|
||||
'paypear_order_data': order_data,
|
||||
}
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
|
||||
await self._finalize_paypear_payment(
|
||||
db,
|
||||
payment,
|
||||
paypear_id=payment.paypear_id,
|
||||
trigger='api_check',
|
||||
)
|
||||
elif internal_status != payment.status:
|
||||
# Обновляем статус если изменился
|
||||
payment = await paypear_crud.update_paypear_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status=internal_status,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error('Error checking PayPear payment status via API', error=e)
|
||||
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': payment.status or 'pending',
|
||||
'is_paid': payment.is_paid,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.exception('PayPear: ошибка проверки статуса', error=e)
|
||||
return None
|
||||
@@ -0,0 +1,629 @@
|
||||
"""Mixin для интеграции с RollyPay (rollypay.io)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from importlib import import_module
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database.models import PaymentMethod, TransactionType
|
||||
from app.services.rollypay_service import rollypay_service
|
||||
from app.utils.payment_logger import payment_logger as logger
|
||||
from app.utils.user_utils import format_referrer_info
|
||||
|
||||
|
||||
# Маппинг статусов RollyPay -> internal
|
||||
ROLLYPAY_STATUS_MAP: dict[str, tuple[str, bool]] = {
|
||||
'created': ('pending', False),
|
||||
'processing': ('processing', False),
|
||||
'paid': ('success', True),
|
||||
'expired': ('expired', False),
|
||||
'canceled': ('canceled', False),
|
||||
'chargeback': ('chargeback', False),
|
||||
}
|
||||
|
||||
|
||||
class RollyPayPaymentMixin:
|
||||
"""Mixin для работы с платежами RollyPay."""
|
||||
|
||||
async def create_rollypay_payment(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
*,
|
||||
user_id: int | None,
|
||||
amount_kopeks: int,
|
||||
description: str = 'Пополнение баланса',
|
||||
email: str | None = None,
|
||||
language: str = 'ru',
|
||||
payment_method_type: str | None = None,
|
||||
return_url: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
Создает платеж RollyPay.
|
||||
|
||||
Returns:
|
||||
Словарь с данными платежа или None при ошибке
|
||||
"""
|
||||
if not settings.is_rollypay_enabled():
|
||||
logger.error('RollyPay не настроен')
|
||||
return None
|
||||
|
||||
# Валидация лимитов
|
||||
if amount_kopeks < settings.ROLLYPAY_MIN_AMOUNT_KOPEKS:
|
||||
logger.warning(
|
||||
'RollyPay: сумма меньше минимальной',
|
||||
amount_kopeks=amount_kopeks,
|
||||
ROLLYPAY_MIN_AMOUNT_KOPEKS=settings.ROLLYPAY_MIN_AMOUNT_KOPEKS,
|
||||
)
|
||||
return None
|
||||
|
||||
if amount_kopeks > settings.ROLLYPAY_MAX_AMOUNT_KOPEKS:
|
||||
logger.warning(
|
||||
'RollyPay: сумма больше максимальной',
|
||||
amount_kopeks=amount_kopeks,
|
||||
ROLLYPAY_MAX_AMOUNT_KOPEKS=settings.ROLLYPAY_MAX_AMOUNT_KOPEKS,
|
||||
)
|
||||
return None
|
||||
|
||||
# Получаем telegram_id пользователя для order_id
|
||||
payment_module = import_module('app.services.payment_service')
|
||||
if user_id is not None:
|
||||
user = await payment_module.get_user_by_id(db, user_id)
|
||||
tg_id = user.telegram_id if user else user_id
|
||||
else:
|
||||
user = None
|
||||
tg_id = 'guest'
|
||||
|
||||
# Генерируем уникальный order_id с telegram_id для удобного поиска
|
||||
order_id = f'rp{tg_id}_{uuid.uuid4().hex[:6]}'
|
||||
amount_rubles = amount_kopeks / 100
|
||||
amount_value = f'{amount_rubles:.2f}'
|
||||
currency = settings.ROLLYPAY_CURRENCY
|
||||
|
||||
# Метаданные
|
||||
metadata = {
|
||||
'user_id': user_id,
|
||||
'amount_kopeks': amount_kopeks,
|
||||
'description': description,
|
||||
'language': language,
|
||||
'type': 'balance_topup',
|
||||
}
|
||||
|
||||
try:
|
||||
# Используем API для создания платежа
|
||||
result = await rollypay_service.create_payment(
|
||||
amount_value=amount_value,
|
||||
currency=currency,
|
||||
order_id=order_id,
|
||||
payment_method=payment_method_type,
|
||||
description=description,
|
||||
redirect_url=return_url or settings.ROLLYPAY_RETURN_URL,
|
||||
customer_id=str(tg_id),
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
payment_url = result.get('pay_url')
|
||||
rollypay_payment_id = result.get('payment_id')
|
||||
|
||||
if not payment_url:
|
||||
logger.error('RollyPay API не вернул URL платежа', result=result)
|
||||
return None
|
||||
|
||||
logger.info(
|
||||
'RollyPay API: создан платеж',
|
||||
order_id=order_id,
|
||||
rollypay_payment_id=rollypay_payment_id,
|
||||
payment_url=payment_url,
|
||||
)
|
||||
|
||||
# Срок действия из expires_at ответа или 30 минут по умолчанию
|
||||
expires_at_str = result.get('expires_at')
|
||||
if expires_at_str:
|
||||
try:
|
||||
expires_at = datetime.fromisoformat(expires_at_str)
|
||||
if expires_at.tzinfo is None:
|
||||
expires_at = expires_at.replace(tzinfo=UTC)
|
||||
except (ValueError, TypeError):
|
||||
expires_at = datetime.now(UTC) + timedelta(minutes=30)
|
||||
else:
|
||||
expires_at = datetime.now(UTC) + timedelta(minutes=30)
|
||||
|
||||
# Сохраняем в БД
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
local_payment = await rollypay_crud.create_rollypay_payment(
|
||||
db=db,
|
||||
user_id=user_id,
|
||||
order_id=order_id,
|
||||
amount_kopeks=amount_kopeks,
|
||||
currency=currency,
|
||||
description=description,
|
||||
payment_url=payment_url,
|
||||
payment_method=payment_method_type or 'sbp',
|
||||
rollypay_payment_id=rollypay_payment_id,
|
||||
expires_at=expires_at,
|
||||
metadata_json=metadata,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
'RollyPay: создан платеж',
|
||||
order_id=order_id,
|
||||
user_id=user_id,
|
||||
amount_rubles=amount_rubles,
|
||||
currency=currency,
|
||||
)
|
||||
|
||||
return {
|
||||
'order_id': order_id,
|
||||
'rollypay_payment_id': rollypay_payment_id,
|
||||
'amount_kopeks': amount_kopeks,
|
||||
'amount_rubles': amount_rubles,
|
||||
'currency': currency,
|
||||
'payment_url': payment_url,
|
||||
'expires_at': expires_at.isoformat(),
|
||||
'local_payment_id': local_payment.id,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.exception('RollyPay: ошибка создания платежа', error=e)
|
||||
return None
|
||||
|
||||
async def process_rollypay_webhook(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
payload: dict[str, Any],
|
||||
) -> bool:
|
||||
"""
|
||||
Обрабатывает webhook от RollyPay.
|
||||
|
||||
Подпись проверяется в webserver/payments.py до вызова этого метода.
|
||||
|
||||
Args:
|
||||
db: Сессия БД
|
||||
payload: JSON тело webhook (signature проверена в webserver)
|
||||
|
||||
Returns:
|
||||
True если платеж успешно обработан
|
||||
"""
|
||||
try:
|
||||
event_type = payload.get('event_type')
|
||||
rollypay_payment_id = payload.get('payment_id')
|
||||
order_id = payload.get('order_id')
|
||||
rollypay_status = payload.get('status')
|
||||
|
||||
if not rollypay_payment_id or not rollypay_status:
|
||||
logger.warning('RollyPay webhook: отсутствуют обязательные поля', payload=payload)
|
||||
return False
|
||||
|
||||
# Определяем is_paid по event
|
||||
is_confirmed = event_type == 'payment.paid'
|
||||
|
||||
# Ищем платеж по order_id (наш) или rollypay_payment_id
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
payment = None
|
||||
if order_id:
|
||||
payment = await rollypay_crud.get_rollypay_payment_by_order_id(db, order_id)
|
||||
if not payment and rollypay_payment_id:
|
||||
payment = await rollypay_crud.get_rollypay_payment_by_rollypay_id(db, rollypay_payment_id)
|
||||
|
||||
if not payment:
|
||||
logger.warning(
|
||||
'RollyPay webhook: платеж не найден',
|
||||
order_id=order_id,
|
||||
rollypay_payment_id=rollypay_payment_id,
|
||||
)
|
||||
return False
|
||||
|
||||
# Lock payment row immediately to prevent concurrent webhook processing (TOCTOU race)
|
||||
locked = await rollypay_crud.get_rollypay_payment_by_id_for_update(db, payment.id)
|
||||
if not locked:
|
||||
logger.error('RollyPay: не удалось заблокировать платёж', payment_id=payment.id)
|
||||
return False
|
||||
payment = locked
|
||||
|
||||
# Проверка дублирования (re-check from locked row)
|
||||
if payment.is_paid:
|
||||
logger.info('RollyPay webhook: платеж уже обработан', order_id=payment.order_id)
|
||||
return True
|
||||
|
||||
# Маппинг статуса
|
||||
status_info = ROLLYPAY_STATUS_MAP.get(rollypay_status, ('pending', False))
|
||||
internal_status, is_paid = status_info
|
||||
|
||||
# Если event = payment.paid, принудительно считаем оплаченным
|
||||
if is_confirmed:
|
||||
is_paid = True
|
||||
internal_status = 'success'
|
||||
|
||||
callback_payload = {
|
||||
'rollypay_payment_id': rollypay_payment_id,
|
||||
'order_id': order_id,
|
||||
'status': rollypay_status,
|
||||
'event_type': event_type,
|
||||
'amount': payload.get('amount'),
|
||||
'currency': payload.get('currency'),
|
||||
}
|
||||
|
||||
# Проверка суммы ДО обновления статуса
|
||||
if is_paid:
|
||||
amount_value = payload.get('amount')
|
||||
if amount_value is not None:
|
||||
received_kopeks = round(float(amount_value) * 100)
|
||||
if abs(received_kopeks - payment.amount_kopeks) > 1:
|
||||
logger.error(
|
||||
'RollyPay amount mismatch',
|
||||
expected_kopeks=payment.amount_kopeks,
|
||||
received_kopeks=received_kopeks,
|
||||
order_id=payment.order_id,
|
||||
)
|
||||
await rollypay_crud.update_rollypay_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status='amount_mismatch',
|
||||
is_paid=False,
|
||||
rollypay_payment_id=rollypay_payment_id,
|
||||
callback_payload=callback_payload,
|
||||
)
|
||||
return False
|
||||
|
||||
# Финализируем платеж если оплачен — без промежуточного commit
|
||||
if is_paid:
|
||||
# Inline field assignments to keep FOR UPDATE lock intact
|
||||
payment.status = internal_status
|
||||
payment.is_paid = True
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
payment.rollypay_payment_id = rollypay_payment_id or payment.rollypay_payment_id
|
||||
payment.callback_payload = callback_payload
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
return await self._finalize_rollypay_payment(
|
||||
db, payment, rollypay_payment_id=rollypay_payment_id, trigger='webhook'
|
||||
)
|
||||
|
||||
# Для не-success статусов можно безопасно коммитить
|
||||
payment = await rollypay_crud.update_rollypay_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status=internal_status,
|
||||
is_paid=False,
|
||||
rollypay_payment_id=rollypay_payment_id,
|
||||
callback_payload=callback_payload,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.exception('RollyPay webhook: ошибка обработки', error=e)
|
||||
return False
|
||||
|
||||
async def _finalize_rollypay_payment(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
payment: Any,
|
||||
*,
|
||||
rollypay_payment_id: str | None,
|
||||
trigger: str,
|
||||
) -> bool:
|
||||
"""Создаёт транзакцию, начисляет баланс и отправляет уведомления.
|
||||
|
||||
FOR UPDATE lock must be acquired by the caller before invoking this method.
|
||||
"""
|
||||
payment_module = import_module('app.services.payment_service')
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
|
||||
# FOR UPDATE lock already acquired by caller — just check idempotency
|
||||
if payment.transaction_id:
|
||||
logger.info(
|
||||
'RollyPay платеж уже связан с транзакцией',
|
||||
order_id=payment.order_id,
|
||||
transaction_id=payment.transaction_id,
|
||||
trigger=trigger,
|
||||
)
|
||||
return True
|
||||
|
||||
# Read fresh metadata AFTER lock to avoid stale data
|
||||
metadata = dict(getattr(payment, 'metadata_json', {}) or {})
|
||||
|
||||
# --- Guest purchase flow ---
|
||||
from app.services.payment.common import try_fulfill_guest_purchase
|
||||
|
||||
guest_result = await try_fulfill_guest_purchase(
|
||||
db,
|
||||
metadata=metadata,
|
||||
payment_amount_kopeks=payment.amount_kopeks,
|
||||
provider_payment_id=str(rollypay_payment_id) if rollypay_payment_id else payment.order_id,
|
||||
provider_name='rollypay',
|
||||
)
|
||||
if guest_result is not None:
|
||||
return True
|
||||
|
||||
# Ensure paid fields are set (idempotent — caller may have already set them)
|
||||
if not payment.is_paid:
|
||||
payment.status = 'success'
|
||||
payment.is_paid = True
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
|
||||
balance_already_credited = bool(metadata.get('balance_credited'))
|
||||
|
||||
user = await payment_module.get_user_by_id(db, payment.user_id)
|
||||
if not user:
|
||||
logger.error('Пользователь не найден для RollyPay', user_id=payment.user_id)
|
||||
return False
|
||||
|
||||
# Загружаем промогруппы в асинхронном контексте
|
||||
await db.refresh(user, attribute_names=['promo_group', 'user_promo_groups'])
|
||||
for user_promo_group in getattr(user, 'user_promo_groups', []):
|
||||
await db.refresh(user_promo_group, attribute_names=['promo_group'])
|
||||
|
||||
promo_group = user.get_primary_promo_group()
|
||||
subscription = getattr(user, 'subscription', None)
|
||||
referrer_info = format_referrer_info(user)
|
||||
|
||||
transaction_external_id = str(rollypay_payment_id) if rollypay_payment_id else payment.order_id
|
||||
|
||||
# Проверяем дупликат транзакции
|
||||
existing_transaction = None
|
||||
if transaction_external_id:
|
||||
existing_transaction = await payment_module.get_transaction_by_external_id(
|
||||
db,
|
||||
transaction_external_id,
|
||||
PaymentMethod.ROLLYPAY,
|
||||
)
|
||||
|
||||
display_name = settings.get_rollypay_display_name()
|
||||
description = f'Пополнение через {display_name}'
|
||||
|
||||
transaction = existing_transaction
|
||||
created_transaction = False
|
||||
|
||||
if not transaction:
|
||||
transaction = await payment_module.create_transaction(
|
||||
db,
|
||||
user_id=payment.user_id,
|
||||
type=TransactionType.DEPOSIT,
|
||||
amount_kopeks=payment.amount_kopeks,
|
||||
description=description,
|
||||
payment_method=PaymentMethod.ROLLYPAY,
|
||||
external_id=transaction_external_id,
|
||||
is_completed=True,
|
||||
created_at=getattr(payment, 'created_at', None),
|
||||
commit=False,
|
||||
)
|
||||
created_transaction = True
|
||||
|
||||
await rollypay_crud.link_rollypay_payment_to_transaction(db, payment=payment, transaction_id=transaction.id)
|
||||
|
||||
should_credit_balance = created_transaction or not balance_already_credited
|
||||
|
||||
if not should_credit_balance:
|
||||
logger.info('RollyPay платеж уже зачислил баланс ранее', order_id=payment.order_id)
|
||||
return True
|
||||
|
||||
# Lock user row to prevent concurrent balance race conditions
|
||||
from app.database.crud.user import lock_user_for_update
|
||||
|
||||
user = await lock_user_for_update(db, user)
|
||||
|
||||
old_balance = user.balance_kopeks
|
||||
was_first_topup = not user.has_made_first_topup
|
||||
|
||||
user.balance_kopeks += payment.amount_kopeks
|
||||
user.updated_at = datetime.now(UTC)
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
# Emit deferred side-effects after atomic commit
|
||||
from app.database.crud.transaction import emit_transaction_side_effects
|
||||
|
||||
await emit_transaction_side_effects(
|
||||
db,
|
||||
transaction,
|
||||
amount_kopeks=payment.amount_kopeks,
|
||||
user_id=payment.user_id,
|
||||
type=TransactionType.DEPOSIT,
|
||||
payment_method=PaymentMethod.ROLLYPAY,
|
||||
external_id=transaction_external_id,
|
||||
)
|
||||
|
||||
topup_status = '\U0001f195 Первое пополнение' if was_first_topup else '\U0001f504 Пополнение'
|
||||
|
||||
try:
|
||||
from app.services.referral_service import process_referral_topup
|
||||
|
||||
await process_referral_topup(
|
||||
db,
|
||||
user.id,
|
||||
payment.amount_kopeks,
|
||||
getattr(self, 'bot', None),
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error('Ошибка обработки реферального пополнения RollyPay', error=error)
|
||||
|
||||
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
|
||||
user.has_made_first_topup = True
|
||||
await db.commit()
|
||||
await db.refresh(user)
|
||||
|
||||
if getattr(self, 'bot', None):
|
||||
try:
|
||||
from app.services.admin_notification_service import AdminNotificationService
|
||||
|
||||
notification_service = AdminNotificationService(self.bot)
|
||||
await notification_service.send_balance_topup_notification(
|
||||
user,
|
||||
transaction,
|
||||
old_balance,
|
||||
topup_status=topup_status,
|
||||
referrer_info=referrer_info,
|
||||
subscription=subscription,
|
||||
promo_group=promo_group,
|
||||
db=db,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error('Ошибка отправки админ уведомления RollyPay', error=error)
|
||||
|
||||
if getattr(self, 'bot', None) and user.telegram_id:
|
||||
try:
|
||||
keyboard = await self.build_topup_success_keyboard(user)
|
||||
await self.bot.send_message(
|
||||
user.telegram_id,
|
||||
(
|
||||
'\u2705 <b>Пополнение успешно!</b>\n\n'
|
||||
f'\U0001f4b0 Сумма: {settings.format_price(payment.amount_kopeks)}\n'
|
||||
f'\U0001f4b3 Способ: {display_name}\n'
|
||||
f'\U0001f194 Транзакция: {transaction.id}\n\n'
|
||||
'Баланс пополнен автоматически!'
|
||||
),
|
||||
parse_mode='HTML',
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
except Exception as error:
|
||||
logger.error('Ошибка отправки уведомления пользователю RollyPay', error=error)
|
||||
|
||||
try:
|
||||
from app.services.payment.common import send_cart_notification_after_topup
|
||||
|
||||
await send_cart_notification_after_topup(user, payment.amount_kopeks, db, getattr(self, 'bot', None))
|
||||
except Exception as error:
|
||||
logger.error(
|
||||
'Ошибка при работе с сохраненной корзиной для пользователя',
|
||||
user_id=payment.user_id,
|
||||
error=error,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
metadata['balance_change'] = {
|
||||
'old_balance': old_balance,
|
||||
'new_balance': user.balance_kopeks,
|
||||
'credited_at': datetime.now(UTC).isoformat(),
|
||||
}
|
||||
metadata['balance_credited'] = True
|
||||
payment.metadata_json = metadata
|
||||
await db.commit()
|
||||
|
||||
logger.info(
|
||||
'Обработан RollyPay платеж',
|
||||
order_id=payment.order_id,
|
||||
user_id=payment.user_id,
|
||||
trigger=trigger,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
async def check_rollypay_payment_status(
|
||||
self,
|
||||
db: AsyncSession,
|
||||
order_id: str,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Проверяет статус платежа через API."""
|
||||
try:
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
payment = await rollypay_crud.get_rollypay_payment_by_order_id(db, order_id)
|
||||
if not payment:
|
||||
logger.warning('RollyPay payment not found', order_id=order_id)
|
||||
return None
|
||||
|
||||
if payment.is_paid:
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': 'success',
|
||||
'is_paid': True,
|
||||
}
|
||||
|
||||
# Проверяем через API по rollypay_payment_id
|
||||
if payment.rollypay_payment_id:
|
||||
try:
|
||||
order_data = await rollypay_service.get_payment(payment.rollypay_payment_id)
|
||||
rollypay_status = order_data.get('status')
|
||||
|
||||
if rollypay_status:
|
||||
status_info = ROLLYPAY_STATUS_MAP.get(rollypay_status, ('pending', False))
|
||||
internal_status, is_paid = status_info
|
||||
|
||||
if is_paid:
|
||||
# Проверка суммы
|
||||
api_amount = order_data.get('amount')
|
||||
if api_amount is not None:
|
||||
received_kopeks = round(float(api_amount) * 100)
|
||||
if abs(received_kopeks - payment.amount_kopeks) > 1:
|
||||
logger.error(
|
||||
'RollyPay amount mismatch (API check)',
|
||||
expected_kopeks=payment.amount_kopeks,
|
||||
received_kopeks=received_kopeks,
|
||||
order_id=payment.order_id,
|
||||
)
|
||||
await rollypay_crud.update_rollypay_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status='amount_mismatch',
|
||||
is_paid=False,
|
||||
rollypay_payment_id=payment.rollypay_payment_id,
|
||||
callback_payload={
|
||||
'check_source': 'api',
|
||||
'rollypay_order_data': order_data,
|
||||
},
|
||||
)
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': 'amount_mismatch',
|
||||
'is_paid': False,
|
||||
}
|
||||
|
||||
# Acquire FOR UPDATE lock before finalization
|
||||
locked = await rollypay_crud.get_rollypay_payment_by_id_for_update(db, payment.id)
|
||||
if not locked:
|
||||
logger.error('RollyPay: не удалось заблокировать платёж', payment_id=payment.id)
|
||||
return None
|
||||
payment = locked
|
||||
|
||||
if payment.is_paid:
|
||||
logger.info('RollyPay платеж уже обработан (api_check)', order_id=payment.order_id)
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': 'success',
|
||||
'is_paid': True,
|
||||
}
|
||||
|
||||
logger.info('RollyPay payment confirmed via API', order_id=payment.order_id)
|
||||
|
||||
# Inline field updates — NO intermediate commit that would release FOR UPDATE lock
|
||||
payment.status = 'success'
|
||||
payment.is_paid = True
|
||||
payment.paid_at = datetime.now(UTC)
|
||||
payment.callback_payload = {
|
||||
'check_source': 'api',
|
||||
'rollypay_order_data': order_data,
|
||||
}
|
||||
payment.updated_at = datetime.now(UTC)
|
||||
await db.flush()
|
||||
|
||||
await self._finalize_rollypay_payment(
|
||||
db,
|
||||
payment,
|
||||
rollypay_payment_id=payment.rollypay_payment_id,
|
||||
trigger='api_check',
|
||||
)
|
||||
elif internal_status != payment.status:
|
||||
# Обновляем статус если изменился
|
||||
payment = await rollypay_crud.update_rollypay_payment_status(
|
||||
db=db,
|
||||
payment=payment,
|
||||
status=internal_status,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error('Error checking RollyPay payment status via API', error=e)
|
||||
|
||||
return {
|
||||
'payment': payment,
|
||||
'status': payment.status or 'pending',
|
||||
'is_paid': payment.is_paid,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.exception('RollyPay: ошибка проверки статуса', error=e)
|
||||
return None
|
||||
@@ -73,6 +73,7 @@ class SeverPayPaymentMixin:
|
||||
user = await payment_module.get_user_by_id(db, user_id)
|
||||
tg_id = user.telegram_id if user else user_id
|
||||
else:
|
||||
user = None
|
||||
tg_id = 'guest'
|
||||
|
||||
# Генерируем уникальный order_id с telegram_id для удобного поиска
|
||||
@@ -94,12 +95,17 @@ class SeverPayPaymentMixin:
|
||||
}
|
||||
|
||||
try:
|
||||
# SeverPay требует обязательный client_email
|
||||
target_email = email or (
|
||||
f'{user.telegram_id}@telegram.org' if user and user.telegram_id else f'{tg_id}@telegram.org'
|
||||
)
|
||||
|
||||
# Используем API для создания платежа
|
||||
result = await severpay_service.create_payment(
|
||||
order_id=order_id,
|
||||
amount=amount_rubles,
|
||||
currency=currency,
|
||||
client_email=email or '',
|
||||
client_email=target_email,
|
||||
client_id=str(tg_id),
|
||||
url_return=return_url or settings.SEVERPAY_RETURN_URL,
|
||||
lifetime=lifetime,
|
||||
|
||||
@@ -286,6 +286,13 @@ class TelegramStarsMixin:
|
||||
sync_error=sync_error,
|
||||
exc_info=True,
|
||||
)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
period_display = period_days
|
||||
if not period_display and getattr(subscription, 'start_date', None) and getattr(subscription, 'end_date', None):
|
||||
|
||||
@@ -680,6 +680,13 @@ class YooKassaPaymentMixin:
|
||||
await subscription_service.create_remnawave_user(db, subscription)
|
||||
except Exception as rw_error:
|
||||
logger.error('Ошибка создания RemnaWave для триала', rw_error=rw_error)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Уведомление админам
|
||||
if getattr(self, 'bot', None):
|
||||
@@ -991,6 +998,13 @@ class YooKassaPaymentMixin:
|
||||
sync_error=sync_error,
|
||||
exc_info=True,
|
||||
)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='create',
|
||||
)
|
||||
|
||||
# Отправляем уведомление пользователю об активации подписки (только Telegram)
|
||||
if getattr(self, 'bot', None) and user.telegram_id:
|
||||
|
||||
@@ -129,6 +129,7 @@ def _get_method_defaults() -> dict:
|
||||
'available_sub_options': [
|
||||
{'id': 'sbp', 'name': 'СБП'},
|
||||
{'id': 'card', 'name': 'Карта'},
|
||||
{'id': 'sberpay', 'name': 'SberPay'},
|
||||
],
|
||||
},
|
||||
'riopay': {
|
||||
@@ -145,6 +146,39 @@ def _get_method_defaults() -> dict:
|
||||
'default_max': settings.SEVERPAY_MAX_AMOUNT_KOPEKS,
|
||||
'available_sub_options': None,
|
||||
},
|
||||
'paypear': {
|
||||
'default_display_name': settings.get_paypear_display_name(),
|
||||
'is_configured': settings.is_paypear_enabled(),
|
||||
'default_min': settings.PAYPEAR_MIN_AMOUNT_KOPEKS,
|
||||
'default_max': settings.PAYPEAR_MAX_AMOUNT_KOPEKS,
|
||||
'available_sub_options': [
|
||||
{'id': 'bank_card', 'name': 'Карта'},
|
||||
{'id': 'sbp', 'name': 'СБП'},
|
||||
{'id': 'sberpay', 'name': 'SberPay'},
|
||||
{'id': 'tpay', 'name': 'T-Pay'},
|
||||
],
|
||||
},
|
||||
'rollypay': {
|
||||
'default_display_name': settings.get_rollypay_display_name(),
|
||||
'is_configured': settings.is_rollypay_enabled(),
|
||||
'default_min': settings.ROLLYPAY_MIN_AMOUNT_KOPEKS,
|
||||
'default_max': settings.ROLLYPAY_MAX_AMOUNT_KOPEKS,
|
||||
'available_sub_options': [
|
||||
{'id': 'sbp', 'name': 'СБП'},
|
||||
{'id': 'card', 'name': 'Карта'},
|
||||
{'id': 'crypto', 'name': 'Криптовалюта'},
|
||||
],
|
||||
},
|
||||
'aurapay': {
|
||||
'default_display_name': settings.get_aurapay_display_name(),
|
||||
'is_configured': settings.is_aurapay_enabled(),
|
||||
'default_min': settings.AURAPAY_MIN_AMOUNT_KOPEKS,
|
||||
'default_max': settings.AURAPAY_MAX_AMOUNT_KOPEKS,
|
||||
'available_sub_options': [
|
||||
{'id': 'card', 'name': 'Карта'},
|
||||
{'id': 'sbp', 'name': 'СБП'},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -187,6 +221,9 @@ DEFAULT_METHOD_ORDER = [
|
||||
'kassa_ai',
|
||||
'riopay',
|
||||
'severpay',
|
||||
'paypear',
|
||||
'rollypay',
|
||||
'aurapay',
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -30,10 +30,13 @@ from app.services.payment import (
|
||||
WataPaymentMixin,
|
||||
YooKassaPaymentMixin,
|
||||
)
|
||||
from app.services.payment.aurapay import AuraPayPaymentMixin
|
||||
from app.services.payment.cloudpayments import CloudPaymentsPaymentMixin
|
||||
from app.services.payment.freekassa import FreekassaPaymentMixin
|
||||
from app.services.payment.kassa_ai import KassaAiPaymentMixin
|
||||
from app.services.payment.paypear import PayPearPaymentMixin
|
||||
from app.services.payment.riopay import RioPayPaymentMixin
|
||||
from app.services.payment.rollypay import RollyPayPaymentMixin
|
||||
from app.services.payment.severpay import SeverPayPaymentMixin
|
||||
from app.services.platega_service import PlategaService
|
||||
from app.services.wata_service import WataService
|
||||
@@ -332,6 +335,114 @@ async def link_severpay_payment_to_transaction(*args, **kwargs):
|
||||
return await severpay_crud.link_severpay_payment_to_transaction(*args, **kwargs)
|
||||
|
||||
|
||||
async def create_paypear_payment(*args, **kwargs):
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
return await paypear_crud.create_paypear_payment(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_paypear_payment_by_order_id(*args, **kwargs):
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
return await paypear_crud.get_paypear_payment_by_order_id(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_paypear_payment_by_paypear_id(*args, **kwargs):
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
return await paypear_crud.get_paypear_payment_by_paypear_id(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_paypear_payment_by_id(*args, **kwargs):
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
return await paypear_crud.get_paypear_payment_by_id(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_paypear_payment_by_id_for_update(*args, **kwargs):
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
return await paypear_crud.get_paypear_payment_by_id_for_update(*args, **kwargs)
|
||||
|
||||
|
||||
async def update_paypear_payment_status(*args, **kwargs):
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
return await paypear_crud.update_paypear_payment_status(*args, **kwargs)
|
||||
|
||||
|
||||
async def link_paypear_payment_to_transaction(*args, **kwargs):
|
||||
paypear_crud = import_module('app.database.crud.paypear')
|
||||
return await paypear_crud.link_paypear_payment_to_transaction(*args, **kwargs)
|
||||
|
||||
|
||||
# --- RollyPay CRUD wrappers ---
|
||||
|
||||
|
||||
async def create_rollypay_payment(*args, **kwargs):
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
return await rollypay_crud.create_rollypay_payment(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_rollypay_payment_by_order_id(*args, **kwargs):
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
return await rollypay_crud.get_rollypay_payment_by_order_id(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_rollypay_payment_by_rollypay_id(*args, **kwargs):
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
return await rollypay_crud.get_rollypay_payment_by_rollypay_id(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_rollypay_payment_by_id(*args, **kwargs):
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
return await rollypay_crud.get_rollypay_payment_by_id(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_rollypay_payment_by_id_for_update(*args, **kwargs):
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
return await rollypay_crud.get_rollypay_payment_by_id_for_update(*args, **kwargs)
|
||||
|
||||
|
||||
async def update_rollypay_payment_status(*args, **kwargs):
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
return await rollypay_crud.update_rollypay_payment_status(*args, **kwargs)
|
||||
|
||||
|
||||
async def link_rollypay_payment_to_transaction(*args, **kwargs):
|
||||
rollypay_crud = import_module('app.database.crud.rollypay')
|
||||
return await rollypay_crud.link_rollypay_payment_to_transaction(*args, **kwargs)
|
||||
|
||||
|
||||
async def create_aurapay_payment(*args, **kwargs):
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
return await aurapay_crud.create_aurapay_payment(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_aurapay_payment_by_order_id(*args, **kwargs):
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
return await aurapay_crud.get_aurapay_payment_by_order_id(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_aurapay_payment_by_invoice_id(*args, **kwargs):
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
return await aurapay_crud.get_aurapay_payment_by_invoice_id(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_aurapay_payment_by_id(*args, **kwargs):
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
return await aurapay_crud.get_aurapay_payment_by_id(*args, **kwargs)
|
||||
|
||||
|
||||
async def get_aurapay_payment_by_id_for_update(*args, **kwargs):
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
return await aurapay_crud.get_aurapay_payment_by_id_for_update(*args, **kwargs)
|
||||
|
||||
|
||||
async def update_aurapay_payment_status(*args, **kwargs):
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
return await aurapay_crud.update_aurapay_payment_status(*args, **kwargs)
|
||||
|
||||
|
||||
async def link_aurapay_payment_to_transaction(*args, **kwargs):
|
||||
aurapay_crud = import_module('app.database.crud.aurapay')
|
||||
return await aurapay_crud.link_aurapay_payment_to_transaction(*args, **kwargs)
|
||||
|
||||
|
||||
# Mapping from model_name to getter function name for providers
|
||||
# where it differs from the standard get_{model_name}_payment_by_id pattern.
|
||||
_GETTER_OVERRIDES: dict[str, str] = {
|
||||
@@ -355,6 +466,9 @@ class PaymentService(
|
||||
KassaAiPaymentMixin,
|
||||
RioPayPaymentMixin,
|
||||
SeverPayPaymentMixin,
|
||||
PayPearPaymentMixin,
|
||||
RollyPayPaymentMixin,
|
||||
AuraPayPaymentMixin,
|
||||
):
|
||||
"""Основной интерфейс платежей, делегирующий работу специализированным mixin-ам."""
|
||||
|
||||
@@ -703,7 +817,7 @@ class PaymentService(
|
||||
return None
|
||||
|
||||
# --- KassaAI ----------------------------------------------------------
|
||||
if payment_method in ('kassa_ai', 'kassa_ai_sbp', 'kassa_ai_card'):
|
||||
if payment_method in ('kassa_ai', 'kassa_ai_sbp', 'kassa_ai_card', 'kassa_ai_sberpay'):
|
||||
if not settings.is_kassa_ai_enabled():
|
||||
logger.warning('KassaAI is not enabled, cannot create guest payment')
|
||||
return None
|
||||
@@ -774,6 +888,72 @@ class PaymentService(
|
||||
}
|
||||
return None
|
||||
|
||||
# --- PayPear ----------------------------------------------------------
|
||||
if payment_method == 'paypear':
|
||||
if not settings.is_paypear_enabled():
|
||||
logger.warning('PayPear is not enabled, cannot create guest payment')
|
||||
return None
|
||||
|
||||
result = await self.create_paypear_payment(
|
||||
db=db,
|
||||
user_id=None,
|
||||
amount_kopeks=amount_kopeks,
|
||||
description=description,
|
||||
return_url=return_url,
|
||||
)
|
||||
if result:
|
||||
await _patch_guest_metadata(result['local_payment_id'], 'paypear')
|
||||
return {
|
||||
'payment_url': result.get('payment_url'),
|
||||
'payment_id': result.get('paypear_id') or result.get('order_id'),
|
||||
'provider': 'paypear',
|
||||
}
|
||||
return None
|
||||
|
||||
# --- RollyPay ---------------------------------------------------------
|
||||
if payment_method == 'rollypay':
|
||||
if not settings.is_rollypay_enabled():
|
||||
logger.warning('RollyPay is not enabled, cannot create guest payment')
|
||||
return None
|
||||
|
||||
result = await self.create_rollypay_payment(
|
||||
db=db,
|
||||
user_id=None,
|
||||
amount_kopeks=amount_kopeks,
|
||||
description=description,
|
||||
return_url=return_url,
|
||||
)
|
||||
if result:
|
||||
await _patch_guest_metadata(result['local_payment_id'], 'rollypay')
|
||||
return {
|
||||
'payment_url': result.get('payment_url'),
|
||||
'payment_id': result.get('rollypay_payment_id') or result.get('order_id'),
|
||||
'provider': 'rollypay',
|
||||
}
|
||||
return None
|
||||
|
||||
# --- AuraPay ----------------------------------------------------------
|
||||
if payment_method == 'aurapay':
|
||||
if not settings.is_aurapay_enabled():
|
||||
logger.warning('AuraPay is not enabled, cannot create guest payment')
|
||||
return None
|
||||
|
||||
result = await self.create_aurapay_payment(
|
||||
db=db,
|
||||
user_id=None,
|
||||
amount_kopeks=amount_kopeks,
|
||||
description=description,
|
||||
return_url=return_url,
|
||||
)
|
||||
if result:
|
||||
await _patch_guest_metadata(result['local_payment_id'], 'aurapay')
|
||||
return {
|
||||
'payment_url': result.get('payment_url'),
|
||||
'payment_id': result.get('aurapay_invoice_id') or result.get('order_id'),
|
||||
'provider': 'aurapay',
|
||||
}
|
||||
return None
|
||||
|
||||
# --- Telegram Stars ---------------------------------------------------
|
||||
if payment_method == 'telegram_stars':
|
||||
if not settings.TELEGRAM_STARS_ENABLED:
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Сервис для работы с API PayPear (paypear.ru)."""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import uuid
|
||||
from base64 import b64encode
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
import structlog
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
API_BASE_URL = 'https://api.paypear.ru/v1'
|
||||
|
||||
|
||||
class PayPearAPIError(Exception):
|
||||
"""Ошибка API PayPear."""
|
||||
|
||||
def __init__(self, status_code: int, message: str):
|
||||
self.status_code = status_code
|
||||
self.message = message
|
||||
super().__init__(f'PayPear API error ({status_code}): {message}')
|
||||
|
||||
|
||||
class PayPearService:
|
||||
"""Сервис для работы с API PayPear."""
|
||||
|
||||
def __init__(self):
|
||||
self._session: aiohttp.ClientSession | None = None
|
||||
|
||||
@property
|
||||
def shop_id(self) -> str:
|
||||
return settings.PAYPEAR_SHOP_ID or ''
|
||||
|
||||
@property
|
||||
def secret_key(self) -> str:
|
||||
return settings.PAYPEAR_SECRET_KEY or ''
|
||||
|
||||
def _basic_auth_header(self) -> str:
|
||||
"""Генерирует HTTP Basic Auth заголовок."""
|
||||
credentials = f'{self.shop_id}:{self.secret_key}'
|
||||
encoded = b64encode(credentials.encode('utf-8')).decode('utf-8')
|
||||
return f'Basic {encoded}'
|
||||
|
||||
async def _get_session(self) -> aiohttp.ClientSession:
|
||||
"""Возвращает переиспользуемую HTTP-сессию."""
|
||||
if self._session is None or self._session.closed:
|
||||
self._session = aiohttp.ClientSession(
|
||||
timeout=aiohttp.ClientTimeout(total=30),
|
||||
)
|
||||
return self._session
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Закрывает HTTP-сессию."""
|
||||
if self._session and not self._session.closed:
|
||||
await self._session.close()
|
||||
self._session = None
|
||||
|
||||
async def create_payment(
|
||||
self,
|
||||
*,
|
||||
order_id: str,
|
||||
amount_rubles: float,
|
||||
currency: str = 'RUB',
|
||||
payment_method_type: str = 'sbp',
|
||||
description: str = '',
|
||||
return_url: str | None = None,
|
||||
webhook_url: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Создает платеж через API PayPear.
|
||||
POST /v1/payment/
|
||||
"""
|
||||
idempotence_key = str(uuid.uuid4())
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
'amount': {
|
||||
'value': f'{amount_rubles:.2f}',
|
||||
'currency': currency,
|
||||
},
|
||||
'order_id': order_id,
|
||||
'payment_method_data': {
|
||||
'type': payment_method_type,
|
||||
},
|
||||
}
|
||||
|
||||
if description:
|
||||
payload['description'] = description
|
||||
if return_url:
|
||||
payload['confirmation'] = {
|
||||
'type': 'redirect',
|
||||
'return_url': return_url,
|
||||
}
|
||||
if webhook_url:
|
||||
payload['webhook_url'] = webhook_url
|
||||
if metadata:
|
||||
payload['metadata'] = metadata
|
||||
|
||||
logger.info(
|
||||
'PayPear API create_payment',
|
||||
order_id=order_id,
|
||||
amount_rubles=amount_rubles,
|
||||
currency=currency,
|
||||
payment_method_type=payment_method_type,
|
||||
)
|
||||
|
||||
try:
|
||||
session = await self._get_session()
|
||||
async with session.post(
|
||||
f'{API_BASE_URL}/payment/',
|
||||
json=payload,
|
||||
headers={
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': self._basic_auth_header(),
|
||||
'Idempotence-Key': idempotence_key,
|
||||
},
|
||||
) as response:
|
||||
data = await response.json(content_type=None)
|
||||
|
||||
if response.status == 200 and data.get('success') is True:
|
||||
result = data.get('result', {})
|
||||
logger.info(
|
||||
'PayPear API payment created',
|
||||
order_id=order_id,
|
||||
paypear_id=result.get('id'),
|
||||
)
|
||||
return result
|
||||
|
||||
error_msg = data.get('message') or data.get('error') or str(data)
|
||||
logger.error(
|
||||
'PayPear create_payment error',
|
||||
status_code=response.status,
|
||||
error_msg=error_msg,
|
||||
response_data=data,
|
||||
)
|
||||
raise PayPearAPIError(response.status, error_msg)
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.exception('PayPear API connection error', error=e)
|
||||
raise
|
||||
|
||||
async def get_payment(self, payment_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
Получает информацию о платеже по ID.
|
||||
GET /v1/payment/{id}/
|
||||
"""
|
||||
logger.info('PayPear get_payment', payment_id=payment_id)
|
||||
|
||||
try:
|
||||
session = await self._get_session()
|
||||
async with session.get(
|
||||
f'{API_BASE_URL}/payment/{payment_id}/',
|
||||
headers={
|
||||
'Authorization': self._basic_auth_header(),
|
||||
},
|
||||
) as response:
|
||||
data = await response.json(content_type=None)
|
||||
|
||||
if response.status == 200 and data.get('success') is True:
|
||||
return data.get('result', {})
|
||||
|
||||
error_msg = data.get('message') or data.get('error') or str(data)
|
||||
logger.error(
|
||||
'PayPear get_payment error',
|
||||
status_code=response.status,
|
||||
error_msg=error_msg,
|
||||
)
|
||||
raise PayPearAPIError(response.status, error_msg)
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.exception('PayPear API connection error', error=e)
|
||||
raise
|
||||
|
||||
async def get_payment_by_order_id(self, order_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
Получает информацию о платеже по order_id.
|
||||
GET /v1/payment/order/{order_id}/
|
||||
"""
|
||||
logger.info('PayPear get_payment_by_order_id', order_id=order_id)
|
||||
|
||||
try:
|
||||
session = await self._get_session()
|
||||
async with session.get(
|
||||
f'{API_BASE_URL}/payment/order/{order_id}/',
|
||||
headers={
|
||||
'Authorization': self._basic_auth_header(),
|
||||
},
|
||||
) as response:
|
||||
data = await response.json(content_type=None)
|
||||
|
||||
if response.status == 200 and data.get('success') is True:
|
||||
return data.get('result', {})
|
||||
|
||||
error_msg = data.get('message') or data.get('error') or str(data)
|
||||
logger.error(
|
||||
'PayPear get_payment_by_order_id error',
|
||||
status_code=response.status,
|
||||
error_msg=error_msg,
|
||||
)
|
||||
raise PayPearAPIError(response.status, error_msg)
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.exception('PayPear API connection error', error=e)
|
||||
raise
|
||||
|
||||
def verify_webhook_signature(self, raw_body: bytes, received_signature: str) -> bool:
|
||||
"""Верификация подписи webhook PayPear через HMAC-SHA256.
|
||||
|
||||
PayPear sends signature in the webhook JSON field 'signature'.
|
||||
The signature is HMAC-SHA256(secret_key, raw_body).
|
||||
"""
|
||||
try:
|
||||
if not received_signature:
|
||||
logger.warning('PayPear webhook: отсутствует signature')
|
||||
return False
|
||||
|
||||
expected = hmac.new(
|
||||
self.secret_key.encode('utf-8'),
|
||||
raw_body,
|
||||
hashlib.sha256,
|
||||
).hexdigest()
|
||||
|
||||
return hmac.compare_digest(expected, received_signature)
|
||||
except Exception as e:
|
||||
logger.error('PayPear webhook verify error', error=e)
|
||||
return False
|
||||
|
||||
|
||||
# Singleton instance
|
||||
paypear_service = PayPearService()
|
||||
@@ -117,6 +117,14 @@ async def claim_phantom(
|
||||
subscription_id=sub.id,
|
||||
exc_info=True,
|
||||
)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
if hasattr(sub, 'id') and hasattr(sub, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=sub.id,
|
||||
user_id=sub.user_id,
|
||||
action='update',
|
||||
)
|
||||
|
||||
return True, phantom
|
||||
|
||||
@@ -205,3 +213,12 @@ async def sync_remnawave_after_phantom_merge(db: AsyncSession, user: User) -> No
|
||||
user_id=user.id,
|
||||
exc_info=True,
|
||||
)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
for sub in subs:
|
||||
if hasattr(sub, 'id') and hasattr(sub, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=sub.id,
|
||||
user_id=sub.user_id,
|
||||
action='update',
|
||||
)
|
||||
|
||||
@@ -216,6 +216,14 @@ class PromoOfferService:
|
||||
subscription_id=subscription.id,
|
||||
exc=exc,
|
||||
)
|
||||
from app.services.remnawave_retry_queue import remnawave_retry_queue
|
||||
|
||||
if hasattr(subscription, 'id') and hasattr(subscription, 'user_id'):
|
||||
remnawave_retry_queue.enqueue(
|
||||
subscription_id=subscription.id,
|
||||
user_id=subscription.user_id,
|
||||
action='update',
|
||||
)
|
||||
|
||||
await db.commit()
|
||||
for payload in log_payloads:
|
||||
|
||||
@@ -61,6 +61,14 @@ class PromoCodeService:
|
||||
if not promocode.is_valid:
|
||||
if promocode.current_uses >= promocode.max_uses:
|
||||
return {'success': False, 'error': 'used'}
|
||||
if not promocode.is_active:
|
||||
return {'success': False, 'error': 'inactive'}
|
||||
from app.database.models import _aware
|
||||
|
||||
now = datetime.now(UTC)
|
||||
aware_from = _aware(promocode.valid_from)
|
||||
if aware_from is not None and aware_from > now:
|
||||
return {'success': False, 'error': 'not_yet_valid'}
|
||||
return {'success': False, 'error': 'expired'}
|
||||
|
||||
existing_use = await check_user_promocode_usage(db, user_id, promocode.id)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import structlog
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.database.crud.subscription import get_active_subscriptions_by_user_id
|
||||
from app.database.models import User
|
||||
from app.services.subscription_service import SubscriptionService
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
async def resync_user_subscriptions_with_panel(
|
||||
db: AsyncSession,
|
||||
user: User,
|
||||
) -> dict[str, Any]:
|
||||
"""Resync all active subscriptions for a user with the RemnaWave panel.
|
||||
|
||||
Should be called after any identity change (TG linking, account merge,
|
||||
email verification) to ensure the panel has up-to-date telegram_id,
|
||||
email, and squads.
|
||||
|
||||
Returns a stats dict with keys:
|
||||
synced - number of subscriptions successfully synced
|
||||
failed - number of subscriptions that failed to sync
|
||||
total - total number of active subscriptions found
|
||||
skipped - True when the panel is not configured
|
||||
"""
|
||||
service = SubscriptionService()
|
||||
service._refresh_configuration()
|
||||
|
||||
if not service.is_configured:
|
||||
logger.warning(
|
||||
'remnawave_resync: panel not configured, skipping resync',
|
||||
user_id=user.id,
|
||||
config_error=service.configuration_error,
|
||||
)
|
||||
return {'synced': 0, 'failed': 0, 'total': 0, 'skipped': True}
|
||||
|
||||
subscriptions = await get_active_subscriptions_by_user_id(db, int(user.id))
|
||||
|
||||
if not subscriptions:
|
||||
logger.info(
|
||||
'remnawave_resync: no active subscriptions found',
|
||||
user_id=user.id,
|
||||
)
|
||||
return {'synced': 0, 'failed': 0, 'total': 0, 'skipped': False}
|
||||
|
||||
synced = 0
|
||||
failed = 0
|
||||
|
||||
for subscription in subscriptions:
|
||||
# Eagerly refresh tariff to avoid lazy-loading in async context.
|
||||
try:
|
||||
await db.refresh(subscription, ['tariff'])
|
||||
except Exception as exc:
|
||||
logger.debug(
|
||||
'remnawave_resync: could not refresh tariff for subscription',
|
||||
subscription_id=subscription.id,
|
||||
error=exc,
|
||||
)
|
||||
|
||||
# Determine whether a panel user already exists for this subscription.
|
||||
if settings.is_multi_tariff_enabled():
|
||||
panel_user_exists = bool(subscription.remnawave_uuid)
|
||||
else:
|
||||
panel_user_exists = bool(user.remnawave_uuid)
|
||||
|
||||
try:
|
||||
if panel_user_exists:
|
||||
result = await service.update_remnawave_user(
|
||||
db,
|
||||
subscription,
|
||||
sync_squads=True,
|
||||
)
|
||||
else:
|
||||
result = await service.create_remnawave_user(db, subscription)
|
||||
|
||||
if result is not None:
|
||||
synced += 1
|
||||
logger.info(
|
||||
'remnawave_resync: subscription synced',
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
action='update' if panel_user_exists else 'create',
|
||||
)
|
||||
else:
|
||||
failed += 1
|
||||
logger.warning(
|
||||
'remnawave_resync: subscription sync returned None',
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
action='update' if panel_user_exists else 'create',
|
||||
)
|
||||
except Exception as exc:
|
||||
failed += 1
|
||||
logger.error(
|
||||
'remnawave_resync: unexpected error syncing subscription',
|
||||
subscription_id=subscription.id,
|
||||
user_id=user.id,
|
||||
error=exc,
|
||||
)
|
||||
|
||||
total = len(subscriptions)
|
||||
logger.info(
|
||||
'remnawave_resync: completed',
|
||||
user_id=user.id,
|
||||
total=total,
|
||||
synced=synced,
|
||||
failed=failed,
|
||||
)
|
||||
|
||||
return {'synced': synced, 'failed': failed, 'total': total, 'skipped': False}
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Deferred retry queue for failed RemnaWave API calls.
|
||||
|
||||
When create_remnawave_user() fails during purchase, the subscription exists
|
||||
in the bot DB but not in the panel. This queue retries the operation
|
||||
periodically until it succeeds or max retries are exhausted.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime
|
||||
from typing import Literal
|
||||
|
||||
import structlog
|
||||
|
||||
from app.database.database import AsyncSessionLocal
|
||||
|
||||
|
||||
logger = structlog.get_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RetryItem:
|
||||
subscription_id: int
|
||||
user_id: int
|
||||
action: Literal['create', 'update']
|
||||
attempts: int = 0
|
||||
created_at: datetime = field(default_factory=lambda: datetime.now(UTC))
|
||||
last_error: str | None = None
|
||||
|
||||
|
||||
class RemnaWaveRetryQueue:
|
||||
def __init__(self, max_retries: int = 5, interval_seconds: int = 120) -> None:
|
||||
self._queue: deque[RetryItem] = deque()
|
||||
self._max_retries = max_retries
|
||||
self._interval = interval_seconds
|
||||
self._task: asyncio.Task | None = None
|
||||
|
||||
@property
|
||||
def pending_count(self) -> int:
|
||||
return len(self._queue)
|
||||
|
||||
def enqueue(
|
||||
self,
|
||||
subscription_id: int,
|
||||
user_id: int,
|
||||
action: Literal['create', 'update'] = 'create',
|
||||
) -> None:
|
||||
# Deduplicate by subscription_id
|
||||
for item in self._queue:
|
||||
if item.subscription_id == subscription_id:
|
||||
return
|
||||
self._queue.append(
|
||||
RetryItem(
|
||||
subscription_id=subscription_id,
|
||||
user_id=user_id,
|
||||
action=action,
|
||||
)
|
||||
)
|
||||
logger.info(
|
||||
'Enqueued RemnaWave retry',
|
||||
subscription_id=subscription_id,
|
||||
user_id=user_id,
|
||||
action=action,
|
||||
queue_size=len(self._queue),
|
||||
)
|
||||
|
||||
async def process_pending(self) -> None:
|
||||
if not self._queue:
|
||||
return
|
||||
|
||||
from app.database.crud.subscription import get_subscription_by_id
|
||||
from app.services.subscription_service import SubscriptionService
|
||||
|
||||
batch = list(self._queue)
|
||||
self._queue.clear()
|
||||
|
||||
for item in batch:
|
||||
item.attempts += 1
|
||||
try:
|
||||
async with AsyncSessionLocal() as db:
|
||||
sub = await get_subscription_by_id(db, item.subscription_id)
|
||||
if not sub:
|
||||
logger.warning(
|
||||
'Retry: subscription not found, dropping',
|
||||
subscription_id=item.subscription_id,
|
||||
)
|
||||
continue
|
||||
|
||||
service = SubscriptionService()
|
||||
if not service.is_configured:
|
||||
self._requeue(item, 'RemnaWave not configured')
|
||||
continue
|
||||
|
||||
if item.action == 'create':
|
||||
await service.create_remnawave_user(db, sub)
|
||||
else:
|
||||
await service.update_remnawave_user(db, sub)
|
||||
|
||||
logger.info(
|
||||
'Retry succeeded',
|
||||
subscription_id=item.subscription_id,
|
||||
attempts=item.attempts,
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
self._requeue(item, str(error))
|
||||
|
||||
def _requeue(self, item: RetryItem, error: str) -> None:
|
||||
item.last_error = error
|
||||
if item.attempts < self._max_retries:
|
||||
self._queue.append(item)
|
||||
logger.warning(
|
||||
'Retry failed, re-enqueued',
|
||||
subscription_id=item.subscription_id,
|
||||
attempts=item.attempts,
|
||||
max_retries=self._max_retries,
|
||||
error=error,
|
||||
)
|
||||
else:
|
||||
logger.error(
|
||||
'Retry exhausted, dropping (MANUAL INTERVENTION NEEDED)',
|
||||
subscription_id=item.subscription_id,
|
||||
user_id=item.user_id,
|
||||
attempts=item.attempts,
|
||||
error=error,
|
||||
)
|
||||
|
||||
async def start(self) -> None:
|
||||
if self._task and not self._task.done():
|
||||
return
|
||||
self._task = asyncio.create_task(self._run_loop())
|
||||
|
||||
async def stop(self) -> None:
|
||||
if self._task and not self._task.done():
|
||||
self._task.cancel()
|
||||
try:
|
||||
await self._task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
async def _run_loop(self) -> None:
|
||||
try:
|
||||
while True:
|
||||
await asyncio.sleep(self._interval)
|
||||
await self.process_pending()
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
|
||||
|
||||
# Global instance
|
||||
remnawave_retry_queue = RemnaWaveRetryQueue()
|
||||
@@ -31,9 +31,9 @@ from app.database.models import (
|
||||
from app.external.remnawave_api import (
|
||||
RemnaWaveAPI,
|
||||
RemnaWaveAPIError,
|
||||
TrafficLimitStrategy,
|
||||
UserStatus,
|
||||
)
|
||||
from app.services.subscription_service import get_traffic_reset_strategy
|
||||
from app.utils.subscription_utils import (
|
||||
resolve_hwid_device_limit_for_payload,
|
||||
)
|
||||
@@ -1516,6 +1516,9 @@ class RemnaWaveService:
|
||||
for telegram_id, db_user in bot_users_by_telegram_id.items()
|
||||
if telegram_id not in panel_telegram_ids
|
||||
and any(True for _ in (getattr(db_user, 'subscriptions', None) or []))
|
||||
# BUG-6 fix: Skip users who have a remnawave_uuid — they exist in panel
|
||||
# but may not have telegram_id set there (OAuth users who linked TG later)
|
||||
and not getattr(db_user, 'remnawave_uuid', None)
|
||||
]
|
||||
|
||||
if users_to_deactivate:
|
||||
@@ -1878,6 +1881,20 @@ class RemnaWaveService:
|
||||
|
||||
_short_id = await generate_unique_short_id(db)
|
||||
|
||||
# Attempt to match tariff by allowed_squads
|
||||
_matched_tariff_id = None
|
||||
if _squad_uuids:
|
||||
try:
|
||||
from app.database.crud.tariff import get_all_active_tariffs
|
||||
|
||||
_all_tariffs = await get_all_active_tariffs(db)
|
||||
for _t in _all_tariffs:
|
||||
if _t.allowed_squads and set(_squad_uuids).issubset(set(_t.allowed_squads)):
|
||||
_matched_tariff_id = _t.id
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
new_sub = Subscription(
|
||||
user_id=_bot_user.id,
|
||||
status=_sub_status.value,
|
||||
@@ -1892,6 +1909,7 @@ class RemnaWaveService:
|
||||
remnawave_short_uuid=panel_user.get('shortUuid'),
|
||||
subscription_url=panel_user.get('subscriptionUrl', ''),
|
||||
subscription_crypto_link=panel_user.get('subscriptionCryptoLink', ''),
|
||||
tariff_id=_matched_tariff_id,
|
||||
)
|
||||
db.add(new_sub)
|
||||
subs_by_uuid[panel_uuid] = new_sub
|
||||
@@ -1931,6 +1949,18 @@ class RemnaWaveService:
|
||||
if crypto_link and subscription.subscription_crypto_link != crypto_link:
|
||||
subscription.subscription_crypto_link = crypto_link
|
||||
|
||||
# Update squads from panel
|
||||
_panel_squads = panel_user.get('activeInternalSquads', []) or []
|
||||
_squad_uuids = []
|
||||
if isinstance(_panel_squads, list):
|
||||
for _sq in _panel_squads:
|
||||
if isinstance(_sq, dict) and 'uuid' in _sq:
|
||||
_squad_uuids.append(_sq['uuid'])
|
||||
elif isinstance(_sq, str):
|
||||
_squad_uuids.append(_sq)
|
||||
if _squad_uuids and set(_squad_uuids) != set(subscription.connected_squads or []):
|
||||
subscription.connected_squads = _squad_uuids
|
||||
|
||||
stats['updated'] += 1
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
@@ -2146,6 +2176,24 @@ class RemnaWaveService:
|
||||
|
||||
# traffic_limit_gb, device_limit: bot is source of truth, do not overwrite from panel
|
||||
|
||||
# Update connected_squads from panel (panel is source of truth for squad assignments)
|
||||
active_squads = panel_user.get('activeInternalSquads', [])
|
||||
panel_squad_uuids = []
|
||||
if isinstance(active_squads, list):
|
||||
for squad in active_squads:
|
||||
if isinstance(squad, dict) and 'uuid' in squad:
|
||||
panel_squad_uuids.append(squad['uuid'])
|
||||
elif isinstance(squad, str):
|
||||
panel_squad_uuids.append(squad)
|
||||
|
||||
if panel_squad_uuids and set(panel_squad_uuids) != set(subscription.connected_squads or []):
|
||||
subscription.connected_squads = panel_squad_uuids
|
||||
logger.info(
|
||||
'Обновлены connected_squads из панели',
|
||||
user_telegram_id=getattr(user, 'telegram_id', '?'),
|
||||
new_squads=panel_squad_uuids,
|
||||
)
|
||||
|
||||
new_short_uuid = panel_user.get('shortUuid')
|
||||
if new_short_uuid and subscription.remnawave_short_uuid != new_short_uuid:
|
||||
old_short_uuid = subscription.remnawave_short_uuid
|
||||
@@ -2240,7 +2288,7 @@ class RemnaWaveService:
|
||||
traffic_limit_bytes=sub.traffic_limit_gb * (1024**3)
|
||||
if sub.traffic_limit_gb > 0
|
||||
else 0,
|
||||
traffic_limit_strategy=TrafficLimitStrategy.MONTH,
|
||||
traffic_limit_strategy=get_traffic_reset_strategy(sub.tariff),
|
||||
telegram_id=user.telegram_id,
|
||||
email=user.email,
|
||||
description=settings.format_remnawave_user_description(
|
||||
@@ -2325,7 +2373,7 @@ class RemnaWaveService:
|
||||
status=status,
|
||||
expire_at=expire_at,
|
||||
traffic_limit_bytes=create_kwargs['traffic_limit_bytes'],
|
||||
traffic_limit_strategy=TrafficLimitStrategy.MONTH,
|
||||
traffic_limit_strategy=get_traffic_reset_strategy(sub.tariff),
|
||||
email=user.email,
|
||||
description=create_kwargs['description'],
|
||||
active_internal_squads=sub.connected_squads,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user