Commit Graph

86 Commits

Author SHA1 Message Date
Fringg
c30c2feee1 fix: handle StaleDataError in webhook user.deleted server counter decrement
When a user is deleted from the panel, the subscription may already be
cascade-deleted by the time the webhook handler tries to decrement
server counters. This caused StaleDataError followed by
PendingRollbackError when accessing subscription.id in the error handler.

- Save subscription.id before DB operations to avoid lazy load after rollback
- Catch StaleDataError explicitly and rollback the session
- Re-fetch subscription/user after potential rollback in _handle_user_deleted
- Skip subscription cleanup if it was already cascade-deleted
2026-02-11 18:35:36 +03:00
Fringg
887ea9cf5a style: format subscription.py with ruff 2026-02-11 04:45:42 +03:00
Fringg
bee4aa4284 fix: protect server counter callers and fix tariff change detection
- Wrap unprotected add/remove_user_to/from_servers calls in try/except
  in miniapp.py and cabinet subscription.py to prevent 500 errors
- Fix is_tariff_change to include classic-to-tariff transitions
  (subscription.tariff_id=None → new tariff_id) so purchased traffic
  is properly reset when switching modes
2026-02-11 04:44:15 +03:00
Fringg
b167ed3dd1 fix: preserve purchased traffic when extending same tariff
extend_subscription was unconditionally resetting purchased_traffic_gb
and deleting TrafficPurchase records whenever traffic_limit_gb was passed,
even when extending the same tariff (not changing). Now only resets
on actual tariff change (is_tariff_change=True), preserving purchased
traffic on same-tariff extensions.
2026-02-11 04:38:08 +03:00
Fringg
184c52d4ea feat: webhook protection — prevent sync/monitoring from overwriting webhook data
Add last_webhook_update_at timestamp to Subscription model. When a webhook
handler modifies a subscription, it stamps this field. Auto-sync, monitoring,
and force-check services skip subscriptions updated by webhook within the
last 60 seconds, preventing stale panel data from overwriting fresh
real-time changes.

- Add last_webhook_update_at column + migration
- Stamp all 8 webhook handlers with commit in every code path
- Add is_recently_updated_by_webhook() guard in 12 sync/monitoring paths
- Add REMNAWAVE_WEBHOOK_* variables to .env.example
- Add webhook setup documentation to README with Caddy/nginx examples
- Fix pre-existing yookassa webhook test (mock AsyncSessionLocal)
2026-02-10 07:16:22 +03:00
Fringg
a3903a252e refactor: remove smart auto-activation & activation prompt, fix production bugs
Remove AUTO_ACTIVATE_AFTER_TOPUP and SHOW_ACTIVATION_PROMPT_AFTER_TOPUP
features from all payment providers, config, system settings, and tests.
Cart auto-purchase (AUTO_PURCHASE_AFTER_TOPUP) is preserved.

Bug fixes:
- fix KeyError 'months' in devices.py for custom locale overrides
- fix IntegrityError on trial subscription retry (update existing PENDING instead of INSERT)
- fix PendingRollbackError cascade by adding db.rollback() before recovery
- fix TelegramForbiddenError not caught in photo_message.py
- fix "query is too old" spam in required_sub_channel_check
- add missing trial locale keys (TRIAL_PAYMENT_DESCRIPTION, TRIAL_REFUND_DESCRIPTION, TRIAL_ACTIVATION_ERROR)
2026-02-09 21:39:53 +03:00
Fringg
b9352a5bd5 fix(autopay): exclude daily subscriptions from global autopay
- Skip daily tariff subscriptions in monitoring autopay cycle
- Filter daily subscriptions in get_subscriptions_for_autopay CRUD
- Block autopay menu and toggle for daily tariffs in bot handler
- Reject autopay enable for daily subscriptions in Cabinet API (HTTP 400)
- Reject autopay enable for daily subscriptions in MiniApp API (HTTP 400)
2026-02-05 07:10:52 +03:00
Egor
5cef11f32b Update subscription.py 2026-02-03 04:14:15 +03:00
c0mrade
1b212cc8d6 ci: add ruff lint workflow and fix formatting 2026-01-25 19:31:00 +03:00
Egor
ac892cc899 Update subscription.py 2026-01-25 13:39:47 +03:00
Egor
658b48f154 Merge pull request #2412 from BEDOLAGA-DEV/email
Email
2026-01-25 11:55:22 +03:00
c0mrade
9a2aea038a chore: add uv package manager and ruff linter configuration
- Add pyproject.toml with uv and ruff configuration
- Pin Python version to 3.13 via .python-version
- Add Makefile commands: lint, format, fix
- Apply ruff formatting to entire codebase
- Remove unused imports (base64 in yookassa/simple_subscription)
- Update .gitignore for new config files
2026-01-24 17:45:27 +03:00
Egor
7e37bc4409 Update subscription.py 2026-01-24 11:23:28 +03:00
Egor
86c2092eff Update subscription.py 2026-01-21 15:43:29 +03:00
Egor
8ad2d50b25 Add files via upload 2026-01-20 00:18:57 +03:00
Egor
7106c89711 Update subscription.py 2026-01-16 08:40:01 +03:00
Egor
395646168d Update subscription.py 2026-01-16 00:50:03 +03:00
Egor
c4382ff69d Add files via upload 2026-01-15 17:31:39 +03:00
Egor
9c2b17af3b Update subscription.py 2026-01-14 04:12:18 +03:00
PEDZEO
a686333603 Add support for custom days and traffic in tariffs
- Introduced fields for custom days and traffic in the tariff model, including enabling flags, pricing, and limits.
- Updated relevant routes and schemas to handle new tariff features.
- Implemented logic for purchasing and managing custom days and traffic in subscriptions.
- Added database migration scripts to accommodate new columns for tariffs and subscriptions.
2026-01-13 02:55:32 +03:00
Egor
40fad0d537 Update subscription.py 2026-01-12 18:56:24 +03:00
Egor
67f60ba41a Update subscription.py 2026-01-12 18:44:34 +03:00
Egor
db54b01f04 Update subscription.py 2026-01-12 18:16:59 +03:00
Egor
26e242cac7 Update subscription.py 2026-01-12 18:12:14 +03:00
Egor
640a80953f Update subscription.py 2026-01-12 16:31:00 +03:00
Egor
472ef37490 Add files via upload 2026-01-12 15:25:25 +03:00
Egor
5d1d561882 Update subscription.py 2026-01-10 20:33:55 +03:00
Egor
bc7470b39d Update subscription.py 2026-01-10 18:20:35 +03:00
Egor
4e6d5b4716 Update subscription.py 2026-01-09 19:30:53 +03:00
Egor
cc3f78c2f8 Update subscription.py 2026-01-08 03:07:31 +03:00
Egor
b50478eda0 Add files via upload 2026-01-07 02:16:33 +03:00
gy9vin
d524088bb8 Обязательная подписка на канал Доработка 2026-01-02 16:14:40 +03:00
gy9vin
08692145d2 fix Массовая синхронизация пользователей с Remnawave
app/database/crud/subscription.py:

  Добавлен await db.flush() в create_subscription_no_commit для консистентности с create_user_no_commit:

  db.add(subscription)

  # Выполняем flush, чтобы получить присвоенный первичный ключ
  await db.flush()

  # Не коммитим сразу, оставляем для пакетной обработки
2025-12-30 23:03:34 +03:00
gy9vin
56cc8bacf2 fix Простая покупка подписки
1. app/database/crud/subscription.py

  Объединены функции create_pending_subscription и create_pending_trial_subscription:
  - Добавлен параметр is_trial: bool = False в create_pending_subscription
  - create_pending_trial_subscription теперь просто вызывает create_pending_subscription(is_trial=True)
  - Сокращено ~75 строк дублированного кода

  Удалён лишний импорт:
  # Было внутри activate_pending_subscription:
  from sqlalchemy import and_  # Удалено — уже импортирован на уровне модуля

  2. app/handlers/subscription/purchase.py

  Устранено дублирование функций:
  - Удалены определения _calculate_simple_subscription_price() и _get_simple_subscription_payment_keyboard() (~75 строк)
  - Добавлен импорт из app.handlers.simple_subscription

  from app.handlers.simple_subscription import (
      _calculate_simple_subscription_price,
      _get_simple_subscription_payment_keyboard,
  )

  Итого сокращено: ~150 строк дублированного кода
2025-12-30 22:56:24 +03:00
Egor
76f465e0f6 Update subscription.py 2025-12-30 18:13:18 +04:00
gy9vin
58c924b70a fix(campaign,channel): исправлена логика рекламных кампаний и проверки подписки на канал
- Рекламные кампании теперь выдают триальную подписку (is_trial=True),
    а не платную — пользователь становится платным только после оплаты

  - Добавлена настройка CHANNEL_REQUIRED_FOR_ALL для проверки подписки
    на канал для ВСЕХ пользователей (платных и триальных)

  - Добавлен параметр is_trial в create_paid_subscription для гибкости
2025-12-26 21:40:28 +03:00
gy9vin
bf6dc3991a feat(trial): платный триал с выбором метода оплаты
Реализована система платного триала с гибким выбором способа оплаты:

- Автоопределение платности: если TRIAL_ACTIVATION_PRICE > 0, триал автоматически платный
- TRIAL_PAYMENT_ENABLED теперь опционален (для обратной совместимости)
- Добавлена функция create
2025-12-26 00:03:08 +03:00
gy9vin
0538d0e337 feat(traffic): улучшение системы докупки и сброса трафика
- Добавлен ENV переключатель TRAFFIC_TOPUP_ENABLED для вкл/выкл докупки
- Добавлена отдельная конфигурация пакетов TRAFFIC_TOPUP_PACKAGES_CONFIG
- Добавлено поле purchased_traffic_gb для отслеживания докупленного трафика
- Добавлены режимы расчета цены сброса (period/traffic/traffic_with_purchased)
- Исправлен абьюз: цена сброса теперь учитывает докупленный трафик
- Сброс purchased_traffic_gb при продлении/покупке подписки
- UX: меню сброса теперь показывает цену и баланс вместо alert
- UX: кнопка пополнения если не хватает средств на сброс
- Добавлена миграция для нового поля purchased_traffic_gb
- Добавлена локализация TRAFFIC_TOPUP_DISABLED (ru/en/ua/zh)
2025-12-25 14:48:24 +03:00
Egor
dc428baa6a Update subscription.py 2025-12-23 11:53:52 +03:00
Egor
0892f494d9 Revert "Add internal squad management for users and trials" 2025-12-08 04:17:05 +03:00
Egor
6c41263511 Add internal squad management for users and trials 2025-12-08 04:15:18 +03:00
Egor
7a70a90d63 Reduce noisy price calculation logging 2025-11-27 23:55:54 +03:00
Egor
fba217b87f Fix trial reset by clearing server links 2025-11-20 22:49:57 +03:00
Egor
991e5a3112 Preserve zero device limit when replacing trials 2025-11-18 01:14:43 +03:00
Egor
cb6d51ed3d Remove trial squad override setting 2025-11-08 07:55:24 +03:00
Pavel Stryuk
427011fe41 1) Отображение скидки на кнопках (красивое!)
2) У промогрупп появится приоритет
3) У пользователя может быть несколько промогрупп, но влиять будет только с наивысшим приоритетом
4) К промокодам можно будет добавить промогруппу. Все активировавшие промокод получат её
5) При выводе пользователей с промогруппой будет также выводиться ссылка на каждого. Можно будет отследить сливы промокодов "для своих". Я в целом это добавлю во все места, где пользователь выводится в админке
6) Исправить баг исчезновения триалки при пополнении
7) Исправить падающие тесты и добавить новых
8) Трафик: 0 ГБ в тестовой подписке исправить на Трафик: Безлимит
2025-11-04 13:05:02 +01:00
Mikhail
92cb1e3971 Merge branch 'Fr1ngg:main' into main 2025-11-02 15:08:01 +03:00
gy9vin
005fc95433 Массовая синхронизация пользователей с ремнем! 2025-11-02 15:07:28 +03:00
Egor
5ce87238c8 Fix subscription timestamps to use configured timezone 2025-11-01 04:54:12 +03:00
Egor
8407f7cdb1 Restore device management button in disabled mode 2025-10-31 19:15:48 +03:00