Compare commits

...

3523 Commits

Author SHA1 Message Date
Egor d6442b87df Merge pull request #2926 from BEDOLAGA-DEV/dev
docs: add Antilopay/Etoplatezhi/Jupiter/Donut/Lava + Apple IAP to pro…
2026-05-04 21:22:17 +03:00
Fringg 31e3ccd24c docs: add Antilopay/Etoplatezhi/Jupiter/Donut/Lava + Apple IAP to provider list
- Bump provider counter 18 → 24+ in Features and Documentation sections
- Add 7 new rows to providers table:
  - Antilopay (RSA signing)
  - Etoplatezhi
  - Jupiter (FPGate P2P) — partner via @k_juppiter
  - Donut (Donut P2P) — partner via @donut_payment
  - Lava Business
  - Apple In-App Purchase
- Add 2 partner cards (Jupiter, Donut) following the Platega/PayPear pattern
2026-05-04 21:20:44 +03:00
Egor 3d4b7b4582 Merge pull request #2925 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.54.0
2026-05-04 20:58:57 +03:00
github-actions[bot] cedf4922fd chore(main): release 3.54.0 2026-05-04 17:57:52 +00:00
Egor 491f09d547 Merge pull request #2924 from BEDOLAGA-DEV/dev
Dev
2026-05-04 20:57:17 +03:00
Fringg 0d0646770d fix(tests): clean up pre-existing ruff lint warnings in apple_iap tests
- Remove unused unittest.mock.patch import (F401)
- Mark hardcoded /tmp/test.p8 path with noqa S108 (only used for
  is_apple_iap_enabled check, no file actually accessed)
- Replace pytest.raises(Exception) with pytest.raises(ValidationError)
  for Pydantic schema validation tests (B017)
2026-05-04 20:50:29 +03:00
Fringg 17732a0370 style: apply ruff format to payment integrations
CI ruff format --check failed on 13 files. Applied ruff format to bring
them in line with project formatting (line wrapping, trailing commas,
quote consistency). No functional changes.
2026-05-04 20:47:48 +03:00
Fringg cd8be32671 fix: register all providers in payment search and verification services
The admin Payments page filter and pending payments tab were missing newer
providers (paypear, rollypay, aurapay, etoplatezhi, antilopay, jupiter, donut,
lava) because they were never registered in the search/verification registries.
Customer payments via these providers were invisible in admin filtering.

payment_search_service.py:
- Add 8 _search_<provider> functions matching the existing pattern
- Register them in _PROVIDER_SEARCH_MAP (now 22 methods total)
- Filter dropdown and stats.by_method now include all providers

payment_verification_service.py:
- Add 8 _is_<provider>_pending and _fetch_<provider>_payments functions
- Wire them into list_recent_pending_payments and get_payment_record
- Add display name and is_enabled dispatch branches for all 8
- Register paypear / rollypay / aurapay in SUPPORTED_MANUAL_CHECK_METHODS and
  SUPPORTED_AUTO_CHECK_METHODS (they have full API+DB sync via check_*)
- Wire them into run_manual_check
- etoplatezhi / antilopay / jupiter / donut / lava remain webhook-driven and
  appear in pending tab without manual-check button (no fake API sync)
2026-05-04 20:43:47 +03:00
Fringg afea054c8f feat: integrate Lava Business payment provider
- Lava Business via gate.lava.ru (HMAC-SHA256 signed JSON requests)
- Sub-methods: card and SBP via includeService filter
- Webhook signature verified from raw bytes with secret_key_2
- Sticky terminal-status guard (success after amount_mismatch escalates to ERROR)
- Order ID with full uuid4 hex (128-bit entropy)
- Cross-row contamination guard: order_id assertion on invoice_id fallback
- Warning when hook URL cannot be derived from webhook/web_api/cabinet bases
- Explicit failure when Lava response lacks payment_url (no orphan rows)
- Adds LAVA settings category, /lava-webhook endpoint, cabinet topup branch
- Mirrors existing Antilopay/Jupiter/Donut mixin pattern
2026-05-04 20:14:31 +03:00
Fringg f321ded9c0 feat: integrate Jupiter (FPGate P2P) and Donut payment providers
- Jupiter: SBP via app.juppiter.tech (FPGate P2P v2.1)
- Donut: CARD/SBP/SBP_QR via gw.donut.business (Donut P2P)
- HMAC-SHA256 signing verified against spec reference vectors
- Sticky terminal-status guard in callback (amount_mismatch/declined/cancelled
  cannot be re-credited by replayed webhook)
- Mirrors existing Antilopay/Etoplatezhi mixin pattern: service, mixin, CRUD,
  Alembic migration, handlers, keyboards, webhook, cabinet route, status mapping
- Adds JUPITER and DONUT settings categories with title/description/prefix
- Backfills missing ANTILOPAY and ETOPLATEZHI category metadata
2026-05-04 19:36:22 +03:00
Fringg 3fce64858c fix: add pycryptodome dependency for Antilopay RSA signing 2026-05-04 17:31:06 +03:00
Fringg 1ab1ff90bf feat: add subscription reissue with 15-min cooldown
- Add revoke handler for classic and multi-tariff modes with 2-step
  confirmation dialog and TOCTOU-safe cooldown enforcement
- Add cabinet API endpoint POST /subscription/revoke with 429 + Retry-After
  for cooldown, IDOR protection via resolve_subscription
- Add last_revoke_at column to subscriptions (Alembic migration 0071)
- Add SUBSCRIPTION_REVOKE_ENABLED and COOLDOWN_SECONDS config settings
- Add revoke button to classic subscription settings keyboard and
  multi-tariff detail keyboard (gated by feature toggle)
- Add locale keys for revoke UI in all 5 languages (ru, en, ua, zh, fa)
2026-05-04 08:08:56 +03:00
Fringg 719664208e feat: integrate Antilopay payment provider (API v2)
- Add antilopay_service.py with SHA256WithRSA signing (pycryptodome),
  private key for requests, public key for callback verification
- Add payment mixin with create/callback/finalize/check_status flows,
  kopeks↔rubles conversion, 7 status mappings, prefer_methods support
- Add CRUD with FOR UPDATE locking, idempotency checks
- Add handlers with SBP/Card/SberPay sub-method selection
- Add Alembic migration for antilopay_payments table
- Add config (ANTILOPAY_ENABLED, SECRET_ID, PRIVATE_KEY, PUBLIC_KEY,
  PROJECT_ID, SBP/CARD/SBERPAY enabled/display names)
- Add webhook endpoint with X-Apay-Callback header signature verification
- Register in keyboard, router, utils, backup, method config
2026-05-04 07:44:17 +03:00
Fringg 6524f66da2 feat: integrate Etoplatezhi payment provider
- Add etoplatezhi_service.py with HMAC-SHA512+base64 signature algorithm,
  payment URL builder, and callback signature verification
- Add payment mixin with create/process/finalize flow, 12 status mappings
- Add CRUD operations with FOR UPDATE locking, idempotency checks
- Add Telegram handlers with SBP/Card sub-method selection
- Add Alembic migration for etoplatezhi_payments table
- Add config settings (ETOPLATEZHI_ENABLED, PROJECT_ID, SECRET_KEY,
  SBP_ENABLED, CARD_ENABLED, display names, min/max amounts)
- Add webhook endpoint with JSON-body signature verification
- Register in payment keyboard, router, utils, backup, method config
2026-05-04 07:17:54 +03:00
Fringg 17ac3da3c4 fix: AuraPay webhook signature + add SBP/Card payment method selection
- Fix webhook signature: str(None) produced "None" (4 chars) instead of
  "" like PHP implode() does, causing all webhooks with custom_fields=null
  to fail signature verification
- Add AURAPAY_SBP_ENABLED / AURAPAY_CARD_ENABLED env vars with display
  names, following Freekassa pattern for sub-method selection
- Add aurapay_sbp / aurapay_card buttons in payment keyboard
- Add start_aurapay_sbp_topup / start_aurapay_card_topup handlers
- Route dispatch handles aurapay / aurapay_sbp / aurapay_card
- payment_utils updated with SBP/Card availability checks
- service parameter ("sbp"/"card") now passed through to AuraPay API
2026-05-04 06:44:03 +03:00
Fringg e85c40f8cd fix: apple refund handler — lock apple_transactions row to prevent double deduction 2026-05-04 05:54:11 +03:00
Fringg ecde2fb8f0 feat: Apple IAP integration with security hardening 2026-05-04 05:49:38 +03:00
Fringg 99648a956e fix: persist campaign across bot→webapp registration handoff via Redis 2026-05-04 05:27:49 +03:00
Fringg 2478ff7c3d fix: expired_1d notification — use PricingEngine instead of hardcoded PRICE_30_DAYS 2026-05-04 05:14:47 +03:00
Fringg 2385814d77 fix: guide mode buttons — support external type alias, extract urlScheme from blocks
From PR #2923 by @dotX12, with improvements:
- Support type: "external" as alias for "externalLink" in app config
- Extract urlScheme from subscriptionLink buttons in blocks[] when not at root
- Wrap custom URL schemes in HTTPS redirect for Telegram compatibility
- Fallback to plain subscription URL when no redirect template configured

Improvements over original PR:
- Also check btn.get('url') not just btn.get('link') for scheme extraction
- Validate extracted scheme contains :// before accepting
- Skip redundant redirect wrapping when create_deep_link already wrapped
2026-05-04 05:04:27 +03:00
Egor df7e397745 Merge pull request #2918 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.53.0
2026-04-29 12:12:57 +03:00
github-actions[bot] 52868eac5b chore(main): release 3.53.0 2026-04-29 09:12:34 +00:00
Egor 4c600b8557 Merge pull request #2917 from BEDOLAGA-DEV/dev
Dev
2026-04-29 12:11:47 +03:00
Fringg 51dfc3a1a2 feat: protect active paid subscriptions from bulk delete
- Backend: _do_delete_subscription refuses to delete active paid subs
  unless force_delete_active_paid=true is explicitly passed
- Backend: add force_delete_active_paid to BulkActionParams (default false)
- Backend: add is_trial to SubscriptionListItem schema + populate it
2026-04-29 11:31:08 +03:00
Fringg 443a826402 fix: PayPear webhook signature — strip signature field before hashing + IP fallback
The old code hashed the full raw body INCLUDING the 'signature' field
itself — a circular computation that can never match (you can't include
the signature in the data being signed).

Fix:
1. Strip 'signature' key from payload before HMAC-SHA256 computation
2. Try both sorted and unsorted keys (PayPear docs don't specify)
3. Fallback to IP allowlist check (158.160.85.101 per PayPear docs)
4. Pass client_ip from request headers to the verification function
2026-04-29 11:23:20 +03:00
Fringg 06db393488 feat: add bulk_actions, info_pages, news to PERMISSION_REGISTRY
- bulk_actions: read, execute (was using users:edit)
- info_pages: read, create, edit, delete (was using settings:read/edit)
- news: read, create, edit, delete (was missing from registry entirely)

Backend endpoints updated to use dedicated permissions instead of
piggybacking on users:edit / settings:read.
2026-04-29 11:14:24 +03:00
Fringg 0bcb804118 fix: block/unblock endpoints — correct args, response schema, panel sync
4 bugs fixed:
1. block_user() called with User object instead of int user_id, missing admin_id
2. Response used wrong fields (user_id/status instead of old_status/new_status)
3. Return value not checked — reported success even on failure
4. unblock endpoint used DB-only update_user_status instead of UserService.unblock_user
2026-04-29 10:51:23 +03:00
Fringg 735e16afeb fix: cabinet /block endpoint now disables panel user in RemnaWave 2026-04-29 10:47:40 +03:00
Fringg a88e3c80ad fix: traffic addon price mismatch — keyboard showed prorated, handler charged full month
Keyboard calculated: price * days_remaining / 30 (true proration)
Handler calculated: price * max(30, days_remaining) / 30 (always >= 30 days)

With 17 days remaining: keyboard showed 84₽, handler charged 149₽.

Fix: change calculate_prorated_price default min_charge_days from 30 to 1.
Now all callers (traffic, countries, servers, miniapp, auto-purchase)
use true proration matching the displayed price.
2026-04-29 10:42:10 +03:00
Fringg 1110d0c781 fix: media upload leaks staging photo to admin chat
The upload endpoint sent files to the admin notification chat to obtain
a Telegram file_id, but never deleted the staging message. Admins saw
uncontextualized images in their chat before any ticket was created.

Fix: send with disable_notification=True and immediately delete the
staging message after capturing the file_id. Telegram persists file_ids
even after message deletion.
2026-04-29 10:32:55 +03:00
Fringg 62e7ecba01 fix: deadlock on user deletion — webhook handler never checked intentional mark
mark_intentional_panel_deletion was called before api.delete_user,
but _is_intentional_panel_deletion_event was never called in the
webhook handler — it was dead code. The user.deleted webhook processed
unconditionally, causing a deadlock between delete_user_account (Tx1
holding subscription row locks) and the webhook handler (Tx2 trying
to lock the same rows via decrement_subscription_server_counts).

Fix: check _is_intentional_panel_deletion_event at the top of
_handle_user_deleted — if True, log and return immediately without
touching the DB.
2026-04-29 10:28:57 +03:00
Fringg c905fa6000 fix: downgrade Pal24 API validation errors from error to debug 2026-04-29 10:25:08 +03:00
Fringg 768e0b6a73 fix: PollResponse has no created_at — use sent_at for ordering 2026-04-29 10:17:40 +03:00
Fringg 83efc214fe fix: add 6 missing payment providers to payment_utils availability checks
RollyPay (and 5 others) showed buttons but triggered "payment methods
unavailable" because get_available_payment_methods() was missing them.
The keyboard builder (inline.py) had all providers, but the text
generator (payment_utils.py) did not — divergent hand-maintained lists.

Added to all 4 functions: get_available_payment_methods,
is_payment_method_available, get_payment_method_status,
get_enabled_payment_methods_count:
- SeverPay, PayPear, RollyPay, Overpay, AuraPay (new)
- RioPay (was in methods list but missing from status/count)
2026-04-29 08:27:37 +03:00
Fringg 29e177d396 fix: cabinet autopay endpoint — same NULL-safe is_trial guard 2026-04-29 08:21:41 +03:00
Fringg 2fbdbf5ab0 fix: autopay renewing trial subscriptions at classic-mode pricing
Three bugs caused trial subscriptions to be auto-renewed without a
tariff at arbitrary prices:

1. try_auto_extend_expired_after_topup: is_trial guard used truthiness
   check — NULL (legacy rows) passed as falsy. Changed to
   `is_trial is not False` (NULL-safe).

2. Multi-tariff branch: `not s.is_trial` treated NULL as not-trial.
   Changed to `s.is_trial is False`.

3. Telegram bot autopay toggle: no is_trial guard — users could enable
   autopay on trial subscriptions. Added trial check before enabling.
2026-04-29 08:16:39 +03:00
Fringg 422844d78d fix: retry queue action uses _should_create instead of stale subscription UUID 2026-04-29 08:08:24 +03:00
Fringg f37eb9a1bd fix: cabinet purchase fails after panel user deletion — stale UUID
Two bugs caused "RemnaWave UUID не найден" when a user repurchased
after their panel user was deleted (expired user cleanup):

1. Webhook handler only cleared subscription.remnawave_uuid in
   multi-tariff mode. In single-tariff mode the stale UUID remained,
   causing the cabinet to try update_remnawave_user on a deleted
   panel user instead of creating a new one.

2. Cabinet purchase-tariff used subscription.remnawave_uuid for the
   create/update decision. In single-tariff mode this was stale.
   Now mirrors the bot handler logic: checks user.remnawave_uuid
   in single-tariff mode (correctly cleared by webhook).
2026-04-29 08:04:23 +03:00
Fringg 1c38b31e60 fix: send admin notification on promo code activation from cabinet 2026-04-29 07:50:09 +03:00
Fringg 43dd0fd92c fix: referral links now clickable — remove <code> wrapping
The invite message wrapped the entire text including the referral URL
in <blockquote><code>...</code></blockquote>. The <code> tag made the
URL non-clickable — Telegram renders it as monospace copyable text.
Recipients couldn't tap the link to open it.

- Invite message: removed <code> from blockquote, Telegram now auto-links the URL
- Stats panel: removed <code> from bot/cabinet referral links, URLs are now clickable
2026-04-29 07:45:28 +03:00
Fringg a506c6be00 fix: add 5 missing payment providers to pending-payments model_map 2026-04-29 07:40:50 +03:00
Fringg ff7b190527 fix: add RollyPay, PayPear, Overpay, AuraPay to REAL_PAYMENT_METHODS 2026-04-29 07:36:48 +03:00
Fringg 527c5b4498 fix: panel sync subscription duration — ceil for days_remaining 2026-04-29 07:32:08 +03:00
Fringg bada41ecd6 fix: remaining pricing-critical .days floor calculations → math.ceil
Same bug as device pricing: timedelta.days floors partial days.
Fixed 14 more pricing-critical locations across 7 files:

- traffic addon pricing (bot handler + cabinet + miniapp)
- country addon pricing (bot handler + miniapp)
- generic addon pricing helper (common.py)
- auto-purchase device recomputation
- subscription CRUD pricing helper

Display-only .days usages intentionally left as floor (correct for
showing "X days left" to users).
2026-04-29 07:27:55 +03:00
Fringg cf60ae2967 fix: device/traffic addon pricing — use ceil instead of floor for days_left
timedelta.days is integer floor: 29 days 23 hours = 29, not 30.
When a user bought extra devices on the same day as their subscription,
they were charged for ~1 day instead of the full remaining period.

Fix: math.ceil(total_seconds / 86400) rounds partial days UP.
Applied to all 11 locations across 4 files:
- app/handlers/subscription/devices.py (5 spots)
- app/cabinet/routes/subscription_modules/devices.py (3 spots)
- app/keyboards/inline.py (3 spots — display pricing)
- app/utils/pricing_utils.py (1 spot — traffic prorated pricing)
2026-04-29 07:21:07 +03:00
Fringg 47c7d45793 fix: traffic addon discount also bypassed tariff-promo-group check 2026-04-29 07:14:14 +03:00
Fringg 4ab5928b61 fix: promo group discount applied to restricted tariffs in autopay
The pricing engine applied promo group discounts unconditionally,
without checking if the tariff is available for the user's promo group.

In autopay: user with VIP group (60% discount, restricted to Premium
tariff) would get 60% off when auto-renewing a Basic tariff that their
group should not cover.

Fix: in _calculate_tariff_core, check tariff.is_available_for_promo_group
before applying group discounts. If tariff is not available for the
user's promo group, the discount is zeroed — subscription renews at
full price. Protects ALL pricing paths (autopay, recurrent, manual).
2026-04-29 07:09:55 +03:00
Fringg fb857d792b feat: per-category enable/disable for admin notifications
Add ADMIN_NOTIFICATIONS_{CATEGORY}_ENABLED settings (default True) for
all 10 notification categories: purchases, renewals, trials, balance,
addons, infrastructure, errors, promo, partners, tickets.

Setting ADMIN_NOTIFICATIONS_PROMO_ENABLED=false now completely suppresses
promo notifications (promocode activations, campaign visits, promo group
changes) instead of silently falling back to the general topic.

Also fix referral_contest_service direct bot.send_message bypass —
now respects ADMIN_NOTIFICATIONS_PROMO_ENABLED setting.
2026-04-29 06:58:57 +03:00
Fringg 59080f7392 fix: handle A018 error code in admin_users sync endpoints (2 more locations) 2026-04-29 06:52:04 +03:00
Fringg c619dbcae2 fix: handle A018 error code as user-not-found fallback to create_user 2026-04-29 06:48:30 +03:00
Fringg 91de6d03fc fix: update cabinet_last_login on every request (throttled, 5 min) 2026-04-29 06:46:02 +03:00
Fringg 1fc04d842f fix: subscription-request-history — correct API client usage, add ownership check 2026-04-29 06:18:32 +03:00
Fringg e22beb7229 feat: subscription request history API + RemnaWave panel method
- Add get_subscription_request_history to RemnaWave API client
  (GET /api/users/{uuid}/subscription-request-history with pagination)
- Add GET /admin/users/{user_id}/subscription-request-history endpoint
  with subscription_id param for multi-tariff support
2026-04-29 06:12:38 +03:00
Fringg 74999fe99d fix: create locales directory with correct permissions in Dockerfile 2026-04-29 05:55:21 +03:00
Fringg 134e7fb0e1 fix: false subscription expiry notifications — 4 bugs fixed
1. _check_expired_subscription_followups: added Subscription.status=EXPIRED
   filter (was matching ALL statuses including ACTIVE), User.status=ACTIVE
   filter, and 30-day lookback window to stop scanning ancient subscriptions

2. _get_expiring_paid_subscriptions: added User.status=ACTIVE filter to
   prevent sending "expiring" notifications to blocked/deleted users

3. Multi-tariff: before sending expired/followup notifications, check if
   user has another ACTIVE subscription with end_date > now — skip if they
   still have service through another tariff

4. Multi-tariff: same check for _check_expired_subscriptions — don't send
   "subscription expired" if user has another active sub
2026-04-29 05:47:56 +03:00
Fringg c743fc81a5 fix: replace all late callback.answer() with edit_text for error feedback
- Fix 7 intermediate error paths (balance deduction failures) that used
  callback.answer() after the early answer was already consumed — user
  got no error feedback at all
- Fix 2 unfixed handlers: confirm_tariff_purchase, confirm_daily_tariff_purchase
  — same early-answer pattern applied
- All 7 purchase/extend/switch handlers now consistently use early
  callback.answer() + edit_text for errors
2026-04-29 05:37:30 +03:00
Fringg 579e4f2a69 fix: callback.answer() before heavy operations to prevent query timeout
Telegram invalidates callback queries after 30 seconds. When the bot
performed panel sync, DB transactions, and admin notifications before
answering, callback.answer() threw TelegramBadRequest: query is too old.

Moved callback.answer() to immediately after guard checks (balance,
tariff availability) in 5 handlers:
- confirm_tariff_extend
- confirm_custom_tariff_purchase
- confirm_tariff_switch
- confirm_daily_tariff_switch
- confirm_instant_switch

Error feedback now uses callback.message.edit_text() instead of the
expired callback.answer().
2026-04-27 16:56:39 +03:00
Fringg b9b695799c refactor: remove unused EXTERNAL_ADMIN_TOKEN functionality
- Delete app/services/external_admin_service.py entirely
- Remove EXTERNAL_ADMIN_TOKEN and EXTERNAL_ADMIN_TOKEN_BOT_ID from config
- Remove build_external_admin_token, get_external_admin_token, get_external_admin_bot_id methods
- Remove unused hashlib/hmac imports from config.py
- Remove from system_settings_service: READ_ONLY_KEYS, PLAIN_TEXT_KEYS,
  category title, category description, prefix mapping, documentation metadata
- Remove from bot_configuration.py category group
- Remove from main.py startup sequence (ensure_external_admin_token call)
- Remove from .env.example
- Remove from docs/project_structure_reference.md
2026-04-26 19:54:33 +03:00
Fringg 5cf19c76e6 fix: backup import crash + upload handler hardening
- Fix PaypearPayment → PayPearPayment (capital P) — import crash
- Fix AurapayPayment → AuraPayPayment (capital P) — import crash
- Update upload instruction message to mention .tar.gz format
- Add null guard on document.file_name before extension check
2026-04-26 19:39:09 +03:00
Fringg eafb243882 fix: backup completeness — add 15 missing tables, accept .tar.gz uploads
Tables added to backup AND clear lists:
- Payment providers: riopay, severpay, paypear, rollypay, overpay, aurapay, saved_payment_methods
- Content: email_templates, info_pages, news_articles, news_categories, news_tags
- Landing: landing_pages, guest_purchases
- Analytics: yandex_client_id_map

Also:
- Telegram backup upload handler now accepts .tar.gz format (was .json/.json.gz only)
- All 92 ORM models + 3 association tables now covered
2026-04-26 19:29:55 +03:00
Egor 56b0b1fb5f Merge pull request #2914 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.52.1
2026-04-24 18:22:53 +03:00
github-actions[bot] 10519bf68e chore(main): release 3.52.1 2026-04-24 15:22:37 +00:00
Egor 7bff56070c Merge pull request #2913 from BEDOLAGA-DEV/dev
Dev
2026-04-24 18:22:09 +03:00
Fringg 5ed9a0d4fb fix: use fresh DB session for deactivate after long unpin loop 2026-04-24 18:13:48 +03:00
Fringg 63e1127353 fix: broadcast preview count — add .correlate(User) to EXISTS subqueries 2026-04-24 18:03:29 +03:00
Fringg ab4661b5c6 fix: unpin messages in Telegram BEFORE deactivating in DB
The "Unpin all" button called deactivate_active_pinned_message() first,
then looped over users to unpin. If Telegram API calls failed or timed
out, the message was already marked inactive in the DB with no way to
retry. Now: get active message → unpin from all chats → deactivate in DB.
2026-04-24 18:01:52 +03:00
Fringg 52bf2a9589 fix: ignore bot's own messages in unknown message handlers 2026-04-24 17:55:37 +03:00
Egor 14e24a546e Merge pull request #2911 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.52.0
2026-04-24 17:12:13 +03:00
github-actions[bot] f60231e104 chore(main): release 3.52.0 2026-04-24 14:11:54 +00:00
Egor 920bab5b4f Merge pull request #2910 from BEDOLAGA-DEV/dev
Dev
2026-04-24 17:11:17 +03:00
Fringg 68d2350dfd fix: stop printing tracebacks for warning-level logs inside except blocks 2026-04-24 17:09:20 +03:00
Fringg 7d512d214a fix: integrate Yandex Metrika offline conv + S2S postback hooks
Restore integration hooks dropped in PR #2851 merge:
- PurchaseRequest accepts yandex_cid, referrer, subid from frontend
- Cache yandex_cid and subid in Redis at purchase creation (24h TTL)
- On fulfill_purchase: extract subid from cache, persist to DB
- Save Yandex CID from Redis to yandex_client_id_map
- Fire on_registration + S2S postback for new accounts
- Fire on_purchase + S2S postback for all paid purchases
- All hooks wrapped in try/except — failures never block delivery
2026-04-24 16:59:27 +03:00
Fringg 2cde38c63b fix: restore referrer field in admin landing purchases response 2026-04-24 16:53:47 +03:00
Fringg 24dc8d2a5e fix: restore HTTP Referer fallback for landing purchases 2026-04-24 16:47:22 +03:00
Fringg 1522d35f2d fix: gift purchases no longer inflate promo group level
Two bugs caused max promo group assignment on gift send/activate:

1. Buyer: GIFT_PAYMENT was counted in get_user_total_spent_kopeks
   alongside SUBSCRIPTION_PAYMENT. Now only SUBSCRIPTION_PAYMENT
   counts as personal spending for promo group auto-assignment.

2. Recipient: fulfill_purchase and activate_purchase created a
   SUBSCRIPTION_PAYMENT transaction for the recipient with the full
   gift price. Now skipped for gift recipients — they didn't pay.
2026-04-24 16:43:32 +03:00
Fringg 2b0d8a2a88 style: ruff format admin_bulk_actions.py 2026-04-24 16:34:43 +03:00
Fringg 9217f4116f fix: sanitize error messages in all bulk action catch-all handlers
Replace str(exc) with generic 'Action failed: internal error' in both
_execute_for_user and _execute_for_subscription catch-all blocks.
Prevents leaking internal paths, SQL details, or connection strings.
2026-04-24 16:24:45 +03:00
Fringg 2e45a93bd7 fix: bulk delete_user — pass real admin_id, sanitize error messages
- Thread admin_id through _execute_for_user to _do_delete_user for audit trail
- Replace raw exception str(e) with generic error message in client response
- Add subscriptions=[] to failure paths to prevent MissingGreenlet
2026-04-24 16:16:50 +03:00
Fringg d77fd81e16 feat: bulk actions — campaign/partner filters, delete_user action
- Add campaign_id and partner_id query params to GET /admin/users
- Filter users by advertising campaign via EXISTS subquery on registrations
- Filter users by partner via JOIN campaign registrations → campaigns
- Add DELETE_USER bulk action type with delete_from_panel param
- Handler calls UserService.delete_user_account for full bot+panel removal
- Permission check: users:delete required for delete_user action
- Add to _USER_LEVEL_ACTIONS (operates on user_ids, not subscription_ids)
2026-04-24 16:07:14 +03:00
Fringg bdb8cab1c9 feat: info page tab replacement — replaces_tab field + API
- Add replaces_tab column to InfoPage ('faq','rules','privacy','offer')
- Migration 0067: add nullable replaces_tab column
- CRUD: clear_replaces_tab ensures one page per tab, get_tab_replacements
  returns {tab: slug} mapping for active pages
- Admin routes: auto-clear old assignment on create/update
- Public route: GET /info-pages/tab-replacements (no auth)
- Schemas: replaces_tab with regex validation in all request/response models
2026-04-24 14:21:32 +03:00
Fringg d394565fe9 feat: FAQ support in info pages — page_type field + migration
- Add page_type column to InfoPage model ('page' or 'faq')
- Migration 0066: ALTER TABLE ADD COLUMN with server_default='page'
- Update schemas with page_type field and regex validation
- Update CRUD: page_type in create, filter in list
- Update admin/public routes with page_type query filter
- Backward compatible: existing pages default to type 'page'
2026-04-24 14:01:18 +03:00
Fringg 122d12db20 fix: /reorder route unreachable — move before /{page_id} path param 2026-04-24 13:50:38 +03:00
Fringg 2071a680d3 fix: info pages review — deduplicate slug index, type reorder items
- Remove triple-redundant slug index: keep only unique=True on column
  (PostgreSQL creates unique index automatically), remove __table_args__
  index and explicit create_index in migration
- Type ReorderRequest.items with ReorderItem(id: int, sort_order: int)
  instead of raw dict — prevents unvalidated input causing 500
- Migration downgrade: just drop_table (unique constraint drops with it)
2026-04-24 08:21:41 +03:00
Fringg e4b4a54797 feat: information pages — CRUD model, admin API, public API
- InfoPage model: slug, title (JSONB locale dict), content (JSONB),
  is_active, sort_order, icon, created_at/updated_at
- CRUD: create, get by id/slug, list, update, delete, reorder
- Admin routes: /admin/info-pages with full CRUD, toggle-active, reorder
  (permissions: settings:read/settings:edit)
- Public routes: /info-pages list active, /info-pages/{slug} get by slug
- Migration 0065: create info_pages table with unique slug index
- Custom pages support: admins can create any info page with any slug
2026-04-24 08:09:54 +03:00
Fringg 59c54c9b39 fix: privacy policy and offer text display HTML links as plain text
parse_mode='HTML' was missing from message sends during /start
registration. HTML tags like <a href="..."> were shown as literal
text instead of rendered links.

Fixed in 4 places:
- Privacy policy edit_text (line 1151)
- Privacy policy fallback answer (line 1158)
- Welcome/offer text in complete_registration_from_callback (line 1729)
- Welcome/offer text in complete_registration (line 2084)
2026-04-24 07:43:54 +03:00
Fringg 0d2b1dfdc9 feat: support multiple tariff_ids in user list filter
tariff_id query param now accepts comma-separated IDs (e.g.
tariff_id=1,3,5). CRUD functions updated to use IN() operator
for multi-tariff server-side filtering. Pagination works correctly
with multiple tariffs selected.
2026-04-24 07:16:33 +03:00
Fringg 605f202191 feat: bulk delete_subscription action — removes from bot DB + RemnaWave
Deactivates user in RemnaWave panel first, then deletes subscription
with related SubscriptionServer and TrafficPurchase records.
Subscription-level action (works with subscription_ids targeting).
2026-04-24 06:50:44 +03:00
Fringg be787a85bf feat: bulk set_devices action + device info in subscription list
- Add SET_DEVICES bulk action: sets device_limit on subscriptions,
  syncs to RemnaWave panel (subscription-level action)
- Add device_limit to SubscriptionListItem and BulkSubscriptionInfo
  schemas for frontend display
- Populate device_limit in _build_user_list_item and
  _build_subscription_info helpers
2026-04-24 06:35:29 +03:00
Fringg ff41ea9abb fix: suppress 'User already enabled' traceback in bulk add_traffic 2026-04-24 06:11:02 +03:00
Fringg cfbcc3082f fix: always return subscriptions list in user list API
subscriptions were only populated when is_multi_tariff_enabled()
was true. Users with multiple subscriptions in regular tariff mode
had empty subscriptions[] — bulk actions couldn't show or select them.
Now subscriptions are always populated regardless of tariff mode.
2026-04-24 06:08:23 +03:00
Fringg 2ad893badf fix: MissingGreenlet in subscription-ids bulk actions
_execute_for_subscription accessed user.subscriptions after commit,
triggering async lazy load → MissingGreenlet. Actions committed
successfully but reported as failed with cryptic error message.

Fix: use _build_subscription_info([sub]) with the already-loaded
targeted subscription instead of trying to lazy-load the full
user.subscriptions list.
2026-04-24 05:55:06 +03:00
Fringg e78177b2fc feat: multi-tariff bulk actions — subscription-level targeting
- Add subscription_ids to BulkExecuteRequest (mutually exclusive with
  user_ids via model_validator). Admins can now target specific
  subscriptions instead of auto-resolving the first active one.
- Add _execute_for_subscription dispatcher that loads subscription by
  ID, gets user, and passes sub_override to action handlers
- Add sub_override parameter to all 5 subscription-level handlers
  (extend, cancel, activate, change_tariff, add_traffic) — bypasses
  _resolve_subscription when a specific subscription is targeted
- Add SubscriptionListItem to UserListItem response — in multi-tariff
  mode, each user row includes all their subscriptions with tariff
  name, status, days remaining, traffic info
- User-level actions (add_balance, assign_promo_group, grant) reject
  subscription_ids with 400
- Add subscription_id field to BulkUserResult and SSE progress events
- Add _stream_bulk_execute_subscriptions SSE generator
- Backward compatible: existing user_ids requests work unchanged
2026-04-24 05:41:04 +03:00
Fringg daa472570c fix: add subscription/tariff/promo_group filters to admin user list API
The bulk actions page filters (subscription_status, tariff_id,
promo_group_id) were sent by the frontend but ignored by the
backend — the list_users endpoint had no such parameters.

- Add subscription_status, tariff_id, promo_group_id query params
  to GET /cabinet/admin/users
- Add subscription-level filtering via subquery in get_users_list
  and get_users_count CRUD functions
- Add tariff_id, tariff_name, traffic_used_gb, traffic_limit_gb,
  device_limit, days_remaining to UserListItem response schema
- Populate tariff info from subscription.tariff relationship in
  _build_user_list_item
2026-04-24 05:24:53 +03:00
Fringg db7b6734fd fix: bulk change_tariff not clearing squads when new tariff has none
When switching to a tariff with empty/null allowed_squads, the old
tariff's squads were preserved on the subscription. Now always sets
connected_squads from the new tariff (or empty list).
2026-04-24 05:10:47 +03:00
Fringg c0e0756b9a feat: bulk actions — SSE streaming progress, grant subscription, multi-tariff info
- Add SSE streaming mode (?stream=true): per-user progress events with
  real-time success/error counts, final summary event
- Add GRANT_SUBSCRIPTION action: creates new subscription with tariff,
  skips users who already have that tariff (multi-tariff aware),
  handles IntegrityError with graceful rollback
- Add BulkSubscriptionInfo: returns all user's subscriptions in each
  result for multi-tariff visibility
- Refactor: extract _validate_and_prepare and _execute_for_user helpers
  shared by streaming and non-streaming paths
2026-04-24 04:32:16 +03:00
Fringg 5b45d4354f fix: bulk actions review — rollback on error, multi-tariff constraint checks
- Add db.rollback() in per-user exception handler to prevent session
  poisoning (one failed commit would abort all subsequent users)
- Add multi-tariff duplicate subscription check in activate_subscription
  (prevents uq_subscriptions_user_tariff_active violation)
- Add multi-tariff duplicate subscription check in change_tariff
  (prevents switching to a tariff the user already holds)
2026-04-24 04:24:20 +03:00
Fringg fb2773fee4 feat: admin bulk actions API — mass operations on users
Add POST /cabinet/admin/bulk/execute endpoint for applying operations
to multiple users at once (up to 500 per request):

- extend_subscription / add_days: extend subscription by N days
- cancel_subscription: deactivate and expire subscriptions
- activate_subscription: reactivate expired subscriptions
- change_tariff: switch tariff without changing remaining days
- add_traffic: add extra GB to subscription traffic
- add_balance: credit balance with transaction record
- assign_promo_group: set or remove promo group for users

Features: dry_run preview mode, partial success handling (per-user
try/except), param validation before loop, auto-panel sync after
subscription mutations, multi-tariff mode support
2026-04-24 04:15:07 +03:00
Fringg ae7feeb726 fix: server squad sync fails on fresh DB without default promo group
On first startup with empty database, ensure_servers_synced() fetched
squads from RemnaWave but create_server_squad() failed with
ValueError('Server squad must be linked to at least one promo group')
because no default promo group existed yet.

Now _get_default_promo_group_id() auto-creates a default promo group
via _get_or_create_default_promo_group() when none exists, matching
the pattern used throughout the codebase for user registration.
2026-04-24 03:32:29 +03:00
Egor bcf5519880 Merge pull request #2904 from BEDOLAGA-DEV/dev
docs: add Overpay to README with partner block
2026-04-23 05:29:22 +03:00
Fringg 70568f82c5 docs: add Overpay to README with partner block 2026-04-23 05:25:49 +03:00
Egor 6fbd0bff28 Merge pull request #2903 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.51.0
2026-04-23 05:20:56 +03:00
github-actions[bot] dff3eb14a1 chore(main): release 3.51.0 2026-04-23 02:20:25 +00:00
Egor fab3d54f24 Merge pull request #2902 from BEDOLAGA-DEV/dev
Dev
2026-04-23 05:20:02 +03:00
Fringg 2c3ffc8c8a feat: integrate Overpay payment provider (pay.overpay.io)
Full integration across bot, cabinet, admin panel and landing pages:

- Config: 16 OVERPAY_* settings (API URL, credentials, P12 cert path,
  project ID, currency, amount limits, webhook path, payment methods)
- Service: overpay_service.py with httpx mTLS (P12 cert) + Basic Auth,
  create_payment, get_payment, refund_payment methods
- Payment mixin: OverpayPaymentMixin with create, webhook processing,
  finalize (balance credit + notifications), status check
- Model: OverpayPayment table + OVERPAY enum value
- CRUD: 9 standard operations (create, get_by_*, for_update, link)
- Bot handler: start_overpay_topup + process_overpay_payment_amount
- Handler registration: route_payment_by_method + callback registration
- Webhook: POST /overpay-webhook with DB-based anti-spoofing validation
- Cabinet: balance topup + guest payment dispatch
- Keyboard: payment method button in bot
- Admin: settings category + test payment button
- Infrastructure: payment_method_config_service, system_settings_service,
  payment_verification_service, payment_search_service
- Migration 0064: create overpay_payments table

Overpay API specifics: amount as string "100.00" (not kopeks),
success status "charged", HPP redirect via resultUrl
2026-04-23 04:36:56 +03:00
Fringg 6f87563789 fix: pad short RemnaWave usernames to meet 3-char minimum
RemnaWave API requires username >= 3 characters. Users with short
Telegram names (e.g. "Su") produced 2-char usernames that failed
validation, preventing subscription sync after payment.

Now format_remnawave_username pads short results with the user
identifier (telegram_id/email/user_id) to ensure minimum length.
2026-04-23 03:49:35 +03:00
Fringg 7005052156 fix: inactive user cleanup deletes users with paid subscriptions
The get_inactive_users query filtered only by last_activity (last bot
interaction), ignoring subscription end dates. Users who bought long
subscriptions (3-6-12 months) but didn't interact with the bot got
flagged as inactive and deleted+banned while their subscription was
still active or recently expired.

Fix: add SQL subquery excluding users who have ANY subscription with
end_date >= threshold_date. A user is now only deletable when BOTH
their last_activity AND their latest subscription end_date are older
than the configured inactivity period.
2026-04-23 03:40:45 +03:00
Fringg 29ae7089aa feat: respond to unknown media messages (photos, videos, documents)
Previously the bot only responded "Не понимаю эту команду" to text
messages. Photos, videos, documents and stickers sent outside of an
active FSM state were silently ignored, causing users to think their
media was received when it wasn't (e.g. support ticket screenshots
sent as separate messages).

Now the bot replies with the same "use menu buttons" message for any
unhandled media when no FSM state is active.
2026-04-23 03:31:21 +03:00
Egor 80e953a07b Merge pull request #2901 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.50.0
2026-04-22 06:18:07 +03:00
github-actions[bot] aebf58068f chore(main): release 3.50.0 2026-04-22 03:17:36 +00:00
Egor a491fe34bd Merge pull request #2900 from BEDOLAGA-DEV/dev
feat: v3.50.0 release
2026-04-22 06:17:09 +03:00
Egor 830e64afe0 Dev (#2899)
* fix: устранить MissingGreenlet в автоплатежах и починить traceback в логах

- subtract_user_balance: пишем promo_offer_log в отдельной сессии вместо rollback после commit, который экспайрил объекты основной сессии и ломал последующие обращения к subscription/user attrs
- monitoring_service._process_autopayments: перезагружаем subscription с eager-load user/tariff после списания, оборачиваем каждую итерацию в try/except + rollback, чтобы одна ошибка не валила весь батч
- logging_config: новый processor _auto_capture_exc_info автоматически подтягивает traceback из sys.exc_info() или error-kwarg → полный traceback в файле, консоли и Telegram без exc_info=True на каждом вызове
- logging_handler: дублирующая логика захвата exc_info в TelegramNotifierProcessor как резерв

* fix: устранить root cause MissingGreenlet в автоплатежах через refetch по id

Трейс показал: subscription.user падает на lazy-load → pool._checkout →
do_ping → await_ → MissingGreenlet. SQLAlchemy 2.0 async session не
поддерживает sync-lazy-load для relationships. Причина рассинхрона:
lock_user_for_pricing делает populate_existing=True + selectinload(
User.subscriptions).selectinload(Subscription.tariff), что разгружает
Subscription.user backref для сестринских подписок того же user.
Последующее обращение sub.user у другой подписки падает.

Фикс: захватываем (sub_id, user_id) пары ДО цикла, каждую итерацию
делаем fresh refetch через async select с eager load user+tariff+
promo_group. Никаких lazy access в горячем пути. В except используем
локально захваченные id вместо getattr(subscription, ...), чтобы
логирование не падало каскадом на expired объекте.

* fix: grant all available squads for unrestricted trials (#2897)

* feat: add WEBHOOK_IP to allow Telegram bypass DNS lookup for webhook (#2894)

* feat: add WEBHOOK_IP to allow Telegram bypass DNS lookup for webhook

* style: ruff format main.py

---------

Co-authored-by: Dmitry Lunin <br@slack.ru>

* fix: do not update first_name/last_name from OIDC claims (#2892)

Co-authored-by: Dmitry Lunin <br@slack.ru>

* fix: do not reset subscription_crypto_link when cryptoLink absent in webhook (#2891)

Co-authored-by: Dmitry Lunin <br@slack.ru>

* fix: FSM state loss on balance topup, PayPear confirmation_url, hidden trial tariff in renewal

- balance/platega: re-set FSM state after min/max validation errors,
  set state before pending_amount path, use balance_topup callback for back button
- balance/main: set FSM state and payment_method in handle_topup_amount_callback
  for all providers before routing, use balance_topup callback in validation errors
- payment/paypear: fix confirmation_url key (was 'url'), add fallback,
  store charged amount with commission for correct webhook amount comparison
- tariff_purchase: redirect to active tariff list when current tariff is
  inactive (hidden trial after promo code activation)
- cabinet/renewal: check tariff.is_active in both GET and POST endpoints
  to prevent hidden trial tariff periods from appearing

* fix: tariff switch pricing showing free for upgrades, admin duplicate subscription guard

- pricing_engine: use shortest period for daily rate comparison instead
  of period closest to remaining_days — fixes incorrect free/zero cost
  for upgrades when tariffs have different period sets
- pricing_engine: remove unused target_days parameter from
  get_tariff_daily_rate_fraction
- admin_users: add duplicate subscription check before create,
  change_tariff and activate actions to prevent UniqueViolationError
  on uq_subscriptions_user_tariff_active constraint
- admin_users: add IntegrityError fallback on create as TOCTOU safety net

* feat: tariff switch direction control, fix device pricing within tariff limit

Tariff switch direction:
- Add TARIFF_SWITCH_UPGRADE_ENABLED and TARIFF_SWITCH_DOWNGRADE_ENABLED
  settings to control allowed switch directions
- Guard all 10 entry points: instant switch (list, preview, confirm),
  legacy switch (list, select, confirm, daily confirm), cabinet (preview,
  execute), purchase-options API
- Filter tariff lists by allowed direction, show "unavailable" when
  both directions disabled
- Expose settings in cabinet purchase-options response for frontend

Device pricing fix:
- Devices within tariff.device_limit are now free when restoring
  (was charging for all devices regardless of tariff inclusion)
- Fix max(100, price) minimum enforcing 1 RUB even when
  chargeable_devices is 0
- Apply fix across all endpoints: bot handlers (confirm_change,
  execute_change, confirm_add), cabinet API (legacy purchase,
  modern purchase, get-price, save-cart), inline keyboard display

* fix: classic mode renewal resets device_limit to 1 via cart key mismatch

- Fix cart key mismatch: extend cart saved 'device_limit' but
  confirm_purchase read 'devices' key, falling back to DEFAULT=1.
  Now both keys are saved in both cart-save paths
- Fix confirm_purchase device resolution: use explicit is None checks
  instead of or-chain to avoid falsy-zero trap
- Fix return_to_saved_cart display: fall back to 'device_limit' and
  'traffic_limit_gb' keys when 'devices'/'traffic_gb' are absent
- Fix second cart-save path in _extend_existing_subscription with
  same dual-key pattern
- Fix RemnaWaveService import path in renewal service
- Add RESET_DEVICES_ON_RENEWAL setting: resets all connected devices
  (hwid) via RemnaWave API on each subscription renewal

* fix: menu layout schema icon limit, traffic_topup_enabled condition, shadowing imports

- Increase icon max_length from 10 to 100 in all three schemas
  (MenuButtonConfig, ButtonUpdateRequest, AddCustomButtonRequest)
  to support Telegram Custom Emoji IDs
- Add traffic_topup_enabled condition to ButtonConditions schema
- Remove shadowing local imports of MenuLayoutService in
  routes/menu_layout.py (top-level import already provides access)

* feat(tickets): multi-media message gallery (media_items JSONB)

- Add media_items JSONB column to TicketMessage model for multi-media
  gallery support (photos/videos/documents in one bubble)
- Add TicketMediaItem schema with type validation and shared
  _validate_media_bundle helper (max 10 items, legacy field compat)
- Update admin and user ticket handlers to store media_items and
  back-fill legacy media_type/media_file_id/media_caption from first
  item for backward compatibility
- Update _message_to_response in both admin and user routes to include
  media_items in API responses
- Allow empty message text when media is attached (message field now
  defaults to empty string with model validator ensuring text or media)
- Add migration 0061 with idempotent column check

Based on PR #2869 by @smediainfo — CI/CD workflow changes excluded
(hardcoded version strings would regress dynamic manifest reading)

* fix: ticket media_items review fixes

- Add if has_media else None guards in user-side ticket handlers
  (create_ticket, add_message) matching admin handler pattern
- Fix Telegram notification using resolved primary_file_id/primary_type
  instead of raw request fields for gallery messages
- Narrow except Exception to (TypeError, KeyError, ValueError) in
  _message_to_response with warning log for debugging
- Add media_items parameter to TicketCRUD.create_ticket and
  TicketCRUD.add_message for CRUD layer parity
- Add TicketMediaItemResponse and media_items field to webapi
  TicketMessageResponse to prevent data loss on read

* feat: landing page analytics goals and sticky pay button

- Add sticky_pay_button, analytics_view_enabled, analytics_view_goal,
  analytics_click_enabled, analytics_click_goal columns to LandingPage
- Add fields to CRUD updatable fields, admin create/update/detail
  schemas, create_landing() kwargs, _landing_to_detail() response
- Expose sticky_pay_button and analytics fields in public landing
  config response for frontend Yandex Metrika integration
- Add migration 0062 with idempotent column checks

Based on PR #2852 by @smediainfo — CI/CD workflow changes excluded
(hardcoded version strings would regress dynamic manifest reading)

* fix: validate analytics goal is set when analytics is enabled on landing

Prevent enabling analytics_view/click without providing the
corresponding goal identifier, which would result in empty
Yandex Metrika calls on the frontend.

* feat: Yandex Metrika offline conversions + S2S postbacks

- Add YandexClientIdMap model for user → yandex_cid mapping with
  upsert-safe CRUD (ON CONFLICT DO UPDATE)
- Add yandex_cid, subid, referrer columns to GuestPurchase
- Add yandex_offline_conv_service: Measurement Protocol integration
  with mc.yandex.ru/collect (registration, trial, purchase events),
  background task management, CID parsing from /start params
- Add s2s_postback_service: server-to-server affiliate postbacks
  with URL template placeholders and URL-safe encoding
- Add analytics offline conversion info to branding API (masked secret)
- Add POST /analytics/yandex-cid endpoint for cabinet CID capture
- Add 11 config settings (YANDEX_OFFLINE_CONV_*, S2S_POSTBACK_*)
- Add migration 0063 (yandex_client_id_map table + guest_purchases cols)
- Fix: mask measurement secret aggressively (show only last 4 chars)
- Fix: always replace {user_id} placeholder in S2S postback URLs
- Fix: use structlog kwargs instead of f-strings with LOG_PREFIX

Based on PR #2851 by @smediainfo — CI/CD workflow changes excluded

---------

Co-authored-by: c0mrade <killmy666@gmail.com>
Co-authored-by: Danila Yudin <danyayudin2012@gmail.com>
Co-authored-by: Dmitry V. Lunin <49199230+BlackRaincoat@users.noreply.github.com>
Co-authored-by: Dmitry Lunin <br@slack.ru>
2026-04-22 06:08:26 +03:00
Fringg 1068c1387a feat: Yandex Metrika offline conversions + S2S postbacks
- Add YandexClientIdMap model for user → yandex_cid mapping with
  upsert-safe CRUD (ON CONFLICT DO UPDATE)
- Add yandex_cid, subid, referrer columns to GuestPurchase
- Add yandex_offline_conv_service: Measurement Protocol integration
  with mc.yandex.ru/collect (registration, trial, purchase events),
  background task management, CID parsing from /start params
- Add s2s_postback_service: server-to-server affiliate postbacks
  with URL template placeholders and URL-safe encoding
- Add analytics offline conversion info to branding API (masked secret)
- Add POST /analytics/yandex-cid endpoint for cabinet CID capture
- Add 11 config settings (YANDEX_OFFLINE_CONV_*, S2S_POSTBACK_*)
- Add migration 0063 (yandex_client_id_map table + guest_purchases cols)
- Fix: mask measurement secret aggressively (show only last 4 chars)
- Fix: always replace {user_id} placeholder in S2S postback URLs
- Fix: use structlog kwargs instead of f-strings with LOG_PREFIX

Based on PR #2851 by @smediainfo — CI/CD workflow changes excluded
2026-04-22 05:57:46 +03:00
Fringg d31632534b fix: validate analytics goal is set when analytics is enabled on landing
Prevent enabling analytics_view/click without providing the
corresponding goal identifier, which would result in empty
Yandex Metrika calls on the frontend.
2026-04-22 05:43:54 +03:00
Fringg 3272b4bb05 feat: landing page analytics goals and sticky pay button
- Add sticky_pay_button, analytics_view_enabled, analytics_view_goal,
  analytics_click_enabled, analytics_click_goal columns to LandingPage
- Add fields to CRUD updatable fields, admin create/update/detail
  schemas, create_landing() kwargs, _landing_to_detail() response
- Expose sticky_pay_button and analytics fields in public landing
  config response for frontend Yandex Metrika integration
- Add migration 0062 with idempotent column checks

Based on PR #2852 by @smediainfo — CI/CD workflow changes excluded
(hardcoded version strings would regress dynamic manifest reading)
2026-04-22 05:36:41 +03:00
Fringg dd177101f7 fix: ticket media_items review fixes
- Add if has_media else None guards in user-side ticket handlers
  (create_ticket, add_message) matching admin handler pattern
- Fix Telegram notification using resolved primary_file_id/primary_type
  instead of raw request fields for gallery messages
- Narrow except Exception to (TypeError, KeyError, ValueError) in
  _message_to_response with warning log for debugging
- Add media_items parameter to TicketCRUD.create_ticket and
  TicketCRUD.add_message for CRUD layer parity
- Add TicketMediaItemResponse and media_items field to webapi
  TicketMessageResponse to prevent data loss on read
2026-04-22 05:29:51 +03:00
Fringg 36571c4275 feat(tickets): multi-media message gallery (media_items JSONB)
- Add media_items JSONB column to TicketMessage model for multi-media
  gallery support (photos/videos/documents in one bubble)
- Add TicketMediaItem schema with type validation and shared
  _validate_media_bundle helper (max 10 items, legacy field compat)
- Update admin and user ticket handlers to store media_items and
  back-fill legacy media_type/media_file_id/media_caption from first
  item for backward compatibility
- Update _message_to_response in both admin and user routes to include
  media_items in API responses
- Allow empty message text when media is attached (message field now
  defaults to empty string with model validator ensuring text or media)
- Add migration 0061 with idempotent column check

Based on PR #2869 by @smediainfo — CI/CD workflow changes excluded
(hardcoded version strings would regress dynamic manifest reading)
2026-04-22 05:23:48 +03:00
Fringg 66f8577448 fix: menu layout schema icon limit, traffic_topup_enabled condition, shadowing imports
- Increase icon max_length from 10 to 100 in all three schemas
  (MenuButtonConfig, ButtonUpdateRequest, AddCustomButtonRequest)
  to support Telegram Custom Emoji IDs
- Add traffic_topup_enabled condition to ButtonConditions schema
- Remove shadowing local imports of MenuLayoutService in
  routes/menu_layout.py (top-level import already provides access)
2026-04-22 05:17:56 +03:00
Fringg 9ca3320a02 fix: classic mode renewal resets device_limit to 1 via cart key mismatch
- Fix cart key mismatch: extend cart saved 'device_limit' but
  confirm_purchase read 'devices' key, falling back to DEFAULT=1.
  Now both keys are saved in both cart-save paths
- Fix confirm_purchase device resolution: use explicit is None checks
  instead of or-chain to avoid falsy-zero trap
- Fix return_to_saved_cart display: fall back to 'device_limit' and
  'traffic_limit_gb' keys when 'devices'/'traffic_gb' are absent
- Fix second cart-save path in _extend_existing_subscription with
  same dual-key pattern
- Fix RemnaWaveService import path in renewal service
- Add RESET_DEVICES_ON_RENEWAL setting: resets all connected devices
  (hwid) via RemnaWave API on each subscription renewal
2026-04-22 05:12:27 +03:00
Fringg 9ed4f086b0 feat: tariff switch direction control, fix device pricing within tariff limit
Tariff switch direction:
- Add TARIFF_SWITCH_UPGRADE_ENABLED and TARIFF_SWITCH_DOWNGRADE_ENABLED
  settings to control allowed switch directions
- Guard all 10 entry points: instant switch (list, preview, confirm),
  legacy switch (list, select, confirm, daily confirm), cabinet (preview,
  execute), purchase-options API
- Filter tariff lists by allowed direction, show "unavailable" when
  both directions disabled
- Expose settings in cabinet purchase-options response for frontend

Device pricing fix:
- Devices within tariff.device_limit are now free when restoring
  (was charging for all devices regardless of tariff inclusion)
- Fix max(100, price) minimum enforcing 1 RUB even when
  chargeable_devices is 0
- Apply fix across all endpoints: bot handlers (confirm_change,
  execute_change, confirm_add), cabinet API (legacy purchase,
  modern purchase, get-price, save-cart), inline keyboard display
2026-04-22 04:54:17 +03:00
Fringg da855a7c89 fix: tariff switch pricing showing free for upgrades, admin duplicate subscription guard
- pricing_engine: use shortest period for daily rate comparison instead
  of period closest to remaining_days — fixes incorrect free/zero cost
  for upgrades when tariffs have different period sets
- pricing_engine: remove unused target_days parameter from
  get_tariff_daily_rate_fraction
- admin_users: add duplicate subscription check before create,
  change_tariff and activate actions to prevent UniqueViolationError
  on uq_subscriptions_user_tariff_active constraint
- admin_users: add IntegrityError fallback on create as TOCTOU safety net
2026-04-22 04:25:42 +03:00
Fringg 7be404b918 fix: FSM state loss on balance topup, PayPear confirmation_url, hidden trial tariff in renewal
- balance/platega: re-set FSM state after min/max validation errors,
  set state before pending_amount path, use balance_topup callback for back button
- balance/main: set FSM state and payment_method in handle_topup_amount_callback
  for all providers before routing, use balance_topup callback in validation errors
- payment/paypear: fix confirmation_url key (was 'url'), add fallback,
  store charged amount with commission for correct webhook amount comparison
- tariff_purchase: redirect to active tariff list when current tariff is
  inactive (hidden trial after promo code activation)
- cabinet/renewal: check tariff.is_active in both GET and POST endpoints
  to prevent hidden trial tariff periods from appearing
2026-04-22 04:05:46 +03:00
Dmitry V. Lunin b71e58c8d2 fix: do not reset subscription_crypto_link when cryptoLink absent in webhook (#2891)
Co-authored-by: Dmitry Lunin <br@slack.ru>
2026-04-21 08:05:11 +03:00
Dmitry V. Lunin 1696e6f884 fix: do not update first_name/last_name from OIDC claims (#2892)
Co-authored-by: Dmitry Lunin <br@slack.ru>
2026-04-21 08:04:00 +03:00
Dmitry V. Lunin 7093d368d3 feat: add WEBHOOK_IP to allow Telegram bypass DNS lookup for webhook (#2894)
* feat: add WEBHOOK_IP to allow Telegram bypass DNS lookup for webhook

* style: ruff format main.py

---------

Co-authored-by: Dmitry Lunin <br@slack.ru>
2026-04-21 08:02:53 +03:00
Danila Yudin 905cea68b4 fix: grant all available squads for unrestricted trials (#2897) 2026-04-21 08:01:28 +03:00
Egor dc5442223d Merge pull request #2898 from BEDOLAGA-DEV/main
w
2026-04-21 07:53:33 +03:00
c0mrade 3b03c253cc fix: устранить root cause MissingGreenlet в автоплатежах через refetch по id
Трейс показал: subscription.user падает на lazy-load → pool._checkout →
do_ping → await_ → MissingGreenlet. SQLAlchemy 2.0 async session не
поддерживает sync-lazy-load для relationships. Причина рассинхрона:
lock_user_for_pricing делает populate_existing=True + selectinload(
User.subscriptions).selectinload(Subscription.tariff), что разгружает
Subscription.user backref для сестринских подписок того же user.
Последующее обращение sub.user у другой подписки падает.

Фикс: захватываем (sub_id, user_id) пары ДО цикла, каждую итерацию
делаем fresh refetch через async select с eager load user+tariff+
promo_group. Никаких lazy access в горячем пути. В except используем
локально захваченные id вместо getattr(subscription, ...), чтобы
логирование не падало каскадом на expired объекте.
2026-04-19 12:08:34 +03:00
c0mrade db79cc9eb0 fix: устранить MissingGreenlet в автоплатежах и починить traceback в логах
- subtract_user_balance: пишем promo_offer_log в отдельной сессии вместо rollback после commit, который экспайрил объекты основной сессии и ломал последующие обращения к subscription/user attrs
- monitoring_service._process_autopayments: перезагружаем subscription с eager-load user/tariff после списания, оборачиваем каждую итерацию в try/except + rollback, чтобы одна ошибка не валила весь батч
- logging_config: новый processor _auto_capture_exc_info автоматически подтягивает traceback из sys.exc_info() или error-kwarg → полный traceback в файле, консоли и Telegram без exc_info=True на каждом вызове
- logging_handler: дублирующая логика захвата exc_info в TelegramNotifierProcessor как резерв
2026-04-19 11:50:40 +03:00
Egor 1b94d9e700 Merge pull request #2890 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.49.0
2026-04-18 04:00:56 +03:00
github-actions[bot] 39a7c92cd4 chore(main): release 3.49.0 2026-04-18 00:58:34 +00:00
Egor 81ebec676c Merge pull request #2889 from BEDOLAGA-DEV/dev
Dev
2026-04-18 03:58:10 +03:00
Fringg 25ea5c60fd docs: add AuraPay to README with partner block 2026-04-18 03:56:48 +03:00
Fringg 29877fc93b fix: handle edge case when all tariffs are daily in legacy renewal 2026-04-18 01:09:53 +03:00
Fringg 5986c00fab fix: redirect legacy users without tariff to tariff selection on renewal
Users created before tariffs were introduced (tariff_id=NULL) got
"Тариф не найден" when pressing "Продлить подписку". Now they see
a tariff selection list instead, allowing them to pick a tariff
and renew with proper parameters (traffic, devices, etc).
2026-04-18 01:05:48 +03:00
Fringg ecc4a6147d fix: rate-limit daily subscription insufficient balance notifications to 6 hours
Users with daily subscriptions and low balance were getting
"Подписка приостановлена" notification every 30 minutes (on each
charge cycle). Now rate-limited via Redis cache to max 1 notification
per 6 hours per subscription.
2026-04-18 00:59:09 +03:00
Fringg 16bc1d4198 fix: align campaign top registrations revenue with period comparison
Top registrations list was summing DEPOSIT + SUBSCRIPTION_PAYMENT
transactions (total user spending), while period comparison revenue
only counted DEPOSIT with real payment methods (actual money paid in).

Now both use the same calculation: only DEPOSIT transactions with
real payment methods. This fixes the discrepancy where a user showed
500₽ in the list but total revenue was 250₽.
2026-04-18 00:50:23 +03:00
Fringg 0f814be1b7 fix: add missing RollyPay CRUD wrappers and guest payment flow
RollyPay was missing:
- 7 CRUD wrapper functions in payment_service.py (create, get, update, link)
- Guest payment block in create_guest_payment()

Both were present for PayPear and AuraPay but omitted for RollyPay.
2026-04-18 00:23:38 +03:00
Fringg 97179360c0 feat: integrate AuraPay payment provider
Full integration following PayPear/RollyPay patterns:
- API client with X-ApiKey + X-ShopId auth, HMAC-SHA256 webhook verification
  (sorted keys, concatenated values, secret key #2)
- AuraPayPaymentMixin with create, webhook, finalize (all side effects), status check
- CRUD, model, migration (0060), PaymentMethod.AURAPAY enum
- Webhook endpoint, cabinet topup, bot handler with sub-options (card, sbp)
- Admin panel: AURAPAY category in bot_configuration + system_settings_service
- Config: AURAPAY_ENABLED, AURAPAY_API_KEY, AURAPAY_SHOP_ID, AURAPAY_SECRET_KEY
2026-04-18 00:02:49 +03:00
Fringg 2aa5927433 fix: register PayPear and RollyPay in admin panel settings
- bot_configuration.py: added PAYPEAR/ROLLYPAY to payment categories
  and test payment buttons
- system_settings_service.py: added category titles, descriptions,
  and prefix mappings for PAYPEAR_* and ROLLYPAY_* settings
2026-04-17 23:44:35 +03:00
Egor 1c696c69e3 Merge pull request #2887 from BEDOLAGA-DEV/dev
docs: add PayPear and RollyPay to README with partner blocks
2026-04-16 06:26:19 +03:00
Fringg b531959982 docs: add PayPear and RollyPay to README with partner blocks 2026-04-16 06:25:33 +03:00
Egor ead0fc99d3 Merge pull request #2886 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.48.0
2026-04-16 06:11:21 +03:00
github-actions[bot] c09ae7436c chore(main): release 3.48.0 2026-04-16 03:10:42 +00:00
Egor 1ea76575ce Merge pull request #2885 from BEDOLAGA-DEV/dev
Dev
2026-04-16 06:10:19 +03:00
Fringg 25447edc9e docs: add SEVERPAY, PAYPEAR, ROLLYPAY to .env.example 2026-04-16 06:08:10 +03:00
Fringg a59858227f fix: support payment_method selection for RollyPay (sbp/card/crypto)
- Mixin accepts payment_method_type parameter (None = show all on form)
- API service sends payment_method only when specified
- Cabinet route passes payment_option to mixin
- Config service has sub_options: sbp, card, crypto
- Keyboard label no longer hardcodes "СБП"
2026-04-16 06:03:33 +03:00
Fringg ccc2f4efec feat: integrate RollyPay payment provider (SBP via USDT)
Full integration following PayPear/SeverPay patterns:
- API client with X-API-Key + X-Nonce auth, HMAC-SHA256 webhook verification
- RollyPayPaymentMixin with create, webhook, finalize (all side effects), status check
- CRUD, model, migration (0059), PaymentMethod.ROLLYPAY enum
- Webhook endpoint, cabinet topup, bot handler
- Statuses: created, processing, paid, expired, canceled, chargeback
- Config: ROLLYPAY_ENABLED, ROLLYPAY_API_KEY, ROLLYPAY_SIGNING_SECRET, etc.
2026-04-16 05:52:25 +03:00
Fringg a18f6caa9b feat: integrate PayPear payment provider
Full integration following SeverPay patterns:
- API client with Basic Auth, idempotency, HMAC webhook verification
- PayPearPaymentMixin with create, webhook, finalize (all side effects), status check
- CRUD, model, migration (0058), PaymentMethod.PAYPEAR enum
- Webhook endpoint, cabinet topup, bot handler, payment verification
- Sub-options: bank_card, sbp, sberpay, tpay
- Config: PAYPEAR_ENABLED, PAYPEAR_SHOP_ID, PAYPEAR_SECRET_KEY, etc.
2026-04-16 05:36:48 +03:00
Fringg 92eaf45311 fix: increase nalogo receipt queue retry window to 12 hours
Changed defaults from 10 attempts × 5min (50min total) to
72 attempts × 10min (12 hours total). When nalog.ru is temporarily
down, receipts now retry for 12 hours before being dropped,
giving the service enough time to recover.
2026-04-16 04:58:54 +03:00
Fringg 61cf495fc5 fix: show menu buttons for limited subscriptions in back-to-menu paths
The previous fix only covered /start command paths. The more common
show_main_menu and handle_back_to_menu in menu.py used their own
is_active check which returned False for limited status.

Now both paths treat limited subscriptions as active for UI, matching
the _calculate_subscription_flags fix in start.py.
2026-04-16 04:54:57 +03:00
Fringg 0c545490b6 fix: show menu buttons for limited (traffic exhausted) subscriptions
When Remnawave webhook set subscription status to 'limited' (traffic
exhausted), the main menu hid ALL buttons (connect, subscription,
buy traffic) because is_active returns False for non-'active' status.

Now 'limited' is treated as active for UI purposes — the subscription
is not expired, just traffic-exhausted. Users can see the "Buy traffic"
button precisely when they need it most.
2026-04-16 04:50:13 +03:00
Fringg 2d5afe5d75 fix: low balance alerts disabled by default, add quiet hours, expiry filter, top-up button
- Default balance_low_enabled changed to False (opt-in via cabinet)
- Quiet hours: alerts skipped between 22:00-09:00 UTC
- Only alerts when subscription expires within LOW_BALANCE_ALERT_EXPIRY_DAYS (default 3)
- Added inline "Top up" button linking to cabinet miniapp
- Synced defaults across notification_prefs, cabinet notifications route
2026-04-16 04:42:36 +03:00
Egor 50dc5a0fd1 Merge pull request #2882 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.47.0
2026-04-15 14:12:24 +03:00
github-actions[bot] 4dc8b4c091 chore(main): release 3.47.0 2026-04-15 11:10:30 +00:00
Egor 4db9e85062 feat: multi-tariff sync fix, daily discount fix, campaign links, TELEGRAM_API_URL
* fix: update subscription_crypto_link when syncing user from panel (#2867)

* fix: update subscription_crypto_link when syncing user from panel

* fix: update subscription_crypto_link when syncing user from panel

* fix: use PROXY_URL for Telegram OIDC JWKS requests (#2866)

* feat: add TELEGRAM_API_URL for custom Telegram Bot API server

Support custom Telegram Bot API server URL via TELEGRAM_API_URL env var.
Enables bot operation in regions where api.telegram.org is blocked
(Cloudflare Worker, self-hosted telegram-bot-api, nginx reverse proxy).
Uses native aiogram TelegramAPIServer.from_base(), works with PROXY_URL.

* fix(ci): read Docker image version from release-please manifest instead of hardcoding (#2859)

The x-release-please-version markers in workflow files were stuck at v3.7.0
since commit 5070bb34 removed them from extra-files (GitHub Actions returns
403 when release-please tries to modify .github/workflows/ via GITHUB_TOKEN).

Instead of hardcoding the version, read it from .release-please-manifest.json
at build time. This file is always kept in sync by release-please and does
not require workflow file write permissions.

---

Маркеры x-release-please-version в workflow-файлах застряли на v3.7.0
после коммита 5070bb34, который удалил их из extra-files (GitHub Actions
возвращает 403 при попытке release-please изменить .github/workflows/
через GITHUB_TOKEN).

Вместо хардкода версии теперь читаем её из .release-please-manifest.json
во время сборки. Этот файл всегда синхронизируется release-please и не
требует прав на запись в workflow-файлы.

* fix: format telegram_auth.py to use single quotes (ruff)

* fix: remove daily tariff fallback to smallest period discount

Daily tariffs (period_days=1) incorrectly inherited the discount
of the smallest configured period (e.g. 90 days -> 5%). This caused
daily prices to show discounts that were never intended for them.

Now daily tariffs only get a discount if explicitly configured for
period_days=1 in the promo group's period_discounts.

* fix: use CABINET_URL for campaign web links instead of MINIAPP_CUSTOM_URL

Campaign web links were generated from MINIAPP_CUSTOM_URL which is often
empty, causing get_campaign_web_link() to return None. Admins and partners
could only share bot links for campaigns, not cabinet links.

Now prefers CABINET_URL (where the auth flow captures ?campaign= param),
falling back to MINIAPP_CUSTOM_URL for backwards compatibility. This is
consistent with how referral web links already use CABINET_URL.

* feat: add DISPLAY_NAME_RESTRICTION_ENABLED toggle

Allows disabling the display name restriction middleware via .env.
Users with special characters in their Telegram name (e.g. "@")
were blocked from using the bot entirely. Default: true (enabled).

Set DISPLAY_NAME_RESTRICTION_ENABLED=false to disable.

* fix: allow clearing all period discounts from promo groups

Empty period_discounts dict was normalized to None by the schema,
making it indistinguishable from "field absent" (don't update).
Now empty dict passes through to CRUD which correctly sets
period_discounts=None in DB, clearing all discounts.

* fix: create panel user instead of update for new subscriptions in multi-tariff mode

In multi-tariff mode, new subscriptions have remnawave_uuid=None.
The old logic fell back to user.remnawave_uuid (from a previous
subscription) and called update_remnawave_user(), which refused
to work because the NEW subscription had no UUID.

Now correctly: in multi-tariff mode, always CREATE if subscription
has no remnawave_uuid. In single-tariff mode, use user-level UUID.

Fixes: "subscription has no remnawave_uuid, cannot update panel"

* fix: apply same create-vs-update fix to renewal and purchase flows

Same bug as the tariff purchase fix: in multi-tariff mode, new
subscriptions without remnawave_uuid incorrectly fell back to
user.remnawave_uuid and called update instead of create.

Fixed in subscription_renewal_service.py and purchase.py to use
the same _should_create pattern based on mode.

* fix: apply create-vs-update fix to all remaining tariff_purchase flows

Fixed 6 more locations in tariff_purchase.py that had the same broken
pattern (custom purchase, daily purchase, trial conversion, tariff
switch, daily switch, instant switch). All now use _should_create
based on multi-tariff mode instead of falling back to user UUID.

* fix: apply create-vs-update fix to cabinet traffic/devices and monitoring

Same multi-tariff create-vs-update bug in 5 more locations:
- cabinet/subscription_modules/traffic.py (2 instances)
- cabinet/subscription_modules/devices.py (2 instances)
- services/monitoring_service.py (1 instance)

All now use _should_create pattern based on subscription.remnawave_uuid
in multi-tariff mode instead of falling back to user.remnawave_uuid.

* fix: ruff format traffic.py and monitoring_service.py

---------

Co-authored-by: Dmitry V. Lunin <49199230+BlackRaincoat@users.noreply.github.com>
Co-authored-by: Gary Jarrel <gary@jarrel.com.au>
2026-04-15 14:10:05 +03:00
Egor fca8d6da97 Dev (#2880)
* fix: update subscription_crypto_link when syncing user from panel (#2867)

* fix: update subscription_crypto_link when syncing user from panel

* fix: update subscription_crypto_link when syncing user from panel

* fix: use PROXY_URL for Telegram OIDC JWKS requests (#2866)

* feat: add TELEGRAM_API_URL for custom Telegram Bot API server

Support custom Telegram Bot API server URL via TELEGRAM_API_URL env var.
Enables bot operation in regions where api.telegram.org is blocked
(Cloudflare Worker, self-hosted telegram-bot-api, nginx reverse proxy).
Uses native aiogram TelegramAPIServer.from_base(), works with PROXY_URL.

* fix(ci): read Docker image version from release-please manifest instead of hardcoding (#2859)

The x-release-please-version markers in workflow files were stuck at v3.7.0
since commit 5070bb34 removed them from extra-files (GitHub Actions returns
403 when release-please tries to modify .github/workflows/ via GITHUB_TOKEN).

Instead of hardcoding the version, read it from .release-please-manifest.json
at build time. This file is always kept in sync by release-please and does
not require workflow file write permissions.

---

Маркеры x-release-please-version в workflow-файлах застряли на v3.7.0
после коммита 5070bb34, который удалил их из extra-files (GitHub Actions
возвращает 403 при попытке release-please изменить .github/workflows/
через GITHUB_TOKEN).

Вместо хардкода версии теперь читаем её из .release-please-manifest.json
во время сборки. Этот файл всегда синхронизируется release-please и не
требует прав на запись в workflow-файлы.

* fix: format telegram_auth.py to use single quotes (ruff)

* fix: remove daily tariff fallback to smallest period discount

Daily tariffs (period_days=1) incorrectly inherited the discount
of the smallest configured period (e.g. 90 days -> 5%). This caused
daily prices to show discounts that were never intended for them.

Now daily tariffs only get a discount if explicitly configured for
period_days=1 in the promo group's period_discounts.

* fix: use CABINET_URL for campaign web links instead of MINIAPP_CUSTOM_URL

Campaign web links were generated from MINIAPP_CUSTOM_URL which is often
empty, causing get_campaign_web_link() to return None. Admins and partners
could only share bot links for campaigns, not cabinet links.

Now prefers CABINET_URL (where the auth flow captures ?campaign= param),
falling back to MINIAPP_CUSTOM_URL for backwards compatibility. This is
consistent with how referral web links already use CABINET_URL.

* feat: add DISPLAY_NAME_RESTRICTION_ENABLED toggle

Allows disabling the display name restriction middleware via .env.
Users with special characters in their Telegram name (e.g. "@")
were blocked from using the bot entirely. Default: true (enabled).

Set DISPLAY_NAME_RESTRICTION_ENABLED=false to disable.

* fix: allow clearing all period discounts from promo groups

Empty period_discounts dict was normalized to None by the schema,
making it indistinguishable from "field absent" (don't update).
Now empty dict passes through to CRUD which correctly sets
period_discounts=None in DB, clearing all discounts.

* fix: create panel user instead of update for new subscriptions in multi-tariff mode

In multi-tariff mode, new subscriptions have remnawave_uuid=None.
The old logic fell back to user.remnawave_uuid (from a previous
subscription) and called update_remnawave_user(), which refused
to work because the NEW subscription had no UUID.

Now correctly: in multi-tariff mode, always CREATE if subscription
has no remnawave_uuid. In single-tariff mode, use user-level UUID.

Fixes: "subscription has no remnawave_uuid, cannot update panel"

* fix: apply same create-vs-update fix to renewal and purchase flows

Same bug as the tariff purchase fix: in multi-tariff mode, new
subscriptions without remnawave_uuid incorrectly fell back to
user.remnawave_uuid and called update instead of create.

Fixed in subscription_renewal_service.py and purchase.py to use
the same _should_create pattern based on mode.

* fix: apply create-vs-update fix to all remaining tariff_purchase flows

Fixed 6 more locations in tariff_purchase.py that had the same broken
pattern (custom purchase, daily purchase, trial conversion, tariff
switch, daily switch, instant switch). All now use _should_create
based on multi-tariff mode instead of falling back to user UUID.

* fix: apply create-vs-update fix to cabinet traffic/devices and monitoring

Same multi-tariff create-vs-update bug in 5 more locations:
- cabinet/subscription_modules/traffic.py (2 instances)
- cabinet/subscription_modules/devices.py (2 instances)
- services/monitoring_service.py (1 instance)

All now use _should_create pattern based on subscription.remnawave_uuid
in multi-tariff mode instead of falling back to user.remnawave_uuid.

* fix: ruff format traffic.py and monitoring_service.py

---------

Co-authored-by: Dmitry V. Lunin <49199230+BlackRaincoat@users.noreply.github.com>
Co-authored-by: Gary Jarrel <gary@jarrel.com.au>
2026-04-15 14:04:16 +03:00
Fringg 4fe67a9c74 fix: ruff format traffic.py and monitoring_service.py 2026-04-15 13:57:15 +03:00
Fringg 30a1a31978 fix: apply create-vs-update fix to cabinet traffic/devices and monitoring
Same multi-tariff create-vs-update bug in 5 more locations:
- cabinet/subscription_modules/traffic.py (2 instances)
- cabinet/subscription_modules/devices.py (2 instances)
- services/monitoring_service.py (1 instance)

All now use _should_create pattern based on subscription.remnawave_uuid
in multi-tariff mode instead of falling back to user.remnawave_uuid.
2026-04-15 13:28:06 +03:00
Fringg c2b68e1afa fix: apply create-vs-update fix to all remaining tariff_purchase flows
Fixed 6 more locations in tariff_purchase.py that had the same broken
pattern (custom purchase, daily purchase, trial conversion, tariff
switch, daily switch, instant switch). All now use _should_create
based on multi-tariff mode instead of falling back to user UUID.
2026-04-15 13:24:07 +03:00
Fringg cea7260a85 fix: apply same create-vs-update fix to renewal and purchase flows
Same bug as the tariff purchase fix: in multi-tariff mode, new
subscriptions without remnawave_uuid incorrectly fell back to
user.remnawave_uuid and called update instead of create.

Fixed in subscription_renewal_service.py and purchase.py to use
the same _should_create pattern based on mode.
2026-04-15 13:17:35 +03:00
Fringg e3c0caabcf fix: create panel user instead of update for new subscriptions in multi-tariff mode
In multi-tariff mode, new subscriptions have remnawave_uuid=None.
The old logic fell back to user.remnawave_uuid (from a previous
subscription) and called update_remnawave_user(), which refused
to work because the NEW subscription had no UUID.

Now correctly: in multi-tariff mode, always CREATE if subscription
has no remnawave_uuid. In single-tariff mode, use user-level UUID.

Fixes: "subscription has no remnawave_uuid, cannot update panel"
2026-04-15 13:14:10 +03:00
Fringg aeaa4f8e0d fix: allow clearing all period discounts from promo groups
Empty period_discounts dict was normalized to None by the schema,
making it indistinguishable from "field absent" (don't update).
Now empty dict passes through to CRUD which correctly sets
period_discounts=None in DB, clearing all discounts.
2026-04-15 04:13:43 +03:00
Fringg e226ac8637 feat: add DISPLAY_NAME_RESTRICTION_ENABLED toggle
Allows disabling the display name restriction middleware via .env.
Users with special characters in their Telegram name (e.g. "@")
were blocked from using the bot entirely. Default: true (enabled).

Set DISPLAY_NAME_RESTRICTION_ENABLED=false to disable.
2026-04-15 04:03:18 +03:00
Fringg 85403da528 fix: use CABINET_URL for campaign web links instead of MINIAPP_CUSTOM_URL
Campaign web links were generated from MINIAPP_CUSTOM_URL which is often
empty, causing get_campaign_web_link() to return None. Admins and partners
could only share bot links for campaigns, not cabinet links.

Now prefers CABINET_URL (where the auth flow captures ?campaign= param),
falling back to MINIAPP_CUSTOM_URL for backwards compatibility. This is
consistent with how referral web links already use CABINET_URL.
2026-04-15 03:56:34 +03:00
Fringg bdd873382c fix: remove daily tariff fallback to smallest period discount
Daily tariffs (period_days=1) incorrectly inherited the discount
of the smallest configured period (e.g. 90 days -> 5%). This caused
daily prices to show discounts that were never intended for them.

Now daily tariffs only get a discount if explicitly configured for
period_days=1 in the promo group's period_discounts.
2026-04-15 03:39:52 +03:00
Fringg 9d750d9eb0 fix: format telegram_auth.py to use single quotes (ruff) 2026-04-15 03:34:49 +03:00
Gary Jarrel 87b83f59c6 fix(ci): read Docker image version from release-please manifest instead of hardcoding (#2859)
The x-release-please-version markers in workflow files were stuck at v3.7.0
since commit 5070bb34 removed them from extra-files (GitHub Actions returns
403 when release-please tries to modify .github/workflows/ via GITHUB_TOKEN).

Instead of hardcoding the version, read it from .release-please-manifest.json
at build time. This file is always kept in sync by release-please and does
not require workflow file write permissions.

---

Маркеры x-release-please-version в workflow-файлах застряли на v3.7.0
после коммита 5070bb34, который удалил их из extra-files (GitHub Actions
возвращает 403 при попытке release-please изменить .github/workflows/
через GITHUB_TOKEN).

Вместо хардкода версии теперь читаем её из .release-please-manifest.json
во время сборки. Этот файл всегда синхронизируется release-please и не
требует прав на запись в workflow-файлы.
2026-04-15 03:15:35 +03:00
Fringg 8ff6f99229 feat: add TELEGRAM_API_URL for custom Telegram Bot API server
Support custom Telegram Bot API server URL via TELEGRAM_API_URL env var.
Enables bot operation in regions where api.telegram.org is blocked
(Cloudflare Worker, self-hosted telegram-bot-api, nginx reverse proxy).
Uses native aiogram TelegramAPIServer.from_base(), works with PROXY_URL.
2026-04-15 03:12:59 +03:00
Dmitry V. Lunin 94da3c35b0 fix: use PROXY_URL for Telegram OIDC JWKS requests (#2866) 2026-04-15 03:08:06 +03:00
Dmitry V. Lunin d35a8bb74c fix: update subscription_crypto_link when syncing user from panel (#2867)
* fix: update subscription_crypto_link when syncing user from panel

* fix: update subscription_crypto_link when syncing user from panel
2026-04-15 03:07:07 +03:00
Egor c635d88764 Merge pull request #2878 from BEDOLAGA-DEV/main
w
2026-04-15 02:53:04 +03:00
c0mrade 5009703676 Merge pull request #2875 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.46.1
2026-04-13 22:09:58 +03:00
github-actions[bot] e88a5989b6 chore(main): release 3.46.1 2026-04-13 19:07:27 +00:00
c0mrade 02747381dc Merge pull request #2874 from BEDOLAGA-DEV/dev
fix: cabinet_refresh_tokens migration + notification_settings jsonb
2026-04-13 22:06:53 +03:00
c0mrade e74fda954c fix: change notification_settings from json to jsonb for DISTINCT compatibility 2026-04-13 21:56:04 +03:00
c0mrade 8587f03f67 fix: add checkfirst guards to cabinet_refresh_tokens migration 2026-04-13 21:47:16 +03:00
c0mrade 4707cdf60c fix: add missing migration for cabinet_refresh_tokens table 2026-04-13 21:43:46 +03:00
c0mrade 0879b8b218 Merge pull request #2873 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.46.0
2026-04-13 19:47:36 +03:00
github-actions[bot] 1d91382b8e chore(main): release 3.46.0 2026-04-13 16:37:54 +00:00
c0mrade 3768b18a39 Merge pull request #2872 from BEDOLAGA-DEV/dev
Bugfixes: campaign, tickets, NaloGO, devices, broadcasts, menu editor
2026-04-13 19:37:16 +03:00
c0mrade 1eeeb39779 fix: exclude users with active subscriptions from expired broadcast
In multi-subscription mode, a user with an expired trial AND an active
paid subscription was incorrectly included in expired broadcast targets.

Fixed in 3 places:
- get_target_users_count (SQL): added NOT EXISTS active sub subquery
- get_target_users 'expired' (Python): skip if has_active
- get_target_users 'expired_subscribers' (Python): same check
2026-04-13 19:21:52 +03:00
c0mrade 570af82dfd fix: raise MAX_BUTTONS_PER_ROW to 8 and allow tg:// deep links in menu editor
MAX_BUTTONS_PER_ROW was 3, causing Pydantic 422 when adding multiple
custom buttons to a row. Telegram allows up to 8 buttons per row.

Also added tg:// to URL_PATTERN so admins can use Telegram deep links
(tg://resolve, tg://user, etc.) in custom menu buttons. webapp mode
still requires https:// as enforced by existing validation.
2026-04-13 17:07:19 +03:00
c0mrade bc3893b934 fix: use MAX_DEVICES_LIMIT instead of hardcoded 10 for device buttons
Admin user device editor had hardcoded limit of 10 in text, validation,
and inline buttons. Now uses settings.MAX_DEVICES_LIMIT dynamically,
generating buttons 1..N in rows of 4. Falls back to text-only input
if limit exceeds Telegram's 100-button cap.
2026-04-13 14:42:16 +03:00
c0mrade 16d91638bc fix: enforce max_attempts limit in NaloGO receipt queue
The _max_attempts property existed but was never checked as a limit.
Receipts were retried indefinitely (55+ attempts observed in logs).
Now receipts exceeding max_attempts are removed from the queue.
2026-04-13 14:42:06 +03:00
c0mrade eb18b3a0f9 fix: handle TelegramBadRequest when deleting old ticket notifications
Messages older than 48 hours cannot be deleted via Telegram API.
Now falls back to editing the message text instead of crashing.
2026-04-13 14:41:59 +03:00
c0mrade a8e2b62f4b feat: save campaign_slug during standalone email registration
Campaign slug was lost during email registration flow — it was only
sent at verification time from localStorage, which is empty if the
user opens the verification link in a different browser/webview.

Now campaign_slug is accepted in the registration request, saved to
user.pending_campaign_slug, and used as fallback during email
verification. Also processed immediately for auto-verified test emails.
2026-04-13 14:41:49 +03:00
c0mrade fb8d2b3ee4 fix: upsert refresh tokens (ON CONFLICT) + periodic cleanup of expired/revoked tokens 2026-04-10 18:08:27 +03:00
c0mrade 2321667ecb fix: add TRAFFIC_WARNING_ALERT and LOW_BALANCE_ALERT localization keys to all locales 2026-04-10 17:58:04 +03:00
c0mrade 113304b212 style: remove unused import (ruff fix) 2026-04-10 16:47:41 +03:00
c0mrade 0300044b00 feat: add category field to broadcast API schemas and routes 2026-04-10 16:10:13 +03:00
c0mrade 931abfe7a5 feat: add broadcast category (system/news/promo) + filter recipients by user prefs 2026-04-10 16:05:43 +03:00
c0mrade 1d96f80f60 feat: add traffic % warning check using user's threshold preference 2026-04-10 15:59:32 +03:00
c0mrade 4e50419171 feat: implement low balance alert + respect user notification preferences
- Add _check_low_balance_alerts to monitoring service
- Notify users with autopay when balance drops below their threshold
- Uses notification_prefs helper for per-user settings
2026-04-10 15:43:32 +03:00
c0mrade 7208a52c94 feat: respect user traffic_warning notification preference in webhook handler 2026-04-10 15:37:33 +03:00
c0mrade 63fdfe4a42 feat: respect user subscription_expiry notification preferences 2026-04-10 15:37:00 +03:00
c0mrade e0e2edf816 feat: add user notification preferences helper utility 2026-04-10 15:35:30 +03:00
c0mrade 522a8779d6 style: fix ruff format for all sync-related changes 2026-04-10 15:13:59 +03:00
c0mrade be32010d63 fix: trial activation fallback to trial-eligible servers when tariff has no squads (BUG-12) + fix misleading button text 2026-04-10 15:04:38 +03:00
c0mrade 7e920fa30f fix: add retry queue to all remaining RemnaWave error handlers 2026-04-10 14:22:10 +03:00
c0mrade 1b376baeca fix: add retry queue to cabinet subscription operation RemnaWave errors 2026-04-10 11:56:48 +03:00
c0mrade 91a756a33e fix: add retry queue to payment webhook and renewal service RemnaWave errors 2026-04-10 11:56:24 +03:00
c0mrade 970dc549df fix: add retry queue to classic mode bot purchase handler 2026-04-10 11:40:20 +03:00
c0mrade 65120f0bad fix: add retry queue to daily subscription service RemnaWave errors 2026-04-10 11:39:39 +03:00
c0mrade 9cb559ff39 fix: enqueue retry on RemnaWave API failure in all purchase flows (BUG-2, BUG-10)
Add remnawave_retry_queue.enqueue() calls in all 10 purchase error handlers
where RemnaWave API failure was caught and swallowed without scheduling a retry:
- cabinet purchase.py: purchase_tariff() and activate_trial() (2 places)
- subscription_purchase_service.py: miniapp purchase flow (1 place)
- tariff_purchase.py: custom, standard, daily, renewal, switch, daily-switch,
  and instant-switch flows (7 places)
2026-04-10 11:04:02 +03:00
c0mrade 8f1882f24c feat: start RemnaWave retry queue on app startup 2026-04-10 10:48:14 +03:00
c0mrade 8542a39305 fix: always sync squads in auto-purchase renewal (BUG-4) 2026-04-10 10:48:01 +03:00
c0mrade 646ac4cfa1 fix: match tariff_id when creating subscriptions from panel sync (BUG-11) 2026-04-10 10:41:50 +03:00
c0mrade abdf296767 feat: add RemnaWave retry queue for failed API calls (BUG-2, BUG-10) 2026-04-10 10:41:49 +03:00
c0mrade a1b6d9bb61 fix: use update_remnawave_user when UUID exists in tariff_purchase (BUG-3) 2026-04-10 10:38:00 +03:00
c0mrade cf19e4e1f7 fix: protect OAuth users with remnawave_uuid from sync deactivation (BUG-6) 2026-04-10 10:36:16 +03:00
c0mrade 35412e9f21 fix: sync connected_squads from panel during sync (BUG-5) 2026-04-10 10:36:02 +03:00
c0mrade 6aed7d355b fix: default sync_squads=True in update_remnawave_user (BUG-4) 2026-04-10 10:34:56 +03:00
c0mrade 9c08ce6948 fix: resync RemnaWave after account merge (BUG-7) 2026-04-10 10:33:45 +03:00
c0mrade 862352139e fix: use 'is not None' for telegram_id in create_user API (BUG-9) 2026-04-10 10:33:25 +03:00
c0mrade d465ccb3ac fix: resync RemnaWave after Telegram account linking (BUG-1) 2026-04-10 10:32:39 +03:00
c0mrade b57f185258 feat: add remnawave_resync_service for identity-change sync
Introduces resync_user_subscriptions_with_panel(), a standalone async
helper that re-pushes all active subscriptions to the RemnaWave panel
after any identity change (TG linking, account merge, email verification).
Handles multi-tariff vs. single-tariff mode, create vs. update branching,
tariff eager-loading, and returns a synced/failed/total stats dict.
2026-04-10 10:31:12 +03:00
c0mrade ffbb3fb8be Merge pull request #2861 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.45.2
2026-04-08 18:46:58 +03:00
github-actions[bot] f01dbff000 chore(main): release 3.45.2 2026-04-08 15:44:09 +00:00
c0mrade 31adcfded4 Merge pull request #2860 from BEDOLAGA-DEV/dev
fix: batch bug fixes from user complaints
2026-04-08 18:42:47 +03:00
c0mrade 78f963bf5e fix: batch bug fixes from user complaints
- 100% discount: daily tariff fallback to smallest configured period discount
- 100% discount: purchase blocked by safety guard (base_price → original_total in 6 guards)
- Gift subscription reset existing days (replace → extend for active/trial subs)
- Cabinet broadcast: target alias active_subscribers not mapped to active
- Promo code: error always "expired" — split into inactive/not_yet_valid/expired
- Multi-tariff: add delete subscription button in admin bot
- Multi-tariff → single: select subscription with most remaining time (end_date DESC)
- Gift purchases not counted in total spent (added GIFT_PAYMENT type)
- Remnawave API: retry on 502/503/504 (was only 429)
- Heleket: add from_referral_code to invoice payload
- Whitespace fix in blacklist_service
2026-04-08 18:33:17 +03:00
Egor 357d94d1b0 Merge pull request #2855 from andreycoast/fix/blacklist-parsing-logic
fix: исправление парсинга черного списка (поддержка '#' и извлечение username)
2026-04-07 15:49:54 +03:00
Egor 0fb4a2c235 Merge pull request #2856 from BEDOLAGA-DEV/main
w
2026-04-07 15:49:20 +03:00
andreycoast 2f7184627a fix: исправление парсинга черного списка (поддержка '#' и извлечение username) 2026-04-07 15:38:32 +03:00
c0mrade d55e9db62a Merge pull request #2849 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.45.1
2026-04-03 20:58:07 +03:00
github-actions[bot] 57adfaf4f3 chore(main): release 3.45.1 2026-04-03 17:57:12 +00:00
c0mrade 4165eaea7a Merge pull request #2848 from BEDOLAGA-DEV/dev
fix: add missing WEBHOOK_TORRENT_DETECTED mapping + dedup before uniq…
2026-04-03 20:56:51 +03:00
c0mrade 3b5d5a18a1 fix: add missing WEBHOOK_TORRENT_DETECTED mapping + dedup before unique index in migration 0053 2026-04-03 20:50:13 +03:00
c0mrade eef41c4bca Merge pull request #2846 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.45.0
2026-04-03 19:13:53 +03:00
github-actions[bot] 987c3c93c2 chore(main): release 3.45.0 2026-04-03 16:12:28 +00:00
c0mrade 7d24e8d704 Merge pull request #2845 from BEDOLAGA-DEV/dev
fix: subscription system bugfixes + torrent notifications + user deletion cleanup
2026-04-03 19:12:06 +03:00
c0mrade 819f09a68e fix: restore missing import + rewrite user.deleted webhook to properly deactivate all subscriptions
- Fix NameError in admin_users.py: re-add get_traffic_reset_strategy import that ruff auto-removed
- user.deleted: remove auto-recreation logic — deleted means deleted, no more recreating users back in panel
- user.deleted: deactivate primary subscription unconditionally (expire + clear all linkage)
- user.deleted: sweep sibling subscriptions — verify each via panel API, deactivate only those whose panel user is gone (safe for multi-tariff where only one of N panel users may be deleted)
- Works across multi-tariff, single-tariff, and classic modes
2026-04-03 18:56:14 +03:00
c0mrade 2f9d00343b feat: send torrent blocker notification to user (not just admin)
- torrent_blocker.report is now a dual event: admin notification + user message
- New _handle_torrent_detected user handler sends WEBHOOK_TORRENT_DETECTED
- process_event handles events registered in both admin and user handlers
- Webhook router passes DB session for dual events (needs_db_session check)
- Add WEBHOOK_NOTIFY_TORRENT_DETECTED setting (default: true)
- Add WEBHOOK_TORRENT_DETECTED locale texts (ru/en/ua/zh/fa)
2026-04-03 18:19:45 +03:00
c0mrade 9b7ac47f16 fix: resolve multiple subscription bugs — LIMITED status, trial tariff blocking, traffic reset strategy, classic mode pricing, 100% discount support
- Include LIMITED status in subscription lookups (get_active_subscriptions_by_user_id, get_subscription_by_user_and_tariff) — fixes duplicate subscriptions when traffic exhausted
- Migration 0053: update partial unique index to include LIMITED
- Trial subscriptions no longer block tariff purchase — excluded from purchased_tariff_ids, handle_extend_subscription routes trial+tariff to tariff extend flow
- Replace hardcoded TrafficLimitStrategy.MONTH with get_traffic_reset_strategy() across all sync/create paths (remnawave_service, monitoring_service, admin_users)
- Subscriptions with tariff_id always use tariff pricing flow regardless of global sales mode — fixes 0₽ renewal in classic mode
- Support 100% promo group discount across all purchase/renewal flows — balance checks skip when price=0, validation allows final_total=0 when base_price>0
2026-04-03 17:22:42 +03:00
Egor 0d5638f778 Merge pull request #2838 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.44.0
2026-04-02 07:24:58 +03:00
github-actions[bot] 7836720db3 chore(main): release 3.44.0 2026-04-02 04:24:32 +00:00
Egor dcb90d6139 Merge pull request #2837 from BEDOLAGA-DEV/dev
Dev
2026-04-02 07:24:07 +03:00
Fringg 96c420e917 style: fix ruff format for severpay.py 2026-04-02 07:17:36 +03:00
Fringg 9d63635502 feat: add SberPay as KassaAI sub-method (payment_system_id=43)
Adds SberPay alongside existing SBP (44) and Card (36) sub-methods.

Changes across all 8 required files:
- config.py: KASSA_AI_SBERPAY_ENABLED, display name, helper methods
- kassa_ai_service.py: payment_system_id=43 in KASSA_AI_SUB_METHODS
- kassa_ai.py handler: method config + start_kassa_ai_sberpay_topup
- main.py: route tuple, import, handler registration
- payment_service.py: guest purchase flow method check
- cabinet/balance.py: KASSA_AI_OPTION_MAP sberpay=43
- payment_method_config_service.py: sub_option for admin panel
- inline.py: keyboard button + fallback condition guard

Env vars: KASSA_AI_SBERPAY_ENABLED, KASSA_AI_SBERPAY_DISPLAY_NAME
2026-04-02 06:47:57 +03:00
Egor c4c5d330be Merge pull request #2836 from BEDOLAGA-DEV/main
w
2026-04-02 06:39:28 +03:00
Fringg 977950b97f fix: address review issues in PR #2829 webhook intentional deletion guard
5 issues found by review agents and fixed:

1. Intentional deletion guard was at top of process_event, skipping ALL
   cleanup (subscription URLs, server counts, expired marking). Moved
   check into _handle_user_deleted so cleanup still runs but re-creation
   is suppressed via subscription_still_valid=False.

2. Variable shadowing: telegram_id loop var in any() generator shadowed
   the outer telegram_id local. Renamed to tid/uid.

3. No hard cap on in-memory dicts: added _MAX_INTENTIONAL_ENTRIES=10000
   with early return in mark_intentional_panel_deletion.

4. mark_intentional_panel_deletion called inside for-loop with single
   UUID — race window if webhook from first delete arrives before
   second UUID is marked. Moved to before the loop with all UUIDs.

5. Tests: @pytest.mark.anyio → @pytest.mark.anyio('asyncio') for
   consistency. Replaced process_event(db=None) test with direct
   mark+detect unit tests + hard cap test.
2026-04-02 06:34:35 +03:00
Fringg 6f6b9fa039 Merge branch 'yazhog/main' into dev 2026-04-02 06:30:45 +03:00
Fringg 6713921887 fix: Pal24 card/sbp option not passed to API in cabinet balance topup
The payment_option (card/sbp) was parsed from the request but never
passed to create_pal24_payment as payment_method. Without it,
_normalize_payment_method(None) defaults to 'sbp', so both Card and
SBP buttons always created SBP payments.
2026-04-02 06:20:21 +03:00
Fringg 2d42152f54 fix: NameError in SeverPay guest payment flow
user variable was unbound when user_id=None (guest purchase path).
Added user=None in the else branch to prevent NameError when
constructing the fallback email.
2026-04-02 06:18:37 +03:00
Fringg 08ca947b2b fix: send telegram_id@telegram.org as email to SeverPay
SeverPay requires a non-empty client_email field. When user has no
email, fallback to {telegram_id}@telegram.org instead of empty string.
2026-04-02 06:16:17 +03:00
Fringg b04157c913 fix: notification sent for non-deactivated subs + webhook race condition
Two fixes for channel subscription enforcement:

1. Middleware notification guard: the deactivation notification was sent
   even when deactivated_subs was empty (no subs actually deactivated).
   Also fixed len(active_subs) -> len(deactivated_subs) for multi-tariff
   notification text selection.

2. Webhook echo race condition: when a user quickly leaves and rejoins
   a channel, the delayed user.disabled webhook from RemnaWave could
   re-deactivate a subscription that was already reactivated.
   Fix: stamp last_webhook_update_at on reactivation (both channel_member
   handler and middleware), then guard _handle_user_disabled against
   re-deactivating recently-reactivated ACTIVE subscriptions using the
   existing is_recently_updated_by_webhook (60s window).
2026-04-02 06:14:45 +03:00
Fringg f284351c51 fix: middleware disables panel VPN for all subs ignoring per-channel settings
In _deactivate_subscription_on_unsubscribe, the loop calling
disable_remnawave_user iterated over all active_subs instead of only
the subscriptions that passed the should_disable_subscription check.

This caused paid subscriptions to be disabled at the RemnaWave panel
level even when disable_paid_on_leave=False, while the DB record
stayed ACTIVE. On rejoin, reactivation found no DISABLED subs in DB
so enable_remnawave_user was never called — VPN stayed off permanently.

Fixed by collecting actually-deactivated subs into a separate list
and using that for both panel disable calls and notifications.
2026-04-02 06:09:39 +03:00
Fringg b607993854 fix: prevent nested state saves and None state loss in promo handler
Two bugs found during review of the previous FSM state restore fix:

1. Re-entering promo flow created nested _prev_data (unbounded growth).
   Now skips save if already in PromoCodeStates.waiting_for_code and
   strips _prev_ keys from saved data to prevent nesting.

2. _restore_previous_state used `if prev_state:` which treated saved
   None state (user at menu) same as "no saved state". Now uses a
   sentinel to distinguish the two cases, correctly restoring None
   state with its data instead of calling state.clear().
2026-04-02 05:59:28 +03:00
Fringg 246659032d fix: promo code activation destroys balance input FSM state
When a user was in BalanceStates.waiting_for_amount and activated a
promo code, process_promocode called state.clear() on all exit paths,
wiping the balance state. Typing the amount then hit the fallback
"Не понимаю эту команду" handler.

Now show_promocode_menu saves the previous FSM state/data before
entering promo flow, and _restore_previous_state restores it after
promo code processing completes.
2026-04-02 05:55:29 +03:00
Fringg 3dc72b00e7 fix: send telegram_id@telegram.org as email to Kassa AI
Kassa AI requires email in format {telegram_id}@telegram.org but we
were sending user_{order_id}@telegram.org as fallback when email was
not provided. Now the fallback uses user.telegram_id directly.
2026-04-02 05:49:01 +03:00
Fringg 033d0da5e0 fix: remove non-existent Platega method code 10, rename 11 to Карты (RUB)
Platega API defines: 2=СБП, 11=Карточный эквайринг, 12=Международная,
13=Крипто. Code 10 does not exist in their API but was defined in our
config as "Банковские карты (RUB)", while real code 11 was mislabeled
as "Банковские карты". This caused two card options to appear in the
admin panel, one of which didn't work.

- Removed code 10 from definitions, defaults, allowed set, .env.example
- Renamed code 11: "Банковские карты" → "Карты (RUB)"
- Removed redundant filter in handlers/balance/platega.py
- Updated tests to match
2026-04-02 05:44:24 +03:00
Fringg 991f0b43e1 fix: autopay failure notifications ignoring 6h cooldown
Two bugs caused users to receive autopay error notifications every
monitoring cycle (hourly) instead of respecting the 6-hour cooldown:

1. subtract_user_balance failure path had no cooldown check at all
2. cache.exists() silently returns False when Redis is disconnected,
   bypassing the try/except cooldown guard

Extracted shared _check_autopay_fail_cooldown / _set_autopay_fail_cooldown
methods with in-memory fallback dict that works even without Redis.
Added cleanup of expired in-memory entries in _cleanup_notification_cache.
2026-04-02 05:44:13 +03:00
c0mrade c9524cb703 Merge pull request #2832 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.43.1
2026-03-31 20:24:44 +03:00
github-actions[bot] 76d4a2124c chore(main): release 3.43.1 2026-03-31 17:20:24 +00:00
c0mrade 4fa230c07f Merge pull request #2831 from BEDOLAGA-DEV/dev
Release: dev → main
2026-03-31 20:19:53 +03:00
c0mrade d580a78403 Merge remote-tracking branch 'origin/main' into dev 2026-03-31 15:13:46 +03:00
c0mrade 312cc728a9 docs: add Platega partnership to README, highlight partner payment providers 2026-03-31 13:04:40 +03:00
yazhog b1820c651d Fix RemnaWave webhook deletion race 2026-03-30 15:56:45 +03:00
c0mrade 0c284b9e99 fix: use subscription-level remnawave_uuid in multi-tariff mode for sync and detail pages
In multi-tariff mode, remnawave_uuid lives on the subscription object,
not the user. The sync status and user detail endpoints were always
returning user.remnawave_uuid, causing some users to see no UUID.
2026-03-30 14:41:58 +03:00
c0mrade 72170b35f5 fix: prevent MissingGreenlet on subscription.tariff lazy load in webhook handlers
Replace unsafe getattr(subscription, 'tariff', None) with sa_inspect().dict.get()
to avoid triggering lazy loads after db.commit()/refresh() in async context.
2026-03-29 17:31:38 +03:00
Egor 9058a9c5d3 Merge pull request #2824 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.43.0
2026-03-29 07:59:08 +03:00
github-actions[bot] be0934c5e5 chore(main): release 3.43.0 2026-03-29 04:58:33 +00:00
Egor cab1946382 Merge pull request #2823 from BEDOLAGA-DEV/dev
Dev
2026-03-29 07:57:34 +03:00
Fringg fd247bc4f4 style: format devices.py with ruff 2026-03-29 07:33:45 +03:00
Fringg adb39c6ef4 fix: load buyer relationship before gift notification, clean up recipient logic
Add 'buyer' to db.refresh attribute_names so the buyer relationship
is available when building the admin notification (prevents expired
attribute access in async context). Restructure recipient icon logic
to only compute when a recipient value exists.
2026-03-29 07:33:03 +03:00
Fringg 48eaa6b072 fix: distinguish cabinet gift notifications from landing page
Cabinet gift purchases now show "ПОДАРОК ИЗ КАБИНЕТА" instead of
"ПОКУПКА В ПОДАРОК С ЛЕНДИНГА". Buyer is resolved from the user
relationship with @username. Recipient shows "по коду активации"
when no direct recipient specified. Landing page slug line removed
for cabinet purchases.
2026-03-29 07:30:20 +03:00
Fringg 972614511f fix: address remaining review issues in device limit patch
- Migrate get_device_reduction_info to get_user_devices_all (was raw _make_request)
- Migrate admin_users and miniapp callers to get_user_devices_all
- Migrate reset_user_devices internal call to paginated version
- Fix tariff_max_devices falsy-zero in handlers (use explicit is not None and > 0)
- Fix device deletion sort: dateless devices now sort last (candidates for removal)
2026-03-29 07:26:35 +03:00
Fringg 34aec0323b fix: address review issues in device limit patch
- Use paginated get_user_devices_all in delete_all_devices and get_devices
- Fix tariff_max falsy-zero check: use explicit `is not None and > 0`
- Unify keyboard fallback to 100 in both get_devices_keyboard and change
- Remove dead expression `devices_count - current_devices`
- Fix stale error message referencing tariff minimum
- Migrate f-string logger to structlog kwargs style
2026-03-29 07:22:45 +03:00
Fringg 931eeb3568 fix: device limit decrease, HWID pagination, tariff max enforcement
1. Device decrease minimum is now always 1 (was incorrectly using
   tariff.device_limit as floor, blocking decrease e.g. 3/3)
2. Cabinet "Already at minimum device limit" fixed — same root cause
3. Added get_user_devices_all() with pagination for HWID cleanup
4. add_subscription_devices now caps by tariff.max_device_limit
5. Keyboard range expanded to 100 when no global limit set (was 20)
2026-03-29 07:18:55 +03:00
Fringg 2628012097 feat: expose MULTI_TARIFF_ENABLED and MAX_ACTIVE_SUBSCRIPTIONS in admin settings
Register both settings under SUBSCRIPTIONS_CORE category with detailed
hints, descriptions, and dependency info for the cabinet admin panel.
2026-03-29 07:04:29 +03:00
Fringg 7f899a7e41 chore: ruff format account_merge_service.py 2026-03-29 06:49:13 +03:00
Fringg 6dbbe5950e chore: ruff format auth.py and remnawave_service.py 2026-03-29 06:48:59 +03:00
Fringg f93c51a677 fix: gift code activation and multi-tariff subscription sync
Gift activation:
- Encode underscores as %5F in share URLs to prevent Telegram markdown corruption
- Strip GIFT-/GIFT_ prefix from URL code params in frontend
- Backend accepts both GIFT- and GIFT_ prefix on activation
- Bot shows feedback on failed gift auto-activation (self-gift, already activated)

Multi-tariff sync (panel↔bot):
- _sync_users_from_panel_multi now creates subscriptions for unmatched panel users
- sync_users_to_panel matches panel users by username suffix (_short_id) instead of taking arbitrary existing_users[0]
- Save sub.remnawave_uuid after update (was pass/noop)
- Generate remnawave_short_id for all new subscriptions
- Include activeInternalSquads in multi-tariff panel dict
- Append _short_id suffix to username in create_kwargs

Email/OAuth sync:
- _sync_subscription_from_panel_by_email loops ALL panel users in multi-tariff
- Auto-verify path now triggers panel subscription sync
- OAuth new users with verified email get panel sync
- cleanup_orphaned_subscriptions skips email-only users (was force-cleaning them)
2026-03-29 06:47:42 +03:00
Fringg da11ec6f94 fix: assign promo group from tariff on guest purchase
When a guest purchases a tariff with allowed_promo_groups, assign the
first allowed group instead of the default one.

Cherry-picked from PR #2819
2026-03-29 05:03:21 +03:00
Fringg 23d1830644 feat(api): expose email field in UserResponse
Cherry-picked from PR #2821 (without version bump artifacts)
2026-03-29 05:00:44 +03:00
Fringg e3d8d21b66 fix: suppress empty reward alerts and clean up referral notifications
- Silence "link for new users only" message for no-reward ad campaigns
- Show commission % in referral notifications only when > 0
- Show fixed bonus in referral notifications only when > 0
- When both bonus and commission are 0, don't promise a reward

Cherry-picked logic from PR #2822 (without version bump artifacts)
2026-03-29 04:59:23 +03:00
Fringg 2c12a4773c fix: account linking broken in multi-tariff mode (MULTI_TARIFF_ENABLED=true)
- Fix subscription tariff conflict during merge: detect
  uq_subscriptions_user_tariff_active violations before they happen,
  resolve by keeping the subscription with later end_date (NULL=lifetime wins)
- Add merge flow to /auth/email/register: when email belongs to another
  active user, return merge_required+token instead of blocking with 400
- Fix missing remnawave_uuid on subscriptions created by panel email sync
  in multi-tariff mode (_sync_subscription_from_panel_by_email)
- Add rate limiting (5/60s) to email register endpoint
- Filter deleted users from email existence check
- Reorder "already has verified email" guard before merge branch
- Clear autopay_enabled on expired subscriptions during conflict resolution
2026-03-29 04:50:03 +03:00
Fringg 7f60196033 feat: support email/OAuth users in referral editing and add remove endpoints
- Bot handler: add email and internal ID (#123) lookup to referral editor
  (previously only supported telegram_id and @username)
- Cabinet API: add DELETE /{user_id}/referrer endpoint to unbind referrer
- Cabinet API: add DELETE /{user_id}/referrals/{referral_user_id} endpoint
  to remove specific referral
- Both endpoints include permission checks and admin action logging
2026-03-29 03:43:29 +03:00
Fringg b59c581e91 feat: include countryEmoji and providerName in realtime metrics 2026-03-28 23:55:29 +03:00
Fringg 81505c8c1d chore: remove debug logging from get_nodes_realtime_usage 2026-03-28 23:47:50 +03:00
Fringg d6a49e8331 debug: log raw metrics structure to find correct key 2026-03-28 23:45:13 +03:00
Fringg 7ecd95aec0 debug: log raw metrics response structure 2026-03-28 23:40:35 +03:00
Fringg 1471320606 fix: parse_bytes now handles IEC units (GiB, MiB, KiB) from API 2026-03-28 23:37:59 +03:00
Fringg 3d0b874cb4 style: format remnawave_api.py per ruff 2026-03-28 23:28:49 +03:00
Fringg 5d173c806a feat: expose per-inbound traffic breakdown in nodes realtime API
get_nodes_realtime_usage() now preserves the per-inbound and
per-outbound traffic stats from /api/system/nodes/metrics instead
of summing them into node-level totals. Each node in the response
includes inbounds[] and outbounds[] arrays with tag, download,
upload, and total bytes.
2026-03-28 22:47:16 +03:00
Fringg 6d167d2922 fix: harden node info display against injection and type errors
- HTML-escape all external strings (cpuModel, node name, address,
  last_status_message, provider_uuid, versions) in Telegram HTML messages
- Add _safe_int() helper for defensive xrayUptime parsing
- Remove redundant int() casts in route serializers
2026-03-28 22:34:54 +03:00
Fringg 173cc374bb refactor: update remnawave API integration for v2.7.0
- Node: replace flat fields (cpuCount, cpuModel, totalRam, xrayVersion,
  nodeVersion) with nested versions and system dicts, add activePluginUuid
- Node: xrayUptime changed from string to int (seconds), usersOnline
  now non-nullable
- User: remove subLastOpenedAt and subLastUserAgent (dropped in v2.7.0)
- System stats: remove cpu.physicalCores, memory.available/active
- Update all layers: dataclass, service, Pydantic schemas, route
  serializers, Telegram admin handlers
- Fix variable scoping in show_node_statistics error fallback
2026-03-28 22:32:15 +03:00
Fringg 960aa44b00 fix: prevent sync/from-panel cross-subscription data mismatch
When a specific subscription_id is provided but that subscription
has no remnawave_uuid yet, block the sync with a clear error instead
of falling through to the all-UUID iteration which could fetch
panel data from a different subscription.
2026-03-28 19:54:40 +03:00
Fringg 54a19a9c50 feat: add subscription_id to admin sync endpoints for multi-tariff
All 3 sync endpoints now accept optional subscription_id query param:
- GET /sync/status: compares specified subscription with its panel data
- POST /sync/from-panel: syncs panel data to specified subscription
- POST /sync/to-panel: pushes specified subscription to panel

In multi-tariff mode, uses subscription.remnawave_uuid for panel
lookup instead of user.remnawave_uuid. Response includes
subscription_id and subscription_tariff_name for UI context.

When subscription_id is not provided, existing first-active-sub
behavior is preserved for backward compatibility.
2026-03-28 19:50:06 +03:00
Fringg f6f330db4a fix: improve UX for legacy users migrating to tariff mode
- instant_switch handler: redirect legacy users (tariff_id=NULL) to
  tariff_switch migration flow instead of dead-end popup
- autopay skip: notify user once (7-day cooldown) when autopay is
  skipped for legacy subscription, explaining they need to choose
  a tariff for autopay to work
2026-03-28 19:33:18 +03:00
Fringg aa36549bb3 fix: fix MiniApp renewal options 500 error for legacy subscriptions
The early-return response for blocked legacy users used wrong field
name 'balance_currency' instead of 'currency' (a required field in
MiniAppSubscriptionRenewalOptionsResponse), causing Pydantic
ValidationError / 500 Internal Server Error.

Fixed to use correct field names and added status_message explaining
why renewal is blocked, plus balance_label and sales_mode fields.
2026-03-28 19:32:21 +03:00
Fringg 78209c8623 fix: block legacy subscription renewal bypass in tariff mode
When switching from configurator to tariff mode, users with old
subscriptions (tariff_id=NULL) could still renew them through
unguarded paths, bypassing tariff pricing entirely.

Vulnerable paths fixed:
- MiniApp POST /subscription/renewal/options: returns empty list
  for classic subscriptions in tariff mode
- MiniApp POST /subscription/renewal: raises 400 with
  classic_subscription_blocked error code
- Bot confirm_extend_subscription: blocks stale extend_period_
  callbacks with tariff mode check
- Monitoring _process_autopayments: skips classic subscriptions
  (tariff_id=NULL) in autopay loop when tariff mode active

Already protected (no changes needed):
- Cabinet GET/POST renewal endpoints (renewal.py:51,117)
- Auto-purchase service (_prepare_auto_extend_context:244)
- Bot handle_extend_subscription menu (purchase.py:1657)
- Tariff extend flow (tariff_purchase.py:2047)
2026-03-28 19:27:08 +03:00
Fringg cddb8d6332 fix: add tariff identification to remaining notification gaps
- MiniApp renewal success message: add tariff label to _build_renewal_success_message
- Admin buy subscription: add tariff line to user notification
- Promocode subscription days: add tariff label to effect message
- Fix cosmetic double-space in autopay success tariff line
2026-03-28 19:19:18 +03:00
Fringg 092b9f63b2 feat: add SeverPay support to cabinet balance top-up
SeverPay was missing from the cabinet create_topup() endpoint,
causing "This payment method is only available through the Telegram bot"
error when users tried to pay via SeverPay in the web cabinet.
2026-03-28 19:17:56 +03:00
Fringg 7dd67e36b3 feat: add tariff identification to all notifications for multi-tariff mode
When MULTI_TARIFF_ENABLED=true users can have multiple subscriptions,
so notifications must identify which tariff they relate to.

- Webhook notifications: _notify_user auto-injects tariff_label from
  subscription.tariff.name into all 16 webhook notification strings
- Monitoring service: tariff labels in expired, expiring, trial ending,
  follow-up waves, autopay success/failed notifications
- Daily subscription: tariff in insufficient balance notification
- Recurrent payments: tariff in card autopay success/failed
- Auto-purchase: tariff in all 4 auto-purchase notification paths,
  with pre-captured names to avoid MissingGreenlet after db.commit()
- Channel checker: plural form for multi-subscription deactivation
- Payment providers: tariff in YooKassa and Stars activation messages
- Admin: tariff in bulk expiry reminder
- Localization: {tariff_label} in 20 notification keys across all 5
  locales (ru, en, ua, zh, fa) + _MULTI channel keys
- Fix: selectinload(Subscription.tariff) in trial expiring query
- Fix: capture tariff_name before expire_subscription to prevent
  MissingGreenlet from db.refresh() expiring ORM relationships
2026-03-28 19:12:34 +03:00
c0mrade 565c08366b feat: add Remnawave panel 2.7.0 API support
- Add MONTH_ROLLING traffic reset strategy (enum, UI, mapping)
- Fix squad remove-users HTTP method POST → DELETE
- Add forceRestart param to restart_all_nodes (API, service, routes)
- Replace removed /bandwidth-stats/nodes/realtime with /system/nodes/metrics
- Fix parse_bytes suffix matching bug (B was catching GB/MB/KB/TB)
- Add torrent_blocker.report webhook event with admin notifications
- Add subpage_config_changed → auto-invalidate app config cache
- Pass webhook meta field to handlers (notConnectedAfterHours)
- Improve CRM/login webhook formatting (providerName, loginAttempt)
- Update bandwidth display: remove /s suffix, show inbound traffic totals
2026-03-28 12:34:15 +03:00
c0mrade 34b5a9ab3a refactor: remove dead multi-tariff check in guest purchase activation
The else branch of is_multi_tariff_enabled() contained a duplicate
is_multi_tariff_enabled() check that could never execute.
2026-03-27 13:11:51 +03:00
c0mrade 181ef1501b fix: test access promo applies to all active subscriptions in multi-tariff
Previously test squad was added to only one subscription. Now iterates
all active non-daily subscriptions and adds the test squad to each,
creating SubscriptionTemporaryAccess entries per subscription and
syncing each with RemnaWave.
2026-03-27 12:31:12 +03:00
c0mrade cd6913cb84 fix: block classic subscription renewal/autopay when tariff mode enabled
Classic subscriptions (without tariff_id) now cannot be renewed or
auto-renewed when tariff mode is active. Users must purchase a tariff.

Blocked in: cabinet renewal endpoints, cabinet autopay, bot autopay
toggle, and auto-purchase service.
2026-03-27 11:23:45 +03:00
c0mrade 84357a1e87 fix: add selectinload for GuestPurchase.user/tariff in gift activation
Bare select() without eager loading caused MissingGreenlet when
accessing purchase.user and purchase.tariff in async handler.
2026-03-26 20:45:23 +03:00
c0mrade 3bec6620b6 fix: async tariff loading in promocode serialization
Replace lazy-loaded promocode.tariff with explicit async
get_tariff_by_id query to avoid MissingGreenlet error.
2026-03-26 20:27:20 +03:00
c0mrade 3bbcc1b560 style: ruff format 2026-03-26 20:20:09 +03:00
c0mrade b8662b8bf6 fix: trial promo extends existing subscription with same tariff
Instead of blocking when user already has the trial tariff, extend
that subscription by the promo days.
2026-03-26 20:17:25 +03:00
c0mrade 63e4296197 feat: add tariff_id to promo codes for trial subscription type
- Add tariff_id column to promocodes table (migration 0052)
- Admin can now select any tariff when creating trial_subscription promo
- Activation uses promocode.tariff_id if set, falls back to system
  trial tariff
- Multi-tariff: blocks trial only if user already has that specific tariff
2026-03-26 20:09:20 +03:00
c0mrade 3cbe09ddd5 fix: promocode system broken in multi-tariff mode
- Remove duplicate `from app.config import settings` inside function that
  shadowed the module-level import, causing UnboundLocalError for all
  SUBSCRIPTION_DAYS and TRIAL_SUBSCRIPTION promo types
- TRIAL_SUBSCRIPTION now resolves trial tariff via get_trial_tariff() /
  TRIAL_TARIFF_ID and passes tariff_id, traffic_limit_gb, device_limit,
  connected_squads to create_trial_subscription (was creating bare trial
  without any tariff params)
- Multi-tariff: trial promo only blocks if user already has the specific
  trial tariff, not any active subscription
- Cabinet endpoint now accepts subscription_id and returns
  select_subscription response for multi-tariff SUBSCRIPTION_DAYS promos
2026-03-26 19:43:22 +03:00
c0mrade 31c67d1565 fix: cabinet admin create subscription now creates new RemnaWave user in multi-tariff mode
When subscription.remnawave_uuid was None, the fallback to user.remnawave_uuid
caused the new subscription to overwrite the existing panel user instead of
creating a separate one.
2026-03-26 16:40:27 +03:00
c0mrade 95ba739958 fix: admin tariff purchase now creates separate RemnaWave user per tariff
In multi-tariff mode _resolve_admin_subscription was returning any active
subscription regardless of tariff_id, causing new tariff purchases to
overwrite the existing RemnaWave user instead of creating a new one.
2026-03-26 16:34:30 +03:00
c0mrade e39c358d5c fix: show all subscriptions in main menu for multi-tariff mode
Display all user subscriptions inside a single blockquote instead of
showing only one via the deprecated user.subscription property.
2026-03-26 16:15:17 +03:00
c0mrade a12ffb1d6c fix: delete subscription from RemnaWave panel + prevent phantom webhook notifications
- Replace disable_remnawave_user() with delete_remnawave_user() on subscription deletion
  so the panel stops sending webhooks for deleted subscriptions
- Add early return in all webhook handlers when subscription is None (already deleted from DB):
  expired, disabled, enabled, limited, traffic_reset, revoked, expiring reminders
- Add "Delete subscription" button in Telegram bot for expired/disabled subscriptions
  with confirmation step and full cleanup (panel delete + server counts + DB hard delete)
2026-03-26 15:59:36 +03:00
Fringg 6d9bd9915c fix: persist referral to Redis on /start to prevent loss when user opens miniapp
When user clicks /start ref_CODE, the referral code was stored only in
FSM state. If the user opened miniapp/cabinet before completing bot
registration, the referral was lost.

Now /start immediately saves pending_referral:{telegram_id} to Redis
(7-day TTL). The referral is consumed by whichever path creates the
user first — bot create_user(), cabinet auth (initdata/widget/oidc).
Redis key is cleared after consumption to prevent double-referral.

- referral_service: save/get/clear_pending_referral Redis helpers
- start.py: save pending referral for new users only
- crud/user.py: create_user checks Redis if no referred_by_id
- cabinet/auth.py: initdata/widget/oidc routes check + cleanup Redis
2026-03-26 11:55:20 +03:00
Egor d97c8531a3 Delete docs/multi-tariff-review.md 2026-03-26 11:23:48 +03:00
Fringg 94ed282381 fix: multi-tariff MEDIUM/LOW batch — 20 issues across 17 files
MEDIUM fixes:
- config: MAX_ACTIVE_SUBSCRIPTIONS=10 limit + check in tariff purchase
- tariff_purchase: add_user_balance return check → _persist_failed_refund
- tariff_purchase: promo restoration atomic with refund (commit=False)
- purchase: handle_toggle_daily_subscription_pause multi-tariff guard
- my_subscriptions: respect HIDE_SUBSCRIPTION_LINK setting
- multi_tariff: delete_subscription uses actual_status
- tariff_switch: guard against switching to already-owned tariff
- monitoring: i18n button texts via texts.t() + per-subscription dedup
- promo_offer_service: multi-tariff subscription resolution
- bot.py: register DisplayNameRestrictionMiddleware + SubscriptionStatusMiddleware on pre_checkout_query
- crud/user: add_user_balance accepts commit=False
- crud/subscription: update_daily_charge_time refresh only on commit, autopay days_before preserved
- daily_subscription: remove redundant outer commit in process_traffic_resets

LOW fixes:
- inline.py: remove dead get_subscription_expiring_keyboard function
- promocode_service: current_uses +1 in response (post-increment)
- yookassa: use already-resolved subscription for admin notification
- subscription_utils: remove dead ensure_single_subscription + update_or_create_subscription
- devices: merge identical daily/non-daily branches in confirm_change_devices
2026-03-26 11:00:15 +03:00
Fringg fec374edba chore: ruff format 2026-03-26 10:34:14 +03:00
Fringg 58d899aab8 fix: renewal status check, int() safety, daily charge atomicity
- renewal.py: block renew/renewal-options for PENDING/DISABLED subscriptions
  (extend_subscription doesn't transition these to ACTIVE — user would pay
  for nothing)
- autopay.py: wrap 2x bare int() card_id parsing in try/except
- devices.py: wrap 2x bare int() device_count parsing in try/except
- daily_subscription_service: atomic daily charge — subtract_user_balance,
  create_transaction, update_daily_charge_time all use commit=False, single
  db.commit() after all three succeed. Prevents re-charge on partial failure.
- subscription.py: update_daily_charge_time accepts commit=False kwarg
2026-03-26 10:05:52 +03:00
Fringg 1bc2581669 fix: cabinet purchase_tariff — handle IntegrityError with compensating refund
When partial unique index (user_id + tariff_id) fires on concurrent or
duplicate tariff purchase via cabinet, the balance was already deducted
but no subscription was created. Now catches IntegrityError, rollbacks,
refunds via add_user_balance, and returns HTTP 409.
2026-03-26 09:57:07 +03:00
Fringg b0273dc8ae fix: account merge no longer nulls transferred subscriptions' remnawave_uuid
In multi-tariff mode, _handle_subscription_merge transfers ALL secondary
subscriptions to primary. Step 14 then iterated stale secondary.subscriptions
and nulled their remnawave_uuid, breaking the panel link for transferred subs.
Removed the UUID-nulling loop since all subs are already on primary.
2026-03-26 09:38:04 +03:00
Fringg 948e4791f4 fix: multi-tariff Stage 5 fixes — auth sync, notifications, cart, race guard
HIGH fixes:
- auth.py: profile description sync now iterates all per-subscription
  remnawave_uuids in multi-tariff mode
- admin_users: sync_from_panel uses subscription UUIDs for panel lookup,
  does not overwrite user.remnawave_uuid in multi-tariff

MEDIUM fixes:
- monitoring_service: _send_subscription_expired_notification now takes
  subscription param, uses se:{sub_id} in multi-tariff
- remnawave_webhook_service: _get_renew_keyboard accepts subscription_id,
  all 7 callers pass it
- recurrent_payment_service: _build_extend_keyboard with subscription_id
- user_service: balance notification keyboards use menu_subscription in
  multi-tariff instead of bare subscription_extend
- autopay.py + purchase.py: per-subscription cart deletion instead of
  global delete_user_cart where subscription context available
- subscription_auto_purchase_service: 60-sec race guard changed from
  per-user to per-subscription (checks subscription.updated_at)
2026-03-26 09:15:50 +03:00
Fringg a49e52cc92 fix: multi-tariff Stage 4 critical fixes — keyboards, guest purchase, monitoring, tariff deletion
- inline.py: open_subscription_link/subscription_connect callbacks now include
  :{subscription_id} suffix in multi-tariff mode. Main menu uses subscription_connect
  (picker) instead of bare open_subscription_link.
- guest_purchase_service: activate_purchase non-tariff path uses proper ordering
  (non-daily, max days_left) instead of arbitrary _active[0]
- monitoring_service: _send_expired_day1_notification and discount notification
  keyboards use se:{subscription.id} in multi-tariff (2 more hardcoded callbacks fixed)
- admin/tariffs: delete_tariff_confirmed now checks active subscription count
  before deletion (RESTRICT FK). Prompt shows blocking message when active subs exist.
  New CRUD function get_active_subscriptions_count_by_tariff_id.
2026-03-26 08:46:00 +03:00
Fringg 6dc5879ffa docs: add Stage 3+4 audit results to multi-tariff review 2026-03-26 08:39:45 +03:00
Fringg aa7e461c44 fix: multi-tariff Stage 3 HIGH fixes — phantom, cart, yookassa, auto-extend
- phantom_service: iterate all subscriptions for panel sync after claim
  (was using deprecated user.subscription singular property)
- tariff_purchase: 6x delete_user_cart replaced with per-subscription
  delete_subscription_cart in multi-tariff mode
- yookassa: recurrent payment subscription_id mismatch now resolves
  correct subscription from metadata instead of just logging warning
- subscription_auto_purchase: try_auto_extend_expired and
  try_resume_disabled_daily now query ALL subs (not just active) to find
  expired/disabled subscriptions that need processing
2026-03-26 08:31:49 +03:00
Fringg 49db5f5eed fix: multi-tariff Stage 3 critical fixes — panel sync UUID, admin grant, wheel
- remnawave_service: sync_users_to_panel uses sub.remnawave_uuid in
  multi-tariff instead of user.remnawave_uuid (was targeting wrong panel user)
- admin/users: admin_buy_subscription_execute saves UUID to
  subscription.remnawave_uuid in multi-tariff (was saving to user)
- wheel_service: _process_days_payment and _apply_prize require subscription
  in multi-tariff mode, fallback converts to balance bonus for prizes
2026-03-26 08:26:09 +03:00
Fringg c6bedc6a06 fix: multi-tariff Stage 2 HIGH fixes — 18 issues across 12 files
Bot handlers (H1-H5):
- confirm_extend_subscription: error alert instead of wrong sub fallback
- open_subscription_link/subscription_connect: startswith registration
- handle_subscription_settings: multi-tariff guard
- confirm_reset_traffic: FSM state check in multi-tariff

Services (H6-H12):
- subscription_service: 5 UUID fallback fixes — no user.remnawave_uuid in
  multi-tariff, return None if subscription.remnawave_uuid missing
- auto_purchase: use cart subscription_id for tariff match
- remnawave_service: migrate_squad_users checks subscription.remnawave_uuid
- campaign_service: extend existing sub or create new in multi-tariff
- broadcast_service: check ALL subs for paid-subscription guard
- blocked_users_service: remnawave_uuids list, iterate in cleanup
- user_service: log sub.remnawave_uuid in multi-tariff

Admin (H13-H16):
- grant_trial/paid_subscription: allow in multi-tariff mode
- promo_offers: pick sub with URL, aggregate squads from all subs

CRUD/Frontend (H17-H18):
- get_users_list: .unique() for outerjoin dedup
- refreshTraffic: withSubId in params instead of body
2026-03-26 08:09:07 +03:00
Fringg 4259ba1cb5 fix: multi-tariff Stage 2 critical fixes — panel sync, guest purchase, cart isolation
CRITICAL fixes:
- remnawave_service: panel_user.uuid AttributeError (3 places) — dict needs
  .get('uuid'), not .uuid attribute access. Silent fail caused duplicate subs.
- remnawave_service: removed traffic_limit_gb, device_limit, connected_squads
  overwrites from panel sync — bot is source of truth for these fields
- guest_purchase_service: multi-tariff now checks per-tariff (not any active
  sub), allowing purchase of different tariffs simultaneously
- subscription_auto_purchase_service + user_cart_service: per-subscription cart
  storage via user_cart:{user_id}:sub:{sub_id} keys. Cart resolution no longer
  falls through to heuristic when saved_subscription_id lookup fails.
  _delete_cart_for_subscription replaces delete_user_cart in all paths.
2026-03-26 07:57:59 +03:00
Fringg 40d2ec6718 docs: update multi-tariff review with Stage 2 full audit results
Stage 2 covered ~60 files across 6 parallel agents:
- Bot handlers (purchase, traffic, devices, links, start, menu, etc.)
- Core services (subscription, auto-purchase, daily, remnawave, guest, campaign)
- Admin handlers + cabinet modules
- CRUD functions + utilities
- Frontend cabinet (React/TypeScript)
- Remaining services (renewal, broadcast, blocked, yookassa, backup)

Found: 5 CRITICAL, 18 HIGH, 18 MEDIUM, 10 LOW issues
Confirmed correct: 15 components
2026-03-26 07:36:31 +03:00
Fringg 5724906517 fix: multi-tariff code review — 13 critical/high bugs fixed across 14 files
CRITICAL fixes:
- promocode_service: NameError (subscription_id not passed), TypeError (dict
  returns), savepoint without commit, dead else branch
- cabinet status/autopay/renewal: resolve_subscription() instead of
  user.subscription fallback in multi-tariff mode
- cabinet devices: MultipleResultsFound crash on 3 POST endpoints
- webhook service: IDOR returning cross-user subscription
- monitoring_service: real expiring notification keyboard with se:{sub_id}

HIGH fixes:
- subscription_purchase_service: FOR UPDATE on both branches of submit_purchase
- miniapp: 8 endpoints now pass subscription_id to _ensure_paid_subscription
- inline.py: se:{subscription_id} callback for expiring keyboard
- tariff_purchase: TransactionType.FAILED_REFUND + _persist_failed_refund()
- account_merge_service: panel sync after subscription transfer
- webhook service: .limit(1) on fallback queries to prevent MultipleResultsFound
2026-03-26 07:26:53 +03:00
c0mrade 1099c5224c Merge pull request #2814 from BEDOLAGA-DEV/feat/multi-subscription
feat: multi-subscription support
2026-03-25 18:48:31 +03:00
c0mrade bd46b4cf6d fix: UUID check in servers/tariff_switch, start.py refresh, delegation state passing
servers.py + tariff_switch.py: use subscription.remnawave_uuid in multi-tariff
instead of user.remnawave_uuid to prevent duplicate panel users.

start.py: exception handler uses ['subscriptions'] (plural) for db.refresh.

my_subscriptions.py: delegation handlers pass state to downstream so
_resolve_subscription can read active_subscription_id from FSM.
2026-03-25 18:40:38 +03:00
c0mrade a232d21edd fix: remove UUID fallback override in admin_tariffs + restore promo on IntegrityError
admin_tariffs.py: removed trailing `or (sub.user.remnawave_uuid ...)`
that silently used wrong user-level UUID when subscription UUID was None.

tariff_purchase.py: IntegrityError handler in confirm_tariff_purchase now
restores consumed promo offer discount, matching the generic Exception handler.
2026-03-25 17:52:07 +03:00
c0mrade dbe247ba6f fix: multi-tariff sync auto-links legacy user-level UUIDs to subscriptions
When sync finds a panel user whose UUID matches User.remnawave_uuid
(legacy single-tariff) but not any Subscription.remnawave_uuid, it now
auto-links that UUID to the user's best active non-daily subscription.
This handles migration from single-tariff to multi-tariff mode without
losing panel user associations.
2026-03-25 17:16:12 +03:00
c0mrade c3c2b8137b fix: RemnaWave sync finds user by Subscription.remnawave_uuid in multi-tariff
get_user_by_remnawave_uuid: fallback query searches Subscription table
when User-level UUID not found (multi-tariff stores UUID per-subscription).

Webhook _resolve_user_and_subscription: direct Subscription lookup before
returning None when user not found by telegram_id or User.remnawave_uuid.

Webhook user.deleted: refresh user.subscriptions before iterating to
ensure relationship is loaded from DB.

Account merge: clear subscription-level remnawave_uuid/short_uuid on
secondary user's subscriptions to prevent orphaned panel users.
2026-03-25 17:05:12 +03:00
c0mrade 87bf65c809 fix: renewal handlers use _resolve_subscription + store subscription_id in FSM
select_tariff_extend_period and confirm_tariff_extend now use
_resolve_subscription instead of next() by tariff_id, preventing
wrong subscription selection with duplicate tariff_ids.
FSM state now stores active_subscription_id alongside extend_tariff_id.
2026-03-25 16:49:36 +03:00
c0mrade 4e12ab3458 fix: daily tariff switch uses _resolve_subscription instead of searching by new tariff_id
confirm_daily_tariff_switch was searching for subscription matching the
TARGET tariff_id (the one being switched TO), which always returns None
since user doesn't have that tariff yet. Now uses _resolve_subscription
to get the source subscription (the one being switched FROM).
2026-03-25 16:42:22 +03:00
c0mrade 25b853d629 fix: post-payment keyboard checks all subscriptions instead of LIMIT 1
The MissingGreenlet fallback path in build_topup_success_keyboard
now queries all active/trial subscriptions and checks if ANY is active
paid, instead of only checking the most recently created one.
2026-03-25 16:30:01 +03:00
c0mrade e42bddb868 fix: comprehensive tariff switch/extend/back button fixes for multi-tariff
tariff_purchase.py:
- Switch lists filter ALL purchased tariffs, not just current one
- Switch handlers use _resolve_subscription (FSM state) instead of
  searching by new tariff_id
- Extend shows subscription picker when >1 active subs
- All success screens return to sm:{sub_id} in multi-tariff

purchase.py:
- confirm_extend_subscription reads active_subscription_id from FSM state

common.py:
- get_reset_devices_confirm_keyboard accepts back_callback param
- get_confirm_switch_traffic_keyboard accepts back_callback param

traffic.py:
- confirm_switch_traffic passes dynamic back_callback
2026-03-25 16:14:58 +03:00
c0mrade 9644135dd7 fix: tariff purchase shows purchased tariffs and blocks re-buying in multi-tariff
show_tariffs_list now fetches purchased_tariff_ids and passes them to
format_tariffs_list_text (marks with ) and get_tariffs_keyboard (marks button).
select_tariff blocks purchase of already-active tariff with alert showing
days remaining and directing user to "Мои подписки" for renewal.
2026-03-25 15:56:30 +03:00
c0mrade 59d4b353a6 fix: pass sub_id to show_devices_page to fix NameError in multi-tariff
show_devices_page used sub_id for back_callback but didn't receive it
as parameter. Added sub_id parameter and pass it from all 3 call sites.
2026-03-25 15:46:33 +03:00
c0mrade f925efbfb4 fix: devices button shows menu with buy + manage options in multi-tariff
When user clicks "Устройства" from subscription detail, shows intermediate
menu with two options:
- "Докупить устройства" (if tariff allows) → change device limit flow
- "Управление устройствами" → view/reset connected devices
Back button returns to subscription detail.
2026-03-25 15:43:14 +03:00
c0mrade 319941d33a fix: back buttons in devices/traffic return to subscription detail in multi-tariff
All keyboard builders (change_devices, confirm_change_devices,
devices_management, traffic_switch) now accept back_callback parameter.
In multi-tariff mode, back button returns to subscription detail (sm:{sub_id})
instead of legacy subscription_settings screen.
2026-03-25 15:37:33 +03:00
c0mrade a39e3554d8 fix: show subscription picker for traffic/connect buttons with multiple subs
When user has >1 active subscription and clicks "Докупить трафик" or
"Подключиться" from main menu, now shows inline subscription picker
instead of just an alert. User selects subscription, then proceeds
to the corresponding flow. Removed redundant parse_mode (set globally).
2026-03-25 15:26:42 +03:00
c0mrade 382e29d3dd fix: back button in subscriptions list uses correct callback
Changed callback_data from non-existent 'menu_main' to registered
'back_to_menu' handler so the back button actually returns to main menu.
2026-03-25 15:17:26 +03:00
c0mrade 05d1ae0560 fix: notifications include tariff name for multi-subscription clarity
Expiry, autopay success, daily charge, and traffic reset notifications
now append tariff name when multi-tariff is enabled, so users know which
subscription the notification is about.
2026-03-25 15:11:39 +03:00
c0mrade 9a27e6db31 fix: admin server/devices/traffic buttons pass subscription_id in multi-tariff
All 4 remaining admin buttons (change server, devices limit, traffic limit,
reset devices) now include _s{subscription_id} suffix in callback_data.
Handlers extract subscription_id and operate on the correct subscription.
2026-03-25 15:11:24 +03:00
c0mrade a1623d94b1 fix: web API routes use multi-subscription resolution for operations
miniapp.py: get_subscription_details, get_tariffs, purchase_tariff,
preview_tariff_switch all resolve subscription from subscriptions list
instead of user.subscription property.
subscriptions.py + users.py: replace_existing and deactivation use
smart selection with len==1 guard.
2026-03-25 11:47:17 +03:00
c0mrade f83ff26332 fix: cabinet routes use smart subscription fallback + per-subscription UUID
helpers.py resolve_subscription picks best non-daily when no subscription_id.
renewal, purchase, wheel: same smart selection in multi-tariff fallback.
devices: uses _resolve_panel_uuid helper for create/update decision.
admin_tariffs: squad sync uses subscription.remnawave_uuid.
admin_traffic: _load_user_map loads subscription-level UUIDs in multi-tariff.
2026-03-25 11:47:10 +03:00
c0mrade fe03b587db fix: UUID warnings, phantom merge, yookassa validation, contest prize notification
channel_member: warns on UUID fallback in multi-tariff.
start.py: phantom merge checks subscription-level UUIDs before user-level transfer.
yookassa: validates subscription_id from recurrent payment metadata.
contest prize: notification includes tariff name for multi-subscription clarity.
2026-03-25 11:47:02 +03:00
c0mrade afd7b6d7ec fix: remnawave service uses per-subscription UUID throughout multi-tariff
Squad sync, user sync, UUID assignment, force_cleanup all use
subscription.remnawave_uuid in multi-tariff. Fallback _subs[0] replaced
with smart selection. phantom_service refreshes 'subscriptions' (plural).
2026-03-25 11:46:55 +03:00
c0mrade f89e326a19 fix: auto-purchase processes each autopay subscription independently
Instead of skipping when multiple active subscriptions exist, auto-purchase
now selects the subscription with autopay_enabled and most urgent renewal
(fewest days left). Handles single/multiple autopay subscriptions correctly.
2026-03-25 11:46:50 +03:00
c0mrade 0866c2ea4b fix: services use smart subscription selection + per-subscription UUID
promocode, campaign, guest_purchase, subscription_purchase, user_service,
daily_subscription — all replace active_subs[0] with best non-daily selection.
daily_subscription_service uses subscription.remnawave_uuid in multi-tariff.
2026-03-25 11:46:42 +03:00
c0mrade 147ef6b22b fix: admin handlers use _resolve_admin_subscription + per-subscription UUID
Centralized admin subscription resolution with smart selection (non-daily,
most days left). All 12+ admin operations use the new helper. UUID operations
(disable, enable, reset devices, update) now use subscription.remnawave_uuid
in multi-tariff mode instead of user-level UUID.
2026-03-25 11:46:36 +03:00
c0mrade 76ba19da17 fix: eligibility and display use best non-daily subscription in multi-tariff
Contests, wheel spin, and menu now select best non-daily subscription
(most days remaining) instead of arbitrary active_subs[0].
2026-03-25 11:46:29 +03:00
c0mrade 90fb0a21e2 fix: pass FSM state to _resolve_subscription across all subscription handlers
All bot subscription handlers (traffic, autopay, devices, links, countries,
purchase, tariff_purchase) now pass state: FSMContext to _resolve_subscription
so multi-tariff subscription context is preserved from my_subscriptions flow.
2026-03-25 11:46:22 +03:00
c0mrade 684f286fcd fix: add_traffic handler passes FSM state to resolve_subscription for multi-tariff context 2026-03-24 22:01:43 +03:00
c0mrade d2bbeb8624 fix: contest prize applies to best non-daily subscription in multi-tariff 2026-03-24 21:36:31 +03:00
c0mrade 72d5bae531 fix: tariff_purchase next() fallbacks use None instead of active_subs[0] in multi-tariff 2026-03-24 21:33:50 +03:00
c0mrade 6d468e9ada fix: multi-subscription support for promocodes, contests, phantom merge
Promocodes with days:
- activate_promocode accepts subscription_id parameter
- Multi-tariff + >1 eligible subs: returns select_subscription for UI
- Bot handler: shows subscription picker keyboard, callback applies to chosen sub
- Single sub: auto-applies as before

Contests:
- _resolve_subscription_for_prize: prefers non-daily sub with most days_left
- All 5 contest endpoints use shared resolver

Phantom service:
- merge_phantom_into_user: uses subscriptions collection instead of single
- sync_remnawave_after_phantom_merge: syncs all subscriptions, not just first
2026-03-24 21:29:17 +03:00
c0mrade 355fef846e fix: centralize trial cleanup in CRUD + shared subscription resolver for bot
Trial cleanup:
- create_paid_subscription: auto-deactivates all trials when creating paid sub
- extend_subscription: auto-deactivates trials when extending converts to paid
- Works from ALL paths: bot, cabinet, miniapp, webhooks, auto-purchase

Bot handlers:
- Shared resolve_subscription_from_context in common.py with FSM state fallback
- Fixes nested callbacks losing subscription context in multi-tariff
- All 5 handlers (traffic, devices, autopay, links, countries) use shared resolver
- my_subscriptions stores active_subscription_id in FSM state on delegation
2026-03-24 20:00:11 +03:00
c0mrade 424fff4ac2 fix: trial reset in multi-tariff only deletes trial subscriptions, keeps paid
- Multi-tariff + has paid subs: only trial subscriptions deleted
- Multi-tariff + all trials: deletes all (correct — no paid to keep)
- Single-tariff: unchanged (deletes all as before)
2026-03-24 19:20:28 +03:00
c0mrade d04f2fc718 fix: set is_daily_paused=True when admin cancels/disables daily subscription to prevent auto-resume 2026-03-24 18:38:45 +03:00
c0mrade 56fffc2415 fix: admin panel per-subscription UUID in multi-tariff mode
_sync_subscription_to_panel: use subscription.remnawave_uuid
panel-info/node-usage/devices: accept subscription_id query param
delete/reset devices: per-subscription UUID
enable after add_traffic: per-subscription UUID
trial/subscription reset, disable user: iterate all subs
push_to_panel: per-subscription UUID + fallback fixes
2026-03-24 16:54:53 +03:00
c0mrade c27f144b76 feat: DELETE /subscriptions/:id for expired/disabled subscriptions 2026-03-24 15:30:40 +03:00
c0mrade 34bb87c7ba fix: import Subscription in wheel_service to fix NameError 2026-03-24 14:44:34 +03:00
c0mrade 24edfb6c3f feat: wheel subscription picker for multi-tariff mode
- SpinAvailability returns eligible_subscriptions (non-daily, enough days)
- spin() accepts subscription_id to target specific subscription
- _process_days_payment and _apply_prize use provided subscription
- WheelConfigResponse includes eligible_subscriptions for frontend picker
- SpinRequest accepts subscription_id in body
- Daily tariffs excluded from wheel eligibility
2026-03-24 14:31:19 +03:00
c0mrade 824d54b7dc fix: accept subscription_id from query param in renew endpoint (consistent with other endpoints) 2026-03-24 14:09:05 +03:00
c0mrade 71082f436c fix: re-fetch subscription after lock_user_for_pricing to prevent selectinload reset 2026-03-24 13:07:33 +03:00
c0mrade 4dd81702ce feat: return is_daily and is_daily_paused in subscription list API 2026-03-24 12:27:52 +03:00
c0mrade 4f76f53d55 fix: add missing ADMIN_PAYMENTS localization keys for ru and en 2026-03-24 12:08:29 +03:00
c0mrade 048d208bc1 feat: trial lifecycle + purchase-options filter for multi-tariff
Trial:
- create_trial_subscription: autopay_enabled=False always
- autopay endpoint: block enabling autopay for trial subscriptions
- Purchase flows: deactivate all user trials on paid purchase,
  transfer remaining days if TRIAL_ADD_REMAINING_DAYS_TO_PAID,
  disable trials on RemnaWave panel

Purchase options:
- Return is_purchased per tariff and all_tariffs_purchased flag
  in multi-tariff mode for frontend filtering
2026-03-24 10:47:14 +03:00
c0mrade 344852b852 fix: trial subscription lifecycle — autopay, cleanup on purchase, bonus days
- create_trial_subscription: always set autopay_enabled=False (trial is a
  probe, autopay makes no sense regardless of operator default setting)
- autopay endpoint: block enabling autopay on trial subscriptions via API
- purchase-tariff (cabinet): before creating/extending paid subscription,
  find and deactivate ALL user's trial subscriptions, collect remaining
  time for TRIAL_ADD_REMAINING_DAYS_TO_PAID, disable trials on RemnaWave
  panel, decrement server counts — works for both tariff-based and
  squad-based trials uniformly
- subscription_purchase_service (miniapp): same trial cleanup logic
- New CRUD: deactivate_user_trial_subscriptions() — finds all active
  trials for user, marks them disabled with is_trial=False
2026-03-23 23:11:18 +03:00
c0mrade 78a7eafcb6 fix: prevent sync from overwriting wrong subscription traffic in multi-tariff mode
Remove fallback to first subscription when panel user UUID doesn't match
any subscription. Previously, _subs_upd[0] was used as fallback, causing
panel data (including traffic_used_gb=0 after reset) from one subscription
to overwrite another subscription's data during periodic sync.
2026-03-23 21:15:06 +03:00
c0mrade 5a7b3d5962 fix: renumber multi-subscription migrations to avoid conflicts with dev
Rename 0041 → 0050 and 0042 → 0051, chain after dev's 0049
to resolve multiple head revisions error on deployment.
2026-03-23 19:16:35 +03:00
c0mrade cefdfc54cc fix: add period_days validation and zero-price guard to tariff purchase
Port validations from dev monolith that were missing after sub-router split:
- Validate period_days against tariff's configured periods
- Allow custom days only if tariff explicitly supports them
- Reject zero-price purchases for non-daily tariffs (defense in depth)
2026-03-23 18:47:57 +03:00
c0mrade b6cf361737 fix: remove unused imports and variables after rebase 2026-03-23 18:46:28 +03:00
c0mrade 4f20e0e4cb chore: update uv.lock 2026-03-23 18:45:46 +03:00
c0mrade d87fb47e88 fix: multi-subscription UUID resolution and ownership validation
- Add _resolve_panel_uuid helper for per-subscription UUID in multi-tariff mode
- Add user ownership validation (user_id check) to all subscription queries
- Add unique partial index on (user_id, tariff_id) for active subscriptions
- Generate remnawave_short_id for new subscriptions in all creation paths
- Fix trial endpoints to check all user subscriptions, not just first
- Fix channel member handler to enable/disable per-subscription UUIDs
- Fix channel checker middleware for multi-subscription iteration
- Fix tariff switch, traffic, and device endpoints to use correct panel UUID
- Fix monitoring, auto-purchase, renewal services for multi-subscription
- Fix user_service, miniapp, subscriptions and users webapi routes
2026-03-23 18:45:46 +03:00
c0mrade 82958801b5 fix: harden webhook signature verification across all payment providers
- Replace fail-open with fail-closed in CryptoBot, Heleket, Tribute webhooks
  (missing API key now rejects instead of accepting)
- Use hmac.compare_digest for timing-safe comparison in Freekassa, KassaAI,
  Pal24, and Platega webhook verification
- CloudPayments: reject webhooks when signature header is missing but
  API_SECRET is configured (check, pay, fail, universal endpoints)
- CloudPayments: return code 13 (reject) instead of code 0 on parse errors
  and exception handlers to prevent fail-open
2026-03-23 18:45:46 +03:00
c0mrade d071269b8c fix: comprehensive multi-subscription audit fixes across routes, handlers, and services
- Fix UUID resolution in monitoring and webhook services for multi-tariff mode
- Update cabinet routes to properly resolve per-subscription UUIDs
- Fix account merge service for multi-tariff subscription transfers
- Update admin handlers (users, promo_offers, servers) for multi-subscription
- Fix traffic, devices, servers, daily subscription modules
- Update payment handlers (stars, yookassa) and purchase services
- Fix broadcast, promocode, and subscription auto-purchase services
- Add multi-subscription support to keyboards and localization
- Fix CRUD operations for subscription queries
- Resolve code quality issues (ruff linting)
2026-03-23 18:40:23 +03:00
c0mrade 18f31c565c fix: validate_and_clean_subscription uses per-subscription UUID in multi-tariff mode, not user-level UUID 2026-03-23 18:40:23 +03:00
c0mrade 2f88b07f05 fix: remove user.subscription setter - use local variable instead 2026-03-23 18:40:23 +03:00
c0mrade c8ecec47a0 fix: use empty path instead of '/' for multi-tariff list endpoint to avoid 404 2026-03-23 18:40:23 +03:00
c0mrade 06feb3fff5 fix: disable redirect_slashes globally to prevent HTTP 307 on subscription endpoints 2026-03-23 18:40:23 +03:00
c0mrade f7f8ea87cf fix: add redirect_slashes=False to prevent HTTP 307 redirects on subscription endpoints 2026-03-23 18:40:23 +03:00
c0mrade e99f3d9a37 fix: rename refresh('subscription') to refresh('subscriptions') in all files 2026-03-23 18:40:23 +03:00
c0mrade 07ebc435cf fix: use '/' instead of empty path in subscription sub-routers 2026-03-23 18:37:18 +03:00
c0mrade 335be66980 feat: multi-subscription support (1 user = N subscriptions)
- Add MULTI_TARIFF_ENABLED feature flag for gradual rollout
- Migration 0041: remove unique constraint on subscriptions.user_id
- Migration 0042: add remnawave_short_id (NOT NULL, UNIQUE) to subscriptions
- Each subscription gets its own Remnawave user (user_{tg_id}_{short_id})
- Add _resolve_subscription() to all 30+ bot handlers for per-subscription routing
- Add my_subscriptions.py with list/detail views and delegation handlers
- Refactor cabinet subscription.py (4687 lines -> 10 focused modules)
- Add subscription_id parameter to all cabinet API endpoints
- Adapt all services: autopay, wheel, contests, campaign, guest purchase,
  monitoring, blocked users, account merge, promo codes, payments
- Replace all user.subscription (singular) with user.subscriptions iteration
- IDOR protection via get_subscription_by_id_for_user on all endpoints
- Full backward compatibility: MULTI_TARIFF_ENABLED=False = legacy behavior
2026-03-23 18:37:17 +03:00
Fringg c805cfd6d8 fix: transliterate Cyrillic slugs instead of stripping to 'untitled'
sanitize_slug validators now use _slugify() for proper transliteration.
2026-03-23 18:19:02 +03:00
Fringg 004dac5b7e fix: resolve MissingGreenlet error on article detail view
Build response dict before increment_views() commit expires ORM attributes.
2026-03-23 18:16:22 +03:00
Egor 7e9cc530e7 Merge pull request #2809 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.42.0
2026-03-23 16:57:38 +03:00
github-actions[bot] 69b824572a chore(main): release 3.42.0 2026-03-23 13:57:17 +00:00
Egor ab4785f8df Merge pull request #2808 from BEDOLAGA-DEV/dev
Dev
2026-03-23 16:56:36 +03:00
Fringg 1642be8bd6 chore: ruff format miniapp.py 2026-03-23 16:49:17 +03:00
Fringg 8175bc8bfe fix: comprehensive security hardening across payment and API layers
- CloudPayments: require webhook signature when secret configured (all 4 handlers)
- Platega: timing-safe HMAC comparison via hmac.compare_digest
- CryptoBot/Heleket: return False when API token unconfigured
- Tribute: return 503 when API key not configured
- Freekassa: use request.client.host instead of X-Forwarded-For
- Pal24: verify webhook amount matches stored payment amount
- YooKassa: reject test-mode payments in production; add YOOKASSA_TEST_MODE config
- CloudPayments: reject test-mode payments in production
- WebAPI: add upper bounds to duration_days, traffic_limit_gb, device_limit schemas
- WebAPI: bound balance update amount to ±100M kopeks
- WebAPI: sign-dispatch for balance updates (negative → subtract_user_balance)
- WebAPI miniapp: add blocked/deleted user checks, restriction_topup/subscription guards
- Admin handlers: add @admin_required and @error_handler to moderator panel
- add_user_balance: guard against negative amounts (use subtract_user_balance instead)
2026-03-23 16:44:38 +03:00
Fringg 4660ca5756 fix: validate period_days against tariff in purchase-tariff and auto-purchase
Critical security fix: the POST /cabinet/subscription/purchase-tariff
endpoint accepted arbitrary period_days from client without validating
against the tariff's configured periods. The pricing engine returned 0
for unknown periods, allowing free subscription creation.

Changes:
- Add period_days whitelist validation in /purchase-tariff endpoint
- Add zero-price safety guard as defense in depth
- Add period_days validation in _auto_purchase_tariff (saved cart)
- Add period_days validation in _prepare_auto_extend_context (saved cart)
2026-03-23 16:35:18 +03:00
Fringg 6bf41a72d0 chore: ruff format news_tags.py 2026-03-23 16:08:10 +03:00
Fringg 6d0b003591 chore: ruff format 2026-03-23 16:07:01 +03:00
Fringg 334db53868 feat: show Platega payment methods inline on main screen (#2720)
Show each Platega method (SBP, cards, crypto) as a separate button
on the main payment screen like YooKassa, instead of behind a sub-menu.

Controlled by PLATEGA_INLINE_METHODS env var (default: true).
Set to false to keep the old sub-menu behavior.
2026-03-23 16:04:27 +03:00
Fringg 76b1f9b036 fix: use IF EXISTS in downgrade for FK indexes 2026-03-23 15:43:07 +03:00
Fringg f0cdd5dc90 fix: validate FK existence, add FK indexes, expand video brand whitelist
- Validate category_id/tag_id exist before creating/updating articles (422 not misleading 409)
- Add indexes on news_articles.category_id and tag_id for efficient FK lookups
- Expand MP4 brand whitelist: iso2-4, qt (MOV/iPhone), 3gp, M4VH/VP, MSNV, NDAS/C/H/S/M/P
- Log unknown ftyp brands for debugging rejected video uploads
2026-03-23 15:40:16 +03:00
Fringg d9cda3a6d6 fix: register categories/tags/media routers before news to avoid route conflict
GET /admin/news/{article_id} was catching /admin/news/categories and
/admin/news/tags requests, parsing "categories" as int → 422.
2026-03-23 15:37:08 +03:00
Fringg 51392d1918 feat: add managed news categories and tags with DB-backed CRUD
- Add news_categories and news_tags tables with case-insensitive unique names
- Add category_id/tag_id FK columns to news_articles (ON DELETE SET NULL)
- CRUD endpoints for categories and tags (admin permissions)
- Sync legacy string fields from FK entities on create/update
- Clear legacy fields on category/tag deletion
- Alembic migration 0049 with backfill from existing article data
2026-03-23 15:29:21 +03:00
Fringg 89bfdc8ed6 fix: add explicit File(...) to UploadFile param to fix 422 on media upload 2026-03-23 15:17:10 +03:00
Fringg 0225fa155b fix: remove future annotations breaking UploadFile, harden media URL generation 2026-03-23 15:10:47 +03:00
Fringg fd410096ea fix: respect X-Forwarded-Proto in media URL generation to prevent mixed content 2026-03-23 15:04:55 +03:00
Fringg b5853ec3b6 feat: enforce single featured news article — unfeature others on toggle/create/update 2026-03-23 15:00:20 +03:00
Fringg 2f19c76357 fix: add user ID to payment descriptions for all providers and fix tuple bug
- Add telegram_user_id and user_db_id to get_balance_payment_description() across
  8 cabinet balance providers (heleket, mulenpay, pal24, wata, cloudpayments,
  freekassa, kassa_ai, riopay), all miniapp endpoints, and recurrent payments
- For email/OAuth users without telegram_id, fallback to DB ID with (U{id}) format
- Fix pre-existing tuple bug in bot_configuration.py (trailing comma created tuple)
- Fix typo in nalogo_queue_service.py log message ("Чек уже попыток")
2026-03-23 14:48:12 +03:00
Fringg 6658af6268 refactor: extract phantom service, replace lightweight merge with execute_merge
- Extract _claim_phantom_user and _merge_phantom_into_active_user from
  start.py into app/services/phantom_service.py
- Replace lightweight 3-4 table merge with full execute_merge (30+ tables)
- Add durable AdminAuditLog records for phantom claims and merges
- Use begin_nested() savepoints for audit log writes (session-safe)
- Move Remnawave panel sync to after commit (no HTTP inside locked txn)
- Fix remnawave_uuid transfer in account_merge_service with two-flush
  pattern (clear→flush→assign) to prevent unique constraint violations
- Add db.refresh after rollback in Path A to prevent stale object access
2026-03-23 14:26:36 +03:00
Fringg fad77f8c80 fix: phantom user merge on claim failure, referral assignment, account merge hardening
- Fix orphaned subscriptions/GuestPurchase when phantom claim fails with
  IntegrityError — now merges phantom into existing user across all 3 call sites
- Add explicit db.commit() after merge in both active-user and registration paths
- Fix remnawave_uuid transfer ordering (clear→flush→assign) to prevent unique
  constraint violation during flush
- Clear phantom.referral_code on soft-delete to prevent unique constraint issues
- Add status != DELETED filter to find_phantom_user_by_username (defense in depth)
- Add WARNING-level logging on phantom claims for admin audit trail
- Add functional index on lower(username) for phantom lookup performance (migration 0048)
- Add ON DELETE CASCADE to subscription_servers.subscription_id (migration 0047)
- Add admin endpoint POST /users/{id}/assign-referrer with recursive CTE cycle
  detection, self-enrichment prevention, and audit logging
- Harden account_merge_service: add SubscriptionServer, RioPayPayment,
  SeverPayPayment, SavedPaymentMethod, GuestPurchase, NewsArticle handling
- Fix logger key typo get= → error= in promocode activation
2026-03-23 13:59:38 +03:00
Fringg 172924df0e fix: catch DecompressionBombError, hoist MP4 brands to module level
- Add PIL.Image.DecompressionBombError to except clause (inherits from
  Exception, not ValueError/OSError — was escaping as unhandled 500)
- Move _MP4_VIDEO_BRANDS to module-level frozenset for consistency
2026-03-23 13:05:11 +03:00
Fringg 7ff73e8492 fix: reject HEIC as MP4, close UploadFile, narrow exception handling
- Add ftyp brand allowlist to reject HEIC/HEIF files misclassified as MP4
- Close UploadFile after read to release resources during processing
- Add exception chaining (from None) on HTTPException raises
- Narrow except to ValueError/OSError (let programming errors propagate)
- Add exc_info=True to thumbnail failure log for debuggability
- Type detect_file_type return as tuple[MediaType, str]
2026-03-23 12:42:21 +03:00
Fringg ce554cb2a8 fix: add Literal type to SavedMedia and close orphaned PIL Image objects
- SavedMedia.media_type now uses Literal['image', 'video'] matching Pydantic schema
- Explicitly close old Image objects after exif_transpose and convert('RGB')
2026-03-23 12:31:34 +03:00
Fringg 165d25ef5f fix: media upload security hardening from 6-agent review
- PIL Image resource leak: wrap in try/finally with img.close()
- Grayscale images: normalize all to RGB for consistent JPEG output
- exif_transpose: defensive None guard
- Thumbnail: explicit close after save
- media_type: use Literal['image', 'video'] in schema
- ensure_upload_dirs: run in asyncio.to_thread (not sync in event loop)
- _SAFE_FILENAME_RE: remove thumb_ prefix (prevent orphaned files)
2026-03-23 12:05:37 +03:00
Fringg 5ed3780f83 fix: create uploads subdirectories in Dockerfile for correct permissions 2026-03-23 12:02:05 +03:00
Fringg a0d40ad432 feat: add media upload/delete API for news articles
Local filesystem storage with Docker volume mount, magic byte validation,
PIL image resize/thumbnail generation, atomic writes, path traversal guards.
2026-03-23 11:58:07 +03:00
Fringg 3e69efe589 fix: replace asyncio.gather with sequential queries on shared session
AsyncSession does not support concurrent operations on the same
connection. Running gather caused InvalidRequestError on news list.
2026-03-23 11:34:25 +03:00
Fringg 015c2da297 fix: simplify 0046 migration downgrade to just drop_table
drop_table automatically removes all indexes, fixing downgrade failure
when indexes were added after initial migration was applied
2026-03-23 11:29:31 +03:00
Fringg 2b91808b0c fix: news module security hardening, perf optimizations, bug fixes
- Server-side HTML sanitization for article content
- URL scheme validation for featured_image_url (http/https only)
- Slug sanitization on create/update
- MissingGreenlet fix in delete (capture attrs before commit)
- Missing rollback after IntegrityError in CRUD
- nullslast() for published_at ordering
- asyncio.gather for parallel DB queries
- Removed selectinload(author) from list queries
- increment_views with RETURNING (no extra SELECT)
- Migration-model index alignment
- Pre-compiled regex, structlog.exception pattern
- View counter dedup cache (5min TTL)
2026-03-23 11:09:45 +03:00
Fringg b93240393f feat: add news articles module with admin CRUD and public API
- NewsArticle model with composite index, Alembic migration
- Admin routes: list, create, update, delete, toggle publish/featured
- Public routes: paginated list with category filter, article detail with view counter
- Pydantic schemas with strict hex color validation, slug auto-generation
- IntegrityError handling for slug race conditions
2026-03-23 10:51:12 +03:00
Fringg 89341baa62 fix: restore connected_squads and admin notification on daily subscription resume
When a daily subscription is resumed after user deletion from RemnaWave panel
and deactivation sync, connected_squads were cleared but never restored,
causing internal squads to not be assigned. Also, admin notifications were
missing from the Telegram bot handler path.

Fixed across all 5 resume code paths:
- cabinet /pause endpoint
- miniapp /subscription/daily/toggle-pause endpoint
- bot handle_toggle_daily_subscription_pause handler
- DailySubscriptionService._process_single_charge
- try_resume_disabled_daily_after_topup auto-resume

Changes in each path:
- Restore connected_squads from tariff.allowed_squads (fallback: all available servers)
- Branch create/update based on remnawave_uuid presence
- Follow-up PATCH after POST to ensure internal squads are assigned
- Use limit=10000 in get_all_server_squads to avoid silent truncation
- Separate try/except for squad restore vs RemnaWave sync for resilience
- Add admin notification in bot handler (was missing)
2026-03-23 09:31:34 +03:00
Fringg cbe630cab0 refactor: simplify referral invite text to single template
Replace 7 fragmented localization keys with one REFERRAL_INVITE_TEXT
template. Remove Share button (switch_inline_query). Wrap invite text
in blockquote+code for visual quote style with tap-to-copy. Update
instruction text in all 5 locales (ru, en, ua, fa, zh).
2026-03-23 08:25:19 +03:00
Fringg 9de34900a2 fix: comprehensive html.escape() for all user/admin data in Telegram HTML messages
Bot uses default HTML parse mode — all messages are HTML-parsed by Telegram.
Added html.escape() to all user-controlled and admin-controlled strings
before interpolation into HTML messages to prevent injection and parse errors.

49 files, ~250+ injection points fixed:
- user.full_name, first_name across all handlers and services
- tariff.name/description in purchase flow, admin panel, auto-purchase service
- campaign.name, start_parameter in admin and user-facing handlers
- group.name, promo_group.name across promo management
- contest.title, prize_text, leaderboard names (including public channels)
- transaction.description (contains raw user.full_name from referral service)
- restriction_reason across all balance and subscription handlers
- ticket.title, message_text, poll.title, poll.description
- welcome text template placeholders (first_name, username)
- maintenance reason, admin_name, selected_prize.display_name

New helpers in app/utils/formatting.py:
- safe_html_name() for escaping display names
- user_html_link() replacing 15+ duplicated inline link patterns
2026-03-23 08:06:15 +03:00
Fringg aec04f0085 fix: correctly price unlimited traffic (0 GB) in classic subscription mode
_calculate_traffic_price treated unlimited traffic as free because
base_gb=0 triggered the `if base_gb > 0 else 0` guard, skipping
the price lookup. Added early return for total_gb==0 to use the
configured unlimited tier price.
2026-03-23 06:42:57 +03:00
Fringg 0fe3c217f7 fix: suppress harmless TelegramBadRequest errors and fix discount promo display
- Reorder middleware: LoggingMiddleware now outermost, GlobalErrorMiddleware inside — prevents full traceback logging for suppressed errors (message not modified, query too old, bot blocked)
- Fix root cause in message_patch.py: _edit_with_photo missing try/except for _original_edit_text when ENABLE_LOGO_MODE=False
- Add "message is not modified" suppression in AuthMiddleware to prevent unnecessary db.rollback() and ERROR-level logging
- Fix discount promo display in admin notifications: subscription_days shown as hours (not days), balance_bonus_kopeks shown as percentage (not price)
2026-03-23 06:16:28 +03:00
Fringg 958ec489a2 fix: respect per-channel disable_on_leave settings in monitoring service
The background monitoring service was deactivating trial subscriptions
when users unsubscribed from channels, ignoring per-channel
disable_trial_on_leave and disable_paid_on_leave settings that the
real-time handler and middleware already respected.

Changes:
- Use shared should_disable_subscription() for all 3 deactivation paths
- Add global CHANNEL_DISABLE_TRIAL_ON_UNSUBSCRIBE override in should_disable_subscription
- Add admin skip in monitoring (consistent with handler/middleware)
- Replace inline reactivation with reactivate_subscription() CRUD
- Switch to enable_remnawave_user() instead of heavy update_remnawave_user()
- Add commit=False to deactivate/reactivate/record/clear_notification for batch atomicity
- Include paid subs in monitoring when any channel has disable_paid_on_leave=True
- Use skip_deactivation flag instead of early return to preserve reactivation path
- Commit batch before create_remnawave_user which internally commits
2026-03-23 05:54:26 +03:00
Egor df9985802b Merge pull request #2801 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.41.0
2026-03-22 10:56:39 +03:00
github-actions[bot] c66849db10 chore(main): release 3.41.0 2026-03-22 07:56:12 +00:00
Egor 8a1da85f3e Merge pull request #2800 from BEDOLAGA-DEV/dev
Dev
2026-03-22 10:55:46 +03:00
Fringg 0335f40b47 chore: ruff format rbac_bootstrap_service.py 2026-03-22 10:51:26 +03:00
Fringg 8ac1183670 chore: ruff format admin_referral_network.py 2026-03-22 10:47:01 +03:00
Fringg bcc761f9d3 fix: add missing total_subscription_revenue_kopeks in scoped graph early return
Prevents Pydantic ValidationError (500) when scoped_user_ids is empty
but campaign_ids is present.
2026-03-22 10:46:08 +03:00
Fringg 1eb4e18c17 fix: add abs() to all remaining subscription payment sum queries
Apply func.abs() consistently to all 5 remaining locations that sum
SUBSCRIPTION_PAYMENT amounts: branch revenue, campaign stats,
user detail branch revenue, campaign detail, and search results.
2026-03-22 10:39:20 +03:00
Fringg 056c13bc23 fix: use abs() for subscription payment amounts in referral network
SUBSCRIPTION_PAYMENT transactions are stored as negative values,
causing negative totals in stats panel and user detail card.
2026-03-22 10:36:13 +03:00
Fringg 2bdb7643f8 feat: add total subscription revenue to referral network stats
Expose total_subscription_revenue_kopeks in NetworkGraphResponse,
computed from the existing personal_spent data (sum of all
SUBSCRIPTION_PAYMENT transactions by scoped users).
2026-03-22 10:31:18 +03:00
Fringg 8b8f1b91f3 refactor: extract _compute_subscription_status shared helper
Eliminates duplicated status mapping logic between _fetch_subscription_info
and get_network_user_detail. Single source of truth for mapping
subscription fields to frontend status labels.
2026-03-22 10:08:50 +03:00
Fringg 5ed2f0c958 fix: treat expired and limited subscription statuses as inactive in referral network graph
Previously only disabled and pending statuses were forced to show as
expired in the network graph. Subscriptions with status='expired' or
status='limited' but with end_date > now would incorrectly display as
active. Now all four non-active statuses are treated as expired.
2026-03-22 09:54:59 +03:00
Fringg 454dc9321b fix: consider subscription status field in network graph
The subscription_status computation now checks the Subscription.status
field. Disabled and pending subscriptions are treated as expired
regardless of end_date, preventing incorrect "active" display.
Also added SubscriptionStatus import.
2026-03-22 09:51:59 +03:00
Fringg de91d3282f feat: add subscription status to referral network graph nodes
Add subscription_status field (trial_active, paid_active, trial_expired,
paid_expired) to NetworkUserNode and NetworkUserDetail schemas. Backend
computes status from Subscription.is_trial and end_date using window
function to pick latest subscription per user.
2026-03-22 09:07:29 +03:00
Fringg e0bedc8e78 fix: superadmin role managed exclusively via env config
Superadmin (level 999) assignments are now the sole domain of
ADMIN_IDS/ADMIN_EMAILS environment variables. On startup, bootstrap
reactivates env-listed users and revokes superadmin from users removed
from env. API assign/revoke endpoints return 403 for superadmin-level
roles. _ensure_role_by_email now requires email_verified (symmetric
with revocation check).
2026-03-22 08:41:36 +03:00
Egor 4a48818bc3 Merge pull request #2798 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.40.0
2026-03-22 07:36:14 +03:00
github-actions[bot] ff7388766c chore(main): release 3.40.0 2026-03-22 04:35:51 +00:00
Egor 6b36dc4df1 Merge pull request #2797 from BEDOLAGA-DEV/dev
Dev
2026-03-22 07:35:24 +03:00
Fringg fe847e35f0 chore: ruff format oauth, auth schemas, webhook service 2026-03-22 07:32:04 +03:00
Fringg 4c2cb63cf9 fix: accept stale Telegram initData to prevent MiniApp auth failures
Telegram Desktop/iOS cache initData with stale auth_date (tdesktop#28303).
Increase max_age_seconds from 24h to 30 days for all cabinet login and
account linking endpoints. HMAC signature still validates authenticity,
JWT tokens handle session expiration. Add structured logging for stale
initData acceptance monitoring.
2026-03-22 07:24:27 +03:00
Fringg d3c994083e fix: daily subscription pause not persisting in cabinet and miniapp
lock_user_for_pricing with populate_existing=True was overwriting the
pending is_daily_paused mutation before db.commit(), silently discarding
the pause toggle. Fix moves lock before state reads, uses commit=False
for subtract_user_balance and create_transaction to ensure single atomic
commit, and re-applies is_daily_paused after any populate_existing reload.
2026-03-22 06:54:39 +03:00
Fringg cce3b0c13b feat: allow inactive tariffs for trial subscription activation
Inactive tariffs with is_trial_available=True can now be used for trial
activation across bot, miniapp, and cabinet. This enables dedicated trial
tariffs with custom limits (traffic, devices, servers) without exposing
them in the regular purchase flow. Paid trial paths now properly resolve
trial tariff parameters instead of using global settings defaults.
2026-03-22 06:01:34 +03:00
Fringg 6c208581d9 fix: sanitize email dots in RemnaWave username generation
Email addresses with dots (e.g., john.doe@gmail.com) caused RemnaWave
API validation failure. Now sanitizes email prefix early in the
identifier construction, not just in the final result. Also sanitizes
the fallback username path for defense in depth.
2026-03-22 04:59:30 +03:00
Fringg c307278231 fix: prevent MESSAGE_TOO_LONG in promo groups list
With 20+ promo groups, the full details per group exceeded Telegram's
4096 char limit. Simplified list to one compact line per group with
name and member count. Full details remain in the group detail view.
2026-03-22 04:17:32 +03:00
Fringg 9eab802000 fix: handle spurious user.deleted webhooks — preserve active subscriptions and prevent orphaned panel users
- Smart end_date check: subscriptions with future end_date are preserved (not expired) and panel user is re-created automatically
- Recreation loop guard: in-memory 120s cooldown prevents unbounded recreate→delete→recreate cycles with stale entry eviction
- Race condition protection: guard timestamp stamped before any await point so concurrent coroutines are serialized
- Admin deletion: force_panel_delete=True ensures panel user is always removed, preventing orphaned subscriptions
2026-03-22 03:20:50 +03:00
Fringg 13ea3768b5 feat: custom broadcast buttons and fix home button to use bot menu
- Add custom buttons support: admins can add up to 10 custom buttons
  with callback_data or URL action types to broadcast messages
- CustomBroadcastButton Pydantic model with validation:
  callback_data checked in UTF-8 bytes (Telegram 64-byte limit),
  URLs restricted to https:// and tg:// schemes only
- Fix home button: removed from CABINET_MINIAPP_BUTTON_KEYS so it
  uses back_to_menu callback instead of opening cabinet WebApp
- Both legacy and combined broadcast endpoints pass custom_buttons
2026-03-22 01:54:05 +03:00
Fringg ed5a92ab96 fix: referral system — self-referral protection, race condition fix, deleted user re-registration
- Add telegram_id-based self-referral protection in all 3 Telegram auth endpoints
  (user doesn't exist yet at referral resolution, so telegram_id is used instead of user.id)
- Add SELECT FOR UPDATE + db.refresh in _process_referral_code to prevent TOCTOU race
  on concurrent referral assignment (matches _process_campaign_bonus pattern)
- Fix _process_referral_code to handle two cases: referred_by_id already set by
  create_user() → fire registration event; not set → resolve code, set, fire event
- Fix deleted user re-registration losing referral: keep status=DELETED in preparation
  block so complete_registration enters the DELETED branch (not "already active")
- Remove unused referral_code from DeepLinkPollRequest (deep link = existing users only)
- Fix OIDC exception handling inconsistency (ValueError/LookupError → Exception)
- Fix bare except clauses in start.py → except Exception
- Pass is_new_user to _finalize_oauth_login (only new user path passes True)
2026-03-21 15:06:10 +03:00
Fringg 48265f1cd4 chore: remove redundant comments from DISABLED status fix 2026-03-21 09:07:43 +03:00
Fringg 3b9568fcc1 style: format long lines in monitoring and subscription services 2026-03-21 09:06:01 +03:00
Fringg 79cfcbcece fix: send DISABLED instead of EXPIRED status to RemnaWave API
RemnaWave API only accepts ACTIVE/DISABLED for user status updates —
EXPIRED and LIMITED are managed internally. The bot was sending EXPIRED
status and past expireAt dates, causing 400 validation errors.

- Change UserStatus.EXPIRED → UserStatus.DISABLED in all 5 call sites
- Add 1-minute buffer to expire_at for inactive subscriptions to avoid
  "expiration date in the past" rejections (matches _safe_expire_at_for_panel)
- Include TRIAL status in is_actually_active checks (consistent with
  remnawave_service.py sync_users_to_panel)
2026-03-21 09:00:59 +03:00
Egor 6d5aceb4ca Merge pull request #2793 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.39.0
2026-03-21 07:41:49 +03:00
github-actions[bot] 905dbcc779 chore(main): release 3.39.0 2026-03-21 04:40:13 +00:00
Egor f33dfdf031 Merge pull request #2792 from BEDOLAGA-DEV/dev
Dev
2026-03-21 07:39:51 +03:00
Egor 59cd74d307 Merge pull request #2791 from BEDOLAGA-DEV/main
w
2026-03-21 07:38:22 +03:00
Fringg 90209ebef1 feat: add NaloGO fiscal receipts for code-only gift purchases
- Create NaloGO receipt when code-only gifts (no recipient) are paid via
  any gateway provider, not just directed gifts
- Add receipt_uuid and receipt_created_at columns to guest_purchases for
  persistent DB-level dedup (covers PENDING_ACTIVATION and code-only paths
  where no Transaction exists at receipt time)
- Use SELECT ... FOR UPDATE in try_fulfill_guest_purchase to prevent
  concurrent webhook double-processing race condition
- Expand idempotency guard to include code-only gifts already in PAID status
- Add db.refresh after PENDING_ACTIVATION nalogo call to guard against
  inner rollback expiring the ORM object
2026-03-21 07:37:03 +03:00
Fringg ab43e74ab7 fix: manual admin top-ups missing from sales statistics
Cabinet API and WebAPI created admin balance transactions with
payment_method=NULL instead of 'manual', making them invisible
to sales statistics filters.

Changes:
- Add payment_method=PaymentMethod.MANUAL to Cabinet and WebAPI
  balance update endpoints
- Add func.abs() to all transaction amount aggregations missing it
  across sales stats, dashboard stats, and reporting queries
- Remove redundant Python abs() on addon_revenue (SQL func.abs
  already applied)
- Add data migration 0044 to fix historical NULL payment_method
  records for admin top-ups
2026-03-21 07:01:22 +03:00
Fringg 4244962337 fix: add NaloGO fiscal receipt creation for landing page purchases
Landing page (guest) payments were completely skipping nalogo receipt
generation because the guest purchase flow returned early in payment
webhook handlers before reaching the nalogo code.

Added _create_nalogo_receipt_for_purchase() helper with:
- payment_id null-check (Redis dedup requires it)
- amount validation (skip zero/negative)
- transaction.receipt_uuid duplicate guard
- inner try/except with db.rollback() for receipt_uuid persistence
- sanitize_proxy_error for credential-safe error logging
- privacy: no telegram_user_id in receipt description sent to tax authority

Called in both DELIVERED and PENDING_ACTIVATION paths.
Added db.refresh(purchase) after nalogo call to handle potential
session expiry from rollback inside the helper.
2026-03-21 06:36:21 +03:00
Fringg ba79d03e38 fix: skip non-JSON payload rows in cryptobot payment index and query
payload column in cryptobot_payments contains plain strings like
"balance_2_10000" alongside JSON objects. CAST(payload AS json) fails
on these rows during CREATE INDEX CONCURRENTLY.

- Add AND payload LIKE '{%' to partial index WHERE clause in migration 0042
- Add .payload.like('{%') filter to guest_purchase_service query
2026-03-21 05:43:22 +03:00
Egor 8e4e2ddd1a Update README.md 2026-03-21 05:09:00 +03:00
Egor 38853cdd5a Merge pull request #2790 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.38.0
2026-03-21 04:32:38 +03:00
github-actions[bot] f837c0c244 chore(main): release 3.38.0 2026-03-21 01:32:11 +00:00
Egor 8a7b9cc651 Merge pull request #2789 from BEDOLAGA-DEV/dev
Dev
2026-03-21 04:31:51 +03:00
Fringg 3bf31055e7 fix: sanitize proxy credentials in all nalogo error paths
- Apply sanitize_proxy_error() to all 8 error handlers in nalogo_service
- Remove exc_info=True from error paths that could expose proxy creds
- Fix regex backreference to preserve original SOCKS scheme
- Consolidate proxy utility imports to module level
- Add source indicator (NALOGO_PROXY_URL vs fallback) to startup log
2026-03-21 04:27:15 +03:00
Fringg 3c5bf4fa22 feat: add SOCKS proxy support for nalogo (tax service) module
Route all nalog.ru API traffic through SOCKS proxy. Uses NALOGO_PROXY_URL
env var (falls back to PROXY_URL if not set). Adds httpx[socks] dependency.

- Thread proxy_url through Client → AuthProviderImpl + AsyncHTTPClient
- Extract mask_proxy_url() and sanitize_proxy_error() utilities
- Add socks5h:// scheme support for remote DNS resolution
- Sanitize proxy credentials in error messages
- Log masked proxy URL at startup and service init
2026-03-21 04:21:11 +03:00
Fringg 4990ddf9e4 fix: add diagnostic payload logging in create_user error path
Consistent with update_user — log full payload before re-raising
non-A039 errors to aid debugging.
2026-03-21 04:08:18 +03:00
Fringg de00612965 fix: retry Remnawave API calls without externalSquadUuid on A039 FK violation
When a tariff has a stale external_squad_uuid that no longer exists in
the Remnawave panel, PATCH/POST /api/users fails with A039 (P2003 FK
constraint violation). This caused subscriptions to not sync with the
panel even though balance was already charged.

Now both update_user() and create_user() catch A039 errors and
automatically retry without externalSquadUuid, logging a warning about
the stale UUID. The subscription sync succeeds without the external
squad assignment rather than failing entirely.
2026-03-21 03:58:21 +03:00
Egor 43f5629c8c Merge pull request #2788 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.37.0
2026-03-21 03:18:30 +03:00
github-actions[bot] 448799a3ed chore(main): release 3.37.0 2026-03-21 00:18:10 +00:00
Egor b2b5f104b5 Merge pull request #2787 from BEDOLAGA-DEV/dev
Dev
2026-03-21 03:17:44 +03:00
Egor 5f71eaa926 Merge pull request #2778 from smediainfo/fix/dashboard-guest-revenue
fix: include SUBSCRIPTION_PAYMENT in dashboard revenue
2026-03-21 03:15:20 +03:00
Fringg 54155b5649 style: ruff format cloudpayments.py 2026-03-21 03:14:15 +03:00
Egor 8dc778654d Merge pull request #2785 from BEDOLAGA-DEV/revert-2783-revert-2779-fix/dashboard-revenue-complete
Revert 2783 revert 2779 fix/dashboard revenue complete
2026-03-21 03:11:03 +03:00
Egor 5175cccab6 Revert "Revert "fix: include landing page revenue in dashboard statistics"" 2026-03-21 03:07:19 +03:00
Egor 39ae095d9b Merge pull request #2786 from BEDOLAGA-DEV/main
w
2026-03-21 03:04:27 +03:00
Egor db3ac254ba Revert "Revert "fix: include landing page revenue in dashboard statistics"" 2026-03-21 03:03:06 +03:00
Egor bff9ebf078 Merge pull request #2783 from BEDOLAGA-DEV/revert-2779-fix/dashboard-revenue-complete
Revert "fix: include landing page revenue in dashboard statistics"
2026-03-21 03:02:57 +03:00
Egor 42ddadec5b Revert "fix: include landing page revenue in dashboard statistics" 2026-03-21 03:02:36 +03:00
Egor c6c1599e14 Merge pull request #2779 from smediainfo/fix/dashboard-revenue-complete
fix: include landing page revenue in dashboard statistics
2026-03-21 03:02:09 +03:00
Egor 77b2d645c5 Merge pull request #2782 from SayonaraQ/pr/remnawave-node-webhook-toggle-dev
add toggle for Remnawave node connection webhook alerts
2026-03-21 03:00:13 +03:00
Fringg 3875335cd7 fix: narrow exception handling and fix session leak in gift.py
- Replace broad `except Exception` with `except TelegramAPIError` in
  balance.py and wheel.py Stars invoice creation (prevents masking
  programming errors)
- Fix session leak in gift.py telegram_stars path: wrap PaymentService
  usage in try/finally to ensure bot.session.close() is called
2026-03-21 02:55:48 +03:00
Fringg 0a53b85b8a refactor: centralize Bot instantiation via create_bot() factory
Replace all ~45 direct Bot() calls across the codebase with a centralized
create_bot() factory function that automatically configures SOCKS5 proxy
session when PROXY_URL is set. This ensures proxy support applies uniformly
to all Telegram API traffic.

Key changes:
- Add app/bot_factory.py with create_bot() factory
- Replace direct Bot() instantiation in 33 files
- Fix session leaks in cloudpayments.py and auth.py (async with)
- Replace 2 direct httpx calls to api.telegram.org with
  bot.create_invoice_link() (balance.py, wheel.py)
- Remove now-unused imports (Bot, DefaultBotProperties, ParseMode, httpx)
2026-03-21 02:49:37 +03:00
Fringg 82b6a8bf70 feat: add SOCKS5 proxy support for Telegram API traffic
Route bot traffic through SOCKS5 proxy when PROXY_URL env var is set.
Validates scheme to reject HTTP proxies (would expose bot token).
Credentials are masked in logs.
2026-03-21 02:32:35 +03:00
Fringg 2a72deadd6 fix: resolve EmailService stale SMTP config causing NoneType crash on from_email
EmailService singleton cached SMTP settings in __init__ at import time.
is_configured() read live from settings, but self.from_email stayed None
when SMTP was unconfigured at startup → AttributeError on .split('@').

Replace cached attributes with @property accessors, snapshot from_email
once per send_email call with validation guard.
2026-03-21 02:21:25 +03:00
Fringg afefcc9c07 fix: resolve remaining TOCTOU issues in RioPay, SeverPay and restore paid_at
- RioPay: use create_transaction(commit=False) to keep FOR UPDATE lock,
  replace update_riopay_payment_status with inline assignment + flush,
  add emit_transaction_side_effects after commit
- SeverPay: add db.flush() before _finalize, remove self-assignment,
  add paid_at to both webhook and status-check paths
- Freekassa/KassaAI: add is_paid and paid_at to webhook and status-check
  inline sections (regression from CRUD→inline migration)
- MulenPay: add is_paid and paid_at to webhook inline section
2026-03-21 02:10:41 +03:00
Fringg 82c79c1306 fix: prevent double-payment TOCTOU race in all payment providers
Apply the same FOR UPDATE locking pattern across 8 providers:
- RioPay: added FOR UPDATE lock (had none at all)
- CryptoBot: moved lock before status check, removed redundant lock
- WATA: moved lock before is_paid commit, removed redundant lock
- Freekassa: moved lock before is_paid commit, removed redundant lock
- KassaAI: moved lock before is_paid commit, removed redundant lock
- MulenPay: moved lock before is_paid commit, removed redundant lock
- Pal24: moved lock before is_paid commit, removed redundant lock
- SeverPay: moved lock before is_paid check, removed redundant lock

Pattern applied to all: acquire FOR UPDATE with populate_existing=True
immediately after finding the payment, replace intermediate commits with
inline assignments + flush(), re-check is_paid from locked row.
2026-03-21 01:52:56 +03:00
Fringg 0e1296e0ea fix: prevent double balance credit on concurrent Platega webhooks
- acquire FOR UPDATE lock immediately after payment lookup, before is_paid check
- use populate_existing=True to prevent SQLAlchemy identity map stale reads
- replace intermediate update_platega_payment(commit) with inline assignments + flush
- re-check locked.is_paid after lock in get_platega_payment_status
- guard _finalize_platega_payment: only called when lock held and is_paid=False
- suppress "message is not modified" TelegramBadRequest in message_patch
2026-03-21 01:46:44 +03:00
Fringg 9dd6b54c6e fix: prevent bootstrap from reactivating revoked superadmin roles
- bootstrap _assign_if_missing no longer reactivates revoked UserRole rows
- revoke_role uses SELECT FOR UPDATE + pg_advisory_xact_lock to prevent TOCTOU race on last-superadmin check
- block self-revocation of superadmin role
- block is_active/level changes on system roles
- block expires_at on superadmin role assignments
- single SUPERADMIN_LEVEL constant in crud/rbac.py, imported everywhere
- get_superadmin_count excludes expired assignments
- removed dead UserRoleCRUD.revoke_role method
- warn when revoking RBAC role from a legacy ADMIN_IDS user
- added migration 0043: indexes on user_roles.role_id, access_policies.role_id, lower(users.email)
2026-03-21 01:09:13 +03:00
SayonaraQ 8a5710aff3 style: align webhook service with ruff format 2026-03-21 00:59:18 +03:00
SayonaraQ ce36fba54f style: format remnawave webhook service 2026-03-21 00:54:54 +03:00
SayonaraQ f601bedb48 add toggle for Remnawave node connection webhook alerts 2026-03-21 00:30:49 +03:00
sMedia.tech 801921ff74 fix: increase landing purchase rate limit from 5 to 30 req/min
Users hitting 429 Too Many Requests when trying to purchase on landing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 23:48:02 +03:00
Fringg 67da390371 feat: show both bot and cabinet referral links everywhere
Previously the bot showed only one referral link (cabinet when CABINET_URL
is set, bot otherwise). Users who received the cabinet link were confused —
they opened a web registration form instead of being directed to the bot.

Now the bot, cabinet API, and miniapp API all return both links:
- Bot link (t.me deep link) — always shown
- Cabinet link (web registration) — shown when CABINET_URL is configured

Changes:
- Add get_bot_referral_link() and get_cabinet_referral_link() to config
- Refactor config methods to eliminate code duplication
- Update bot referral handler to display both links
- Fix switch_inline_query 256-char limit with auto-truncation
- Add html_escape() to all user-controlled strings in HTML messages
- Add translations for 5 new keys in all 5 locale files (ru/en/ua/zh/fa)
- Simplify cabinet route to use new methods instead of inline URL construction
- Add bot_referral_link to MiniApp API schema and response
2026-03-20 23:12:22 +03:00
sMedia.tech d400cd7b49 feat: broadcast caption validation + landing daily created stats
- Validate message length for media broadcasts (1024 char Telegram limit)
- Add created count per day to landing stats API (separate from successful)
- Fix total_purchases to show total_created instead of total_successful

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 17:14:27 +03:00
sMedia.tech bf0ba22790 style: ruff format email_templates.py
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 16:30:47 +03:00
sMedia.tech f82a713110 feat: expose cabinet_email/password vars in subscription delivered template admin UI
Add cabinet_email and cabinet_password to context_vars and sample_contexts
for guest_subscription_delivered template type so they appear in the admin
email template editor.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 16:28:18 +03:00
sMedia.tech fedcf2569a feat: include cabinet credentials in subscription delivered email
Add login/password block to the "subscription ready" email template
so users receive their cabinet credentials in the first email.
The credentials block is only shown when cabinet_password is present
(new accounts). All 5 locales updated (ru, en, zh, ua, fa).

The separate credentials email (GUEST_CABINET_CREDENTIALS) is still
sent as before — this provides redundancy in case one email doesn't
arrive (e.g. due to SMTP quota limits).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 16:22:22 +03:00
sMedia.tech 1882909b3e fix: derive income_today from revenue_chart to ensure consistency
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 12:25:39 +03:00
sMedia.tech 226d3f2766 fix: default payment_method to BALANCE for bot subscription payments
Prevents double-counting in revenue: bot users create DEPOSIT (real
money) + SUBSCRIPTION_PAYMENT (balance debit). Without explicit
payment_method, subscription_payment had NULL which was patched to
kassa_ai, causing both to count as real revenue.

Now create_transaction defaults to BALANCE for SUBSCRIPTION_PAYMENT
when no payment_method is specified.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 12:19:55 +03:00
sMedia.tech 6982d27378 fix: include SUBSCRIPTION_PAYMENT in recent payments today/week totals
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 12:19:55 +03:00
sMedia.tech 27ef75214e fix: include SUBSCRIPTION_PAYMENT in sales summary and deposits stats
Same fix as transaction.py — sales dashboard summary and deposits
breakdown were only counting DEPOSIT transactions, missing all
landing page purchases (SUBSCRIPTION_PAYMENT).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 12:19:55 +03:00
sMedia.tech 13dba5a303 fix: include SUBSCRIPTION_PAYMENT in dashboard revenue calculations
Guest/landing purchases create SUBSCRIPTION_PAYMENT transactions (not
DEPOSIT), so they were excluded from income_today, total_income,
revenue_by_period, and payment_methods breakdown.

Also use func.abs() for SUBSCRIPTION_PAYMENT amounts since they are
stored as negative values.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 12:19:55 +03:00
sMedia.tech d7f91c8358 fix: include SUBSCRIPTION_PAYMENT in dashboard revenue calculations
Guest/landing purchases create SUBSCRIPTION_PAYMENT transactions (not
DEPOSIT), so they were excluded from income_today, total_income,
revenue_by_period, and payment_methods breakdown.

Also use func.abs() for SUBSCRIPTION_PAYMENT amounts since they are
stored as negative values.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 10:10:56 +03:00
Egor ee9f0b7382 Merge pull request #2777 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.36.1
2026-03-20 08:48:30 +03:00
github-actions[bot] e16eba10d9 chore(main): release 3.36.1 2026-03-20 05:48:16 +00:00
Egor 1771cc4d13 Merge pull request #2776 from BEDOLAGA-DEV/dev
Dev
2026-03-20 08:47:53 +03:00
Egor 3bda0a2001 Merge pull request #2775 from BEDOLAGA-DEV/main
w
2026-03-20 08:47:02 +03:00
Fringg 877b1cde11 fix: handle duplicate admin roles in RBAC bootstrap
Use scalars().first() instead of scalar_one_or_none() to tolerate
duplicate rows in admin_roles table by (is_system, level).
2026-03-20 08:45:23 +03:00
Fringg 5faf7015ac fix: make migration 0042 idempotent for retry_count column 2026-03-20 08:44:19 +03:00
Egor 55f386d7e8 Merge pull request #2774 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.36.0
2026-03-20 07:23:48 +03:00
github-actions[bot] e6a310dc32 chore(main): release 3.36.0 2026-03-20 04:21:42 +00:00
Egor ccd8f86e96 Merge pull request #2773 from BEDOLAGA-DEV/dev
Dev
2026-03-20 07:21:11 +03:00
Egor b6d4373933 Merge pull request #2771 from smediainfo/fix/kassa-ai-guest-metadata
fix: use base model name for KassaAI guest metadata patch
2026-03-20 07:20:25 +03:00
Egor 266620904d Merge pull request #2772 from BEDOLAGA-DEV/main
w
2026-03-20 07:18:45 +03:00
Fringg 479af5741a style: ruff format 2026-03-20 07:15:15 +03:00
Fringg 79c110ff41 fix: address review findings for multi-provider recovery
- Use atomic UPDATE SET retry_count = retry_count + 1 instead of
  SELECT+modify+commit to avoid identity map pollution
- Filter retry_count < max_retries in SQL WHERE clause to avoid
  wasting LIMIT slots on exhausted purchases
- Extract _fail_exhausted_purchases_batch() — separate pass for
  exhausted purchases, alert sent outside session context
- HTML-escape all user-controlled values in admin alert messages
- Mark purchases FAILED on amount mismatch (prevents repeated
  error logs every scheduler cycle) with admin alert
- Accept plain dict in _send_stuck_purchase_alert instead of ORM
  object (avoids expired-attribute access after commit)
2026-03-20 07:02:47 +03:00
Fringg 3d78974af7 feat: add multi-provider recovery, retry_count, amount verification, and indexes
- Add retry_count column to guest_purchases with Alembic migration
- Add expression indexes on metadata_json->>'purchase_token' for all 12
  payment provider tables (partial indexes filtered by is_paid/status)
- Implement _find_succeeded_provider_payment() covering all providers:
  YooKassa, Heleket, MulenPay, Pal24, Wata, Platega, CloudPayments,
  Freekassa, KassaAi, RioPay, SeverPay, and CryptoBot (payload field)
- Add amount verification in _check_and_recover_pending_purchase():
  compares provider payment amount with GuestPurchase.amount_kopeks,
  skips for CryptoBot (USD conversion imprecision)
- Increment retry_count on each retry attempt in retry_stuck_paid_purchases
  and retry_stuck_pending_activation
- Mark purchases as FAILED after 20 retries with admin Telegram alert
  via AdminNotificationService (ERRORS category)
2026-03-20 06:53:49 +03:00
Fringg 57c5c679ee fix: address review findings for guest purchase recovery
- Add FOR UPDATE to recovery path in try_fulfill_guest_purchase to prevent
  TOCTOU race that could overwrite DELIVERED back to PAID
- Isolate monitoring phases with independent try/except so Phase 1 failure
  does not block Phase 2/3
- Optimize recover_stuck_pending_purchases to select only token and
  payment_method columns instead of full ORM objects
- Remove dead elif branch in stars_payments.py (try_fulfill_guest_purchase
  no longer returns False)
- Add Phase 3 comment for consistency
2026-03-20 06:45:21 +03:00
Fringg 2781236011 fix: prevent guest purchases from getting stuck in PENDING/FAILED status
- Mark guest purchases as PAID (not FAILED) on transient fulfillment errors
  so monitoring service can retry them automatically
- Use fresh AsyncSessionLocal session for recovery to avoid tainted-session
  issues after rollback
- Add status guard to prevent overwriting terminal states (DELIVERED, etc.)
- Add recover_stuck_pending_purchases() to detect PENDING purchases where
  provider payment already succeeded (checks YooKassa payments table)
- Use SELECT ... FOR UPDATE to prevent TOCTOU races in recovery
- Add 3-phase monitoring pipeline: recover PENDING → retry PAID → retry
  PENDING_ACTIVATION
- Extract shared _resolve_base_payment_method() helper
2026-03-20 06:39:01 +03:00
Fringg 4a002b7db1 fix: allow repeated auto-assignment of promo groups on each purchase
Remove the threshold barrier that prevented re-assignment to the same
promo group tier. Previously, _get_best_group_for_spending was called
with min_threshold_kopeks=previous_threshold, which meant once a user
was auto-assigned to a tier (e.g. 100 kopeks), the check 100 > 100
would fail and the function would skip cleanup of promocode groups.

Now the function always finds the best group for the user's spending
without threshold filtering. The threshold ratchet is preserved only
for the watermark update (auto_promo_group_threshold_kopeks only
increases, never decreases).

Also elevate promo group assignment failure logging from DEBUG to
WARNING across all 3 call sites in transaction.py.
2026-03-20 05:46:59 +03:00
Fringg 8b2668087b fix: prevent premature commits in promocode promo group operations
add_user_to_promo_group and remove_user_from_promo_group in
promocode_service used default commit=True, causing mid-transaction
commits that flushed all pending session changes before the outer
db.commit() at lines 163/404.
2026-03-20 05:33:30 +03:00
Fringg 3ec9e71de7 fix: propagate exceptions from get_primary_user_promo_group
Consistent with has_user_promo_group and get_user_promo_groups which
now propagate exceptions instead of masking them with default returns.
2026-03-20 05:30:42 +03:00
Fringg da7a9cc3c5 fix: prevent duplicate promo groups during auto-assignment after purchase
Root cause: auto-assignment did not remove old auto/promocode groups before
adding new one, causing users to accumulate multiple simultaneous promo groups.
The primary group selection then picked the wrong one.

Changes:
- Remove old auto/promocode groups atomically before adding new one
- Add SELECT FOR UPDATE (lock_user_for_update) to serialize concurrent webhooks
- Fix CRUD rollback when commit=False — re-raise instead of destroying caller tx
- Fix sort order: desc(PromoGroup.id) to match model's get_primary_promo_group()
- Let has_user_promo_group/get_user_promo_groups propagate exceptions (fail-open bug)
- Fix replace_user_promo_groups: remove dead query, add _sync_user_primary_promo_group
- Use SQL COUNT in count_user_promo_groups instead of loading all rows
- Refresh user after removal loop to avoid stale ORM state
2026-03-20 05:25:41 +03:00
Fringg b5471b7720 perf: add covering indexes for referral network queries
Add composite indexes on advertising_campaign_registrations(user_id,
created_at) and transactions(user_id, type, is_completed, amount_kopeks)
to enable index-only scans. Uses CREATE INDEX CONCURRENTLY for zero
downtime. Also enable transaction_per_migration in Alembic env.py.
2026-03-20 02:31:03 +03:00
Fringg 6a4ce3dd38 feat: multi-select scope for referral network graph API
Support multiple campaigns, partners, and users in a single scoped
graph request. Dedup inputs, soft-skip invalid IDs, and discover
campaign registrations across all scope types.
2026-03-20 02:30:56 +03:00
Fringg df086b09c7 feat: add scoped referral network graph with scope selector API
- GET /scope-options: lightweight campaign/partner lists for selector
- GET /scoped?scope=campaign|partner|user&id=N: returns subgraph
- Recursive CTE helpers for ancestor/descendant traversal
- GRAPH_MAX_NODES cap applied to scoped graphs
- Campaign nodes shown even with zero registrations
2026-03-20 01:49:59 +03:00
Fringg 01132a7bc7 feat: add partner → campaign edges to referral network graph 2026-03-20 01:16:57 +03:00
sMedia.tech 182667ecb8 fix: use 'kassa_ai' base model name for guest metadata patch
kassa_ai_sbp has no separate CRUD module, causing guest purchase
metadata to not be saved, which breaks webhook fulfillment.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 22:56:39 +03:00
Fringg c8f4cca340 fix: correct revenue calculations in referral network
Campaign revenue now uses actual subscription payments by campaign
users instead of referral commission earnings (which were often 0).

Branch revenue for user detail now sums subscription payments by
branch users via recursive CTE instead of referral earnings.

Batch branch_revenue helper also updated to use Transaction spending.
2026-03-19 08:51:52 +03:00
Fringg ac9fcd8d30 fix: improve referral network query correctness and cleanup
- Use UNION ALL + count(distinct) for recursive CTE (faster, cycle-safe)
- Derive total_earnings from personal_revenue dict (remove redundant query)
- Merge duplicate campaign registration queries into single query
- Add MAX_REFERRAL_DEPTH constant, _format_datetime type hint
2026-03-19 08:08:16 +03:00
Fringg c08c903e8f feat: add referral network graph visualization admin API
4 endpoints for referral network analysis: full graph with batched
aggregation queries, user detail with recursive CTE branch counting,
campaign detail with conversion metrics, and search with LIKE escaping.

All endpoints rate-limited, scoped queries to prevent full-table scans,
depth-limited recursive CTE, fail_closed on expensive graph endpoint.
2026-03-19 07:55:51 +03:00
Fringg 69bb399b63 feat: add media attachment support for admin ticket replies
Admin can now attach photos, videos, and documents when replying to tickets
via the cabinet. Media is uploaded through the existing /cabinet/media/upload
endpoint and stored as Telegram file_id references in TicketMessage.

Added media_type, media_file_id, media_caption fields to AdminReplyRequest
with cross-field validation via model_validator.
2026-03-19 06:38:54 +03:00
Egor 463c5385d6 Merge pull request #2770 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.35.0
2026-03-18 23:35:06 +03:00
github-actions[bot] 41dfe39518 chore(main): release 3.35.0 2026-03-18 20:34:40 +00:00
Egor f44c9b6903 Merge pull request #2769 from BEDOLAGA-DEV/dev
Dev
2026-03-18 23:34:11 +03:00
Egor 1f35d45dc6 Merge pull request #2768 from BEDOLAGA-DEV/main
w
2026-03-18 23:32:42 +03:00
Fringg ef8f6625bf chore: ruff format 2026-03-18 23:31:31 +03:00
Fringg 7101555da0 feat: add user_email to admin payments API response 2026-03-18 23:30:17 +03:00
Fringg e15b18fb41 feat: раздельные топики для админских уведомлений
Добавлены 9 новых env-переменных для маршрутизации уведомлений по отдельным топикам:
- PURCHASES, RENEWALS, TRIALS, BALANCE, ADDONS
- INFRASTRUCTURE, ERRORS, PROMO, PARTNERS

Обратная совместимость: если топик для категории не задан — fallback на ADMIN_NOTIFICATIONS_TOPIC_ID.
2026-03-18 23:16:54 +03:00
Fringg b80eeea089 feat: include manual admin top-ups in sales statistics revenue 2026-03-18 22:39:31 +03:00
Fringg cb61014d9c fix: remove forced white background from custom email template overrides
Custom email templates with their own styling (background colors, <style> tags)
were wrapped in a white base template, causing visible white areas around dark-themed
templates. Added three-tier detection: full HTML documents pass through as-is,
styled content gets a minimal wrapper, simple fragments keep the base template.
2026-03-18 22:24:58 +03:00
Fringg 5b3353433b fix: undefined currency variable in RioPay payment creation
currency was referenced but never defined in create_riopay_payment,
causing NameError. Use settings.RIOPAY_CURRENCY instead.
2026-03-18 22:05:45 +03:00
Fringg f1d45343e9 fix: handle None autopay_days_before in autopayment processing
Existing subscriptions may have NULL autopay_days_before in DB,
causing TypeError in min(None, 3). Default to 3 when None.
2026-03-18 21:16:08 +03:00
Fringg b40a812f3a fix: fix Platega and CryptoBot webhook verification
Platega: handle verification ping POST without auth headers (empty body → 200 OK)
CryptoBot: always use API token for signature verification per docs, not WEBHOOK_SECRET
CryptoBot: reject requests without signature in both FastAPI and aiohttp handlers
Remove dead self.webhook_secret from CryptoBotService
Update tests to match new behavior
2026-03-18 20:11:55 +03:00
Egor ac00434645 Merge pull request #2765 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.34.1
2026-03-18 18:25:15 +03:00
github-actions[bot] 964c33c772 chore(main): release 3.34.1 2026-03-18 15:23:42 +00:00
Egor ec875837a4 Merge pull request #2767 from BEDOLAGA-DEV/dev
Dev
2026-03-18 18:22:52 +03:00
Egor db0e169a41 Merge pull request #2766 from BEDOLAGA-DEV/main
w
2026-03-18 18:21:41 +03:00
Fringg a6dcf26c20 chore: ruff format and cleanup 2026-03-18 18:20:50 +03:00
Fringg 5081debee7 fix: add null check for subscription in execute_change_devices 2026-03-18 18:15:20 +03:00
Fringg 0ceff44c30 fix: sync crypto link from happ.cryptoLink in webhook handlers
Webhook only checked subscriptionCryptoLink field, missing happ.cryptoLink
fallback that sync already used. Also clear stale crypto link when URL
changes but no new crypto link is provided.
2026-03-18 18:05:53 +03:00
Fringg 136f29c1eb refactor: remove quick amount buttons feature entirely
Removed across 16 files: config, all payment handlers, handler registrations, env example.
2026-03-18 17:55:16 +03:00
Fringg d0eab3f7aa fix: disable quick amount buttons in balance topup
Buttons showed incorrect prices. Hardcoded is_quick_amount_buttons_enabled to False.
2026-03-18 17:47:51 +03:00
Fringg d7ad9d7033 fix: correct CryptoBot webhook signature verification and auto-fill topup amount from cart
- Use API token as fallback for webhook signature verification per CryptoBot docs
- Try raw body, re-serialized compact JSON, and ASCII-escaped JSON for signature matching
- Auto-fill payment amount from saved cart in show_payment_methods instead of hardcoded 0
2026-03-18 17:44:52 +03:00
Fringg 1a87d438fe fix: correct RioPay API header case and remove undocumented fields
Header was 'x-api-token' but RioPay API expects 'X-Api-Token'
(case-sensitive check on their side), causing 403 Invalid API token.

Also removed undocumented 'currency' and 'failUrl' fields from
create_order payload per official RioPay API docs.
2026-03-18 17:00:56 +03:00
Fringg aec01ce0d4 fix: reset device limit to new tariff base on tariff switch
Previously, extra purchased devices were carried over when switching
tariffs, causing incorrect pricing — users upgrading to a more
expensive plan kept the old per-device rate until next renewal.

Now tariff switch resets device_limit to the new tariff's base limit.
Extra purchased devices are not carried over.
2026-03-18 16:57:08 +03:00
c0mrade a33a893d1a Update README.md
Фикс WATA в редми
2026-03-18 10:58:18 +03:00
Egor 37c9b931ca Merge pull request #2763 from BEDOLAGA-DEV/dev
Dev
2026-03-18 07:23:12 +03:00
Fringg 22e7f150b3 docs: increase logo size to 800px 2026-03-18 07:22:27 +03:00
Fringg 688882237f docs: replace header logo with new artwork 2026-03-18 07:21:03 +03:00
Egor c14d7ab0af Merge pull request #2761 from BEDOLAGA-DEV/dev
docs: add Redis to tech stack
2026-03-18 07:13:38 +03:00
Fringg e12cc9f248 docs: add Redis to tech stack 2026-03-18 07:12:53 +03:00
Egor 6ff0460607 Merge pull request #2759 from BEDOLAGA-DEV/dev
Dev
2026-03-18 07:07:53 +03:00
Fringg 8d5a002996 docs: WATA partnership block with logo and table card 2026-03-18 07:07:06 +03:00
Fringg 31bdf8a0ae docs: add WATA partnership block to payments section 2026-03-18 07:04:57 +03:00
Egor 1364158e6c Merge pull request #2757 from BEDOLAGA-DEV/dev
Dev
2026-03-18 06:55:47 +03:00
Fringg d7931a2afa docs: add bot preview screenshot to README 2026-03-18 06:53:44 +03:00
Fringg b032c8f354 docs: add cabinet preview screenshot to README 2026-03-18 06:50:00 +03:00
Fringg 1306c24fa3 docs: add icons and list all 14+1 payment providers 2026-03-18 06:41:43 +03:00
Fringg 38deb70f81 docs: redesign README — concise feature showcase, link to docs
Replace 2200-line README with a clean 190-line version:
- Centered header with badges (for-the-badge style)
- Feature grid (2x2 HTML table)
- Payment providers showcase (14 providers)
- Quick start (4 lines → link to full docs)
- Tech stack table
- Cabinet section with link to repo
- Documentation links to docs.bedolagam.ru
- Community section

All setup/config details moved to docs.bedolagam.ru.
2026-03-18 06:37:49 +03:00
Egor c1e015fb6e Merge pull request #2756 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.34.0
2026-03-18 05:58:02 +03:00
github-actions[bot] 0730173e5b chore(main): release 3.34.0 2026-03-18 02:56:31 +00:00
Egor 968f18b6e4 Merge pull request #2755 from BEDOLAGA-DEV/dev
Dev
2026-03-18 05:56:06 +03:00
Egor 7eea35f111 Merge pull request #2754 from BEDOLAGA-DEV/main
w
2026-03-18 05:54:06 +03:00
Fringg 6920e3a0fb style: ruff format 2026-03-18 05:53:31 +03:00
Fringg fddf8ef5eb fix: remove contains_eager conflicting with selectinload on user relationship
Loader strategies for the same ORM path cannot coexist. The
_apply_user_join_filter helper added contains_eager(model.user) on top
of the selectinload(Model.user) already present in each query, causing
InvalidRequestError at runtime. Removed contains_eager — selectinload
handles user loading correctly on its own.
2026-03-18 05:50:00 +03:00
Fringg ad268329be fix: добавлен импорт MAX_ALL_TIME_DAYS в admin_payments routes 2026-03-18 05:43:22 +03:00
Fringg 1804c28f05 feat: поиск платежей в админ-панели с фильтрами и статистикой
Новый сервис поиска по 13 платёжным провайдерам с ILIKE (escape от инъекций),
фильтрами по статусу/периоду/методу, кастомным диапазоном дат, пагинацией.
Эндпоинты: GET /search, GET /search/stats с валидацией входных данных.
2026-03-18 05:40:49 +03:00
Fringg f967c29bd7 fix: добавлены RioPay и SeverPay в REAL_PAYMENT_METHODS
Без этого платежи через RioPay и SeverPay не учитывались
в статистике доходов, разбивке по методам и отчётах
2026-03-18 03:59:33 +03:00
Fringg 06a00e367c feat: добавлен SeverPay в админ-панель и настройки кабинета
- Категория SEVERPAY в настройках бота
- Кнопка тестового платежа
- Конфигурация метода в кабинете
- DEFAULT_METHOD_ORDER обновлён
2026-03-18 03:55:24 +03:00
Fringg abaf279533 feat: добавлена интеграция SeverPay для пополнения баланса
- API клиент (HMAC-SHA256 подпись, создание/получение платежа)
- CRUD операции с FOR UPDATE блокировкой
- Payment mixin с обработкой webhook и финализацией
- Хендлеры бота для пополнения через SeverPay
- Миграция 0040: таблица severpay_payments
- Webhook endpoint (всегда 200 для предотвращения ретраев)
- Интеграция с payment_verification_service
- Поддержка гостевых покупок (лендинги, подарки)
2026-03-18 03:49:19 +03:00
Egor 6d4430c639 Merge pull request #2753 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.33.0
2026-03-18 02:02:09 +03:00
github-actions[bot] 911df7a05c chore(main): release 3.33.0 2026-03-17 23:01:41 +00:00
Egor f106ce8216 Merge pull request #2752 from BEDOLAGA-DEV/dev
Dev
2026-03-18 02:00:59 +03:00
Fringg dcff6947dd style: ruff format 2026-03-18 01:59:12 +03:00
Fringg 4966e39eb9 fix: скрыть плашку верификации email при выключенной верификации
- Добавлен verification_enabled в ответ /cabinet/branding/email-auth
- Фронтенд использует его для скрытия баннера и бейджа
2026-03-18 01:52:54 +03:00
Fringg 4abb8cb1a3 fix: исправлены проблемы RioPay интеграции после ревью
- Модель: user_id nullable=True + ondelete='SET NULL' (не применилось ранее)
- order_id для гостей: 'rpguest_xxx' вместо 'rpNone_xxx'
- Миграция: добавлено пересоздание FK с ON DELETE SET NULL
- get_latest_payment_by_method: добавлен RioPayPayment в model_map
2026-03-18 00:18:15 +03:00
Fringg 04f4e6bf6e feat: добавлена поддержка RioPay для лендингов и подарков
- Добавлен RioPay в create_guest_payment (landing/gift покупки)
- user_id в RioPayPayment теперь nullable (для гостевых платежей)
- Добавлен guest purchase flow в _finalize_riopay_payment
- Миграция 0039: riopay_payments.user_id nullable
2026-03-18 00:10:51 +03:00
Fringg 3d1fbc70f8 feat: добавлена поддержка RioPay в кабинете
- Добавлен RioPay в create_topup endpoint (cabinet balance)
- Добавлен маппинг статусов RioPay в _get_status_info
- Добавлена поддержка ручной проверки RioPay платежей
- Добавлена автопроверка RioPay в payment_verification_service
- Добавлены success_url/fail_url параметры в create_riopay_payment mixin
2026-03-18 00:05:07 +03:00
Fringg 3089c1704b fix: исправлен расчёт конверсии в статистике продаж
- Добавлен fallback через has_had_paid_subscription для подсчёта конверсий
- Исправлен знаменатель: total_trial_starters = new_trials + conversions
- Ограничение conversion_rate до 100% максимум
- Исправлен .is_(True) вместо == True в subscription_conversion.py
2026-03-17 23:46:15 +03:00
Fringg 20eff6170f fix: add back button to payment amount validation errors
All min/max amount error messages in payment handlers now include
a back button keyboard, so users aren't stuck without navigation.
Fixed 30 message.answer() calls across 12 payment handler files.
2026-03-17 23:34:05 +03:00
Fringg 038c34e52a fix: swap Caddy auth headers — api_key to Authorization, caddy_token to X-Api-Key
Caddy Security expects the caddy token in X-Api-Key and the Remnawave
API key in Authorization: Bearer. The headers were swapped, causing
401 errors for users with Caddy auth type.
2026-03-17 23:28:44 +03:00
Fringg 77f1a764d5 fix: merge phantom users into active accounts on /start
When a user purchases on a landing page by username and Bot.get_chat()
fails, a phantom user (telegram_id=NULL) is created. If that user
already has an active bot account, the phantom was never merged,
creating duplicate user records.

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 08:53:34 +03:00
root 603b9a1f46 fix: sub-method enabled check, guest payment provider, silent FSM return 2026-03-16 04:40:36 +00:00
root 557af5994d style: ruff format kassa_ai files 2026-03-16 04:31:04 +00:00
root 808818ca2b style: ruff format server_squad.py 2026-03-16 04:30:32 +00:00
root b563796091 fix: protect external squads from deletion during server sync 2026-03-16 04:27:59 +00:00
sMedia.tech 6a3e9d92b5 style: ruff format kassa_ai_service.py 2026-03-16 04:12:41 +00:00
root cda2392411 refactor: move KASSA_AI_SUB_METHODS to service layer, add early enabled checks
- Move KASSA_AI_SUB_METHODS from handler to kassa_ai_service.py (fixes service→handler import violation)
- Remove KASSA_AI_PAYMENT_METHODS set (was defined but unused)
- Import KASSA_AI_SUB_METHODS in payment_service.py from service layer
- Add is_kassa_ai_sbp/card_enabled() checks at start of entry handler functions
2026-03-16 04:12:41 +00:00
root 04419fdff7 feat: add SBP and Card sub-options to kassa_ai payment method
- kassa_ai shows single admin entry with СБП/Карта sub-option checkboxes
- SBP routes to payment_system_id=44, Card to payment_system_id=36
- Bot: added kassa_ai_sbp/card handlers and FSM flow (mirrors freekassa pattern)
- Cabinet: KASSA_AI_OPTION_MAP reads payment_option to select correct ps_id
- Config: KASSA_AI_SBP_ENABLED / KASSA_AI_CARD_ENABLED env vars + helpers
- Guest payments: kassa_ai_sbp/card supported in landing page checkout
- payment_method_config_service: kassa_ai has available_sub_options=[sbp,card]
2026-03-16 04:12:41 +00:00
Egor 713146dd6b Merge pull request #2745 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.32.4
2026-03-16 04:14:18 +03:00
github-actions[bot] 7d41ab44be chore(main): release 3.32.4 2026-03-16 01:13:22 +00:00
Egor 98f6f93487 Merge pull request #2744 from BEDOLAGA-DEV/dev
Dev
2026-03-16 04:12:59 +03:00
Egor 3752b7b067 Merge pull request #2743 from BEDOLAGA-DEV/main
w
2026-03-16 04:10:54 +03:00
Fringg 2f33e55144 fix: режим «Контакт и тикеты» возвращает support_type='both' вместо 'tickets' 2026-03-16 04:09:21 +03:00
Fringg c0b282a189 fix: уведомление об истечении подписки теперь учитывает autopay_enabled пользователя
- Статус автоплатежа в уведомлении основан на subscription.autopay_enabled, а не на глобальном ENABLE_AUTOPAY
- Продление с баланса (_process_autopayments) работает всегда при autopay_enabled=True
- Рекуррентные карточные платежи по-прежнему за гейтом ENABLE_AUTOPAY + YOOKASSA_RECURRENT_ENABLED
2026-03-16 04:04:01 +03:00
Fringg e1bcb1ba91 fix: реферальный бонус инвайтера — сумма вместо максимума, защита флага первого пополнения
- referral_service: inviter_bonus = fixed + commission вместо max(fixed, commission)
- 13 платёжных провайдеров: has_made_first_topup ставится только для нереферальных юзеров
- riopay: критический фикс — флаг ставился до вызова referral_service
- Обновлены уведомления с разбивкой бонуса
- Исправлен и дополнен тест referral_service
2026-03-16 03:57:50 +03:00
Fringg 3d68db0a51 fix: не пересылать externalSquadUuid в рутинных обновлениях RemnaWave
Стейловый externalSquadUuid (c6c0a338-062d-4d3a-826d-7015a24d681c) из тарифа
не существует в таблице ExternalSquads панели → FK violation → A039.
Теперь externalSquadUuid отправляется только при sync_squads=True (создание подписки).
2026-03-16 03:47:13 +03:00
Fringg 8d7f0eea0f fix: лог полного payload при ошибке PATCH /api/users для диагностики A039 2026-03-16 03:44:45 +03:00
Fringg 4aaf0ddd25 fix: не пересылать activeInternalSquads в рутинных обновлениях RemnaWave (A039)
Стейловые UUID сквадов в connected_squads вызывали FK violation в RemnaWave → A039.
- update_remnawave_user: добавлен параметр sync_squads (default=False)
- Сквады шлются только при явном sync_squads=True (promo_offer, countries)
- monitoring_service: убрана пересылка сквадов в рутинном sync
- Расширен лог PATCH payload для диагностики
2026-03-16 03:41:56 +03:00
Fringg db2f0c93f2 fix: расширен лог PATCH /api/users payload для диагностики A039 2026-03-16 03:35:06 +03:00
Fringg 3f8e8993b2 fix: сохранение user_id до rollback чтобы избежать MissingGreenlet при lazy load 2026-03-16 03:28:12 +03:00
Fringg e453521098 fix: устранена отправка externalSquadUuid=null в RemnaWave API (A039) и исправлен reduce_devices
- reduce_devices: убрано молчаливое проглатывание ошибки RemnaWave, теперь при неудаче делается rollback и возвращается HTTP 502
- Убрана отправка external_squad_uuid=None в 8 местах: subscription_service, monitoring_service, remnawave_service, admin/users, cabinet/admin_users
2026-03-16 03:25:24 +03:00
Fringg 8d3cd50098 refactor: централизация всех расчётов цен в PricingEngine
- Мигрирован confirm_purchase() на calculate_classic_new_subscription_price()
- Мигрирован compute_simple_subscription_price на делегацию в PricingEngine
- Мигрирован handle_custom_confirm на calculate_tariff_purchase_price()
- Мигрированы daily confirm handlers (confirm_daily_tariff_purchase,
  confirm_daily_tariff_switch, confirm_instant_switch daily path)
- Мигрирован gift.py на calculate_tariff_purchase_price()
- Мигрированы FSM cache prices (select_period, select_devices, toggle_country)
- Добавлен lock_user_for_pricing в admin_buy_tariff_execute (TOCTOU fix)
- Добавлен lock + recompute в _auto_add_devices и _auto_add_traffic
- Исправлено двойное применение promo-offer в simple_subscription (критический баг)
- Унифицирован daily price display (group+offer) на всех 6 поверхностях
- PricingEngine.get_addon_discount_percent: добавлен promo_group= kwarg
- PricingEngine._calculate_switch_to/from_daily: добавлен promo-offer discount
- Удалён мёртвый код из common.py (_get_addon_discount_percent_for_user)
- Miniapp period_discounts: исправлен доступ через get_discount_percent()
2026-03-16 03:10:22 +03:00
Fringg f80912e444 fix: убрана отправка externalSquadUuid=null в RemnaWave API и исправлен ложный лог синхронизации рулетки
- Не отправляем externalSquadUuid: null — RemnaWave отвечал 500 (A039)
- Проверяем результат update_remnawave_user вместо ложного " синхронизировано"
2026-03-15 17:34:31 +03:00
Egor 484d2f7e34 Merge pull request #2740 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.32.3
2026-03-15 01:24:46 +03:00
github-actions[bot] 842fb697e6 chore(main): release 3.32.3 2026-03-14 22:24:27 +00:00
Egor 3ac3a92e26 Merge pull request #2739 from BEDOLAGA-DEV/dev
Dev
2026-03-15 01:24:05 +03:00
Fringg 7648707ca2 fix: campaign registration, revenue calculation, backup restore, autopay errors, referral links
- fix campaign registration not recorded when CHANNEL_IS_REQUIRED_SUB + SKIP_RULES_ACCEPT enabled (missing _apply_campaign_bonus_if_needed in required_sub_channel_check fast path)
- fix revenue calculation counting bonus-funded subscription payments as income (now deposits only via REAL_PAYMENT_METHODS)
- fix backup restore PendingRollbackError cascade on unique constraint violations (savepoint wrapping in _restore_table_records and _restore_users_without_referrals)
- fix AttributeError on message.text.strip() when users send media in referral code handlers
- suppress 'message is not modified' TelegramBadRequest in autopay toggle
- add bot_referral_link to referral API response with URL encoding
2026-03-15 01:13:50 +03:00
Egor 7e466ef464 Merge pull request #2736 from Legacyyy777/main
fix: implement case-insensitive email checks in authentication and user retrieval
2026-03-14 22:30:56 +03:00
Egor 28321df4d2 Merge pull request #2738 from SayonaraQ/pr/topup-cart-fix
fix(payment): prioritize saved cart after topup over expired auto-extend
2026-03-14 22:27:56 +03:00
Fringg 6adf70b2da fix: refresh CLASSIC_PERIOD_PRICES when admin changes PRICE_*_DAYS or SALES_MODE
CLASSIC_PERIOD_PRICES was built once at import time and never updated,
causing classic mode to always show hardcoded defaults instead of
admin-configured prices.
2026-03-14 22:24:08 +03:00
SayonaraQ 2d204275da Fix race payment cart 2026-03-14 20:11:47 +03:00
Legacyyy777 ebee8348ca fix: implement case-insensitive email checks in authentication and user retrieval
Updated email queries in authentication routes and user CRUD operations to be case-insensitive. This change ensures that email comparisons ignore case, improving user experience and preventing potential registration/login issues with differently cased emails.
2026-03-14 04:39:11 +05:00
c0mrade 06954c1711 Merge pull request #2735 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.32.2
2026-03-14 00:18:51 +03:00
github-actions[bot] 5e04e2a020 chore(main): release 3.32.2 2026-03-13 21:17:32 +00:00
c0mrade 08d69fb47f Merge pull request #2734 from BEDOLAGA-DEV/dev
Dev
2026-03-14 00:17:06 +03:00
c0mrade 3306e02902 fix: add nested selectinload and referrer eager loading to prevent MissingGreenlet
Added selectinload(UserPromoGroup.promo_group) nested under
user_promo_groups to prevent lazy-load in get_primary_promo_group().
Added selectinload(User.referrer) for format_referrer_info().
Broadened except clause in format_referrer_info as safety net.
2026-03-14 00:14:42 +03:00
c0mrade 14dceaa39f fix: silence PARTICIPANT_ID_INVALID error in channel subscription check
Handle PARTICIPANT_ID_INVALID same as 'user not found' — expected for
users who authenticated via Telegram Login Widget but never interacted
with the bot or channel directly.
2026-03-13 21:39:39 +03:00
c0mrade 5442f288d4 fix: add selectinload to user lock queries to prevent MissingGreenlet
lock_user_for_update, subtract_user_balance, and add_user_balance use
select(User).with_for_update().populate_existing which expires loaded
relationships. Added selectinload for subscription, user_promo_groups
and promo_group to prevent lazy-load in async context.
2026-03-13 21:39:31 +03:00
c0mrade 5bf4aeb31e Merge pull request #2733 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.32.1
2026-03-13 19:17:37 +03:00
github-actions[bot] 7356921eeb chore(main): release 3.32.1 2026-03-13 16:11:39 +00:00
c0mrade f24337fb41 Merge pull request #2732 from BEDOLAGA-DEV/dev
Dev
2026-03-13 19:11:14 +03:00
c0mrade 69a38dad25 fix: invalid ISO date format in node usage stats API call
datetime.now(UTC).isoformat() produces +00:00 suffix, appending Z
created invalid +00:00Z format causing RemnaWave API 500 errors.
Use .replace('+00:00', 'Z') instead of concatenation.
2026-03-13 18:58:36 +03:00
c0mrade aa3459b846 fix: platega webhook ID fallback for SBP and card payments
SBP sends `id`, cards send `transactionId`. Use fallback chain
to resolve transaction ID from all known field variants.
2026-03-13 18:41:14 +03:00
c0mrade 4d695be7d5 fix: resolve MissingGreenlet in switch_tariff endpoint
Use local subscription variable and db.refresh() to avoid lazy-load
of expired relationship after subtract_user_balance invalidates
the User identity map entry.
2026-03-13 18:30:32 +03:00
Egor b8fcbc7661 Merge pull request #2729 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.32.0
2026-03-13 06:19:11 +03:00
github-actions[bot] 96042782d9 chore(main): release 3.32.0 2026-03-13 03:18:41 +00:00
Egor a625eaae4f Merge pull request #2728 from BEDOLAGA-DEV/dev
Dev
2026-03-13 06:18:08 +03:00
Egor 869fe06831 Merge pull request #2727 from BEDOLAGA-DEV/main
w
2026-03-13 06:10:27 +03:00
Fringg a5fbd7400f fix: user deletion FK error + connected_squads None TypeError
Bug 1: DELETE /cabinet/admin/users/{id}/full failed with
"saved_payment_methods_user_id_fkey" FK violation.
Root cause: delete_user_account() didn't clean up saved_payment_methods
and riopay_payments before deleting the user row.
Fix: add DELETE for both tables before final user deletion.

Bug 2: show_user_management crashed with TypeError on
len(subscription.connected_squads) when connected_squads was None.
Root cause: remnawave_webhook_service explicitly set connected_squads=None
when clearing subscription data, but 5 call sites assumed it was always a list.
Fix: change None assignment to [] + add "or []" guards at all 5 call sites.
2026-03-13 06:08:54 +03:00
Egor 995d66483b Delete docs/plans directory 2026-03-13 05:57:37 +03:00
Egor 5c77bd7a0f Merge pull request #2726 from BEDOLAGA-DEV/feat/unified-pricing-engine
Feat/unified pricing engine
2026-03-13 05:55:27 +03:00
Fringg 04697fd4cb style: ruff format 8 files 2026-03-13 05:53:02 +03:00
Fringg c9f2dffabf fix: address 6-agent review findings for PricingEngine
H1: log error when tariff_id set but tariff relationship not loaded
H2: warn on CLASSIC_PERIOD_PRICES→PERIOD_PRICES fallback
M1: fix float division in miniapp tariff purchase (use PricingEngine.apply_discount)
M2: fix format_period Russian pluralization for teen-hundreds (111-119, etc.)
M3: deduplicate _resolve_discount_percent — import from pricing_utils
M4: fix N+1 queries in compute_simple_subscription_price (batch fetch)
M5: add period_days validation tests (negative, zero, float)
M6: add user=None tests for tariff and classic modes
M7: fix float division in calculate_prorated_price (use // instead of /)
L1: add context to _calculate_servers_price error log
L2: add comment clarifying ClassicBreakdown.group_discount_pct type
L3: add test for original_total property
L4: inline _apply_percentage_discount wrapper in subscription_purchase_service
L5: replace global _server_id_counter with itertools.count() in tests
2026-03-13 05:45:46 +03:00
Fringg fe4e6acb53 refactor: unify first-purchase discount algorithm with PricingEngine
apply_percentage_discount now delegates to PricingEngine.apply_discount
(floor division). Removes ruble-rounding that caused inconsistency between
first-purchase and renewal pricing.

subscription_purchase_service._apply_percentage_discount now delegates
to the shared apply_percentage_discount.

All 60+ callers across handlers, keyboards, cabinet, miniapp, balance
automatically use the unified algorithm without code changes.
2026-03-13 05:30:44 +03:00
Fringg e24b911283 refactor: migrate all callers to pricing_engine singleton + fix miniapp discount
- 13 PricingEngine() instantiation sites → import pricing_engine singleton
- miniapp _apply_promo_discount now delegates to PricingEngine.apply_discount
  (fixes float division vs floor division inconsistency)
2026-03-13 05:22:18 +03:00
Fringg b551def340 refactor: add typed breakdowns + module-level singleton to PricingEngine
- TariffBreakdown and ClassicBreakdown frozen dataclasses for type safety
- Module-level `pricing_engine` singleton eliminates repeated instantiation
- breakdown remains dict[str, Any] at runtime for backward compatibility
2026-03-13 05:22:10 +03:00
Fringg 5e9a462261 refactor: extract shared formatting helpers into app/utils/formatting.py
Consolidate duplicated _format_traffic, _format_price_kopeks, _format_period
from tariff_purchase.py and admin/tariffs.py into a shared module.
2026-03-13 05:22:04 +03:00
Fringg 3a3bd9d499 test: expand PricingEngine tests + update CryptoBot payment tests
- Add 45 unit tests covering tariff/classic modes, discounts, edge cases
- Update CryptoBot payment tests for new PricingEngine integration
- Add original_total identity tests for both pricing modes
2026-03-13 05:12:47 +03:00
Fringg 75dbd2b4fc refactor: migrate remaining callers to PricingEngine + cleanup dead CRUD
- Migrate bot purchase handlers, menu, admin users to PricingEngine
- SubscriptionRenewalService.finalize() accepts both old and new pricing types
- Remove dead subscription CRUD pricing functions (get_subscription_renewal_cost etc.)
- Remove dead pricing_utils functions
2026-03-13 05:12:32 +03:00
Fringg b4ef52caa4 fix: payment providers — lock_user_for_update + commit=False atomicity
All payment providers now use lock_user_for_update before balance mutations
and commit=False pattern for atomic payment status + fulfillment.
Tribute service refund also uses proper locking.
2026-03-13 05:12:15 +03:00
Fringg ae99358ae9 fix: pricing audit — display/charge parity, race conditions, balance locks
M-2: tariff_purchase.py — _apply_promo_discount delegates to PricingEngine,
     _get_user_period_discount returns (group_pct, offer_pct, combined),
     all ~15 call sites updated for display/charge price parity

M-4: miniapp switch_tariff — add FOR UPDATE lock on subscription,
     commit=False for atomic balance+transaction, emit_transaction_side_effects

M-6: CryptoBot — defer status commit (commit=False) so webhook retry works
     if fulfillment fails

WARNING: add lock_user_for_update before balance_kopeks mutations in
     contest_attempt_service, wheel_service, admin/referrals,
     account_merge_service, cabinet/routes/contests
2026-03-13 05:11:59 +03:00
Fringg 08bea704de fix: address review findings from 5-agent audit
- Add period_days validation (> 0) in PricingEngine
- Add int() cast for tariff period_prices (prevent JSON type errors)
- Fix structlog.get_logger(__name__) in pricing_engine
- Use pricing.original_total property instead of manual reconstruction
- Add CryptoBot price decrease audit logging
- Remove stale cart price fallback in auto-purchase (fail instead)
- Fix _apply_promo_discount_for_tariff to use PricingEngine.apply_discount
- Remove dead code: _get_tariff_price_for_period, _get_countries_price,
  calculate_addon_price_with_remaining_period, _resolve_addon_discount_percent
2026-03-13 05:11:35 +03:00
Fringg 18e2e7841a fix: add period_days whitelist validation and type annotations
Security fix: cabinet /renew endpoint now validates period_days against
available periods (tariff or settings), preventing arbitrary period abuse.

Also:
- Add proper type annotations (AsyncSession, Subscription, User) to PricingEngine
- Add max(0, final_total) guard in both tariff and classic modes
- Type breakdown field as dict[str, Any]
2026-03-12 23:27:51 +03:00
Fringg 652b6dabde refactor: migrate menu.py renewal pricing to PricingEngine
Replace 3 renewal_service.calculate_pricing() calls with
PricingEngine.calculate_renewal_price() in the balance activation handler.
finalize() already supports RenewalPricing via duck typing.
2026-03-12 23:15:37 +03:00
Fringg c9a9816daa refactor: remove dead pricing code and fix miniapp classic mode
- Remove SubscriptionService.calculate_renewal_price (zero callers, replaced by PricingEngine)
- Remove SubscriptionService.calculate_renewal_price_with_months (zero callers)
- Remove _calculate_subscription_renewal_pricing wrapper in miniapp (zero callers)
- Fix miniapp classic mode: pass PricingEngine result directly to finalize() instead of old wrapper
- Fix potential NameError: pricing_snapshot in cryptobot path used undefined 'pricing' variable
- Net: -396 lines of duplicate pricing logic
2026-03-12 23:12:59 +03:00
Fringg 49c0f3fc10 refactor: migrate admin user price calculation to PricingEngine
Replace SubscriptionService.calculate_renewal_price() with PricingEngine
in _calculate_subscription_period_price for admin panel.
2026-03-12 23:04:29 +03:00
Fringg cb43acab31 refactor: migrate miniapp renewal display + execute to PricingEngine 2026-03-12 23:00:58 +03:00
Fringg f59b215645 style: fix import sorting and formatting after lint
ruff auto-fix for import ordering in cabinet/subscription.py and
formatting adjustments across changed files.
2026-03-12 22:58:35 +03:00
Fringg 3efa24bab3 refactor: make finalize() accept both old and new pricing types
SubscriptionRenewalService.finalize() now supports both
SubscriptionRenewalPricing and RenewalPricing from PricingEngine.
Adapts access to promo_discount_value, server_ids, and
servers_individual_prices via duck typing.
2026-03-12 22:58:08 +03:00
Fringg bd2e93a6a5 refactor: migrate cart auto-purchase to PricingEngine (fresh calc)
Replaces stale cart-based pricing and _apply_promo_discount_for_tariff
(4th discount formula with float division) with fresh PricingEngine
calculation. Falls back to saved cart price on PricingEngine error.
2026-03-12 22:51:03 +03:00
Fringg 978f68e7be refactor: migrate recurrent and monitoring services to PricingEngine
Mechanical re-point of calculate_renewal_price calls to use unified
PricingEngine. Both services now get consistent pricing with correct
discount formulas and server fallback behavior.
2026-03-12 22:50:13 +03:00
Fringg 28fc36dca4 refactor: migrate cabinet renewal display + execute to PricingEngine
Replaces inline pricing logic in get_renewal_options and renew_subscription
with unified PricingEngine.calculate_renewal_price(). Fixes:
- Wrong discount formula (int(p*(100-d)/100) vs integer floor division)
- Missing servers/traffic costs in classic mode display
- Inconsistent discount stacking between display and execute paths
2026-03-12 22:49:22 +03:00
Fringg 1660b24f98 fix: add per-category discounts and months multiplier to classic mode
Classic mode now correctly:
- Applies separate promo group discounts per category (period, servers,
  traffic, devices) via promo_group.get_discount_percent(category, days)
- Multiplies servers/traffic/devices monthly prices by months_in_period
- Applies promo offer discount to entire subtotal after per-category discounts
- Tracks total group discount as sum of per-category discounts
2026-03-12 22:46:34 +03:00
Fringg acf27a1023 refactor: migrate bot renewal execute to PricingEngine
Replace ~95 lines of manual pricing calculation in confirm_extend_subscription
with PricingEngine.calculate_renewal_price. Removes per-component discount
logic (period, servers, devices, traffic with separate category discounts,
months multiplication, and validate_pricing_calculation check). Downstream
logic preserved: balance check, cart save, subtract_user_balance,
subscription update, Remnawave sync, transaction creation, and admin
notification all use pricing.final_total and pricing.promo_offer_discount.

Removes unused imports: _apply_promo_offer_discount, validate_pricing_calculation.
2026-03-12 22:41:41 +03:00
Fringg ce82c2c009 refactor: migrate bot renewal display to PricingEngine
Replace manual per-component price calculation in handle_extend_subscription
with PricingEngine.calculate_renewal_price. This eliminates ~55 lines of
duplicated pricing logic (period, servers, devices, traffic calculations with
separate category-specific promo group discounts and months multiplication)
in favor of a single PricingEngine call per period. Also fixes double-application
of promo offer discount that existed in the old code path.
2026-03-12 22:37:55 +03:00
Fringg e6ebc6722d refactor: migrate try_auto_extend_expired to PricingEngine
Replace SubscriptionService.calculate_renewal_price() call in
try_auto_extend_expired_after_topup with PricingEngine.calculate_renewal_price().
Add structured log with pricing breakdown after calculation.
All downstream business logic (balance check, deduction, extend) unchanged.
2026-03-12 22:32:41 +03:00
Fringg 02e5401327 feat: implement calculate_renewal_price with tariff and classic modes
Add the main public method calculate_renewal_price to PricingEngine,
routing to _calculate_tariff_mode or _calculate_classic_mode based on
whether the subscription has a linked tariff. Both modes apply stacked
discounts (promo-group then promo-offer). Classic mode tries
CLASSIC_PERIOD_PRICES first, falling back to PERIOD_PRICES. Adds 8
new tests covering both modes, discounts, extra devices, and fallback.
2026-03-12 22:29:44 +03:00
Fringg c3bb63ffed feat: add CLASSIC_PERIOD_PRICES to config
Add a standalone dict that always reflects env PRICE_*_DAYS settings,
independent of tariffs mode. Unlike PERIOD_PRICES (which may use DB
tariff prices), CLASSIC_PERIOD_PRICES is the canonical source for
classic (non-tariff) subscription pricing. Includes refresh helper.
2026-03-12 22:29:37 +03:00
Fringg 88369eec50 feat: add _calculate_servers_price (fixed fallback) and _calculate_traffic_price
_calculate_servers_price ALWAYS uses real server.price_kopeks even when
is_available=False or is_full=True, fixing the silent zero-price bug.
_calculate_traffic_price separates base from purchased GB to prevent
purchased top-ups from inflating the tier lookup.
2026-03-12 22:20:48 +03:00
Fringg 83ca51cd5b feat: add RenewalPricing dataclass and PricingEngine discount methods 2026-03-12 22:18:08 +03:00
Egor f9dad615ee Merge pull request #2721 from FireWookie/feature/recurrent_method_inline
Отображение привязанных карт в разделе в боте
2026-03-12 20:28:31 +03:00
Fringg ba049ca017 fix: resolve merge conflict with dev (accept calc_device_limit_on_tariff_switch) 2026-03-12 20:27:48 +03:00
Fringg 585baaf63c fix: harden remnawave API error handling and YooKassa user cross-validation
- remnawave_api: use str() before .lower() to handle non-string API messages
- yookassa recovery: cross-validate user_telegram_id metadata against resolved
  user to prevent misattribution when legacy telegram_id fits in int32 range
2026-03-12 20:17:51 +03:00
Fringg 04197817fe fix: downgrade known-harmless RemnaWave 400s to warning level
"User already enabled" and "User already disabled" are expected
responses when reactivating subscriptions (e.g., traffic top-up on
active subscription with exhausted traffic). These should not
trigger error notifications in the admin chat.
2026-03-12 20:08:53 +03:00
Fringg b2ee6c766a fix: add missing settings import in admin_users tariff switch 2026-03-12 19:59:59 +03:00
Fringg d35ee58aa6 fix: harden YooKassa webhook recovery user lookup
- Reject user_id <= 0 early (corrupted metadata)
- Use `is None` checks instead of `or` to avoid falsy-value collisions
- Separate int parse from DB call in telegram_id fallback
- Move _INT32_MAX to module-level constant
2026-03-12 19:51:52 +03:00
Fringg 815a1d9136 fix: handle legacy telegram_id in YooKassa webhook recovery metadata
Legacy payments may store telegram_id (>int32) in metadata['user_id']
instead of internal User.id. The recovery path now:
- Detects values exceeding int32 range and queries by telegram_id
- Falls back to metadata['user_telegram_id'] if primary lookup fails
- Resolves to internal user.id before creating FK-linked payment record
2026-03-12 19:41:48 +03:00
Fringg b7775b72dc fix: guard rollback on commit flag, add flush to promo_offer_log
- subtract_user_balance: only rollback when commit=True, re-raise when
  commit=False so caller controls transaction lifecycle
- log_promo_offer_action: add db.flush() when commit=False to surface
  constraint errors immediately instead of deferring to caller's commit
2026-03-12 19:33:25 +03:00
Fringg ba54819f9c fix: atomicity refactor, review fixes, and DELETED recovery logging
- subtract_user_balance: add commit=False parameter for atomic balance+subscription ops
- extend_subscription: add commit=False parameter, propagate to clear_notifications
- wata_service: wire _MIN_EXPIRATION_MINUTES constant to actual usage
- admin_users: fix no-op ternary in sync_user_from_panel timezone normalization
- start.py: log warning when DELETED recovery zeros non-zero balance (3 locations)
- remnawave_service: preserve PromoCodeUse records and used_promocodes in force_cleanup
2026-03-12 19:26:36 +03:00
Fringg 266340aad1 fix: prevent balance loss on auto-purchase for DISABLED subscriptions and fix WATA expiration
- Block auto-purchase from stale cart when subscription is DISABLED
  (balance deduction is irreversible, Remnawave update would fail)
- Preserve user balance in force_cleanup_user_data (paid money must not be destroyed)
- Keep has_had_paid_subscription flag on cleanup (prevents promo code abuse)
- Add warning in sync_from_panel when local end_date is newer than panel
- Fix WATA payment expiration: enforce minimum 15 minutes to avoid
  hitting WATA API's exclusive lower bound (now + 10 min)
2026-03-12 19:09:16 +03:00
Fringg 8f434525eb feat: add LIMITED subscription status and preserve extra devices on tariff switch
- Add SubscriptionStatus.LIMITED for traffic-exhausted subscriptions
- Webhook user.limited now sets LIMITED directly instead of DISABLED
- Add LIMITED to reactivation, extend, resume, auto-purchase, contest eligibility
- Add traffic_exhausted error response in miniapp API
- Fix device_limit being overwritten on tariff switch in all code paths:
  admin change_tariff, user switch-tariff, miniapp, bot tariff_purchase,
  auto_purchase_service — now preserves extra purchased devices via
  calc_device_limit_on_tariff_switch() helper
- Fix truthiness checks on device_limit (0 is valid, use `is not None`)
2026-03-12 18:35:59 +03:00
Egor efa1b11db5 Merge pull request #2724 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.31.0
2026-03-12 08:30:35 +03:00
github-actions[bot] d0ce193edb chore(main): release 3.31.0 2026-03-12 05:30:07 +00:00
Egor 92d872236f Merge pull request #2723 from BEDOLAGA-DEV/dev
Dev
2026-03-12 08:29:34 +03:00
Egor a11f492801 Merge pull request #2722 from BEDOLAGA-DEV/main
ц
2026-03-12 08:25:26 +03:00
Fringg c8162505ed chore: apply ruff formatting to 4 files 2026-03-12 08:24:47 +03:00
Fringg 076290e0c1 feat: auto-sync squads to Remnawave when admin updates tariff
When admin changes allowed_squads or external_squad_uuid on a tariff,
automatically sync the new squad config to all active/trial subscriptions
in Remnawave panel via a background task (fire-and-forget).
2026-03-12 08:20:25 +03:00
firewookie 2f5674fcd7 правки линтера 2026-03-12 09:40:29 +05:00
FireWookie b9058e115a Merge pull request #8 from FireWookie/dev
Dev
2026-03-12 09:39:58 +05:00
firewookie 673afccb8c правки линтера 2026-03-12 09:35:54 +05:00
firewookie 1badb39c49 правки по импортам 2026-03-12 09:35:07 +05:00
firewookie 23ff40cd2c Отображение привязанных карт в разделе в боте 2026-03-12 09:31:46 +05:00
Fringg bf72f241d8 fix: preserve purchased devices when admin changes user tariff
Previously subscription.device_limit was blindly overwritten with the new
tariff's base limit, losing any extra devices the user had purchased.
Now extra devices are calculated from the old tariff base and carried over,
capped at tariff.max_device_limit or global MAX_DEVICES_LIMIT.
2026-03-12 06:55:56 +03:00
Fringg 12ae871653 feat: referral links now point to web cabinet instead of bot
Centralized referral link generation into settings.get_referral_link().
When CABINET_URL is configured, links use {CABINET_URL}?ref={code}.
Falls back to Telegram bot deep link when CABINET_URL is not set.

- URL-encodes referral_code for safety
- Handles CABINET_URL with existing query params (uses & vs ?)
- Guards against None referral_code in all call sites
- QR code caching uses link hash for auto-invalidation
2026-03-12 06:45:17 +03:00
Fringg 8a362db783 fix: correct skipped_count in sync-squads circuit breaker and simplify ternary
- Add missing skipped_count increment when early-aborting due to circuit breaker
- Remove redundant `new_squads if new_squads else []` (already [] when empty)
- Add comment explaining asyncio safety of shared counter mutations
2026-03-12 06:28:13 +03:00
Fringg b1e2146254 feat: add sync-squads endpoint for bulk updating subscription squads in Remnawave
POST /admin/tariffs/{tariff_id}/sync-squads updates active_internal_squads
and external_squad_uuid for all active/trial subscriptions on a tariff.

- Concurrent API calls (semaphore=5) with circuit breaker (10 consecutive failures)
- Local DB updated only on successful API response to avoid split-brain
- Error messages sanitized (details in server logs only)
- Uses joinedload to avoid N+1 query for User.remnawave_uuid
2026-03-12 06:17:13 +03:00
Fringg 68bc8eb57c fix: update promo group via M2M table so admin changes persist
The admin endpoint wrote only to the legacy users.promo_group_id FK,
which got overwritten by sync_user_primary_promo_group on the next
transaction. Now writes to user_promo_groups M2M table (authoritative
source) and re-derives the FK via sync.

Also re-raise exceptions in _sync_user_primary_promo_group to prevent
committing inconsistent state between M2M and FK columns.
2026-03-12 06:03:26 +03:00
Fringg 9957259881 fix: add post_update=True to User.referrals self-referential relationship
Without post_update, SQLAlchemy's flush ordering cannot resolve the
circular dependency when both a user and their referrer are in the same
session. This caused referred_by_id to be silently NULLed during flush,
breaking Telegram login (which eagerly loads User.referrer) and causing
apparent admin rights loss in the cabinet.

OAuth login was unaffected because it uses a bare select(User) without
eager loading the referrer relationship.

Root cause confirmed by 6 parallel investigation agents tracing the
exact code paths through get_user_by_telegram_id → selectinload →
flush → circular dependency.
2026-03-12 05:39:29 +03:00
Fringg b3f3eba575 fix: prevent account takeover via auto_login_token, ensure promo group on all purchase paths
- Gate auto_login_token generation behind is_new_account flag in all 3 locations
  (fulfill_purchase PENDING/DELIVERED paths + activate_purchase) — prevents attacker
  from buying cheapest plan with victim's email to get their session token
- Assign default promo group in all _find_or_create_user paths including telegram
  IntegrityError fallbacks (7 return paths total)
- Create transaction records for landing purchases so promo group auto-assignment
  and contest tracking work correctly
- Add _resolve_payment_method helper for enum conversion with sub-option suffix stripping
2026-03-12 05:26:16 +03:00
Fringg a798f1143e refactor: remove estimated price from balance, simplify server sync, fix HTML injection
- Remove estimated renewal price display from balance top-up screen
- Remove country name generation during server/squad sync, use original RemnaWave name as display_name
- Add html.escape() for all display_name/country name values rendered in HTML-parsed Telegram messages
2026-03-12 04:58:49 +03:00
Fringg cb5126aff8 feat: add show_in_gift toggle for tariffs in admin panel
Add a per-tariff visibility flag (show_in_gift) that controls whether
a tariff appears in the /gift section. Enforced server-side in gift
config query, gift purchase endpoint, and landing page gift purchases.

Includes Alembic migration with idempotency guard and server_default.
2026-03-12 04:15:40 +03:00
Fringg 8b35428055 fix: reactivate subscription after traffic top-up when status is EXPIRED
When traffic is exhausted, RemnaWave may send user.expired webhook setting
local status to EXPIRED (not just DISABLED). reactivate_subscription() only
handled DISABLED→ACTIVE, silently ignoring EXPIRED subscriptions. After
purchasing additional GB, the subscription stayed expired and VPN remained
blocked despite payment.

Changes:
- reactivate_subscription() now handles both DISABLED and EXPIRED→ACTIVE
  when end_date is still in the future
- Inverted null end_date guard to block reactivation (defense-in-depth)
- Added enable_remnawave_user() call after update in all traffic/device
  top-up paths to ensure panel exits LIMITED state
- Gated enable call on subscription.status == 'active' to prevent
  enabling when reactivation was a no-op
- Fixed all 12 call sites across bot handlers, cabinet routes,
  miniapp, webapi, and auto-purchase service
2026-03-12 03:57:35 +03:00
Fringg 5424d8c314 fix: add Telegram Stars payment support for gift subscriptions
- Add telegram_stars handler in create_guest_payment() using
  bot.create_invoice_link() with guest_purchase_{token} payload
- Add guest_purchase_ prefix handling in Stars pre-checkout and
  successful_payment handlers with amount tolerance check (±5%)
- Pass Bot instance to PaymentService when payment method is Stars
- Add purchase_token format validation via regex guard
2026-03-12 03:32:08 +03:00
Egor df7411138e Merge pull request #2718 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.30.0
2026-03-11 03:56:12 +03:00
github-actions[bot] 4545bef7ea chore(main): release 3.30.0 2026-03-11 00:55:56 +00:00
Egor d7eb1e776a Merge pull request #2716 from BEDOLAGA-DEV/dev
Dev
2026-03-11 03:55:35 +03:00
Egor f8fc382143 Merge pull request #2717 from BEDOLAGA-DEV/main
w
2026-03-11 03:55:10 +03:00
Fringg e67b8e448e fix: reset subscription for paid users, trial-to-paid tariff conversion, gift purchase MissingGreenlet
- Remove is_active_paid_subscription guard from reset-subscription endpoint
- Add is_trial=False and status=ACTIVE on admin tariff change (guarded by
  tariff.is_trial_available and end_date check)
- Eagerly load user_promo_groups and promo_group in gift purchase locked query
- Move user_promo_groups access inside try/except in get_primary_promo_group()
2026-03-11 03:46:39 +03:00
Fringg bca8bab433 feat: add gifts section to admin user detail API
Add GET /{user_id}/gifts endpoint returning sent and received gift
subscriptions with COUNT queries for true totals, token truncation
for security, and noload() optimization for unused relationships.
2026-03-11 03:30:12 +03:00
Fringg 2fd0f6aa4e feat: add promo group and promo offer discounts to gift subscriptions
Apply promo group and active promo offer discounts to gift purchase flow.
Discounts stack multiplicatively with max(1, price) floor. FOR UPDATE
row lock prevents concurrent promo offer double-spend. Promo offers
consumed after purchase in both balance and gateway modes.
2026-03-11 02:58:34 +03:00
Fringg 864a4ed700 fix: record transactions for free tariff switches and admin tariff changes
- Add transaction records for free tariff switches (downgrade, upgrade_cost=0) in miniapp and cabinet
- Add atomic transaction records for admin tariff changes in bot handler and cabinet API
- Use commit=False for admin flows to ensure subscription change and transaction are committed together
2026-03-11 02:17:35 +03:00
Fringg 2879996455 fix: use keyword args for Path.mkdir in asyncio.to_thread
Positional args caused mode=True(1) and exist_ok=False(default),
raising FileExistsError when directories already existed.

Fixed 8 instances: 2 in log_rotation_service, 6 in backup_service.
2026-03-11 01:22:02 +03:00
Egor 4b4fced442 Merge pull request #2714 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.29.0
2026-03-10 23:01:35 +03:00
github-actions[bot] 8859e73890 chore(main): release 3.29.0 2026-03-10 20:01:13 +00:00
Egor d79866819c Merge pull request #2713 from BEDOLAGA-DEV/dev
Dev
2026-03-10 23:00:25 +03:00
Fringg 5a62f91ca2 chore: ruff format 4 files 2026-03-10 22:57:32 +03:00
Fringg def594bbb5 fix: panel sync now updates end_date in both directions
Previously, both webhook (user.modified) and batch sync paths
only updated end_date if the panel date was LATER than the local date.
This silently blocked any date reduction from the panel, causing
the bot to show stale expiry dates after admin changes in the panel.

Now the panel is treated as authoritative — end_date is synced
in both directions (forward and backward) for ACTIVE subscriptions.
2026-03-10 22:23:39 +03:00
Fringg 641ff86bf6 fix: stars rate rounding + device/traffic purchase stats
- Stars: ceil → round в rubles_to_stars, нормализация kopeks в cabinet invoice
- Устройства/трафик: добавлен transaction_type в subtract_user_balance,
  покупки устройств и трафика теперь создают SUBSCRIPTION_PAYMENT (не WITHDRAWAL),
  что исправляет отображение в статистике продаж
2026-03-10 21:50:20 +03:00
Fringg 2e59330e95 chore: resolve uv.lock merge conflict 2026-03-10 21:19:28 +03:00
Fringg 3c96c2affd fix: 3 bugs — notification type, referral with channel sub, BOT_USERNAME
1. Admin notification showed "renewal" instead of "first purchase" for new
   users because has_had_paid_subscription was set before notification.
   All 21 call sites now pass explicit purchase_type.

2. Partner referral not counted when mandatory channel subscription enabled.
   required_sub_channel_check saved campaign_id but not referrer_id from
   campaign.partner_user_id. Also removed duplicate DB query.

3. BOT_USERNAME auto-detection moved before web server start to close
   race window on /cabinet/branding/telegram-widget endpoint.
2026-03-10 21:19:18 +03:00
c0mrade 541f64d5bc Merge pull request #2711 from FireWookie/dev_nikita
FIX PR Problems
2026-03-10 14:17:12 +03:00
firewookie e82a1ccf6d FIX PR Problems 2026-03-10 16:16:18 +05:00
c0mrade 015be30a27 Merge pull request #2710 from FireWookie/feature/riopay
FIX PR Problems
2026-03-10 14:13:25 +03:00
firewookie 6817b9e256 FIX PR Problems 2026-03-10 16:11:28 +05:00
c0mrade 59248011c2 Merge pull request #2678 from FireWookie/dev_nikita
Add: Рекуренты Юкасса + fix: скрытие нулевых бонусов в реферальной программе
2026-03-10 13:06:35 +03:00
firewookie 39d007ff3e FIX PR Problems 2026-03-10 15:01:28 +05:00
firewookie 94b211e2a7 FIX PR Problems 2026-03-10 15:00:41 +05:00
firewookie c84dbf82fc update 2026-03-10 14:50:26 +05:00
FireWookie 9ad684c8c9 Merge pull request #7 from FireWookie/dev
Dev
2026-03-10 14:42:53 +05:00
FireWookie d147be0316 Merge pull request #6 from FireWookie/dev
Dev
2026-03-10 14:42:05 +05:00
c0mrade 9281523e96 Merge pull request #2690 from FireWookie/feature/riopay
RioPay
2026-03-10 12:41:53 +03:00
firewookie fd3466b75c fix PR problems 2026-03-10 14:29:29 +05:00
FireWookie dcfd54a7cb Merge pull request #5 from FireWookie/dev
Dev
2026-03-10 14:18:49 +05:00
FireWookie 5c2e5dfaab Merge branch 'BEDOLAGA-DEV:main' into feature/riopay 2026-03-10 14:14:23 +05:00
firewookie df112f3659 fix PR problems 2026-03-10 14:08:10 +05:00
Fringg a90d2d9367 fix: 3 critical issues from second-round review
1. Balance-mode gift purchase leaked full 64-char token in response.
   Gateway path truncated to [:12] but balance path didn't. Fixed.

2. retry_stuck_pending_activation referenced GuestPurchase.updated_at
   which doesn't exist on the model. Changed to paid_at (mirrors
   retry_stuck_paid_purchases pattern).

3. clear_notifications() called db.commit() unconditionally, defeating
   commit=False in replace_subscription. Added commit parameter with
   default=True for backward compat, passed through from caller.
2026-03-10 07:09:39 +03:00
Fringg 5c34656476 fix: address review findings from 6-agent audit
1. Truncate tokens to 12 chars in all API responses (SentGift,
   PendingGift, ReceivedGift, PurchaseStatus, PurchaseResponse,
   return URL) — full token no longer leaves the server
2. Status endpoint supports prefix-based token lookup
3. create_paid_subscription/replace_subscription accept commit=False
   — activate_purchase now uses single atomic commit for subscription
   + purchase status update (fixes double-commit gap)
4. Bot handler uses flush() instead of commit() before svc_activate
   — consistent with cabinet endpoint, allows rollback on failure
5. Add retry_stuck_pending_activation() for purchases stuck in
   PENDING_ACTIVATION status (10 min threshold)
6. Add varchar_pattern_ops index for prefix queries on token column
2026-03-10 07:02:14 +03:00
Fringg 8a8337f538 fix: add minimum 8-char length check for gift token in bot deep link 2026-03-10 06:56:08 +03:00
Fringg 42b6c80a48 refactor: rename GIFTCODE_ start parameter prefix to GIFT_ 2026-03-10 06:48:49 +03:00
Fringg b30c73c300 feat: prevent self-activation of gift codes
Buyer cannot activate their own gift, both via cabinet API
(returns 400 "Cannot activate your own gift") and bot deep link
(silently skips activation).
2026-03-10 06:44:58 +03:00
Fringg 363ccce56d fix: refresh user subscription after gift activation in /start
After svc_activate creates a subscription, the user object still
has stale cached data. Refresh the subscription attribute so the
main menu immediately shows the active subscription status.
2026-03-10 06:36:33 +03:00
Fringg 0005d59da1 fix: remove begin_nested that breaks activate_purchase transaction
activate_purchase -> create_paid_subscription calls db.commit()
internally, which closes the savepoint context and causes
InvalidRequestError on subsequent db.refresh(). Replace savepoint
with a plain commit before calling svc_activate.
2026-03-10 06:33:31 +03:00
Fringg 38c6adfdb4 fix: pass full token to svc_activate instead of truncated prefix
Telegram truncates start parameters to 64 chars, so gift_token from
deep link may be a prefix. svc_activate does exact match internally,
so we must pass gift_purchase.token (full token from DB) instead.
2026-03-10 06:23:55 +03:00
Fringg 4fb72ae6e3 fix: support prefix-based gift code lookup for activation
Displayed gift codes (GIFT-XXXXXXXXXXXX) are 12-char prefixes of the
full 64-char token. Activation now accepts prefix match (min 8 chars)
so both the short display code and full token work. Also fixes Telegram
deep link truncation (64-char limit cuts the token).
2026-03-10 06:20:07 +03:00
Fringg 05bcac502e fix: code-only gifts skip fulfillment in gateway webhook + retry service
- Gateway webhook: skip fulfill_purchase() for code-only gifts (is_gift=True, no recipient)
- Retry service: exclude code-only gifts from stuck PAID retry query
- Status endpoint: return is_code_only and purchase_token for code-only gifts
2026-03-10 06:03:26 +03:00
Fringg 769d3a0b30 refactor: deduplicate gift activation in start.py
Replace inline gift activation block (30+ lines) with a call to
_activate_pending_gift_after_registration() helper. Eliminates
code duplication between existing-user and new-user activation paths.
2026-03-10 05:41:05 +03:00
Fringg 5ffce175dc feat: gift subscription code-only purchase + activation via deep link
- Add code-only gift purchase (no recipient required)
- Gift activate endpoint: accept PAID + PENDING_ACTIVATION statuses
- Bot deep link: /start GIFTCODE_{token} auto-activation for new and existing users
- Add _activate_pending_gift_after_registration() helper with savepoint isolation
- Security: FOR UPDATE on activation queries to prevent race conditions
- Security: rate limiting on activate, ownership check before status leak
- Security: uniform 404 responses to prevent token enumeration
- Add selectinload for tariff/user/buyer relationships in all gift queries
- Add .limit(100) to pending gifts query
- Make recipient_type/recipient_value optional in GiftPurchaseRequest schema
2026-03-10 05:37:41 +03:00
Egor 1a2f0fcbe8 Merge pull request #2709 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.28.1
2026-03-10 03:39:48 +03:00
github-actions[bot] fd1e728396 chore(main): release 3.28.1 2026-03-10 00:39:15 +00:00
Egor ec41d65501 Merge pull request #2708 from BEDOLAGA-DEV/dev
Dev
2026-03-10 03:38:54 +03:00
Egor 5212877801 Merge pull request #2707 from BEDOLAGA-DEV/main
w
2026-03-10 03:37:02 +03:00
Fringg bc9003c336 chore: ruff format 2026-03-10 03:36:32 +03:00
Fringg fcdeff1ee5 fix: migrate pricing to days-based proration, fix promo revenue leaks, fix admin panel bugs
- Migrate all addon pricing (devices, traffic, countries) from months-based to days-based proration
- Remove get_remaining_months() utility, use days_left / 30 consistently
- Fix promo/campaign balance bonuses counted as revenue in reports (add REAL_PAYMENT_METHODS filter)
- Fix partner stats, campaign stats, miniapp stats, referral fraud detection promo deposit leaks
- Fix admin balance history showing deductions with + sign (use -abs for expense types)
- Fix promo offer deactivation returning 400 for non-promocode offers
- Fix daily tariff renewal requesting 30-day renewal instead of 1-day purchase
2026-03-10 03:31:07 +03:00
Egor bcc35d6e22 Merge pull request #2706 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.28.0
2026-03-09 23:41:57 +03:00
github-actions[bot] b850e81897 chore(main): release 3.28.0 2026-03-09 20:41:35 +00:00
Egor 4d9e42c3f1 Merge pull request #2705 from BEDOLAGA-DEV/dev
Dev
2026-03-09 23:41:08 +03:00
Egor 834a0478ae Merge pull request #2704 from BEDOLAGA-DEV/main
w
2026-03-09 23:39:56 +03:00
Fringg 0e968987fb style: format guest_purchase_service.py with ruff 2026-03-09 23:39:24 +03:00
Fringg acd2cff9ca style: format inline.py with ruff 2026-03-09 23:38:34 +03:00
Fringg 69dbd6a2df fix: enforce HTTPS for webapp mode, deduplicate keyboard builder, fix long line 2026-03-09 23:37:35 +03:00
Fringg 497a8ee5b5 feat: add open_in setting for custom buttons (external browser / webapp) 2026-03-09 23:33:18 +03:00
Fringg dd8d7f6920 feat: add cabinet menu layout editor with row arrangement, custom URL buttons, and drag-and-drop reordering
- Add menu_layout_cache.py for CABINET_MENU_LAYOUT in-process cache
- Add admin_menu_layout.py routes (GET/PUT/POST reset) with merged view
- Rewrite _build_cabinet_main_menu_keyboard to use cached row layout
- Support custom URL buttons with style, emoji, labels, enabled toggle
- Atomic dual-key DB writes for layout + button styles
- Add language button to default layout and DEFAULT_BUTTON_STYLES
- Pydantic validation with Literal types, max_length, duplicate ID checks
- Register routes and cache loading in bot startup
2026-03-09 23:07:32 +03:00
Fringg b9089e693f fix: normalize threshold 0→NULL in create_promo_group for consistency 2026-03-09 22:16:30 +03:00
Fringg b815abf2b1 fix: loyalty tiers current status based on spending, not assigned group
- current_tier_name and is_current now determined by highest achieved
  tier threshold instead of user's assigned promo group
- Backend update_promo_group converts threshold 0 to NULL for clean state
2026-03-09 22:08:41 +03:00
Fringg 95a32e8574 fix: payment gateway issues — YooKassa polling, PAL24 card 500
- YooKassa: return local_payment_id instead of UUID for frontend polling
  (parseInt on UUID produced wrong ID → eternal spinner)
- PAL24: remove unsupported payment_method param from API call
  (cabinet and miniapp routes — URL selection is client-side)
2026-03-09 21:53:53 +03:00
Fringg cd04f3b622 feat: implement gateway payment for gifts, persist recipient warning
- Replace 501 stub with full gateway payment flow via PaymentService
- Move telegram username pre-check (DB-first) above gateway/balance branch
- Add recipient_warning column to GuestPurchase model + migration 0034
- Return warning in gift purchase status endpoint
- Add db.refresh(purchase) after commit in gateway branch
2026-03-09 21:25:49 +03:00
Fringg 6a4140e3e2 fix: harden gift subscription feature after multi-agent review
- Add self-gift prevention (telegram username + email)
- Unify 404 response on purchase status (eliminate token oracle)
- Add period_days upper bound (le=3650) in schema
- Handle NULL paid_at in retry query with or_()
- Capture purchase_token before fulfill_purchase (session safety)
- Upgrade Bot API pre-check logging to warning level
- Add exc_info=True for monitoring retry errors
- Add database indexes: (user_id, is_gift, status), (status, paid_at), buyer_user_id
- Use datetime instead of str for created_at in PendingGiftResponse
- Align GuestPurchase model __table_args__ with all migrations
2026-03-09 20:34:39 +03:00
Fringg f80b058380 fix: negate GIFT_PAYMENT amounts and remove dead code 2026-03-09 18:47:36 +03:00
Fringg 6a61b09575 feat: add cabinet gift subscription API routes and schemas
Create Pydantic schemas for gift config/purchase/status responses,
FastAPI routes for GET /gift/config, POST /gift/purchase, and
GET /gift/purchase/{token}, update GuestPurchaseService.create_purchase
to accept optional source and buyer_user_id params with nullable landing,
and register the gift router in the cabinet routes.
2026-03-09 18:44:38 +03:00
Fringg 759bfe1bdb feat: add CABINET_GIFT_ENABLED branding toggle 2026-03-09 18:41:07 +03:00
Fringg 0936d4a7f6 feat: add source and buyer_user_id fields to GuestPurchase model
- Add source column (landing/cabinet) to track purchase origin
- Add buyer_user_id FK to link cabinet gift purchases to authenticated users
- Add GIFT_PAYMENT to TransactionType enum for balance deductions
- Add foreign_keys disambiguation to existing user relationship
- Migration 0032: adds columns, index on source, FK constraint
2026-03-09 18:35:52 +03:00
firewookie c7bebae14a back docker 2026-03-09 14:11:50 +05:00
firewookie 8ee287f8cd remove locales from git 2026-03-09 14:11:34 +05:00
firewookie 6f99b83c61 remove locales from git 2026-03-09 14:09:16 +05:00
firewookie 1a3c6fafa3 update saved payment method 2026-03-09 14:07:42 +05:00
firewookie be2ec091a6 Правки по замечаниям 2026-03-09 14:06:00 +05:00
firewookie d4dc0b76ba fix linter 2026-03-09 13:38:46 +05:00
firewookie 2dfd0e6452 Правки по замечаниям 2026-03-09 13:34:25 +05:00
Fringg 680c22c017 fix: support Telegram OIDC id_token in account linking endpoint
Email users couldn't link Telegram when OIDC was enabled because
the link_telegram endpoint only accepted init_data and Login Widget
data. Add id_token field to LinkTelegramRequest with JWKS validation,
replay protection, and rate limiting.
2026-03-09 06:23:02 +03:00
Egor 8c9efd5127 Merge pull request #2703 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.27.0
2026-03-09 05:08:42 +03:00
github-actions[bot] 4663097a24 chore(main): release 3.27.0 2026-03-09 02:07:55 +00:00
Egor dc51a55c98 Merge pull request #2702 from BEDOLAGA-DEV/dev
Dev
2026-03-09 05:07:31 +03:00
Fringg 275f249bbd fix: encode payment status in provider return URLs and wire failed_url
- Add &status=success/failed to cabinet return URLs for instant UX feedback
  without needing API auth in external browser
- Platega: pass cabinet_failed_url (was hardcoded to server URL)
- Heleket: add success_url param, pass cabinet_success_url for url_success
- WATA: add failed_url param, pass cabinet_failed_url to failRedirectUrl
- CloudPayments: add failed_url param, pass cabinet_failed_url
- Strip trailing slash from CABINET_URL for safety
2026-03-09 04:59:56 +03:00
Fringg 7a9264b173 fix: latest-payment endpoint returns all payments, not just pending
The /latest endpoint was using list_recent_pending_payments which only
returns unpaid payments. By the time the user returns from the payment
provider, the webhook has already marked the payment as paid, so the
endpoint returned 404. Now queries the payment table directly without
filtering by is_paid status.
2026-03-09 04:41:25 +03:00
Fringg 32d58b04b9 fix: add method query param to return_url and latest-payment endpoint
Payment providers redirect to external browser where sessionStorage is
unavailable. Now includes method in return_url query params and adds
GET /pending-payments/{method}/latest endpoint so TopUpResult can poll
payment status without sessionStorage data.
2026-03-09 04:34:14 +03:00
Fringg 7ca96195a7 fix: pass cabinet return_url to payment providers for top-up redirects
Payment providers were redirecting users back to the bot after completing
cabinet top-up payments. Now passes CABINET_URL/balance/top-up/result as
return_url to YooKassa, Platega, Heleket, WATA, and CloudPayments.
2026-03-09 04:16:10 +03:00
Fringg 5752b5e7c6 chore: apply ruff formatting to 4 files 2026-03-09 03:02:32 +03:00
Egor e6f577697b Merge pull request #2701 from BEDOLAGA-DEV/main
w
2026-03-09 03:01:02 +03:00
Fringg f4a776319e fix: add table existence guards to migrations for optional payment tables
Migrations 0019, 0022, 0031 crashed with UndefinedTableError when
payment provider tables (e.g. kassa_ai_payments) or contest_templates
did not exist. Added _table_exists() checks before ALTER/DROP operations.
2026-03-09 02:57:01 +03:00
Fringg 2649e12f64 fix: use parsed HTML length for Telegram caption limit checks
Replace hardcoded raw HTML length checks (len(text) <= 900/1000/1024)
with centralized caption_exceeds_telegram_limit() that strips HTML tags
and unescapes entities before measuring against the real 1024-char limit.
Fixes logo disappearing when promo discounts add HTML markup to captions.
2026-03-09 02:43:43 +03:00
Fringg 4a5cacda38 fix: resolve concurrent AsyncSession bug and sanitize error responses
- Fix critical concurrency issue in propagate_tariff_squads: preload
  users/tariffs before asyncio.gather, use single API client, no DB
  operations inside gather, single commit after all API calls
- Replace all str(e) leaks in admin_users.py with sanitized messages
- Fix double callback.answer by using callback.message.answer for
  failure alerts
- Move PropagateSquadsResult to module level, use field(default_factory)
- Compute traffic_strategy once before gather instead of N times
- Add warning logging on tariff refresh failures
- Reset synced counters on commit failure for accurate reporting
2026-03-09 02:26:38 +03:00
Fringg 79161eaae4 refactor: move squad propagation to service layer with parallel Remnawave sync
- Move _propagate_squads_to_subscriptions from handler to
  SubscriptionService.propagate_tariff_squads()
- Use asyncio.gather with semaphore (concurrency=5) for parallel
  Remnawave API calls instead of sequential O(N)
- Track failed subscription IDs for better observability
- Fix get_all_server_squads limit=50 default in admin handlers
  (now limit=10000 to prevent silent truncation)
- Add docstring to force_panel_delete parameter
- Return PropagateSquadsResult dataclass with total/synced/failed_ids
2026-03-09 01:58:23 +03:00
Fringg 289cbe966e fix: conditional log messages and sanitize panel_error in user deletion
- Log disable success/failure separately instead of unconditional success
- Sanitize panel_error to not leak internal exception details to API
- Make fallback disable log conditional on actual result
2026-03-09 01:52:37 +03:00
Fringg 7ccfb66690 fix: propagate tariff squad changes to existing subscriptions and fix user deletion from Remnawave
Squad toggle: when admin changes servers for a tariff, the changes now
propagate to all active/trial subscriptions and sync to Remnawave panel.
Previously only took effect on new purchases.

User deletion: full delete from Cabinet now actually deletes from Remnawave
panel. Previously lied about panel deletion status and skipped deletion
for users with active subscriptions.
2026-03-09 01:46:45 +03:00
Fringg 536525c9c0 fix: admin tariff server selection - 64-byte overflow and callback routing conflicts
1. Shortened squad toggle callback_data from admin_tariff_toggle_squad
   to trf_sq to stay within Telegram's 64-byte callback_data limit
   (was overflowing at tariff_id >= 10)

2. Fixed toggle_tariff handler capturing squad/promo/daily/traffic_topup
   toggle callbacks by adding exclusion filters

3. Fixed admin_tariff_edit_traffic capturing admin_tariff_edit_traffic_topup
   by registering traffic_topup handler before traffic handler

4. Fixed admin_tariff_delete capturing admin_tariff_delete_confirm
   by registering delete_confirm handler before delete handler
2026-03-09 01:23:03 +03:00
Fringg 4186159a61 fix: keep DB session alive in Tribute payment notification handler
The _send_success_notification method was closing the DB session (via
break) before calling send_cart_notification_after_topup, causing all
post-topup auto-renewal logic to silently fail for Tribute payments.

Moved break after all work is done so the session stays open during
auto-renewal operations. Added None guard for user lookup.
2026-03-09 01:07:47 +03:00
Fringg 6349b2f442 fix: align tariff pricing with calculate_renewal_price reference
- balance/main.py: single period discount on combined total (base + devices),
  add promo-offer discount, fix device_limit fallback to tariff_device_limit
- pricing.py: same combined discount + promo-offer, proper device_limit
  fallback matching reference (is not None check)
- admin/users.py: delegate to calculate_renewal_price() which handles both
  tariff and classic modes correctly, removing classic-only calculate_subscription_price
- menu.py: use renewal_service.calculate_pricing() for both price check and
  charge to ensure consistency, add try/except with user-facing error,
  show actual charged amount in success message
2026-03-09 00:39:16 +03:00
Fringg bfbefeb1e2 fix: renewal cost estimate double-counts servers and traffic in tariff mode
In tariff mode, period_prices already includes servers and traffic costs.
But show_payment_methods() and get_subscription_cost() were using the classic
additive formula, adding server and traffic prices on top of the tariff price.

Example: 49₽ tariff + 150₽ server + 150₽ traffic = 349₽ shown, should be 49₽.

Now both functions detect tariff mode and only add extra device costs beyond
the tariff's device_limit. Classic mode formula unchanged.
2026-03-08 23:14:57 +03:00
Fringg f9f07f360c fix: enforce tariff device_price and max_device_limit across all purchase paths
The miniapp, legacy cabinet endpoint, auto-purchase service, and Telegram bot
handlers were using only global settings (PRICE_PER_DEVICE, MAX_DEVICES_LIMIT)
for device purchases, completely ignoring tariff-level device_price_kopeks and
max_device_limit. This allowed users to buy devices when tariff price was 0
(should be blocked) and exceed the tariff's max device limit.

Fixed in all 4 code paths:
- miniapp _build_subscription_settings + update_subscription_devices_endpoint
- cabinet legacy POST /devices (+ added subscription status check, RemnaWave sync)
- subscription_auto_purchase_service._auto_add_devices
- telegram bot handlers confirm_change_devices, execute_change_devices, confirm_add_devices
2026-03-08 23:08:32 +03:00
Fringg 770b31d3d0 feat: auto-resume disabled daily subscriptions on balance topup
- Add try_resume_disabled_daily_after_topup() for instant resume when balance is topped up
- Fix all 5 resume paths to charge daily fee BEFORE activating subscription
- Remove unsafe inline auto-resume from add_user_balance() that bypassed fee charging
- Add NULL-safe is_daily_paused filter in subscription queries
- Use create_remnawave_user() instead of enable_remnawave_user() for full VPN panel sync
- Add DAILY_SUBSCRIPTION_RESUMED_AFTER_TOPUP localization key (ru, en, fa, zh, ua)
2026-03-08 21:36:17 +03:00
Egor ae710f41fc Merge pull request #2700 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.26.0
2026-03-08 15:47:30 +03:00
github-actions[bot] f86b8614b1 chore(main): release 3.26.0 2026-03-08 12:46:24 +00:00
Egor 61b2fcc2aa Merge pull request #2699 from BEDOLAGA-DEV/dev
Dev
2026-03-08 15:46:01 +03:00
Fringg 928e3e98f8 chore: format balance/main.py and promocode.py 2026-03-08 15:41:59 +03:00
Fringg 7dc5e4ab94 fix: auto-purchase classic extend missing device_limit and traffic_limit_gb
- Add device_limit and traffic_limit_gb to classic extend cart data in
  confirm_extend_subscription handler
- Add classic mode branch in cabinet renew_subscription to save
  device_limit and traffic_limit_gb (previously only saved for tariffs)
- Ensure device_limit >= DEFAULT_DEVICE_LIMIT when converting trial
  subscription to paid via auto-extend
- Add None guards for subscription.device_limit in both trial and
  non-trial branches of _apply_extension_updates
2026-03-08 15:31:58 +03:00
Fringg 5ebe1072c9 fix: quick topup buttons include device/server/traffic costs, broadcast button crash on media messages
- Quick amount buttons now calculate full renewal cost (base + devices + servers + traffic with discounts)
- Tariff mode uses tariff-specific device pricing (device_price_kopeks, device_limit)
- Broadcast inline buttons no longer crash with "no text in message to edit" on photo/video messages
- Media messages are now handled in _edit_with_photo: delete old message + send new text
2026-03-08 14:58:17 +03:00
Fringg 20727b1017 fix: respect send_before_menu flag for pinned messages during new user registration
All 6 registration paths now check pinned_message.send_before_menu
to send pinned message before or after the menu, matching the
existing user flow behavior.
2026-03-08 14:25:54 +03:00
Fringg f4eeb9a503 fix: multiple payment and notification bugs
- CloudPayments: add missing process_referral_topup, has_made_first_topup flag, and admin notification (matching other adapters)
- Promocode: handle TelegramBadRequest for broadcast messages without text (fallback to answer())
- Devices: unify price prorating to day-based calculation (matching cabinet behavior)
- Auth: pass Bot instance to process_referral_registration for campaign referral notifications
- Wata: remove WATA_TERMINAL_PUBLIC_ID from is_wata_enabled() (not used in API calls), make type field conditional, add transactionId webhook fallback
2026-03-08 14:17:44 +03:00
Fringg 1f664a9083 fix: remove is_active_paid_subscription guard from admin deactivation
The guard silently blocked admins from deactivating active paid
subscriptions, returning a generic error with no explanation.
Admin deactivation is intentional (with confirmation step) and
should not be prevented. The guard remains in automated processes
(monitoring, broadcast, user_service) where it makes sense.
2026-03-08 13:05:52 +03:00
Fringg 330d1cb6fe fix: gift purchase notification and activation flow
- Refresh purchase.user relationship after setting user_id to fix
  stale None value that prevented Telegram gift notifications
- Route gift purchases with expired subscriptions through
  PENDING_ACTIVATION instead of auto-activating
- Hide subscription URL from gift buyer in API response
2026-03-08 12:47:25 +03:00
firewookie 8e53b81b3d fix recurrent linter 2026-03-08 09:36:47 +05:00
firewookie 69ca37bc6e fix project 2026-03-08 09:35:10 +05:00
FireWookie 26daf9f6c8 Merge pull request #4 from FireWookie/main
Merge as main project
2026-03-08 09:32:37 +05:00
firewookie 34aae0dd26 fix formatting 2026-03-08 09:30:47 +05:00
firewookie 0551a6e23c fix migrations 2026-03-08 09:28:32 +05:00
firewookie 92cc602892 Merge remote-tracking branch 'origin/feature/riopay' into dev 2026-03-08 09:26:32 +05:00
firewookie 555b887952 Merge remote-tracking branch 'origin/dev' into dev 2026-03-08 09:23:08 +05:00
firewookie 848c9f71a2 reviewers fix 2026-03-08 09:22:44 +05:00
FireWookie 4477e03d83 Merge pull request #3 from FireWookie/main
merge as main project
2026-03-08 09:20:33 +05:00
Fringg 9ba61a0879 feat: add telegram gift notification with inline activation button
- New gift_activation handler for gift_activate:{id} callback buttons
- Send Telegram notification to gift recipients with activate button
- Add skip_notification param to activate_purchase to prevent duplicates
- Fix telegram username regex minimum length (4→5 chars) in landing routes
- Add BOT_TOKEN guard in telegram gift notification sender
- Pre-resolve notification params before commit to avoid DetachedInstanceError
2026-03-07 20:39:04 +03:00
Egor d7f05ae409 Merge pull request #2696 from BEDOLAGA-DEV/main
w
2026-03-07 17:42:20 +03:00
Egor bf2d5e48e5 Merge pull request #2694 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.25.0
2026-03-07 17:22:38 +03:00
github-actions[bot] 93bf21e55b chore(main): release 3.25.0 2026-03-07 14:21:25 +00:00
Egor fea44f5ad4 Merge pull request #2693 from BEDOLAGA-DEV/dev
Dev
2026-03-07 17:20:52 +03:00
Fringg 923b36a8b9 fix: use --frozen instead of --locked in Dockerfile to avoid version mismatch 2026-03-07 17:17:35 +03:00
Fringg a7fea86c99 chore: update uv.lock 2026-03-07 17:15:49 +03:00
Fringg fbe56c15ac style: ruff format 2026-03-07 17:13:56 +03:00
Egor 213f82b9a4 Merge pull request #2692 from BEDOLAGA-DEV/main
w
2026-03-07 17:13:03 +03:00
Fringg d72ea6b7f9 fix: remaining context_vars/SAMPLE_CONTEXTS mismatches found by agents
- traffic_reset: traffic_limit → reset_gb, current_limit_gb
- payment_received: amount → formatted_amount
- guest_activation_required: added missing is_gift to context_vars
- daily_debit SAMPLE_CONTEXTS: added missing amount_rubles, new_balance_rubles
- traffic_reset SAMPLE_CONTEXTS: aligned with runtime keys
- payment_received SAMPLE_CONTEXTS: added amount_rubles
2026-03-07 17:11:57 +03:00
Fringg c507634398 fix: align subscription_renewed/activated context_vars with runtime keys
- subscription_renewed: new_end_date → new_expires_at
- subscription_activated: end_date → expires_at
- Added traffic_limit_gb and device_limit to both types
- Fixed SAMPLE_CONTEXTS keys to match
2026-03-07 17:11:57 +03:00
Fringg c9ea2b15e9 fix: strip newlines from subject substitution, fix subscription notification context
- Defense-in-depth: strip \r\n from context values in subject line
  substitution to prevent email header injection at composition layer
- Add missing tariff_name to classic mode subscription notification context
  (prevents literal {tariff_name} in DB override templates)
- Remove SQLAlchemy model object from notification context dict
  (str() on model produces garbage in DB override templates)
2026-03-07 17:11:57 +03:00
Fringg ab5313a381 fix: align context_vars and SAMPLE_CONTEXTS with actual runtime context keys
TEMPLATE_TYPES context_vars showed wrong placeholder names to admins
(e.g. 'amount' instead of 'formatted_amount', 'balance' instead of
'formatted_balance'). SAMPLE_CONTEXTS had mismatched keys causing
test emails to render with empty values.

Fixed types: balance_topup, balance_change, autopay_success,
autopay_insufficient_funds, daily_debit, daily_insufficient_funds,
referral_bonus.
2026-03-07 17:11:57 +03:00
Fringg 351d714f2d fix: substitute sample context in admin test email for template overrides
Same bug as notification_delivery_service — send_test_email used
get_template_override (raw template) instead of get_rendered_override.
Admins testing custom templates saw literal {days_left} placeholders
instead of sample values.
2026-03-07 16:48:18 +03:00
Fringg d52c87b2b7 fix: substitute context variables in email template overrides
The send_notification method was calling get_template_override which
returns raw template HTML without variable substitution. Placeholders
like {days_left} and {expires_at} were sent to users as literal text.

Switched to get_rendered_override which properly substitutes context
variables via str.replace before wrapping in the base email template.
2026-03-07 16:40:35 +03:00
Fringg d9f9f3dca1 fix: add or [] guard to remaining connected_squads call site in fulfill_purchase
Missed the create_paid_subscription branch (line 275) in the previous
commit — now all 4 call sites consistently use `or []` to guard against
None from tariff.allowed_squads JSON column.
2026-03-07 16:34:15 +03:00
Fringg 44d46feb0a fix: correct device_limit and connected_squads in guest purchase fulfillment
- Remove `or settings.DEFAULT_DEVICE_LIMIT` from fulfill_purchase expired
  subscription branch — tariff.device_limit is NOT NULL so the `or` pattern
  would incorrectly convert 0 (unlimited) to DEFAULT_DEVICE_LIMIT
- Add `or []` guard to connected_squads in activate_purchase to match
  replace_subscription's list[str] type contract (tariff.allowed_squads
  can be None from JSON column)
2026-03-07 16:29:04 +03:00
Fringg 9e78509284 fix: handle expired subscription in guest purchase fulfillment
When a user with an expired subscription makes a landing page purchase,
the code tried to INSERT a new subscription, violating the user_id
unique constraint. Now uses replace_subscription for expired/inactive
subscriptions instead of create_paid_subscription.
2026-03-07 16:02:06 +03:00
Fringg f4ab174d32 fix: support {total_amount} placeholder in cart notification templates
Add total_amount as an alias for cart_total in format() calls so custom
locale overrides using {total_amount} are properly substituted instead
of appearing as literal text in user messages.
2026-03-07 15:50:42 +03:00
Fringg fc65e2de4c fix: use information_schema for constraint existence checks in migrations
Replace pg_class lookup with information_schema.table_constraints query
that is schema-qualified and consistent with migration 0028 pattern.
Fixes constraint detection on fresh installs where create_all() creates
constraints that pg_class lookups could miss.
2026-03-07 15:50:31 +03:00
Fringg ba335fe784 fix: use pg_class lookup for constraint existence checks in migrations
inspector.get_unique_constraints() fails to detect constraints created
by Base.metadata.create_all() on fresh installs, causing
DuplicateTableError. Query pg_class directly for reliable detection.
2026-03-07 15:38:11 +03:00
Fringg 5214f55f46 fix: drop legacy prize_days column from contest_templates
The column was left over from the old schema before prize_type/prize_value
refactoring. Its NOT NULL constraint caused INSERT failures since the
SQLAlchemy model no longer includes it.
2026-03-07 15:34:54 +03:00
firewookie a6849242ff add riopay 2026-03-07 15:35:26 +05:00
Fringg 9d5329d9d1 fix: resolve NameError in YooKassa successful payment processing
event_object was referenced in _process_successful_yookassa_payment
but never passed to the method, causing all YooKassa webhook payments
to fail. Use payment.amount_kopeks from the database model instead.
2026-03-07 13:28:25 +03:00
Fringg bbd353ff38 fix: resolve alembic migration failures on fresh database install
Migration 0001 uses Base.metadata.create_all() which creates ALL tables
from current models.py, causing subsequent migrations (0015+) to fail
with "already exists" errors when they try to re-create constraints,
indexes, columns, and tables.

Three-layer fix:

1. migrations.py: detect fresh DB (no tables) and bootstrap via
   create_all() + stamp head, bypassing all migrations entirely.

2. models.py: add EmailTemplate model, CheckConstraints to LandingPage,
   and indexes to GuestPurchase so create_all() produces a complete
   schema identical to running all 30 migrations sequentially.

3. Idempotency guards in migrations 0015-0030: _has_unique_constraint,
   _has_table, _has_index, _has_column, _has_check_constraint checks
   before DDL operations, protecting against re-runs via make migrate.
2026-03-07 13:17:04 +03:00
Fringg 11d3e637c1 feat: add configurable animated background for landing pages
Add background_config JSON field to LandingPage model, enabling
per-landing animated backgrounds (aurora, sparkles, vortex, etc).

- Add background_config column (JSON, nullable) with Alembic migration
- Add validated background_config to create/update/detail/public schemas
- Reuse ALLOWED_BG_TYPES and _validate_settings from branding module
- Strip unknown keys via whitelist, validate all fields including reducedOnMobile
2026-03-07 12:46:02 +03:00
Fringg 0ba1127469 feat: add paginated purchases list endpoint for landing pages
Add GET /admin/landings/{id}/purchases with offset/limit pagination,
optional status filter (validated against GuestPurchaseStatus enum),
tariff name join, and truncated token display.
2026-03-07 09:49:57 +03:00
Fringg 25478ced20 feat: add landing page statistics endpoint with charts data
Add GET /admin/landings/{id}/stats endpoint returning:
- Summary stats (purchases, revenue, gifts, conversion rate)
- Daily breakdown for last 30 days (purchases, revenue, gifts per day)
- Tariff distribution (purchases and revenue per tariff)

Uses case() expressions for SQLite compatibility, timezone-safe
date grouping via func.timezone('UTC', ...), and composite index
(landing_id, status, paid_at) for query performance.
2026-03-07 09:35:21 +03:00
Egor 57b95671ea Merge pull request #2686 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.24.0
2026-03-07 07:31:21 +03:00
github-actions[bot] eecf2b4183 chore(main): release 3.24.0 2026-03-07 04:30:05 +00:00
Egor 5a97fc2fa1 Merge pull request #2685 from BEDOLAGA-DEV/dev
Dev
2026-03-07 07:26:29 +03:00
Fringg 26b486cdd9 chore: sync uv.lock with pyproject.toml version bump 2026-03-07 07:18:43 +03:00
Egor ba05c5ce92 Merge pull request #2684 from BEDOLAGA-DEV/main
w
2026-03-07 07:16:05 +03:00
Fringg 372d628908 fix: remove executable bit from email_service.py 2026-03-07 07:14:52 +03:00
Fringg ceac29d5e3 style: format admin_landings.py 2026-03-07 07:13:01 +03:00
Egor 3ee108fce8 Merge pull request #2658 from thegrayfoxxx/fix_logo_from_show_qr
fix: reset QR photo when returning to referral
2026-03-07 07:09:38 +03:00
Egor de541ea1c3 Merge pull request #2682 from smediainfo/fix/email-message-id-headers
fix: add Message-ID and Date headers to outgoing emails
2026-03-07 07:08:37 +03:00
Fringg 6d65e15266 fix: read discount overrides from landing model instead of response DTO
After removing overrides from the public LandingDiscountInfo response,
_load_landing_tariffs still referenced discount.overrides which no
longer exists. Read from landing.discount_overrides directly.
2026-03-07 07:05:38 +03:00
Fringg aa7d98630d feat: add discount system for landing pages
Add time-bounded percentage discounts with per-tariff overrides
and countdown timer support for landing pages.

- Add 5 discount columns to LandingPage model (percent, overrides,
  starts_at, ends_at, badge_text) with Alembic migrations 0027-0028
- Add DB CHECK constraints for discount_percent range and date ordering
- Add discount price calculation in validate_and_calculate() and
  public landing config endpoint with consistent formula
- Add admin CRUD with Pydantic validation, cascade-clear on removal,
  merged date validation on partial updates, size bounds
- Remove discount_overrides from public API (baked into prices)
- Add size limits for allowed_tariff_ids and allowed_periods
2026-03-07 07:01:35 +03:00
Fringg 8b77cdae2c feat: add GET /admin/rbac/users endpoint for listing all RBAC users 2026-03-07 06:23:14 +03:00
Fringg c93dbec7a0 feat: add landings to permission registry
Register landings:read, landings:create, landings:edit, landings:delete
permissions so they appear in the role editor permission matrix.
2026-03-07 06:05:03 +03:00
Fringg fa21549cac fix: add activate hint to gift pending activation email link
Append ?activate=1 to success page URL in recipient notification email
for gift purchases with pending_activation status, so the frontend can
distinguish buyer from recipient and show the activate button only to
the recipient.
2026-03-07 06:00:29 +03:00
Fringg c10d6780ba feat: add external squad support for tariffs
- Add external_squad_uuid column to Tariff model with Alembic migration
- Add external_squad_uuid parameter to RemnaWave API create_user/update_user
- Pass external squad from tariff to RemnaWave on subscription creation/update
- Sync external squad in monitoring service, sync service, admin user management
- Clear external squad when tariff has none (consistent across all call sites)
- Add GET /available-external-squads endpoint with UUID validation and response model
- Update tariff schemas with UUID pattern validation
- Fix db.refresh to include tariff relationship for async safety
2026-03-07 05:44:19 +03:00
Fringg 770f19e846 fix: address review findings for guest purchase admin notifications
- Remove double html.escape on payment_method (already escaped in helper)
- Use attribute_names=['landing'] keyword arg in db.refresh for consistency
- Use async with Bot() for guaranteed session cleanup
2026-03-07 04:48:52 +03:00
Fringg dbb9757a3c feat: add admin topic notifications for landing page purchases
- New send_guest_purchase_notification() method in AdminNotificationService
  with blockquote for payment details, landing slug, buyer/recipient info
- Called from fulfill_purchase() for both DELIVERED and PENDING_ACTIVATION
- Called from activate_purchase() when pending purchase is activated
- Different titles: regular purchase, gift purchase, pending activation
- Properly typed GuestPurchase, html.escape on all user data
- Refresh purchase with ['landing'] relationship after commit
- html.escape fallback in _get_payment_method_display
- ruff formatting fixes
2026-03-07 04:44:02 +03:00
Fringg 77456efb75 fix: add X-CSRF-Token and X-Telegram-Init-Data to CORS allow_headers
The security hardening commit changed allow_headers from ['*'] to
['Authorization', 'Content-Type'], but the frontend sends X-CSRF-Token
on all POST/PUT/DELETE/PATCH requests and X-Telegram-Init-Data on all
requests. The missing headers caused preflight OPTIONS requests to fail
with 400 "Disallowed CORS origin".
2026-03-07 04:30:29 +03:00
Fringg c165cca323 fix: use get_rendered_override for proper variable substitution in guest email overrides
Admin-created email template overrides were not substituting {tariff_name},
{period_days}, {cabinet_url} etc. because get_template_override returns raw
body_html. Switched to get_rendered_override which performs variable
substitution with html.escape. Also removed dead is_existing_user from
sample context.
2026-03-07 04:26:09 +03:00
Fringg 6970340e62 feat: add quick purchase email templates to admin panel
- Register 4 guest purchase template types in admin email templates:
  guest_subscription_delivered, guest_activation_required,
  guest_gift_received, guest_cabinet_credentials
- Add sample contexts with placeholders for preview/test
- Add DB override support to send_guest_notification for all 4 types
2026-03-07 04:13:41 +03:00
Fringg 9217352685 fix: remove subscription connection links from guest purchase emails
Replace VPN subscription URLs with cabinet links in all email templates:
- GUEST_SUBSCRIPTION_DELIVERED: unified to always show cabinet link
- GUEST_GIFT_RECEIVED: replaced subscription URL with cabinet link
Both self-purchase and gift flows now only include cabinet links.
2026-03-07 04:10:27 +03:00
Fringg a539d69854 fix: code style and formatting from review
- Format long dict literal in admin_landings.py
- Add blank line after validator in admin_payment_methods.py
- Fix ruff E203 slice spacing in landing.py
- Fix long line wrapping in payment_service.py
2026-03-07 03:50:15 +03:00
Fringg e96fe1ecd8 fix: comprehensive security hardening from 7-agent review
Schema validation:
- Add max_length to init_data (4096), widget fields (first_name 64,
  last_name 64, username 32, photo_url 512, hash 64)
- Add max_length=2048 to all token fields (verify, refresh, reset, auto-login)
- Add max_length=128 to EmailLoginRequest.password (bcrypt DoS prevention)
- Add pattern to OAuthCallbackRequest.referral_code (was missing)
- Add pattern=r'^\d{6}$' to EmailChangeVerifyRequest.code
- Add pattern/max_length to language field (ISO 639-1)

Auth endpoints:
- Add user.status check to auto-login (banned users could authenticate)
- Add exception chaining (from e) to refresh and auto-login endpoints
- Add IP rate limiting to initData, register standalone, verify email,
  forgot password, and reset password endpoints

CORS:
- Add PATCH to allow_methods in both unified_app and webapi (38+ PATCH
  endpoints were blocked for cross-origin requests)

JWKS:
- Fix race condition: move force-refresh cooldown check and cache
  invalidation inside asyncio.Lock via dedicated _force_refresh_jwks()
2026-03-07 03:47:58 +03:00
Fringg 5499ad62dc fix: add referral_code pattern validation, email login rate limiting, and Retry-After headers
- Add pattern=r'^[a-zA-Z0-9_-]+$' to referral_code in TelegramAuthRequest,
  TelegramWidgetAuthRequest, and EmailRegisterStandaloneRequest for consistency
  with TelegramOIDCAuthRequest
- Add IP-based rate limiting (10 req/min) to /email/login endpoint
- Add Retry-After: 60 header to /login/auto 429 response
2026-03-07 03:37:25 +03:00
Fringg 6495384bcf fix: transaction boundary and CORS in webapi
- Revert OIDC flush to commit before _store_refresh_token
  (matches widget/initData pattern, prevents rollback losing user updates)
- Fix CORS wildcard+credentials in webapi/app.py (same as unified_app fix)
2026-03-07 03:33:37 +03:00
Fringg 5c55662e2c fix: comprehensive security and quality fixes from 7-agent review
Security:
- CORS: disable credentials when wildcard origin, restrict methods/headers
- Token replay: Redis-based id_token dedup with TTL matching expiry
- JWT secret: warn when falling back to BOT_TOKEN
- Rate limiting: add to legacy widget endpoint (was missing)
- Retry-After: add header to all 429 responses

Quality:
- Read OIDC CLIENT_ID from DB with env fallback (admin panel works)
- Consolidate db.commit() — flush mid-handler, single commit at end
- Move get_setting_value import to top-level
2026-03-07 03:27:00 +03:00
Fringg b78c01cae9 fix: critical OIDC fixes from 7-agent review
- Fix broken import (system_settings → system_setting) that crashed
  OIDC endpoint on every request
- Extract get_setting_value to shared CRUD module
- Add JWKS force-refresh cooldown (30s) to prevent abuse
- Remove dead _OIDC_TOKEN_URL constant
- Add raise from for exception chaining
- Remove unused _photo_url variable
- Add pattern validation on referral_code field
2026-03-07 03:18:20 +03:00
Fringg 2405dc5c1b fix: read OIDC enabled setting from DB in auth endpoint
Match branding endpoint pattern — check system_settings first,
fall back to env var, ensuring admin panel toggle takes effect.
2026-03-07 03:04:42 +03:00
Fringg da1cc4fe5a fix: address code review findings for Telegram OIDC
- JWKS cache: add asyncio.Lock to prevent thundering herd, extract
  _build_public_keys helper, retry JWKS fetch on kid mismatch (key rotation)
- Remove dead code: exchange_telegram_oidc_code (unused, popup sends id_token directly)
- OIDC auth endpoint: add rate limiting, fix int() parse with try/except,
  extract last_name/photo_url/language from claims, narrow bare Exception
  to (ValueError, LookupError)
- Schema: add max_length=4096 to id_token field
- Branding: read TELEGRAM_OIDC_ENABLED from DB settings with env fallback
2026-03-07 02:54:29 +03:00
Fringg 000b0c0592 feat: expose oidc_enabled and oidc_client_id in telegram-widget config 2026-03-07 02:33:52 +03:00
Fringg 3a400d9f8b feat: add POST /auth/telegram/oidc endpoint for OIDC popup flow 2026-03-07 02:32:40 +03:00
Fringg 2f0a9dc4f3 feat: add Telegram OIDC id_token validation and code exchange 2026-03-07 02:30:33 +03:00
Fringg 3a361628aa feat: register TELEGRAM_OIDC category, hints in admin settings
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 02:25:54 +03:00
Fringg 833df518d0 feat: add TELEGRAM_OIDC_* settings for new Telegram Login
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 02:24:13 +03:00
Fringg 084a3cd16f feat: configurable Telegram Login Widget with admin settings
- Add 4 TELEGRAM_WIDGET_* settings to config (size, radius, userpic, request_access)
- Register TELEGRAM_WIDGET category with choices, hints, and prefix mapping
- Add public GET /branding/telegram-widget endpoint returning widget config
- Use Literal type for size validation, Field(ge=0, le=20) for radius bounds
- Clamp radius values from DB to prevent out-of-range values
2026-03-07 01:48:14 +03:00
Fringg 694aeccc31 fix: remove decorative cloudpayments sub-options
CloudPayments doesn't support programmatic card/sbp routing — the user
selects the payment method on the provider's payment page. Remove
available_sub_options so no misleading choice is shown on landing pages.
2026-03-07 00:04:32 +03:00
Fringg 5f01783dcb fix: validate payment sub-option suffix and harden payment method handling
- Add regex pattern + max_length constraint on payment_method field
- Validate sub-option suffix against known available_sub_options
- Validate sub-option is enabled on the landing (not disabled via config)
- Sort methods by ID length desc to prevent freekassa/freekassa_sbp ambiguity
- Accept yookassa_card and cloudpayments_card/sbp in create_guest_payment
- Send single sub-option to frontend (not just when >1) for correct routing
2026-03-07 00:01:44 +03:00
Fringg c53e9af744 feat: expose payment sub-options with labels in public landing API
Resolve sub-option display names from payment_method_config_service
and return them as a list of {id, name} in the public landing config.
Accept suffixed payment_method IDs (e.g. platega_2, yookassa_sbp)
in the purchase endpoint for sub-option selection.
2026-03-06 23:53:28 +03:00
Fringg 220196fb7a feat: add sub_options support for landing page payment methods
Allow per-landing override of payment method sub-options (e.g. Card/SBP
for Yookassa). Add validated sub_options field to admin and public schemas
with opt-out model (missing keys = enabled, null = all available).
2026-03-06 23:30:44 +03:00
sMedia.tech e9b4d8e444 fix: add Message-ID and Date headers to outgoing emails
Without these RFC 5322 required headers, Postfix sends messages with
empty message-id=<> which triggers spam filters at receiving MTAs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 22:53:39 +03:00
Fringg d86c29a5d3 fix: preserve connected_squads during subscription replacement cleanup
Root cause: validate_and_clean_subscription() wiped connected_squads=[]
before create_remnawave_user() could send them to the Remnawave panel.
This caused replaced subscriptions to lose squad (server) assignments.

Also: add update_server_counters=True to all guest purchase flows,
commit tariff_id before create_remnawave_user to ensure fresh ORM state.
2026-03-06 22:28:39 +03:00
Fringg 8510597ddb fix: add pending_activation to purchase stats and show total count 2026-03-06 22:16:28 +03:00
Fringg f8edfd7746 feat: guest purchase → cabinet account integration
Create verified cabinet accounts for email-based guest purchasers:
- Auto-generate password for new/existing users without password_hash
- Auto-login JWT token (72h TTL) stored once at fulfillment
- POST /login/auto endpoint with rate limiting (5 req/60s)
- Credentials email template (5 languages)
- Fix forgot_password for guest-created email users
- Clear plaintext password from DB after email delivery
- TTL-capped credential exposure (24h delivered, 72h pending_activation)
- DB cleanup of expired credentials on poll
2026-03-06 21:59:36 +03:00
Fringg 776fc3aadc feat: guest purchase delivery & activation system
- Add PENDING_ACTIVATION status for users with existing subscriptions
- Add activation endpoint POST /landing/activate/{token}
- Send email notifications on delivery and pending activation
- Add 3 email templates (delivered, activation required, gift received) in 5 languages
- Extract purchase status response builder to reusable helper
- Move activation logic to service layer
- Add header injection protection in email service
- Add Literal type guard for contact_type parameter
- Fix _mask_email crash on malformed input
- Pre-resolve notification params before commit to avoid DetachedInstanceError
2026-03-06 19:56:37 +03:00
Fringg b85646af85 fix: pass return_url to all payment providers for guest purchases
Platega, Heleket, WATA, CloudPayments now accept optional return_url
and pass it to their APIs. Guest payments redirect back to cabinet
success page instead of Telegram bot.
2026-03-06 18:18:42 +03:00
Fringg e0f2243f49 fix: make users.promo_group_id nullable — sync DB with model
Migration 0023: ALTER COLUMN promo_group_id SET nullable=True.
Fixes NOT NULL violation when creating guest users during landing purchases.
2026-03-06 18:18:40 +03:00
Fringg ab981dce0d fix: treat empty icon_url as None in payment method validation 2026-03-06 18:00:34 +03:00
Fringg 6f871edc9d fix: CryptoBot guest payment — remove is_paid @property write, use correct status
- Remove `locked.is_paid = True` — is_paid is a read-only @property computed from status
- Change status from 'completed' to 'paid' (matching is_paid property check)
- Use db.commit() instead of db.flush() for guest payment persistence
2026-03-06 16:54:25 +03:00
Fringg 3d3bb3badb fix: миграция 0021 — drop server_default перед сменой типа на JSON
PostgreSQL не может автоматически привести строковый default к типу JSON.
Решение: убрать default, сменить тип, затем поставить новый default через raw SQL.
2026-03-06 16:45:03 +03:00
Fringg 6deab7dd8c feat: мультиязычные лендинги + гостевые платежи для всех провайдеров
Мультиязычность:
- Миграция 0021: текстовые поля лендингов → JSON с ключами локалей
- Утилита resolve_locale_text с fallback-цепочкой (lang → ru → en → first)
- Админ API: dict[str, str] для title/subtitle/footer/meta/features
- Публичный API: ?lang= параметр, резолвит в плоские строки
- Обратная совместимость: plain strings → {"ru": value}

Гостевые платежи:
- Миграция 0022: user_id nullable во всех платёжных таблицах
- Поддержка всех провайдеров кроме Stars
- Общий хелпер try_fulfill_guest_purchase в common.py
- YooKassa переведена на общий хелпер

Исправления по ревью:
- CryptoBot: guest fulfillment после FOR UPDATE lock
- _patch_guest_metadata: commit вместо flush
- Freekassa/KassaAI: metadata как dict вместо JSON-строки
- purchase_token маскирован в логах
- None → "guest" в order_id
- Rate limit на GET /landing/{slug}
- Маскирование contact_value
2026-03-06 16:10:09 +03:00
firewookie 861ffe5424 fix migration 2026-03-06 12:36:32 +05:00
firewookie 06ccf4b275 webhook install bugfix + add info in readme 2026-03-06 11:56:15 +05:00
firewookie 7ed91b13eb - RioPay payment system integration 2026-03-06 11:44:22 +05:00
firewookie 319f49435a - Карточки "Бонус новому пользователю" и "Бонус пригласившему"
скрыты когда значение = 0
- Динамический grid-cols в зависимости от количества видимых карточек
- Добавлено поле max_commission_payments в тип ReferralTerms
- Уведомления бота: строки с бонусом нового пользователя и бонусом
    пригласившего скрываются если соответствующие настройки = 0
- Раздел "Как работают награды": карточки бонусов скрыты при значении 0
- Invite message: строка про бонус за первое пополнение скрыта при 0
- Текст комиссии: "с каждого пополнения" при без лимита,
    "с пополнений" при наличии REFERRAL_MAX_COMMISSION_PAYMENTS- API /terms: добавлено поле max_commission_payments
- Добавлен ключ локали REFERRAL_REWARD_COMMISSION_LIMITED (ru/en/ua/zh/fa)
2026-03-06 11:08:52 +05:00
firewookie 23761a74f2 fix formatting 2026-03-06 09:57:24 +05:00
firewookie 8620aaedb1 fix formatting 2026-03-06 09:54:55 +05:00
firewookie aaffc26a90 - Интеграция рекурентов от Юкассы
- Багфикс личного кабинета
2026-03-06 09:47:58 +05:00
Fringg ef450955e6 fix: безопасность и качество кода лендингов — 16 исправлений
- CRITICAL: блокировка fulfillment при несовпадении суммы
- CRITICAL: верификация суммы webhook перед фулфилментом
- CRITICAL: TTL 24ч на доступ к subscription_url + rate limit статуса
- HIGH: IntegrityError для telegram-пользователей (race condition)
- HIGH: валидация icon_url (HTTPS/relative only)
- HIGH: строгий whitelist setattr для update_purchase_status
- HIGH: SAVEPOINT вместо full rollback в _find_or_create_user
- HIGH: отложенный commit покупки до успеха платежа
- MEDIUM: N+1 запрос в списке лендингов → batch stats
- MEDIUM: лимиты длины текстовых полей в схемах
- MEDIUM: строгий email regex
- MEDIUM: индекс на guest_purchases.landing_id (миграция 0020)
- LOW: token prefix 5 символов, расширенные reserved slugs
2026-03-06 07:22:48 +03:00
Fringg 5e404cc082 feat: публичные лендинг-страницы для быстрой покупки VPN-подписок
- Модели LandingPage и GuestPurchase + миграции 0018/0019
- CRUD для лендингов и гостевых покупок
- Публичные роуты: GET /{slug}, POST /{slug}/purchase, GET /purchase/{token}
- Админ-роуты: CRUD лендингов с RBAC (manage_landings)
- Сервис guest_purchase_service: валидация, создание, фулфилмент
- Интеграция с PaymentService (YooKassa card/SBP) для гостевых платежей
- Webhook-обработка с идемпотентностью и атомарными транзакциями
- Rate limiting на публичных эндпоинтах
- YooKassaPayment.user_id теперь nullable для гостевых платежей
2026-03-06 07:02:42 +03:00
Egor c669c5951a Merge pull request #2676 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.23.2
2026-03-06 05:33:40 +03:00
github-actions[bot] b68c1c751a chore(main): release 3.23.2 2026-03-06 02:33:15 +00:00
Egor 0c0e219691 Merge pull request #2673 from BEDOLAGA-DEV/dev
Dev
2026-03-06 05:32:55 +03:00
Egor 8eb6a8c460 Merge pull request #2675 from BEDOLAGA-DEV/main
fix: sync uv.lock version with pyproject.toml 3.23.1
2026-03-06 05:27:56 +03:00
Fringg bc52fd2711 fix: sync uv.lock version with pyproject.toml 3.23.1
release-please обновляет version в pyproject.toml, но не
перегенерирует uv.lock — Docker build падает на uv sync --locked.
2026-03-06 05:27:05 +03:00
Egor 6da408fe15 Merge pull request #2672 from BEDOLAGA-DEV/main
w
2026-03-06 05:22:22 +03:00
Fringg 15fe45d113 fix: миграция 0016 падает если FK constraint отсутствует в БД
Вместо хардкода имён constraint'ов — ищем реальное имя через
pg_constraint. Пропускаем несуществующие таблицы и FK.
Исправляет краш при обновлении у пользователей с неполной схемой.
2026-03-06 05:17:51 +03:00
Fringg 3e26832e74 fix: device_limit fallback 1→0 для корректного отображения безлимита
Значение 0 означает «без ограничений» — фронтенд показывает ∞.
Старый fallback=1 некорректно ограничивал подписки без лимита.
2026-03-06 05:17:44 +03:00
Egor 4c21e3a2a9 Merge pull request #2671 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.23.1
2026-03-06 04:50:21 +03:00
github-actions[bot] c4ea17507f chore(main): release 3.23.1 2026-03-06 01:50:06 +00:00
Egor 19d30dd292 Merge pull request #2670 from BEDOLAGA-DEV/dev
Dev
2026-03-06 04:49:43 +03:00
Fringg 1e930af7d4 chore: regenerate uv.lock for v3.23.0 2026-03-06 04:46:15 +03:00
Fringg 833227a717 Merge remote-tracking branch 'origin/main' into dev 2026-03-06 04:45:52 +03:00
Fringg 04562fd7e7 fix: кнопка «Назад» в тарифах ведёт в админ панель, а не в настройки
Тарифы доступны напрямую из главного меню админки, но кнопка назад
вела в подменю настроек. Исправлено во всех 4 местах.
2026-03-06 04:23:05 +03:00
Fringg 4984f20e8f fix: устранение race conditions и атомарность платёжной системы
- SELECT FOR UPDATE блокировка во всех 9 провайдерах (кроме YooKassa — свой паттерн)
- create_transaction(commit=False) + единый db.commit() для атомарности
- emit_transaction_side_effects() для отложенных событий после коммита
- Все link_*_payment_to_transaction используют db.flush() вместо db.commit()
- Freekassa/KassaAI: прямое присвоение transaction_id + flush вместо update_status
- MulenPay: прямая мутация balance_kopeks вместо add_user_balance
- Platega: блокировка перед чтением metadata, инлайн обновления полей
- CloudPayments: int(round(amount * 100)) для корректного округления
- Heleket добавлен в SUPPORTED_AUTO_CHECK_METHODS
- Удалены PII из логов yookassa webhook (заголовки, IP)
- UniqueConstraint(external_id, payment_method) на транзакциях + миграция 0017
- Cabinet: PaymentService(bot=bot) внутри try блока
- verify_payment_amount утилита для проверки суммы webhook
2026-03-06 04:20:41 +03:00
Fringg fe393d2ca6 fix: complete FK migration — add 27 missing constraints, fix broadcast_history nullable
- broadcast_history.admin_id: CASCADE→SET NULL (column is nullable, preserve audit trail)
- Added nullable=True to broadcast_history.admin_id in model
- Added 27 missing FK constraints to _FK_CHANGES (were only cleaned for orphans
  but not recreated with ondelete)
- All 53 FK→users.id now consistently handled in both orphan cleanup and constraint recreation
2026-03-06 01:56:36 +03:00
Fringg 34c82c3488 fix: добавить ON DELETE CASCADE/SET NULL на все FK к users.id
27 FK ссылающихся на users.id не имели ondelete — при физическом удалении
юзера или восстановлении бэкапа с сиротами FK constraints не создавались.

Миграция 0016:
1. Чистит сироты во всех 53 child-таблицах (DELETE для non-nullable, SET NULL для nullable)
2. Пересоздаёт 27 FK с ON DELETE CASCADE (user_id) или SET NULL (created_by, processed_by)
2026-03-06 01:47:23 +03:00
Fringg 00a7db2690 fix: дедупликация promocode_uses при мерже аккаунтов
После добавления UniqueConstraint(user_id, promocode_id) на promocode_uses,
простое переназначение user_id при мерже падает с IntegrityError если оба
юзера использовали один промокод. Теперь сначала удаляются дубликаты.
2026-03-06 01:42:09 +03:00
Fringg 7fb839aef6 fix: промокоды — конвертация триалов, race condition, savepoints
- trial подписки теперь конвертируются в платные вместо отказа (ошибка ~20 из 300 юзеров)
- extend_subscription: добавлен переход TRIAL→ACTIVE
- UniqueConstraint на PromoCodeUse(user_id, promocode_id) + миграция 0015 с дедупликацией
- create_promocode_use: begin_nested()+flush() вместо commit/rollback (без коррупции сессии)
- race condition: create_promocode_use вызывается ДО _apply_promocode_effects
- cleanup: удаление зарезервированной записи при ValueError от эффектов
- atomic SQL increment для current_uses (защита от lost-update)
- mark_user_as_had_paid_subscription: savepoint вместо commit/rollback
- удалён мёртвый код: use_promocode(), trial_subscription_not_eligible из маппингов
2026-03-06 01:33:18 +03:00
Fringg 6713b34978 fix: исправления системы реферальных конкурсов
- float precision: int(round(amount * 100)) вместо int(amount * 100) для рублей→копейки
- порядок регистрации callback-хендлеров (специфичные startswith первыми)
- FSM state filter на callback хендлере для предотвращения случайных срабатываний
- upsert паттерн в add_contest_event вместо дубликатов
- расширенный SQL фильтр в get_contests_for_events (все активные конкурсы)
- нормализация end-of-day (23:59:59.999999) для границ конкурсных периодов
- guard is_completed в create_transaction
2026-03-06 01:33:06 +03:00
Fringg 7a7fb71bf5 fix: дубликаты системных ролей при переименовании и сброс permissions
1. Поиск системных ролей по (is_system + level) вместо name —
   переименование через UI больше не создаёт дубликаты
2. Bootstrap только добавляет новые permissions из кода,
   не перезатирая кастомизацию админа
2026-03-05 23:49:07 +03:00
Fringg 1c89bd8b2a fix: UniqueViolation при мерже аккаунтов с общим OAuth/telegram/email ID
SQLAlchemy не гарантирует порядок UPDATE при flush — если primary
обновлялся раньше secondary, unique constraint срабатывал до очистки
старого значения. Теперь: очистка secondary → flush → установка primary.
2026-03-05 23:36:30 +03:00
Egor 050be0fe0e Merge pull request #2669 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.23.0
2026-03-05 11:35:44 +03:00
github-actions[bot] 297240f8ef chore(main): release 3.23.0 2026-03-05 08:35:09 +00:00
Egor 2b16a00464 Merge pull request #2668 from BEDOLAGA-DEV/dev
Dev
2026-03-05 11:34:32 +03:00
Fringg b31a893b13 fix: синхронизация версии pyproject.toml с main и обновление uv в Dockerfile
- pyproject.toml: 3.18.0 → 3.22.0 (соответствие main)
- Dockerfile: uv 0.10.7 → 0.10.8
- uv.lock: перегенерирован с новой версией
2026-03-05 11:29:35 +03:00
Fringg b9e17be855 fix: реактивация DISABLED подписок при покупке устройств и в REST API
Добавлен вызов reactivate_subscription перед update_remnawave_user в 4 пропущенных местах:
- handlers/subscription/devices.py (2 пути покупки устройств)
- webapi/routes/subscriptions.py (эндпоинты добавления трафика и устройств)
2026-03-05 11:29:23 +03:00
Fringg 900be65617 fix: добавить пробелы в формат тарифов (1000 ГБ / 2 📱) 2026-03-05 11:16:53 +03:00
Fringg 53a67d7573 chore: автоформатирование ruff 2026-03-05 10:56:17 +03:00
Fringg 7d28f5516a fix: реактивация DISABLED подписок при покупке трафика для LIMITED пользователей
Когда RemnaWave ставит пользователю статус LIMITED (трафик исчерпан),
webhook бота устанавливает локальный статус подписки в DISABLED. При
покупке дополнительного трафика update_remnawave_user() видел DISABLED
и отправлял status=EXPIRED, что RemnaWave отвергал с ошибкой 400.

Добавлен вызов reactivate_subscription() перед синхронизацией с RemnaWave
во всех 8 потоках покупки/переключения трафика:
- handlers/subscription/traffic.py (add_traffic, execute_switch_traffic)
- cabinet/routes/subscription.py (purchase_traffic)
- cabinet/routes/admin_users.py (admin add_traffic)
- handlers/admin/users.py (_add_subscription_traffic)
- webapi/routes/miniapp.py (purchase_traffic_topup)
- subscription_auto_purchase_service.py (_auto_add_traffic, _auto_add_devices)

Также разрешён статус DISABLED в guard автопокупки трафика и устройств,
чтобы LIMITED пользователи могли автоматически докупать ресурсы.
2026-03-05 10:56:10 +03:00
Fringg 849b3a7034 fix: убрать избыточный минус в amount_kopeks для create_transaction
amount_kopeks=-X → amount_kopeks=X в 10 местах:
- tariff_purchase.py (8 локаций)
- miniapp.py (1 локация)
- admin/users.py (1 локация)

create_transaction автоматически негирует для SUBSCRIPTION_PAYMENT,
поэтому передача положительного значения — правильная конвенция.
2026-03-05 10:15:39 +03:00
Fringg 374907b607 fix: добавить create_transaction для 6 потоков оплаты с баланса
- trial_activation_service: create_transaction после списания за триал
- purchase.py: create_transaction для платного триала через бот
- cabinet/subscription.py: create_transaction для продления и триала,
  исправлены transaction=None → реальный объект в 5 уведомлениях
- simple_subscription.py: create_transaction в обоих обработчиках,
  transaction передаётся в admin-уведомление вместо None
2026-03-05 10:15:32 +03:00
Fringg 9f35088788 fix: добавить create_transaction и admin-уведомления для автопродлений
- monitoring_service: добавлен create_transaction(SUBSCRIPTION_PAYMENT, BALANCE)
  и admin-уведомление через with_admin_notification_service
- daily_subscription_service: исправлен PaymentMethod.MANUAL → BALANCE,
  добавлено admin-уведомление через with_admin_notification_service
- subscription_auto_purchase_service: admin-уведомления вынесены из блока
  if bot: и используют with_admin_notification_service (3 локации)
2026-03-05 10:15:25 +03:00
Fringg fd139b28a2 fix: abs() for transaction amounts in admin notifications and subscription events
- send_subscription_purchase_notification: abs(transaction.amount_kopeks) when no explicit amount_kopeks passed
- send_subscription_renewal_notification: abs(transaction.amount_kopeks) for SubscriptionEvent storage
- Prevents negative amounts in admin Telegram messages and SubscriptionEvent records
2026-03-05 09:30:27 +03:00
Fringg de6f80694b fix: add abs() to expenses query, display flip, contest stats, and recent payments
- expenses_kopeks: func.abs() handles WITHDRAWAL stored as negative by approve_request
- admin_users.py: abs() in display instead of sign flip for mixed-sign WITHDRAWAL/SUBSCRIPTION_PAYMENT
- referral_contest.py: func.abs() on get_contest_payment_stats total_amount sum
- admin_stats.py: abs() on RecentPaymentItem to prevent negative amounts in API
2026-03-05 09:12:01 +03:00
Fringg b87535ad48 fix: изолировать stored_amount от downstream consumers в create_transaction
- stored_amount используется только для БД записи, оригинальный
  amount_kopeks передаётся в event emitter и contest service через abs()
- Добавлен func.abs() в leaderboard конкурсов (referral_contest.py)
- Предотвращает негативные суммы в событиях и рейтинге конкурсов
2026-03-05 09:05:55 +03:00
Fringg 6da61d7951 fix: убрать WITHDRAWAL из автонегации, добавить abs() в агрегации, исправить all_time_stats
- Убран WITHDRAWAL из автонегации в create_transaction (ломал profit,
  expenses и display flip в admin_users)
- Добавлен func.abs() в by_type агрегацию (transaction.py)
- Добавлен func.abs() в total_spent user.py (_build_spending_stats_select)
- Исправлен all_time_stats в боте и webapi: передаём явный диапазон дат
  вместо дефолтного текущего месяца
2026-03-05 09:05:02 +03:00
Fringg 968d147046 fix: передать явный диапазон дат для all_time_stats в дашборде
get_transactions_statistics() без аргументов по умолчанию возвращает
текущий месяц, а не все время. Передаём явный start_date=2020-01-01
для корректного расчёта общего дохода и дохода от подписок.
2026-03-05 09:02:05 +03:00
Fringg 93a55df4c0 fix: гарантировать положительный доход от подписок и исправить общий доход
- Добавлен abs() на уровне API-ответов для subscription_income (защита от
  негативных значений при несогласованных знаках SUBSCRIPTION_PAYMENT)
- Нормализация знаков в create_transaction: SUBSCRIPTION_PAYMENT и WITHDRAWAL
  всегда сохраняются как отрицательные (дебет)
- Исправлен income_total в дашборде: показывал месячный доход вместо общего
  (теперь используется отдельный запрос all_time_stats)
2026-03-05 08:58:49 +03:00
Fringg 82592784d0 fix: устранение каскадного PendingRollbackError при восстановлении бэкапа
TRUNCATE 83 таблиц таймаутился из-за command_timeout=30s в asyncpg.
После таймаута в fallback-цикле PendingRollbackError каскадировал
на все остальные таблицы и восстановление данных.

Исправление:
- Выделенный engine с command_timeout=300s и statement_timeout=5min
  для TRUNCATE операций (NullPool, без overhead)
- Каждая таблица в fallback очищается в отдельном соединении,
  что предотвращает каскад PendingRollbackError
- lock_timeout=2min для ограничения ожидания блокировок
  (бот продолжает обрабатывать сообщения во время восстановления)
2026-03-05 08:32:50 +03:00
Fringg acfa4b3c2e fix: показывать кнопку покупки тарифа вместо ошибки для триальных подписок
При нажатии «Продлить подписку» из webhook-уведомления триальный
пользователь получал ошибку «Продление доступно только для платных
подписок». Теперь вместо этого показывается сообщение с кнопкой
«Купить подписку», которая ведёт к выбору тарифа.
2026-03-05 08:25:16 +03:00
Fringg a7a18dd0d1 fix: устранение race condition при покупке устройств через re-lock после коммита
subtract_user_balance() делает внутренний коммит, что освобождает
SELECT FOR UPDATE блокировки. Добавлен паттерн re-lock + re-validate +
refund после вызова subtract_user_balance во всех 8 путях мутации
device_limit:

- cabinet: /devices, /devices/purchase, /devices/reduce
- miniapp: /subscription/devices
- bot handlers: execute_change_devices, confirm_add_devices
- auto-purchase: _auto_add_devices
- CRUD: add_subscription_devices

Также добавлен populate_existing=True ко всем SELECT FOR UPDATE запросам
для корректного обновления SQLAlchemy identity map.
2026-03-05 08:15:00 +03:00
Fringg 1cfede28b7 fix: prevent concurrent device purchases exceeding max device limit
Add SELECT FOR UPDATE row lock on subscription before checking device
limit in all 3 device purchase endpoints (cabinet new, cabinet legacy,
miniapp). Without the lock, two concurrent requests both read the old
device_limit, both pass validation, and both increment — resulting in
device count exceeding max_device_limit (e.g., 5 devices when limit is 3).

Also moved max-devices check before balance check in legacy endpoint
to fail fast under lock.
2026-03-05 07:33:09 +03:00
Fringg c8ef808539 fix: consume promo offer in tariff_purchase.py, fix negative transaction amount
- Add consume_promo_offer to 5 call sites in tariff_purchase.py where
  _get_user_period_discount() stacks promo_offer into blended discount
  (lines 823, 1134, 1706, 2238, 2971)
- Fix negative amount_kopeks in miniapp.py:5351 transaction record
  (was -final_total, all other SUBSCRIPTION_PAYMENT use positive)
- Replace duplicate _get_user_promo_offer_discount_percent in
  monitoring_service with shared get_user_active_promo_discount_percent
2026-03-05 07:25:27 +03:00
Fringg b8857e789e fix: consume promo offer in miniapp tariff-mode renewal path
The tariff-mode renewal in miniapp applied promo_offer_discount_percent
to final_total but never passed consume_promo_offer to subtract_user_balance,
allowing infinite reuse of first-purchase-only promo discounts via miniapp.
2026-03-05 07:15:41 +03:00
Fringg 5f2d855702 fix: add missing mark_as_paid_subscription, fix operation order, remove dead code
- Add mark_as_paid_subscription=True to cabinet trial activation
- Reorder menu.py: charge balance BEFORE creating subscription (prevents orphaned subscription)
- Remove dead _consume_user_promo_offer_discount method from monitoring_service (55 lines)
- Remove unused imports (get_latest_claimed_offer_for_user, log_promo_offer_action)
- Fix inconsistent _get_promo import alias to use full function name
2026-03-05 07:02:12 +03:00
Fringg 0466528925 fix: centralize balance deduction and fix unchecked return values
- Replace inline SELECT FOR UPDATE in renew_subscription with subtract_user_balance
- Replace direct balance_kopeks -= in trial activation with subtract_user_balance
- Add success checks to 4 unchecked subtract_user_balance calls (devices x2, menu, tariff switch)
- Add consume_promo_offer to monitoring_service autopay (was non-atomic)
- Add mark_as_paid_subscription=True to trial_activation_service, daily_subscription_service, admin purchase paths
- Remove 3 redundant has_had_paid_subscription assignments in auto_purchase_service
- Fix stale cart consume_promo_offer: compute from live user state instead of cart data
2026-03-05 06:45:57 +03:00
Fringg e4a6aad621 fix: centralize has_had_paid_subscription into subtract_user_balance
Add mark_as_paid_subscription parameter to subtract_user_balance() that
atomically sets has_had_paid_subscription=True within the same FOR UPDATE
transaction as the balance deduction. This closes ALL purchase paths:

- Cabinet renew: add SELECT FOR UPDATE row lock (fix race condition),
  set has_had_paid_subscription atomically, remove standalone call
- Cabinet purchase_tariff: pass consume_promo_offer to subtract_user_balance
  (fix: inline clearing was wiped by db.refresh), remove standalone call
- Cabinet switch_tariff: add mark_as_paid_subscription=True
- Auto-extend: add mark_as_paid_subscription, remove standalone call
- Auto-purchase tariff: add consume_promo_offer + mark_as_paid_subscription
- Auto-purchase daily: add mark_as_paid_subscription
- Bot purchase/extend/trial handlers: add mark_as_paid_subscription
- All 8 tariff_purchase.py handlers: add mark_as_paid_subscription
- Both simple_subscription.py handlers: add mark_as_paid_subscription
- Menu smart activation: add mark_as_paid_subscription
- Monitoring autopay: add mark_as_paid_subscription
- Renewal service finalize: add mark_as_paid_subscription
- MiniApp purchase service: add mark_as_paid_subscription, remove standalone
- MiniApp renewal/tariff/switch: add mark_as_paid_subscription
2026-03-05 06:29:34 +03:00
Fringg 2cec8dc4a4 fix: prevent infinite reuse of first_purchase_only promo code discounts
- Add consume_promo_offer flag to all cabinet cart_data dicts (renew, daily tariff, non-daily tariff) so auto-purchase service clears discount fields after purchase
- Add mark_user_as_had_paid_subscription calls after cabinet renew and tariff purchase to prevent re-activation of first_purchase_only promo codes
- Add mark_user_as_had_paid_subscription to auto-purchase service for non-trial purchases
2026-03-05 06:14:41 +03:00
Fringg 667291a2dc fix: redis cache uses sync client due to import shadowing
import redis.exceptions overwrites the redis name binding from
import redis.asyncio as redis, causing from_url() to create a
sync client. ping() then returns bool instead of coroutine.

Fix: from redis.exceptions import NoScriptError
2026-03-05 06:00:30 +03:00
Fringg eff74bed5b fix: auto-update permissions for system roles on bootstrap
Previously preset roles were only seeded on first run. Now if a
system role's permissions differ from the preset definition, they
are updated automatically on startup.
2026-03-05 05:53:07 +03:00
Fringg 8f29e2eee2 feat: add dedicated sales_stats RBAC permission section
Separate sales statistics permissions from general stats:
- Add sales_stats section to PERMISSION_REGISTRY (read, export)
- Update all 6 sales-stats endpoints to require sales_stats:read
- Add sales_stats:* to Admin preset, sales_stats:read to Marketer preset
2026-03-05 05:46:01 +03:00
Fringg 9d7a557ef0 fix: показывать только активные провайдеры на странице /profile/accounts
Заменён хардкод _ALL_PROVIDERS на _get_active_providers():
- Telegram — всегда
- Email — только при CABINET_EMAIL_AUTH_ENABLED
- OAuth — только включённые в настройках (OAUTH_*_ENABLED)
2026-03-05 05:34:01 +03:00
Fringg 2664b4956d feat: account merge system — atomic user merge with full FK coverage
- Реализован execute_merge: атомарное слияние двух аккаунтов (primary поглощает secondary)
- Покрыты все 54 FK на users.id (38 таблиц): платежи, подписки, реферралы, тикеты, аудит
- Admin-actor FK (created_by, processed_by, admin_id, assigned_by, actor_user_id) — SET NULL
- User-ownership FK — переназначение на primary
- Dedup-then-reassign для таблиц с unique constraints
- Cross-referral deletion для ReferralEarning и ReferralContestEvent
- UserRole secondary удаляются (защита от эскалации привилегий)
- Merge token: Redis GETDEL (атомарное потребление), restore при ошибке
- Preview endpoint с rate limiting по IP
- Перенос баланса, email, telegram_id, OAuth провайдеров, партнёрского статуса
2026-03-05 05:23:39 +03:00
Fringg f7caf0de70 refactor: extract shared OAuth linking logic, add Literal types for providers
- Extract _exchange_and_link_oauth() helper to deduplicate link_provider_callback
  and link_server_complete (exchange code, fetch user info, check conflict, link)
- Use Literal['google','yandex','discord','vk'] for provider path parameters
  (FastAPI validates automatically, removes manual checks)
- Add safe int parsing for user_id from state with proper error handling
- Remove redundant provider validation checks (handled by Literal type)
2026-03-05 03:12:17 +03:00
Fringg 0c1dc580c6 fix: add IntegrityError handling on link commit and format fixes
- Wrap db.commit() in try/except IntegrityError for both
  link_provider_callback and link_server_complete (race condition guard)
- Fix ruff format issues (line wrapping)
2026-03-05 02:33:24 +03:00
Fringg f867989557 feat: add server-complete OAuth linking endpoint for Mini App flow
- Add POST /link/server-complete endpoint (no JWT, auth via state token)
- Make provider optional in ServerCompleteRequest (resolved from Redis)
- Make provider optional in validate_oauth_state (skip check if None)
- Endpoint validates linking state, exchanges code, links or creates merge
2026-03-05 02:24:32 +03:00
Fringg 467dea1315 fix: review findings — exception chaining, redundant unquote, validator tightening
- Add `from exc` to IntegrityError raise for consistent exception chaining
- Remove redundant unquote() in validate_telegram_init_data (parse_qsl already decodes)
- Tighten model_validator to require all 3 widget fields (id, auth_date, hash) together
- Extract _MAX_CLOCK_SKEW_SECONDS constant replacing magic number -300
- Use logger.exception() instead of logger.error(exc_info=True) in 2 places
2026-03-04 17:21:14 +03:00
Fringg da40d5662d feat: add Telegram account linking endpoint with security hardening
- POST /cabinet/auth/account/link/telegram supporting both initData (Mini App) and Login Widget flows
- Pydantic model_validator enforces mutual exclusivity of init_data vs widget fields
- IntegrityError handling for TOCTOU race on telegram_id UNIQUE constraint
- Username guard: only set if user has no existing username
- Max-length constraints on all string fields
- Future auth_date rejection (< -300s) in both validation functions
2026-03-04 17:03:40 +03:00
Fringg 7b4e9488f6 fix: clean email verification and password fields from secondary user during merge 2026-03-04 16:21:00 +03:00
Fringg d7a9d2bfba fix: reassign orphaned records on merge, eliminate TOCTOU race
- Reassign SubscriptionConversion, SubscriptionEvent, DiscountOffer
  from secondary to primary during merge (previously orphaned)
- Consume-first pattern: atomically GETDEL merge token before
  validation, restore on invalid input (eliminates TOCTOU window)
2026-03-04 16:05:23 +03:00
Fringg 531d5cff30 fix: negative balance transfer, linking state validation, referrer migration
- Transfer negative balances on merge (debt must not vanish)
- Validate OAuth state was initiated for account linking flow
- Transfer secondary's referrer to primary when primary has none
- Type MergePreviewSubscription schema (replace dict[str, Any])
- Cap restore_merge_token TTL to prevent clock-skew extension
- Add 4 new tests (negative balance, referrer transfer scenarios)
2026-03-04 15:57:03 +03:00
Fringg 8ee97ba1ba test: relax hardcoded execute count, add telegram_id conflict assertion
- Change == 17 to >= 17 so test doesn't break on new bulk updates
- Assert secondary.telegram_id is None in conflict test
2026-03-04 15:46:51 +03:00
Fringg 0e8c61a776 fix: use short TTL fallback in restore_merge_token on parse error
Fail closed with 60s instead of full 30min TTL when created_at cannot
be parsed, preventing accidental token lifetime extension.
2026-03-04 15:35:20 +03:00
Fringg 9582758d1c fix: restore merge token on DB failure, fix partner_status priority
- Add restore_merge_token() to re-store consumed token if execute_merge
  or db.commit fails, allowing the user to retry instead of being stuck
- Fix partner_status priority: PENDING (2) now beats REJECTED (1), so
  an active application is not lost during merge
- Add tests for pending-vs-rejected edge cases (47 tests total)
2026-03-04 15:29:50 +03:00
Fringg f204b67880 fix: delete cross-referral earnings before bulk reassignment, clear secondary.referred_by_id
Prevents data corruption when merging accounts that have mutual referral
relationships. Cross-referral ReferralEarning rows are now deleted before
any bulk UPDATE to avoid self-referral records. Secondary's referred_by_id
is cleared during cleanup to prevent orphaned FK references.
2026-03-04 15:22:23 +03:00
Fringg db61365e11 fix: prevent self-referral loops, invalidate all sessions on merge
- Add User.id != primary.id filter to referred_by_id reassignment to
  prevent self-referral loops when primary was referred by secondary
- Clear primary.referred_by_id if it pointed to secondary
- Add exclusion filter to ReferralEarning.referral_id reassignment to
  prevent user_id == referral_id rows
- Invalidate refresh tokens for BOTH primary and secondary during merge
  (primary gets a fresh session after merge)
- Fix duplicate step 4 comment numbering in execute_merge_endpoint
- Add referred_by_id field to test fixture _make_user
2026-03-04 15:01:51 +03:00
Fringg bc1e6fb22c fix(merge): validate before consuming token, add flush, defensive balance
- Validate keep_subscription_from BEFORE consuming merge token (read
  first with get_merge_token_data, then consume) — prevents token loss
  on validation failure
- Add missing await db.flush() after db.delete(secondary_sub) in
  keep_subscription_from='primary' branch (consistency with 'secondary')
- Capture transferred_kopeks in local var before zeroing secondary
  balance (defensive against log reordering)
2026-03-04 08:12:10 +03:00
Fringg 64ee0459e4 fix: second round review fixes for account merge
- Rename _compute_auth_methods to compute_auth_methods (public API)
- Add Literal type to _handle_subscription_merge param
- Add Literal type to keep_from in route handler
- Add Path(min_length=32, max_length=64) on merge_token params
- Import Path and Literal in account_linking routes
2026-03-04 07:55:26 +03:00
Fringg d855e9e47f fix: harden account merge security and correctness
- Clear ALL unique constraint fields on secondary user after merge
  (telegram_id, OAuth IDs, email, referral_code, remnawave_uuid)
- Add Literal type + runtime validation for keep_subscription_from
- Reject merge when primary user is deleted
- Validate OAuth state user_id matches authenticated user in link callback
- Replace leaked ValueError messages with generic error detail
- Fix exc_info usage for idiomatic structlog
- Fix _get_remnawave_api return type to AsyncIterator
- Remove unnecessary from __future__ import annotations
- Add 3 new tests (42 total, all passing)
2026-03-04 07:46:07 +03:00
Fringg dc7b8dc72a feat: account linking and merge system for cabinet
Add OAuth provider linking/unlinking endpoints, merge token service
(Redis-backed, 30-min TTL), and atomic account merge executor that
transfers OAuth IDs, telegram_id, email, balance, subscriptions,
transactions, payments, referral data, and partner status between
two user accounts. Unchosen subscription is deleted from RemnaWave
with disable as fallback.

Includes 39 unit tests covering all merge scenarios.
2026-03-04 07:24:15 +03:00
Egor 57b5216306 Merge pull request #2663 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.22.0
2026-03-04 06:14:51 +03:00
github-actions[bot] e249bff5d6 chore(main): release 3.22.0 2026-03-04 03:14:27 +00:00
Egor 85489cff3f Merge pull request #2662 from BEDOLAGA-DEV/dev
Dev
2026-03-04 06:14:02 +03:00
Fringg 57aaca82f5 fix: empty JSONB values exported as None in backup
`if value` treated [] and {} as falsy, losing empty JSONB arrays/dicts
during backup export. Changed to `if value is not None`.
2026-03-04 06:11:15 +03:00
Fringg ff1c8722c9 fix: backup restore fails on FK constraints and transaction poisoning
Root cause: 7 tables (admin_audit_log, admin_roles, user_roles,
access_policies, partner_applications, required_channels,
user_channel_subscriptions) were missing from backup/restore.
DELETE FROM users hit FK constraint from admin_audit_log, poisoning
the entire PostgreSQL transaction — all subsequent operations failed.

Fixes:
- Add 8 missing models to backup (+ CabinetRefreshToken)
- Replace individual DELETE FROM with TRUNCATE ... CASCADE
  (handles FK deps automatically, resets sequences)
- Fallback: per-table TRUNCATE with savepoints if batch fails
- Fix _restore_users_without_referrals: wrap flush in savepoint
  instead of db.rollback() which killed entire transaction
- Add sync_postgres_sequences() after ORM restore to prevent
  PK conflicts before bot restart
2026-03-04 06:03:14 +03:00
Fringg 018f18fa0c fix: MissingGreenlet on campaign registrations access
Access registrations from instance dict instead of ORM descriptor
to avoid lazy load triggering MissingGreenlet in async context.
2026-03-04 05:55:44 +03:00
Fringg eaeee7a765 fix: handle duplicate remnawave_uuid on email sync
- Check if another user already owns the panel UUID before assigning
- Rollback + refresh user on sync failure instead of leaving session dirty
- Save user.email before try block for safe error logging
2026-03-04 05:49:38 +03:00
Fringg 618c936ac9 fix: close remaining daily subscription expire paths
- get_all_subscriptions: add selectinload(tariff) so validate_and_fix guard works
- get_subscriptions_batch: add selectinload(tariff) for sync flows
- get_expiring_subscriptions: exclude active daily subs (prevents spurious notifications)
- update_remnawave_user: add daily guard to prevent expire during panel sync
- _handle_user_disabled webhook: add daily guard to prevent deactivation
2026-03-04 05:46:37 +03:00
Fringg 0ed6397fa9 fix: prevent daily subscriptions from being expired by middleware/CRUD/webhook
Daily subscriptions have end_date = +24h, and between 30-min check cycles
they would get expired by 5 different code paths before DailySubscriptionService
could charge and renew them. Users saw "subscription expired" while having balance.

Root cause fixes (6 paths protected):
- subscription_checker middleware: skip active daily subscriptions
- check_and_update_subscription_status CRUD: skip active daily subscriptions
- monitoring_service: run autopay BEFORE expired check, expand query to
  include recently-expired subscriptions (2h window)
- remnawave_webhook_service: _handle_user_expired skips daily tariffs
- remnawave_service: validate_and_fix_subscriptions skips daily tariffs

Recovery mechanisms:
- New get_expired_daily_subscriptions_for_recovery() CRUD function
- DailySubscriptionService.process_auto_resume() restores DISABLED (balance
  topped up) and EXPIRED (incorrectly expired) daily subscriptions
- Runs before daily charges in each monitoring cycle
2026-03-04 05:12:19 +03:00
Fringg dce9eaa597 fix: reset traffic purchases on expired subscription renewal + pricing fixes
- Reset TrafficPurchase records and purchased_traffic_gb when renewing
  expired subscriptions (was incorrectly preserving stale purchases,
  inflating traffic limit e.g. 100GB+20GB=120GB instead of fresh 100GB)
- Fix in extend_subscription() CRUD, cabinet /renew, bot handlers,
  simple_subscription handlers
- Add RemnaWave sync to cabinet /renew endpoint after subscription changes
- Fix device_price_kopeks=0 falsy-zero bug (11+ instances, or → is not None)
- Fix double-increment of purchased_traffic_gb in cabinet traffic purchase
- Fix orphaned TrafficPurchase records in 5 locations (replace_subscription,
  extend_subscription fixed_with_topup, classic mode, switch_tariff,
  purchase.py is_traffic_fixed)
- Fix admin_users.py UnboundLocalError from TrafficPurchase inline import
  shadowing module-level import
- Standardize pricing order: base + devices → promo_group → promo_offer
  across all 5+ pricing paths (cabinet, miniapp, autopay, auto-purchase,
  monitoring)
- Fix exception handlers in calculate_renewal_price (raise instead of
  returning fallback 0)
- Fix monitoring_service double-discount (promo_offer applied twice)
- Fix auto-purchase _get_tariff_price_for_period return type to tuple
  (base_price, discount_percent) so callers add devices before discount
- Pass traffic_limit_gb/device_limit to extend_subscription in
  simple_subscription.py instead of manual overwrites
2026-03-04 04:46:29 +03:00
Fringg 628a99e7aa fix: classic mode prices overridden by active tariff prices
Root cause: ensure_tariffs_synced runs BEFORE bot_configuration_service.initialize(),
so SALES_MODE from system_settings is not yet applied. If SALES_MODE=classic is set
via cabinet (not .env), load_period_prices_from_db sees tariffs mode and loads tariff
prices into _DB_PERIOD_PRICES. Then refresh_period_prices() always prefers
_DB_PERIOD_PRICES over settings.PRICE_*_DAYS, even in classic mode.

Three fixes:
1. refresh_period_prices() now checks settings.is_tariffs_mode() before using
   _DB_PERIOD_PRICES — classic mode always uses settings.PRICE_*_DAYS
2. initialize() calls refresh_period_prices() after all DB overrides are applied,
   so SALES_MODE is correct when prices are recalculated
3. Switching SALES_MODE to classic via cabinet now clears _DB_PERIOD_PRICES
2026-03-04 03:12:34 +03:00
Fringg 4d74afd711 fix: add selectinload for campaign registrations in list query
MissingGreenlet error when accessing campaign.registrations
in show_campaigns_list handler — lazy load not supported in async.
2026-03-04 02:53:29 +03:00
Fringg e2c9aab7ba chore: sync uv.lock with pyproject.toml version 2026-03-03 01:57:13 +03:00
Fringg e23d69fcec feat: replace pip with uv in Dockerfile
- Use uv 0.10.7 with pyproject.toml + uv.lock instead of pip + requirements.txt
- Bind mounts for pyproject.toml/uv.lock with BuildKit cache for faster rebuilds
- UV_COMPILE_BYTECODE=1 for pre-compiled .pyc, UV_LINK_MODE=copy for multi-stage
- UV_PYTHON_DOWNLOADS=never to prevent uv from downloading its own Python
- Replace wget healthcheck with Python stdlib (removes apt layer from runtime)
- Increase start-period to 60s for migration headroom
- Fix redundant chown -R on entire /app
- Add .venv, tests, .mypy_cache, .ruff_cache to .dockerignore
2026-03-03 01:55:39 +03:00
anatoliy 1afcd84e0e fix: photo handling in QR messages
Add check to ensure photo is only used for non-QR messages
2026-03-02 23:57:34 +03:00
Egor e850419f10 Merge pull request #2656 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.21.0
2026-03-02 22:28:11 +03:00
github-actions[bot] 360d579415 chore(main): release 3.21.0 2026-03-02 19:27:36 +00:00
Egor c67f55fe0d Merge pull request #2654 from BEDOLAGA-DEV/dev
Dev
2026-03-02 22:26:56 +03:00
Fringg 310edae013 fix: use float instead of int | float (PYI041) 2026-03-02 22:25:06 +03:00
Fringg 8fb97d9359 chore: ruff format 3 files 2026-03-02 22:23:43 +03:00
Fringg d33c5d6c07 feat: add daily deposits by payment method breakdown
Add daily_by_method field to deposits endpoint with GROUP BY
(date, payment_method) query. Uses raw column instead of coalesce
since base_filter already excludes NULLs via .in_(REAL_PAYMENT_METHODS).
2026-03-02 22:05:57 +03:00
Fringg 2449a5cbbe feat: add daily device purchases chart to addons stats
- Add DailyDeviceItem schema and daily_devices field to AddonsStatsResponse
- Query device transactions grouped by date reusing existing device_filter
2026-03-02 21:54:34 +03:00
Fringg e5f29eb041 fix: resolve GROUP BY mismatch for daily_by_tariff query
Use a single coalesce expression object shared across SELECT, GROUP BY,
and ORDER BY clauses so PostgreSQL sees the same expression reference
instead of separately parameterized literals.
2026-03-02 21:45:55 +03:00
Fringg 31c7e2e9c1 feat: enhance sales stats with device purchases, per-tariff daily breakdown, and registration tracking
- Add device purchase count and revenue to addons endpoint (filter by 'устройств' in transaction descriptions)
- Add daily_by_tariff series to sales endpoint (group subscriptions by date and tariff name)
- Split trials daily data into separate registrations and trials series with date union merge
- Add total_registrations count to trials stats response
2026-03-02 21:41:50 +03:00
Fringg e25fcfc6ef fix: renewals stats empty on all-time filter
For "all time" period, define renewals as users with >1 subscription
payment (repeat customers) instead of filtering by created_at < 2020
which always yields empty results.
2026-03-02 21:15:04 +03:00
Fringg b2cf4aaa91 fix: eliminate double panel API call on tariff change, harden cart notification
Bug 1 improvement: Replaced double API call pattern (sync + update_remnawave_user)
with single _sync_subscription_to_panel call that accepts reset_traffic parameter.
This prevents TRIAL status being overwritten to EXPIRED by the second call's
different status computation logic.

Bug 2 improvement: Moved keyboard construction inside try block to prevent
AttributeError crash if locale keys are missing. Switched button text from
attribute access (texts.KEY) to defensive texts.get('KEY', fallback).
Added empty template guard to prevent sending empty messages to Telegram API.
2026-03-02 20:53:59 +03:00
Fringg 1256ddcd1a fix: restore panel user discovery on admin tariff change, localize cart reminder
Bug 1: Admin tariff change used update_remnawave_user() which returns
early when user has no remnawave_uuid. Restored _sync_subscription_to_panel()
which discovers/creates panel users via telegram_id/email fallback, then
applies traffic reset if RESET_TRAFFIC_ON_TARIFF_SWITCH is enabled.

Bug 2: Post-topup cart reminder in payment/common.py had hardcoded Russian
text sent to all users regardless of language. Replaced with localized
BALANCE_TOPPED_UP_CART_SUFFICIENT/INSUFFICIENT keys and used existing
MY_BALANCE_BUTTON/MAIN_MENU_BUTTON for inline keyboard buttons.
Added new i18n keys to all 5 locales (ru, en, ua, zh, fa).
2026-03-02 20:48:02 +03:00
Fringg 58faf9eaec feat: add admin sales statistics API with 6 analytics endpoints
- Add /cabinet/admin/stats/sales/* endpoints: summary, trials,
  subscriptions, renewals, addons, deposits
- Period params: days preset or custom start_date/end_date range
- MAX_PERIOD_DAYS=730 validation with proper date parsing
- Conversion rate capped at 100% to handle cross-period conversions
- Use EXTRACT(epoch)/86400 for accurate interval day calculation
- Consolidated subscription queries with CASE expressions
- Renewals with period-over-period comparison and trend detection
- Permission-gated with require_permission('stats:read')
- Shared link utilities in cabinet/utils/links.py
2026-03-02 20:35:09 +03:00
Fringg ded5c899f7 fix: improve campaign routes, schemas, and add database indexes
- Use PartnerStatus.APPROVED.value instead of hardcoded 'approved'
- Extract shared deep_link/web_link helpers to cabinet/utils/links.py
- Add _safe_div() helper for None-safe division
- Add try/except error handling on campaign endpoints
- Use model_fields_set for PATCH-style field detection
- Replace deprecated class Config with ConfigDict(from_attributes=True)
- Remove unnecessary selectinload(registrations) from campaign list
- Extract _calc_change to module-level in partner_stats_service
- Add composite indexes for stats queries on Subscription, Transaction,
  SubscriptionConversion, and TrafficPurchase models
2026-03-02 20:34:57 +03:00
Fringg fa7de589c1 feat: add admin campaign chart data endpoint with deposits/spending split
- Add get_admin_campaign_chart_data() to PartnerStatsService with daily registrations, revenue trends, period comparison, and top registrations
- Add total_deposits_kopeks and total_spending_kopeks as separate aggregates
- Add 6 Pydantic schemas for admin chart data response
- Add GET /{campaign_id}/chart-data endpoint with campaigns:stats permission
- Add partner application endpoints and schemas for campaign detailed stats
2026-03-02 06:10:30 +03:00
Fringg 69868418e5 style: format 6 files with ruff 2026-03-02 04:35:16 +03:00
Fringg 062c4865db fix: add min_length to state field, use exc_info for referral warning 2026-03-02 04:34:18 +03:00
Fringg 1dfa78013c fix: migrate VK OAuth to VK ID OAuth 2.1 with PKCE
VK deprecated oauth.vk.com on Sep 30, 2025. Migrate to VK ID (id.vk.ru)
with mandatory PKCE S256 and device_id support.

- Rewrite VKProvider: new endpoints, PKCE code_verifier/challenge, user_info format
- Add prepare_auth_state() hook for provider-specific state (PKCE)
- Use atomic Redis GETDEL for OAuth state validation (prevent TOCTOU race)
- Add CacheService.getdel() method
- Check cache.set() result in generate_oauth_state
- Filter ephemeral keys (_prefix) from Redis storage
- Fix garbled log messages, use exc_info for tracebacks
- Add input validation (min_length, max_length on code/state)
- Generic error messages (no provider name leakage)
2026-03-02 04:10:01 +03:00
Fringg 60c97f778b fix: eliminate referral system inconsistencies
- Fix balance history display: referral_reward, refund, poll_reward now
  shown as credits (💰 +amount) instead of expenses
- Fix double-counting: remove all Transaction-based REFERRAL_REWARD sum
  queries from crud/referral.py, admin_stats.py, admin_users.py —
  ReferralEarning is now the single source of truth
- Unify "active referrals" definition across cabinet, bot, and admin:
  JOIN Subscription WHERE status=ACTIVE AND end_date > now()
- Add payment_method IS NOT NULL guard to get_user_own_deposits() to
  exclude referral rewards historically mistyped as deposits
- Replace hardcoded transaction type strings with TransactionType enum
  values in referral_withdrawal_service.py
- Add Alembic data migration (0014) to fix historical transactions:
  UPDATE deposit → referral_reward WHERE payment_method IS NULL and
  description matches referral patterns
2026-03-02 02:25:32 +03:00
Fringg 83c6db4834 fix: correct referral withdrawal balance formula and commission transaction type
The available_referral formula incorrectly treated all post-earning spending
as spent from referral balance, making withdrawable balance stay at 0 even
as earnings increased. Changed to min(wallet_balance, earned - withdrawn - pending).

- Fix available_referral in withdrawal service and referral info endpoint
- Use TransactionType.REFERRAL_REWARD for all commission/bonus balance additions
- Gate create_referral_earning behind add_user_balance success check
- Move notifications inside balance_ok guards to prevent false confirmations
2026-03-02 01:35:24 +03:00
Fringg ed3ae14d0c fix: partner system — CRUD nullable fields, per-campaign stats, atomic unassign, diagnostic logging
- Fix update_campaign() CRUD to allow setting nullable fields (partner_user_id, tariff_id, etc.) to None
- Add per-campaign statistics (registrations, referrals, earnings) to partner detail page
- Scope registrations_count to partner-referred users only (JOIN with User.referred_by_id)
- Make unassign_campaign atomic (UPDATE...WHERE) to prevent TOCTOU race condition
- Add audit logging to campaign assign/unassign with admin_id
- Add diagnostic logging to process_referral_topup and commission resolution
- Document process_referral_purchase as intentionally unused (no double-commission)
2026-03-02 01:09:47 +03:00
Fringg 69a9899d40 fix: use direct is_trial access, add missing error codes to promo APIs
- Use subscription.is_trial instead of getattr for reliable check
- Fix structlog key typo: format_user_log → _format_user_log
- Add missing error codes (active_discount_exists, not_first_purchase,
  daily_limit) to miniapp and cabinet promo code endpoints
2026-03-01 23:43:04 +03:00
Fringg e32e2f779d fix: reject promo codes for days when user has no subscription or trial
SUBSCRIPTION_DAYS promo codes now require an active or expired non-trial
subscription. Users without any subscription or with a trial subscription
get a clear error message instead of silently creating/extending.
2026-03-01 23:39:02 +03:00
Fringg ccb61d6473 chore: remove dead BALANCE_TOPUP_CART_REMINDER_DETAILED keys and unused cryptobot cart payload 2026-03-01 23:28:26 +03:00
Fringg 2fab50c340 fix: correct cart notification after balance top-up
- Remove misleading "Важно" and "При наличии корзины" warnings from all
  payment success notifications
- Fix cart total bug: show actual cart price from Redis instead of top-up
  amount, and suppress "insufficient funds" when balance is enough
- Extract shared send_cart_notification_after_topup() in common.py to
  replace duplicated code across all 10 payment providers
2026-03-01 23:09:49 +03:00
Fringg 69b5ca0670 fix: use .is_(True) and add or 0 guards per code review 2026-03-01 21:24:32 +03:00
Fringg 06c3996da4 fix: count sales from completed payment transactions instead of subscription created_at
Previously 'Продажи' stats counted by Subscription.created_at which only
reflects initial creation date. Renewals update end_date on existing record
without changing created_at, so renewals were never counted as sales.

Now counts completed SUBSCRIPTION_PAYMENT transactions which are created
for every purchase and renewal. Also standardized date boundaries to use
explicit midnight UTC datetime instead of date objects.
2026-03-01 21:17:05 +03:00
Fringg faba3a8ed6 fix: enforce user restrictions in cabinet API and fix poll history crash
- Add restriction_topup check to POST /cabinet/balance/topup
- Add restriction_subscription check to 6 subscription endpoints:
  /renew, /purchase, /purchase-tariff, /traffic, /devices/purchase, /devices (legacy)
- All restricted endpoints return 403 Forbidden
- Fix TypeError in broadcast history when message_text is None (polls)
2026-03-01 20:59:06 +03:00
Fringg 4c72058d4a fix: generate missing crypto link on the fly and skip unresolved templates
Root cause: sync uses enrich_happ_links=False so subscription_crypto_link
is empty for 31k+ synced users. RemnaWave config buttons use
{{HAPP_CRYPT4_LINK}} template which stays unresolved, and since
the unresolved template is truthy it prevents the subscriptionUrl fallback
in the frontend — isValidDeepLink fails (no ://) and button is not rendered.

Fixes:
- /app-config endpoint: generate crypto link via encrypt API when missing,
  persist to DB so it's only generated once per user
- Template enrichment: skip setting resolvedUrl when templates remain
  unresolved, allowing frontend to fall through to subscriptionUrl
2026-02-27 23:04:58 +03:00
Fringg 9c004791f2 fix: prevent sync from overwriting subscription URLs with empty strings
- Guard sync update to only overwrite subscription_url when panel_url is non-empty
- Add fallback in /app-config and /subscription endpoints to fetch subscription URL
  from RemnaWave panel when missing in local DB (auto-heals synced users on access)
2026-02-27 22:42:04 +03:00
Fringg cdcabee80d fix: handle NULL used_promocodes for migrated users
Migrated EvoVPN users have NULL used_promocodes in DB.
Pydantic v2 doesn't apply field default when None is passed explicitly.
2026-02-27 22:06:42 +03:00
Fringg 9ae5d7bb60 fix: handle expired ORM attributes in sync UUID mutation
Two fixes for MissingGreenlet during panel user synchronization:

1. _capture_user_state: catch exceptions when reading potentially
   expired attributes (updated_at, remnawave_uuid). SQLAlchemy throws
   MissingGreenlet, not AttributeError, so getattr default doesn't help.
   Use sentinel to skip restoring uncaptured attrs on rollback.

2. Update branch: refresh db_user before sync _ensure_user_remnawave_uuid
   call if any attributes are expired (detected via sa_inspect).
2026-02-27 21:53:54 +03:00
Fringg efdf2a3189 fix: add exc_info traceback to sync user error log
Helps pinpoint exact location of MissingGreenlet errors during
panel user synchronization.
2026-02-27 21:42:57 +03:00
Fringg 2a90f871b9 fix: use SAVEPOINT instead of full rollback in sync user creation
Full db.rollback() in _get_or_create_bot_user_from_panel expires ALL
ORM objects in the session, causing MissingGreenlet errors when
subsequent sync iterations access user attributes from synchronous code.

Replace with begin_nested() (SAVEPOINT) so only the failed INSERT is
rolled back while the parent transaction and all cached objects remain
valid.
2026-02-27 21:32:10 +03:00
Fringg b47678cfb0 fix: remove premature tariff_id assignment in _apply_extension_updates
_apply_extension_updates was setting subscription.tariff_id before
extend_subscription() ran, causing the CRUD's is_tariff_change
detection to always return False. This skipped TrafficPurchase
cleanup and purchased_traffic_gb reset on auto-purchase tariff changes.

extend_subscription() already handles tariff_id assignment internally.
2026-02-27 10:19:15 +03:00
Fringg d708365aca fix: sync traffic reset across all tariff switch code paths
- cabinet admin change_tariff: add full reset logic (traffic_used_gb,
  purchased_traffic_gb, TrafficPurchase deletion, RemnaWave sync)
- cabinet switch_tariff: add local traffic_used_gb reset
- miniapp switch_tariff: add local traffic_used_gb reset + TrafficPurchase deletion
- auto_purchase_service: fix or→if/else branching for reset_traffic logic
2026-02-27 10:10:21 +03:00
Fringg 2cdbbc09ba fix: add local traffic_used_gb reset in all tariff switch handlers
- admin users handler: add reset_traffic param + local traffic_used_gb reset
- confirm_daily_tariff_switch: add local traffic_used_gb reset before commit
- confirm_instant_switch: add local traffic_used_gb reset before commit

Ensures DB traffic counter stays in sync with RemnaWave panel reset.
2026-02-27 10:03:46 +03:00
Fringg 4eaedd33bf feat: add RESET_TRAFFIC_ON_TARIFF_SWITCH admin setting
New boolean setting (default: True) controls whether user traffic
is reset when switching between tariff plans.

Changes:
- config.py: add RESET_TRAFFIC_ON_TARIFF_SWITCH setting
- system_settings_service.py: category override (TRAFFIC) + hints
- pricing.py: admin bot handler toggle entry
- cabinet/routes/subscription.py: pass reset_traffic to RemnaWave on switch
- webapi/routes/miniapp.py: same for miniapp tariff switch
- tariff_purchase.py: use setting in 3 switch handlers (was hardcoded)
- subscription_auto_purchase_service.py: separate tariff switch vs payment logic
- crud/subscription.py: conditional traffic_used_gb reset on tariff change
2026-02-27 09:57:37 +03:00
Fringg f605d8a39c chore: ruff format 4 files 2026-02-27 06:48:35 +03:00
Fringg cc5be7059f fix: address review findings from agent verification
Throttling:
- Init _last_cleanup with time.monotonic() instead of 0.0
- Use split(maxsplit=1) to avoid unnecessary list allocation
- Downgrade general throttle log from warning to debug

ChannelChecker:
- Guard from_user None in Update branch (lines 98-101)
- Widen TelegramBadRequest → TelegramAPIError to catch 403 Forbidden

Renewal pricing:
- Fix double-charging when base_traffic <= 0: pass purchased_traffic
  as sole traffic_limit and clear purchased_traffic flag to prevent
  the add-on block from adding it again
2026-02-27 05:43:04 +03:00
Fringg 739ba2986f fix: separate base and purchased traffic in renewal pricing
When a user has 25GB base + 100GB purchased = 125GB total,
the renewal priced it at the 250GB tier (nearest tier >= 125GB)
instead of pricing each component separately at its own tier:
base 25GB + purchased 100GB.

- Split traffic_limit_gb into base and purchased components
- Price each component at its own tier via get_traffic_price()
- Apply same discount percentage to purchased portion
- Log warning when purchased >= total (data corruption)
- Fix in both subscription_renewal_service and subscription CRUD
2026-02-27 05:32:08 +03:00
Fringg f52e6aedac fix: handle expired callback queries and harden middleware error handling
- Throttling: catch TelegramAPIError instead of bare Exception on .answer()
- Throttling: share single instance across message/callback dispatchers
- Throttling: fix from_user None crash, memory leak (cleanup on timer now)
- Throttling: use time.monotonic(), fix /start matching, fix log messages
- ChannelChecker: wrap .answer() in try/except for expired queries
- ChannelChecker: guard from_user None access
- DisplayNameRestriction: wrap .answer() in try/except TelegramAPIError
2026-02-27 05:21:26 +03:00
Fringg 256cbfcadf fix: email verification bypass, ban-notifications size limit, referral balance API
- Fix CABINET_EMAIL_VERIFICATION_ENABLED=false not working: auto-verify
  users on registration, allow login without verification when disabled
- Fix ban-notifications/send 400 error: paginate get_all_users (size<=1000)
- Add available_balance_kopeks and withdrawn_kopeks to referral info endpoint
2026-02-27 04:53:40 +03:00
Fringg dc3d22f52d fix: include desired_commission_percent in admin notification
Add the field to the notification data dict and render it in the
Telegram message sent to admins on new partner applications.
2026-02-27 04:08:10 +03:00
Fringg 7ea8fbd584 feat: add desired commission percent to partner application
Allow partners to specify their desired commission percentage (1-100%)
when applying. Field is optional and shown to admins during review.

Includes DB model, Alembic migration 0013, schema, route, and service changes.
2026-02-27 04:02:17 +03:00
Fringg b96e819da4 fix: add missing subscription columns migration
Adds last_webhook_update_at, is_daily_paused, last_daily_charge_at,
remnawave_short_uuid to subscriptions table for databases where
these columns were not created by the initial schema migration.
2026-02-27 03:03:43 +03:00
Fringg 399ca86561 fix: hide traffic topup button when tariff doesn't support it
In tariffs mode, check tariff.can_topup_traffic() instead of just
checking tariff_id existence. Prevents showing a button that leads
to an error when the tariff has traffic limits but no topup packages.
2026-02-27 01:01:55 +03:00
Fringg 200f91ef17 fix: freekassa OP-SP-7 error and missing telegram notification
- Replace test@example.com fallback with pool of 20 random emails
  to avoid OP-SP-7 duplicate email errors from payment provider
- Fix metadata_json parsing: handle both dict (SQLAlchemy JSON column)
  and string cases to prevent json.loads crash on dict input
- Add TypeError to exception handler for robustness
2026-02-27 01:00:50 +03:00
Fringg 59f0e42be7 fix: prevent squad drop on admin subscription type change, require subscription for wheel spins
- Fix active_internal_squads sent unconditionally as [] clearing Remnawave squads
- Fix dead code in _change_subscription_type (was_trial saved before mutation)
- Block wheel spins for users without active subscription (API + bot handler)
- Add has_subscription field to wheel config response
- Refund Stars to balance if spin payment arrives without subscription
- Fix SQL injection in promocode lookup (f-string → parameterized query)
- Remove redundant get_or_create_wheel_config call in stars handler
2026-02-27 00:53:46 +03:00
Egor 2044cecc6e Merge pull request #2650 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.20.1
2026-02-25 15:29:42 +03:00
github-actions[bot] ffffccb389 chore(main): release 3.20.1 2026-02-25 12:29:17 +00:00
Egor 28d263fc8d Merge pull request #2649 from BEDOLAGA-DEV/dev
Dev
2026-02-25 15:28:51 +03:00
Fringg bfef7cc629 fix: prevent race condition expiring active daily subscriptions
MonitoringService._check_expired_subscriptions() was marking daily
subscriptions as expired before DailySubscriptionService could charge
and extend them. Now get_expired_subscriptions() excludes active
(non-paused) daily subs — they are managed by DailySubscriptionService.

Also fix cabinet "0m until next charge" display: return None when
next_daily_charge_at is in the past instead of a stale datetime.
2026-02-25 15:07:24 +03:00
Fringg a696896d2c fix: make migrations 0010/0011 idempotent, escape HTML in crash notification
- 0010: add _has_column() guard before adding disable_trial/paid_on_leave
  (columns already exist from 0001 create_all on fresh DB)
- 0011: add _has_table() guard — skip if admin_roles already exists
- startup_notification_service: html.escape() error_type and error_message
  to prevent TelegramBadRequest when error contains <class ...>
2026-02-25 13:48:39 +03:00
Egor fd2e419e8e Merge pull request #2648 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.20.0
2026-02-25 12:49:20 +03:00
github-actions[bot] aaf0263fda chore(main): release 3.20.0 2026-02-25 09:48:22 +00:00
Egor d4d5031cc2 Merge pull request #2647 from BEDOLAGA-DEV/dev
Dev
2026-02-25 12:47:57 +03:00
Fringg b2d7abf5bd fix: resolve ruff lint errors (import sorting, unused variable) 2026-02-25 12:42:26 +03:00
Fringg 0f9f843236 style: format branding routes 2026-02-25 12:40:49 +03:00
Fringg cab425cfac style: format freekassa handler and keyboard files 2026-02-25 12:39:21 +03:00
Fringg 0da0c5547d feat: add separate Freekassa SBP and card payment methods
Split Freekassa into sub-methods: СБП/QR (i=44) and Карты РФ (i=36).
Each method has independent enable/display_name settings, dedicated
handlers, keyboard buttons, and correct payment_system_id routing.
Webhook notifications resolve display name from payment metadata.
2026-02-25 12:32:05 +03:00
Fringg 988d0e5c2f fix: initialize logger in bot_configuration.py
Add missing structlog import and logger initialization.
Without this, any code path hitting logger.info/warning/error
would raise NameError at runtime.
2026-02-25 11:55:07 +03:00
Fringg 1ce91749aa fix: resolve sync 404 errors, user deletion FK constraint, and device limit not sent to RemnaWave
1. Remove pointless HWID reset during auto-sync deactivation — user
   doesn't exist in panel, API returns 404, UUID is cleaned up below.

2. Clean up RESTRICT FK references (AdminAuditLog, WithdrawalRequest,
   AdminRole, UserRole, AccessPolicy) before deleting user to prevent
   IntegrityError on admin_audit_log_user_id_fkey.

3. Fix device limit not being sent to RemnaWave when
   DEVICES_SELECTION_DISABLED_AMOUNT=0: treat 0 as "no forced override"
   instead of sending hwidDeviceLimit:0 (which Remnawave interprets as
   unlimited). Now falls through to subscription.device_limit from tariff.

4. Add info-level logging to POST /api/users (was debug) to match
   existing PATCH logging for device limit diagnostics.
2026-02-25 11:53:49 +03:00
Fringg 731eb24364 fix: remove gemini-effect and noise from allowed background types 2026-02-25 07:43:46 +03:00
Fringg a15403b8b6 feat: add validation to animation config API
- Add Literal type whitelist for background type field
- Add settings dict validation (max 20 keys, no nested objects, bounded values)
- Add opacity (0-1) and blur (0-100) bounds with Pydantic Field constraints
- Fix mutable default dict with Field(default_factory=dict)
2026-02-25 07:13:07 +03:00
Egor ff8f3d02cf Merge pull request #2646 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.19.0
2026-02-25 06:37:01 +03:00
github-actions[bot] 69f57eddd6 chore(main): release 3.19.0 2026-02-25 03:36:23 +00:00
Egor fe567fffa8 Merge pull request #2645 from BEDOLAGA-DEV/dev
Dev
2026-02-25 06:35:59 +03:00
Fringg f300e07ce2 chore: ruff format 2026-02-25 06:34:22 +03:00
Fringg 628997fb48 fix: stack promo group + promo offer discounts in bot (matching cabinet) 2026-02-25 05:49:09 +03:00
Fringg 3dc0b93bdf fix: always include details in successful audit log entries 2026-02-25 05:31:32 +03:00
Fringg bea9da96d4 feat: capture query params in audit log details for all requests 2026-02-25 05:24:16 +03:00
Fringg 388fc7ee67 feat: add resource_type and request body to audit log entries 2026-02-25 05:11:43 +03:00
Fringg f6b6e22a95 feat: allow editing system roles 2026-02-25 04:45:41 +03:00
Fringg 60c4fe2e23 feat: add granular user permissions (balance, subscription, promo_group, referral, send_offer)
Split users:edit into fine-grained permissions for balance management,
subscription actions, promo group editing, referral commission, and
sending promo offers.
2026-02-25 04:42:32 +03:00
Fringg c1da8a4dba fix: RBAC audit log action filter and legacy admin level
- Change audit log action filter from exact match to ILIKE substring
  search so admins can search by partial action names
- Return level 1000 (not 999) for legacy config-based admins in
  /me/permissions so frontend correctly enables role management buttons
2026-02-25 04:07:09 +03:00
Fringg af6686ccfa fix: extract real client IP from X-Forwarded-For/X-Real-IP headers
Behind Docker reverse proxy, request.client.host always returns
the proxy container IP (172.20.0.2). Now reads X-Forwarded-For
first, then X-Real-IP, falling back to request.client.host.
2026-02-25 03:49:33 +03:00
Fringg 8893fc128e fix: grant legacy config-based admins full RBAC access
Legacy admins (ADMIN_IDS/ADMIN_EMAILS) had no RBAC roles in DB,
so check_permission returned 'No active roles assigned' and
role_level was 0, disabling all role management UI.

- check_permission: bypass RBAC for legacy admins
- get_user_permissions: return *:* and level 999 for legacy admins
- _get_admin_level: legacy admins get level 1000 (above superadmin)
2026-02-25 03:47:37 +03:00
Fringg 4598c2785a fix: RBAC API response format fixes and audit log user info
- Simplify permission registry to return flat list[PermissionSection] with actions as list[str]
- Add user_first_name and user_email to audit log entries via selectinload
- Fix unused import and naming convention lint warnings
2026-02-25 03:40:40 +03:00
Fringg 5a7dd3f164 fix: align RBAC route prefixes with frontend API paths
Frontend expects /admin/rbac/* namespace but backend used /admin/roles,
/admin/policies, /admin/audit-log. Updated:
- admin_roles.py: prefix /admin/roles → /admin/rbac, endpoints get /roles prefix
- admin_policies.py: prefix /admin/policies → /admin/rbac/policies
- admin_audit_log.py: prefix /admin/audit-log → /admin/rbac/audit-log
- assignments endpoints: /assign → /assignments
- role users endpoint: GET /roles/{role_id}/users with per-role filtering
2026-02-25 03:28:14 +03:00
Fringg bc7d0612f1 fix: specify foreign_keys on User.admin_roles_rel to resolve ambiguous join
UserRole has two FKs to users (user_id and assigned_by), causing
SQLAlchemy AmbiguousForeignKeysError on mapper initialization.
2026-02-25 03:23:41 +03:00
Fringg 1646f04bde fix: address RBAC review findings (CRITICAL + HIGH)
- stats:read → remnawave:manage for node restart/toggle (CRITICAL)
- add is_system guard on role update endpoint
- add Query bounds on /users limit/offset (ge/le)
- add db.rollback() in bootstrap exception handler
- migration: default=0 → server_default for level/priority columns
- CSV export: add formula injection sanitization
2026-02-25 03:17:06 +03:00
Fringg 3fee54f657 feat: add RBAC + ABAC permission system for admin cabinet
Backend:
- 4 new models: AdminRole, UserRole, AccessPolicy, AdminAuditLog
- Permission engine with RBAC wildcard matching + ABAC policy evaluation
- 26 permission sections (78 unique permissions) covering all admin routes
- require_permission() FastAPI dependency for route-level access control
- JWT tokens carry permissions, roles, role_level for frontend checks
- Admin roles CRUD with level-based hierarchy (viewers → superadmin)
- ABAC policies with time ranges and IP whitelist conditions
- Full audit log with CSV export
- Bootstrap service seeds 5 preset roles and assigns superadmins at startup
- Alembic migration 0011 for all RBAC tables
2026-02-25 03:02:40 +03:00
Fringg a594a0f79f fix: improve campaign notifications and ticket media in admin topics
- Campaign notifications: add tariff bonus display, hide empty promo group,
  compact format matching purchase notification style
- Ticket notifications: send media (photos) in the same topic as the text
  notification instead of separately. Uses caption for short texts, sequential
  messages for long texts with correct message_thread_id routing
2026-02-25 00:44:44 +03:00
Fringg 3642462670 feat: add per-channel disable settings and fix CHANNEL_REQUIRED_FOR_ALL bug
- Fix critical bug: is_active_paid_subscription() guard was blocking
  CHANNEL_REQUIRED_FOR_ALL from disabling paid subscriptions
- Add disable_trial_on_leave and disable_paid_on_leave columns to
  RequiredChannel model with Alembic migration 0010
- Refactor enforcement logic in channel_member.py and channel_checker.py
  to use per-channel settings instead of global env vars
- Update CRUD, Pydantic schemas, and admin API routes for new fields
- Add should_disable_subscription() and get_channel_settings() to
  channel_subscription_service for per-channel decision logic
2026-02-25 00:24:31 +03:00
Fringg 26efb157e4 fix: restore subscription_url and crypto_link after panel sync
_sync_subscription_to_panel() discarded the update_user() return value,
leaving subscription_url and subscription_crypto_link as None when
updating existing panel users. This caused "Connect devices" button
and HAPP_CRYPT4_LINK to disappear after admin subscription reset.

Also adds subscription_crypto_link sync to webhook user_modified handler
(was already present in user_revoked but missing from user_modified).
2026-02-24 23:50:21 +03:00
Egor c7ce80e882 Merge pull request #2643 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.18.0
2026-02-24 06:38:48 +03:00
github-actions[bot] 83e04a2e93 chore(main): release 3.18.0 2026-02-24 03:38:23 +00:00
Egor 351ebcf9eb Merge pull request #2642 from BEDOLAGA-DEV/dev
Dev
2026-02-24 06:37:51 +03:00
Fringg e5fa45f74f fix: correct broadcast button deep-links for cabinet mode
- promocode button now opens /balance instead of /subscription
- add menu_promocode to CALLBACK_TO_CABINET_PATH and style mappings
2026-02-24 06:33:56 +03:00
Fringg 25f014fd89 feat: add ChatTypeFilterMiddleware to ignore group/forum messages
Drop all messages and callback queries from non-private chats
(groups, supergroups with forum topics, channels) before they
reach any handler or heavy middleware (DB, throttle, blacklist).

- Registered after ContextVarsMiddleware, before GlobalErrorMiddleware
- chat_member events intentionally excluded (needed for channel tracking)
- pre_checkout_query excluded (no chat context, always private)
- Uses ChatType.PRIVATE enum for type safety
- Debug logging on dropped events for observability
2026-02-24 06:19:03 +03:00
Fringg 6f473defef fix: restore RemnaWave config management endpoints
The previous refactoring accidentally deleted RemnaWave API routes
(/remnawave/status, /uuid, /config, /configs) along with the legacy
file-based CRUD routes. Restore only the RemnaWave endpoints that
the cabinet frontend depends on.
2026-02-24 06:02:36 +03:00
Fringg 59fb08c3ea style: format 5 files with ruff 2026-02-24 05:59:08 +03:00
Fringg 295d2e877e refactor: remove legacy app-config.json system
Replace dual-configuration architecture (Remnawave API + local file fallback)
with Remnawave-only approach. When config is unavailable, show explicit
"not configured" message instead of silent file fallback.

- Delete app-config.json and admin_apps.py CRUD module (~1260 lines)
- Remove sync loaders, legacy step format handlers, device_mapping dicts
- Remove miniapp /app-config.json endpoint and filesystem search
- Remove backup service app-config.json snapshot/restore
- Remove APP_CONFIG_PATH setting, env var, docker volume mount
- Remove hardcoded 6-device keyboard fallback
- Remove legacy step-based keyboard rendering (installationStep etc.)
- Add "config not configured" message when Remnawave config is missing
- Update admin UI: "clear config" disables guide mode instead of reverting
2026-02-24 05:58:25 +03:00
Fringg 711ec344c6 fix: HTML-escape all externally-sourced text in guide messages
- Escape app names, device names, and other_app_names in
  handle_device_guide, handle_app_selection, handle_specific_app_guide
- Redact internal paths and exception details from cabinet API
  error responses in _load_config, _save_config, and Remnawave
  fetch endpoints
2026-02-24 05:27:59 +03:00
Fringg 978726a785 fix: invalidate app config cache on local file saves
_save_config() in admin_apps.py now calls invalidate_app_config_cache()
after writing app-config.json, so changes via cabinet API are immediately
visible in guide mode without waiting for TTL expiry.
2026-02-24 05:26:27 +03:00
Fringg 6a50013c21 fix: callback routing safety and cache invalidation order
- Add explicit negative filter for app_ vs app_list_ callback routing
  to prevent fragile registration-order dependency
- Reorder invalidate_app_config_cache to set timestamp to 0 first,
  ensuring fast-path check fails immediately without lock
- Add debug logging to _get_remnawave_config_uuid fallback path
2026-02-24 05:26:02 +03:00
Fringg 1bb939f63a fix: pre-existing bugs found during review
- Fix NameError: texts used before assignment in handle_single_device_reset
  (crash on malformed callback_data)
- HTML-escape subscription_link in all <code> tag interpolations
  (3 locations in devices.py)
2026-02-24 05:24:55 +03:00
Fringg 6feec1eaa8 fix: address security review findings
- Replace format_map with regex-based placeholder substitution to
  prevent format string injection via attribute traversal (CRITICAL)
- Add UUID format validation in select_remna_config handler
- Redact exception details from user-facing callback answers
- HTML-escape current_uuid in admin config menu
- HTML-escape title/description in format_additional_section
2026-02-24 05:19:57 +03:00
Fringg fae6f71def fix: address code review issues in guide mode rework
- Add fallback else branch for subscriptionLink in blocks format
  (prevents silent button drop when deep link resolution fails)
- Extract render_guide_blocks() helper to eliminate duplicated
  block-rendering logic between handle_device_guide and
  handle_specific_app_guide
- Add HTML escaping for admin-controlled config text in guide blocks
- Remove unused get_localized_value import from devices.py
2026-02-24 05:18:25 +03:00
Fringg 5a269b249e feat: rework guide mode with Remnawave API integration
- Add async Remnawave config loader with TTL cache and asyncio.Lock
- Normalize both legacy (steps) and Remnawave (blocks) formats to unified structure
- Build dynamic platform selection keyboard from config instead of hardcoded 6-device layout
- Add colored buttons via Bot API 9.4 (green for connect, blue for download)
- Add admin panel handler for selecting Remnawave subscription page config
- Add cache invalidation from both bot admin and cabinet API
- Fix callback data parsing for app IDs with underscores
- Add Linux platform support across all device mappings
2026-02-24 05:16:18 +03:00
Fringg 0b3b2e5dc5 feat: colored channel subscription buttons via Bot API 9.4 style
- Subscribed channels shown as green (style=success) with checkmark
- Unsubscribed channels shown as blue (style=primary)
- Clicking "I subscribed" now updates keyboard with colored status
  instead of just showing error alert
- Extracted _normalize_channels helper for DRY
2026-02-24 03:58:11 +03:00
Fringg 314c892c4d style: format monitoring_service.py 2026-02-24 03:30:00 +03:00
Fringg 1bc9074c1b fix: translate required channels handler to Russian, add localization keys
- All bot handler strings translated from English to Russian
- Back button now correctly navigates to admin_submenu_settings
- Added ADMIN_SETTINGS_REQUIRED_CHANNELS key to all 5 locales
2026-02-24 03:22:39 +03:00
Fringg 3af07ff627 feat: add required channels button to admin settings submenu in bot 2026-02-24 03:18:21 +03:00
Fringg 2aead9a68b fix: improve deduplication log message wording in monitoring service 2026-02-24 03:16:03 +03:00
Fringg a7db469fd7 fix: remove @username channel ID input, auto-prefix -100 for bare digits
@username resolution via bot.get_chat() was unreliable for subscription
checking. Now only numeric channel IDs are accepted with automatic -100
prefix when entering bare digits (e.g. 1234567890 -> -1001234567890).
2026-02-24 03:06:57 +03:00
Fringg a47ef67090 fix: add missing CHANNEL_CHECK_NOT_SUBSCRIBED localization key
Added to all 5 locales (en, ru, fa, ua, zh) to fix runtime warning
when user clicks subscription check button in middleware.
2026-02-24 03:00:08 +03:00
Fringg 8375d7ecc5 feat: add multi-channel mandatory subscription system
- Multi-channel subscription enforcement via middleware, events, and cabinet API
- 3-layer cache architecture: Redis -> PostgreSQL -> rate-limited Telegram API
- ChatMemberUpdated event-driven tracking with automatic VPN access control
- Admin management via bot FSM handler and REST API with full CRUD
- Channel ID normalization: @username resolved to numeric ID at creation time
- Fail-closed error handling: API errors deny access (security-first)
- Background reconciliation with keyset pagination (100 per batch)
- Per-user rate limiting on subscription check button (5s cooldown)
- Redis connection pooling via cache singleton (no per-request connections)
- Database: channel_id index, multi-row upsert optimization
- Localization: en, ru, zh, fa, ua translations for all new strings
- Frontend blocking UI with channel list and subscription status
- Admin channel management page with toggle, delete, and create
2026-02-24 02:50:31 +03:00
Egor 751e312f28 Merge pull request #2641 from BEDOLAGA-DEV/main
dev
2026-02-23 23:39:09 +03:00
Egor 4eaaf06a17 Merge pull request #2640 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.17.1
2026-02-23 21:33:25 +03:00
github-actions[bot] 1930a9dcde chore(main): release 3.17.1 2026-02-23 18:33:00 +00:00
Egor b876c6dd0b Merge pull request #2639 from BEDOLAGA-DEV/dev
Dev
2026-02-23 21:32:13 +03:00
Fringg d15b69710c style: ruff format 2026-02-23 21:29:54 +03:00
Fringg 708bb9eec7 fix: migrate all remaining naive timestamp columns to timestamptz
Old universal_migration.py created some tables (including email_templates)
with `timestamp` (naive) columns and had a catch-all that converted all
naive columns to `timestamptz` on each startup. After switching to Alembic,
that catch-all stopped running.

Users whose email_templates table was created by universal_migration.py
before the catch-all ran still have naive `timestamp` columns. The code
uses `datetime.now(UTC)` (timezone-aware), causing asyncpg to raise:
  "can't subtract offset-naive and offset-aware datetimes"

Migration 0007 finds and converts ALL remaining naive timestamp columns
in public schema to timestamptz, assuming UTC for existing data.

Fixes: email template save returning 503 with DataError
2026-02-23 21:26:16 +03:00
Fringg 97b3f899d1 fix: add diagnostic logging for device_limit sync to RemnaWave
Users report tariff change doesn't update device count and device
purchase doesn't sync to panel. Added structured logging to trace:
- resolve_hwid_device_limit: forced limit vs subscription limit
- PATCH /api/users: payload hwidDeviceLimit vs response value
2026-02-23 19:45:00 +03:00
Fringg 5ee45f97d1 fix: show negative amounts for withdrawals in admin transaction list
Admin endpoints returned amount_kopeks as always-positive from DB,
causing withdrawals and subscription payments to display as credits
in the admin panel. User-facing balance.py already handled this correctly.
2026-02-23 19:12:51 +03:00
Fringg d4c4a8a211 fix: add missing broadcast_history columns and harden subscription logic
- Add migration 0006 for blocked_count, channel, email_subject,
  email_html_content columns missing from broadcast_history table
- Fix infinite trial reactivation loop in monitoring service
- Prevent webhook from overwriting freshly extended end_date
- Use tariff-specific pricing for auto-renewal instead of global config
2026-02-23 19:07:59 +03:00
Fringg 205c8d987d fix: use aiogram 3.x bot.download() instead of document.download() 2026-02-23 18:31:31 +03:00
Fringg ebe508302b fix: uploaded backup restore button not triggering handler
Callback data prefix was 'backup_restore_uploaded_' but the handler
listens for 'backup_restore_execute_' and 'backup_restore_clear_'.
2026-02-23 18:29:10 +03:00
Fringg c20355b06d fix: repair missing DB columns and make backup resilient to schema mismatches
- Add migration 0005 to re-apply missing columns from 0002-0004
  (fixes DBs that were auto-stamped to head without running migrations)
- Add per-table error handling in backup ORM export so one table
  failure doesn't break the entire backup
- Escape HTML in error notifications to prevent Telegram parse errors
2026-02-23 18:22:32 +03:00
Fringg 50a931ec36 fix: add int32 overflow guards and strengthen auth validation
- Add le= bounds to all user-facing Pydantic int fields (balance, subscription, traffic, devices)
- Add self-referral guard in process_referral_registration
- Add Telegram identity cross-validation to get_optional_cabinet_user
- Log when initData validation fails but header is present
2026-02-23 18:12:58 +03:00
Fringg 115c0c84c0 fix: prevent partner self-referral via own campaign link
When a partner clicks their own campaign link (any bonus_type), they get
attributed as their own referral — their purchases counted as campaign
revenue and they earn referral commissions on their own payments.

Add self-referral guards in three layers:
- auth.py: early return in _process_campaign_bonus if user is campaign partner
- campaign_service.py: defense-in-depth check in apply_campaign_bonus
- start.py: guards on all referrer_id assignments and process_referral calls
2026-02-23 18:02:25 +03:00
Fringg 973b3d3d3f fix: cross-validate Telegram identity on every authenticated request
Telegram Mini App WebView shares localStorage across accounts on the
same device. This allows refresh tokens from user A to be reused by
user B if they open the same Mini App.

Add server-side defense: read X-Telegram-Init-Data header (already sent
by the frontend), validate it cryptographically, and reject requests
where the Telegram user ID doesn't match the JWT user's telegram_id.
2026-02-23 17:53:44 +03:00
Fringg 2ef6185715 fix: cap expected_monthly_referrals to prevent int32 overflow
Add le=2_000_000_000 constraint to Pydantic schema so PostgreSQL Integer
column doesn't receive values outside int32 range.
2026-02-23 17:27:33 +03:00
Fringg ed4624c664 fix: handle RemnaWave API errors in traffic aggregation
Catch exceptions from get_all_nodes() in _aggregate_traffic() to prevent
unhandled ASGI errors when RemnaWave returns HTTP 502. Cache empty result
on failure to avoid request storms from parallel frontend calls.
2026-02-23 17:25:01 +03:00
Fringg 1b6bbc7131 fix: protect active paid subscriptions from being disabled in RemnaWave
Add is_active_paid_subscription() helper that checks if subscription is
non-trial, active, and not expired. Use it across all disable_remnawave_user
call sites to prevent disabling VPN access for users with paid subscriptions.

Protected paths: block_user, delete_user_account, broadcast cleanup,
channel unsubscribe, admin deactivation, webapi endpoints, cabinet
reset-trial, reset-subscription, and disable-user endpoints.
2026-02-23 16:49:31 +03:00
Fringg 1f4430f3af fix: suppress web page preview when logo mode is disabled
When ENABLE_LOGO_MODE is on, messages are sent as photos which
naturally don't show URL previews. When off, messages are sent as
text but disable_web_page_preview was never set, causing link
previews in menu, welcome, and other messages.

Always patch Message.answer/edit_text and inject
disable_web_page_preview=True for all text message paths.
2026-02-23 15:55:53 +03:00
Fringg 67f3547ae2 fix: allow tariff switch when less than 1 day remains
Check subscription.end_date <= now instead of remaining_days == 0 to
allow switching when hours remain. The .days property truncates to whole
days, blocking users with a few hours left from switching tariffs.
2026-02-23 15:49:08 +03:00
Egor 49f64cacd7 Merge pull request #2634 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.17.0
2026-02-19 02:14:24 +03:00
github-actions[bot] 9101c98244 chore(main): release 3.17.0 2026-02-18 23:14:04 +00:00
Egor 311f278123 Merge pull request #2633 from BEDOLAGA-DEV/dev
Dev
2026-02-19 02:13:31 +03:00
Fringg 493f315a65 fix: skip blocked users in trial notifications and broadcasts without DB status change
- Add User.status filter to trial notification SQL queries
- Add pre-send blocked/deleted user check in _send_message_with_logo
- Fix UserStatus import shadowing (alias RemnaWaveUserStatus)
- Remove broadcast cleanup that marked users as BLOCKED in DB
- Remove dead _background_tasks variable
2026-02-19 02:08:39 +03:00
Fringg 18c2477173 feat: add referral code tracking to all cabinet auth methods + email_templates migration
Referral links from cabinet (?ref=CODE) were only tracked for email registration.
Now referral_code is accepted and processed in Telegram initData, Telegram Widget,
and OAuth authentication endpoints. Includes self-referral protection by email
for OAuth, proper error logging, and the missing email_templates table migration.
2026-02-18 23:59:29 +03:00
Fringg 6e28a1a22b fix: prevent 'caption is too long' error in logo mode
Telegram limits photo captions to 1024 characters. When menu_text or
rules_text exceeds 900 chars (with promo hints, random messages etc),
bot.send_photo fails with TelegramBadRequest.

Added len() check before each of 3 send_photo calls in
required_sub_channel_check — falls back to send_message when text
is too long, consistent with _answer_with_photo in message_patch.py.
2026-02-18 18:26:26 +03:00
Egor be00256618 Merge pull request #2631 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.16.3
2026-02-18 15:01:49 +03:00
github-actions[bot] 7f693f2b58 chore(main): release 3.16.3 2026-02-18 12:00:19 +00:00
Egor c3bf0dc0fd Merge pull request #2630 from BEDOLAGA-DEV/dev
Dev
2026-02-18 14:59:51 +03:00
Fringg d651a6c02f fix: eliminate deadlock by matching lock order with webhook
Deadlock: DELETE locks server_squads first, then subscriptions.
Webhook locks subscriptions first, then server_squads. Classic deadlock.

Fix: remove duplicate decrement block (was decrementing server_squads
twice), restructure subscription block to delete subscription FIRST
then decrement server_squads — matching webhook's lock acquisition order.
2026-02-18 12:24:08 +03:00
Fringg d7039d75a4 fix: connected_squads stores UUIDs, not int IDs — use get_server_ids_by_uuids
connected_squads JSON contains squad UUIDs like 'b4d782fa-...', not
integer IDs. int() cast fails on these. Now resolves UUIDs to integer
IDs via get_server_ids_by_uuids() before passing to remove_user_from_servers.
2026-02-18 12:17:27 +03:00
Fringg 6409b0c023 fix: auth middleware catches all commit errors, not just connection errors
When a handler swallows a DB error (e.g. ProgrammingError for missing
column), the transaction is aborted but the handler returns normally.
The auth middleware then tries db.commit() which fails with DBAPIError.

Now catches any exception on commit and does rollback, preventing the
cascade of "current transaction is aborted" errors through all
subsequent middleware layers.
2026-02-18 12:01:40 +03:00
Fringg af31c551d2 fix: 3 user deletion bugs — type cast, inner savepoint, lazy load
1. connected_squads JSON stores IDs as strings but server_squads.id is
   integer — cast to int before passing to remove_user_from_servers
2. Wrap remove_user_from_servers in its own db.begin_nested() so its
   failure doesn't abort the parent savepoint (subscription deletion)
3. Pre-fetch admin.id before delete_user_account to avoid MissingGreenlet
   when transaction rollback expires the ORM object
2026-02-18 11:59:25 +03:00
Fringg a38dfcb75a fix: wrap user deletion steps in savepoints to prevent transaction cascade abort
When one deletion step fails (e.g. missing campaign_id column in referral_earnings),
PostgreSQL aborts the entire transaction. All subsequent operations then fail with
"current transaction is aborted, commands ignored until end of transaction block".

Each of the 24 try/except blocks now uses `async with db.begin_nested():`
(PostgreSQL SAVEPOINT) so individual failures are isolated and rolled back
without poisoning the outer transaction.
2026-02-18 11:48:37 +03:00
Fringg b7b83abb72 fix: deadlock on user deletion + robust migration 0002
Decrement server_squads.current_users BEFORE deleting subscription
to match lock ordering with webhook handler, preventing deadlocks.

Also made migration 0002 robust with table existence checks to
prevent failures on DBs missing referral_earnings or
advertising_campaign_registrations tables.
2026-02-18 11:34:07 +03:00
Fringg f076269c32 fix: make migration 0002 robust with table existence checks
Migration was failing on DBs where referral_earnings or
advertising_campaign_registrations tables didn't exist yet,
causing campaign_id column to never be added. Added _has_table
and _has_column guards, wrapped backfill in existence check.
2026-02-18 11:30:38 +03:00
Egor 8d16935c1c Merge pull request #2629 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.16.2
2026-02-18 11:18:08 +03:00
github-actions[bot] 49d8de76a2 chore(main): release 3.16.2 2026-02-18 08:17:02 +00:00
Egor b4d8cabbd8 Merge pull request #2628 from BEDOLAGA-DEV/dev
Dev
2026-02-18 11:16:34 +03:00
Fringg a7f3d652c5 fix: use AwareDateTime TypeDecorator for all datetime columns
TypeDecorator with process_result_value guarantees naive datetimes
from pre-TIMESTAMPTZ databases are converted to UTC-aware on every
load. Replaces unreliable event listener approach. All 175 DateTime
columns now use AwareDateTime.
2026-02-18 11:11:58 +03:00
Fringg 38f3a9a16a fix: handle naive datetime in raw SQL row comparison (payment/common) 2026-02-18 11:02:09 +03:00
Fringg f7d33a7d2b fix: auto-convert naive datetimes to UTC-aware on model load
SQLAlchemy event listener on Base ensures all DateTime columns are
timezone-aware after loading from DB. Fixes TypeError crashes in
50+ comparison sites across handlers, services, and middlewares
for pre-TIMESTAMPTZ databases.
2026-02-18 11:01:04 +03:00
Fringg bd11801467 fix: extend naive datetime guard to all model properties
Move _aware() to module level and apply to 4 more models:
- PromoCode.is_valid (valid_from, valid_until)
- TrafficPurchase.is_expired (expires_at)
- CabinetRefreshToken.is_expired (expires_at)
- Ticket.is_user_reply_blocked (user_reply_block_until)
2026-02-18 10:44:13 +03:00
Fringg e512e5fe6e fix: handle naive datetimes in Subscription properties
Databases that haven't run the TIMESTAMPTZ migration return naive
datetimes from end_date. Comparing with datetime.now(UTC) raises
TypeError. Added _aware() helper to normalize naive→aware in
is_active, is_expired, should_be_expired, actual_status, days_left,
time_left_display, and extend_subscription.
2026-02-18 10:36:46 +03:00
Egor 799c83dd84 Merge pull request #2627 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.16.1
2026-02-18 10:29:59 +03:00
github-actions[bot] 4cc18cbc9a chore(main): release 3.16.1 2026-02-18 07:29:30 +00:00
Egor 4645be53cb Merge pull request #2626 from BEDOLAGA-DEV/dev
fix: add migration for partner system tables and columns
2026-02-18 10:29:04 +03:00
Fringg 79ea398d1d fix: add migration for partner system tables and columns
Existing databases stamped at 0001 (create_all checkfirst=True) are
missing new columns/tables from the partner system:
- users.partner_status
- broadcast_history.blocked_count
- advertising_campaigns.partner_user_id
- withdrawal_requests table
- partner_applications table

All checks are idempotent — safe for fresh and existing databases.
2026-02-18 10:26:07 +03:00
Egor 30b1402b54 Merge pull request #2625 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.16.0
2026-02-18 09:57:20 +03:00
github-actions[bot] 15d848c1ca chore(main): release 3.16.0 2026-02-18 06:56:54 +00:00
Egor c9877a3cbe Merge pull request #2624 from BEDOLAGA-DEV/dev
Dev
2026-02-18 09:56:08 +03:00
Fringg 68499ee043 chore: ruff format 2026-02-18 09:51:56 +03:00
Fringg bdb61613de fix: add missing payment providers to payment_utils and fix {total_amount} formatting
- Add freekassa, cloudpayments, kassa_ai to get_available_payment_methods(),
  is_payment_method_available(), get_payment_method_status(), and
  get_enabled_payment_methods_count()
- Fix cart reminder message showing literal {total_amount} in platega,
  stars, mulenpay, wata by adding .format() call
2026-02-18 09:50:36 +03:00
Fringg 59383bdbd8 feat: expose traffic_reset_mode in subscription response 2026-02-18 09:41:33 +03:00
Fringg 5d4a94b8ce feat: expose traffic_reset_mode in tariff API response 2026-02-18 09:36:36 +03:00
Fringg 0c07812ecc feat: add campaign_id to ReferralEarning for campaign attribution
Adds nullable FK campaign_id to referral_earnings table, enabling
direct campaign ROI analytics without JOINing through registrations.

- Model: campaign_id column + AdvertisingCampaign relationship
- CRUD: get_user_campaign_id() helper, campaign_id param in create_referral_earning
- Service: resolve campaign_id in all earning creation paths
- Cabinet API: campaign_name in earnings response
- Migration 0002: add column + deterministic backfill via DISTINCT ON
2026-02-18 09:12:01 +03:00
Fringg eb9dba3f47 fix: add selectinload for subscription in campaign user list
Prevents MissingGreenlet error when accessing user.subscription
in the admin campaign users filter view.
2026-02-18 08:42:53 +03:00
Fringg 6c4e035146 fix: correct subscription_service import in broadcast cleanup
Import SubscriptionService class and instantiate locally, matching
the pattern used throughout the codebase.
2026-02-18 08:39:50 +03:00
Fringg e78b1040a5 fix: prevent fileConfig from destroying structlog handlers
Only apply alembic.ini logging config when root logger has no handlers
(CLI mode). When running programmatically, structlog is already configured
and fileConfig would replace its handlers, breaking all logging.
2026-02-18 08:25:38 +03:00
Egor b6c7f91a7c Merge pull request #2623 from BEDOLAGA-DEV/refactor/alembic-migration
refactor: replace universal_migration.py with Alembic
2026-02-18 08:13:56 +03:00
Fringg e998059d81 style: format admin_campaigns, admin_partners, referral_withdrawal_service 2026-02-18 08:13:04 +03:00
Fringg 764e063bfe style: apply ruff formatting 2026-02-18 08:11:33 +03:00
Fringg 784616b349 refactor: replace universal_migration.py with Alembic
Remove the 7,791-line universal_migration.py and 16 incomplete individual
Alembic migrations. Replace with a single initial schema migration using
Base.metadata.create_all(checkfirst=True).

Changes:
- Add programmatic Alembic runner (app/database/migrations.py) with
  auto-stamp logic for existing databases transitioning from
  universal_migration
- Extract ensure_default_web_api_token() to web_api_token_service.py
- Extract sync_postgres_sequences() to database.py with SQL injection
  prevention via _quote_ident()
- Add HMAC token hashing support with backward-compatible dual-hash
  fallback and automatic rehashing
- Remove dead init_db() function and unused imports
- Add Makefile targets: migrate, migration, migrate-stamp, migrate-history
- Fix fileConfig() destroying structlog config (disable_existing_loggers)
- Remove duplicate migrations/alembic/alembic.ini with credentials
- Add script.py.mako template for future migration generation
- Update startup flow: alembic upgrade → sync sequences → ensure token
- Harden database.py: ParamSpec for retry decorator, safe URL logging,
  echo='debug' mode, execute_with_retry validation
- Update documentation references

31 files changed, 302 insertions(+), 9,226 deletions(-)
2026-02-18 08:10:20 +03:00
Fringg b4b10c998c fix: add blocked_count column migration to universal_migration.py
The column existed in the SQLAlchemy model and Alembic migration but was
missing from universal_migration.py which is used for auto-migrations on
startup, causing "column broadcast_history.blocked_count does not exist"
error in the broadcasts admin page.
2026-02-18 06:57:03 +03:00
Fringg 366df18c54 feat: enforce 1-to-1 partner-campaign binding with partner info in campaigns
- Add partner_user_id/partner_name to campaign list and detail responses
- Add partner_user_id to campaign create/update schemas
- Add GET /available-partners endpoint for partner dropdown
- Atomic assign with UPDATE...WHERE to prevent race conditions
- Validate partner exists and is approved in create/update
- Set updated_at on assign/unassign operations
- Eager-load partner relationship in campaign queries
2026-02-18 06:47:02 +03:00
Fringg 7883efc3d6 fix: return zeroed stats dict when withdrawal is disabled
can_request_withdrawal returned empty dict {} when withdrawal feature
was disabled, causing KeyError on 'total_earned' in withdrawal route.
2026-02-18 05:37:32 +03:00
Fringg 6881d97bbb feat: add admin partner settings API (withdrawal toggle, requisites text, partner visibility)
- GET/PATCH /admin/partners/settings endpoints with .env persistence
- New config: REFERRAL_WITHDRAWAL_REQUISITES_TEXT, REFERRAL_PARTNER_SECTION_VISIBLE
- Serve requisites_text in withdrawal balance and partner_section_visible in referral terms
- Sanitize newlines in requisites_text before .env write to prevent injection
2026-02-18 04:12:15 +03:00
Fringg 90278f1f5f style: fix ruff formatting in broadcast_service and tests 2026-02-17 18:50:25 +03:00
Fringg df5b1a072d fix: handle YooKassa NotFoundError gracefully in get_payment_info
Catch NotFoundError (404) separately from generic exceptions.
Old/expired payments return 404 from YooKassa API — this is expected
and should be logged as WARNING without traceback, not ERROR.
2026-02-17 18:46:32 +03:00
Fringg 10e231e52e feat: blocked user detection during broadcasts, filter blocked from all notifications
- Broadcast tri-state return: 'sent'/'blocked'/'failed' with blocked_count tracking
- Background cleanup: mark blocked users + disable their subscriptions + Remnawave
- blocked_count in BroadcastHistory model, schemas, API responses, admin UI
- Filter User.status==ACTIVE in subscription queries: get_expiring_subscriptions,
  get_expired_subscriptions, get_subscriptions_for_autopay,
  get_daily_subscriptions_for_charge, get_disabled_daily_subscriptions_for_resume
- Guard in notification_delivery_service.send_notification for BLOCKED/DELETED users
- Fix subscription tariff switch: preserve remaining days with total_seconds()
- Fix redundant local UTC imports across 16 files
- Fix test mocks: add **kwargs, correct assertion, remove dead expression
2026-02-17 18:37:25 +03:00
Fringg 7c20fde4e8 fix: medium-priority fixes for partner system
- replace unsafe referral code generator with unique DB-checked version
- remove dead code in get_global_partner_stats
- validate status filter params with Literal types in admin routes
2026-02-17 12:42:40 +03:00
Fringg fcf3a2c806 fix: resolve HIGH-priority performance and security issues in partner system
- fix N+1 query in money laundering analysis with GROUP BY batch query
- fix N+1 query in cabinet referral earnings with batch user fetch
- eliminate double balance stats computation in withdrawal flow
- replace in-memory referral counting with SQL COUNT/CASE aggregation
- fix HTML injection in admin Telegram notifications via html.escape()
- standardize return types for reject/complete withdrawal methods
2026-02-17 12:38:25 +03:00
Fringg 88997492c3 fix: critical security and data integrity fixes for partner system
- Add SELECT FOR UPDATE locking on all financial state transitions
  (withdrawal approve/reject/complete/create, partner approve/reject)
- Add html.escape() on all user-controlled values in email templates
- Wrap sync SMTP send_email in asyncio.to_thread to avoid blocking event loop
- Add missing database indexes on referral_earnings(user_id, referral_id),
  users(referred_by_id, partner_status), withdrawal_requests(user_id, status),
  advertising_campaigns(partner_user_id)
2026-02-17 12:28:30 +03:00
Fringg 327d4f4d15 feat: notify users on partner/withdrawal approve/reject
4 notification types via NotificationDeliveryService:
- Partner application approved/rejected
- Withdrawal request approved/rejected

Telegram + email + WebSocket routing handled automatically.
Email templates in ru/en/zh/ua.
2026-02-17 12:04:23 +03:00
Fringg cf7cc5a84e feat: add admin notifications for partner applications and withdrawals
Send notifications to admin chat when a partner application is submitted
or a withdrawal request is created, following existing notification pattern.
2026-02-17 11:48:38 +03:00
Fringg 28f524b762 fix: campaign web link uses ?campaign= param, not ?start=
The cabinet frontend captures ?campaign= from URL (campaign.ts utility),
not ?start=. Fixed the partner-facing link from /login?start= to /?campaign=.
2026-02-17 11:36:40 +03:00
Fringg c4dc43e054 feat: link campaign registrations to partner for referral earnings
Two separate fixes for bot and cabinet auth paths:

Bot (start.py): store referrer_id from campaign.partner_user_id in FSM
state, skip referral code prompt when partner already set.

Cabinet (auth.py): in _process_campaign_bonus, set user.referred_by_id
to campaign.partner_user_id and call process_referral_registration.

Both paths now correctly attribute campaign users to the partner,
enabling commission earnings from their future purchases.
2026-02-17 11:33:31 +03:00
Fringg 767e965028 feat: attribute campaign registrations to partner for referral earnings
When a user registers through a campaign link that has partner_user_id,
store that partner as referrer_id in FSM state. This connects the
campaign system to the referral earning system — the partner now earns
commissions from all purchases made by users who came through their
campaign links.

Changes in all registration paths:
- cmd_start: store referrer_id from campaign.partner_user_id
- language/rules/privacy handlers: skip referral code prompt when
  referrer_id already set from campaign
- channel check: pick up referrer_id from state instead of hardcoding None
2026-02-17 11:22:38 +03:00
Fringg d39063b22f fix: unassign all campaigns when revoking partner status
Previously revoke_partner only changed partner_status and commission,
leaving campaigns orphaned with invalid partner_user_id. Now sets
partner_user_id=NULL on all campaigns belonging to the revoked partner.
2026-02-17 11:11:25 +03:00
Fringg ea5d932476 feat: include partner campaigns in /partner/status response
Return assigned active campaigns with bonus info, deep_link and
web_link so the partner's referral page can display shareable links.
2026-02-17 10:45:11 +03:00
Fringg acc1323a54 fix: move PartnerStatus enum before User class to fix NameError
PartnerStatus was defined after the User class that references it,
causing a NameError on startup.
2026-02-17 09:56:11 +03:00
Fringg 58bfaeaddb feat: add partner system and withdrawal management to cabinet
- Partner application flow: user applies, admin reviews/approves/rejects
- Individual commission % per partner with admin management
- Campaign assignment/unassignment to partners
- Withdrawal system: balance check, create request, cancel
- Admin withdrawal management with risk scoring and fraud analysis
- Database migration: partner_applications table, user partner fields, campaign partner_user_id
- Pydantic schemas with proper validation bounds
- Batch user fetching to prevent N+1 queries
- Row locking on cancel to prevent race conditions
2026-02-17 09:51:36 +03:00
Fringg df5415f30b fix: reorder button_click_logs migration to nullify before ALTER TYPE
ALTER COLUMN user_id TYPE INTEGER failed with "integer out of range"
because the column contained telegram_id values (BIGINT) exceeding
INTEGER max. Swapped order: SET NULL first, then ALTER TYPE.
2026-02-17 08:19:21 +03:00
Egor 330d670f3f Merge pull request #2621 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.15.1
2026-02-17 07:55:52 +03:00
github-actions[bot] 41cb122a2f chore(main): release 3.15.1 2026-02-17 04:54:40 +00:00
Egor 1b3e6f2f11 Merge pull request #2620 from BEDOLAGA-DEV/dev
fix: add naive datetime guards to fromisoformat() in Redis cache readers
2026-02-17 07:54:20 +03:00
Fringg 6fa49485d9 fix: add naive datetime guards to fromisoformat() in Redis cache readers
Old Redis entries saved before utcnow→now(UTC) migration lack timezone
info, causing TypeError on subtraction with aware datetimes.
2026-02-17 07:52:26 +03:00
Egor 71aa023133 Merge pull request #2619 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.15.0
2026-02-17 07:25:32 +03:00
github-actions[bot] e567c02658 chore(main): release 3.15.0 2026-02-17 04:01:31 +00:00
Egor f393dc0840 Merge pull request #2618 from BEDOLAGA-DEV/dev
Dev
2026-02-17 07:01:07 +03:00
Fringg 5dc4b0ec15 chore: ruff format oauth.py, auth schemas, admin_notification_service 2026-02-17 06:57:30 +03:00
Fringg e68760cc66 fix: remove local UTC re-imports shadowing module-level import in purchase.py
Caused UnboundLocalError on datetime.now(UTC) at line 209 because
Python treats the function-local `from datetime import UTC` (lines 351, 362)
as a local variable declaration, making UTC unbound before those lines.
2026-02-17 06:45:46 +03:00
Fringg d9552799c1 feat: add web campaign links with bonus processing in auth flow
- Add web_link generation for campaigns (uses MINIAPP_CUSTOM_URL)
- Process campaign_slug in all auth endpoints (telegram, widget, email, oauth)
- Apply campaign bonus (balance/subscription/tariff) with SELECT FOR UPDATE lock
- Add rollback + user refresh on campaign bonus failure
- Fix N+1 query in campaign registrations (batch subscription check)
- Remove duplicate queries in get_campaign_statistics (~60 lines dead code)
- Simplify _store_refresh_token (remove TOCTOU pre-check, keep IntegrityError)
- Remove dead expression in campaign_service.py
- Align start_parameter max_length to 64 (matches DB column)
- Remove unused campaign_slug from EmailRegisterStandaloneRequest
2026-02-17 06:44:03 +03:00
Fringg c75ec0b22a fix: AttributeError in withdrawal admin notification (send_to_admins → send_admin_notification) 2026-02-17 05:23:49 +03:00
Fringg 27309f53d9 feat: add LOG_COLORS env setting to toggle console ANSI colors 2026-02-17 05:15:03 +03:00
Egor 4193f717ee Merge pull request #2617 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.14.1
2026-02-17 05:04:03 +03:00
github-actions[bot] d297985b0b chore(main): release 3.14.1 2026-02-17 02:03:34 +00:00
Egor 6dcf3a9f0d Merge pull request #2616 from BEDOLAGA-DEV/dev
Dev
2026-02-17 05:03:06 +03:00
Fringg 094609005a fix: add naive datetime guards to parsers and fix test datetime literals 2026-02-17 05:00:13 +03:00
Fringg eb18994b7d fix: complete datetime.utcnow() → datetime.now(UTC) migration
- Migrate 660+ datetime.utcnow() across 153 files to datetime.now(UTC)
- Migrate 30+ datetime.now() without UTC to datetime.now(UTC)
- Convert all 170 DateTime columns to DateTime(timezone=True)
- Add migrate_datetime_to_timestamptz() in universal_migration with SET LOCAL timezone='UTC' safety
- Remove 70+ .replace(tzinfo=None) workarounds
- Fix utcfromtimestamp → fromtimestamp(..., tz=UTC)
- Fix fromtimestamp() without tz= (system_logs, backup_service, referral_diagnostics)
- Fix fromisoformat/isoparse to ensure aware output (platega, yookassa, wata, miniapp, nalogo)
- Fix strptime() to add .replace(tzinfo=UTC) (backup_service, referral_diagnostics)
- Fix datetime.combine() to include tzinfo=UTC (remnawave_sync, traffic_monitoring)
- Fix datetime.max/datetime.min sentinels with .replace(tzinfo=UTC)
- Rename panel_datetime_to_naive_utc → panel_datetime_to_utc
- Remove DTZ003 from ruff ignore list
2026-02-17 04:45:40 +03:00
Fringg ff21b27b98 fix: address remaining abs() issues from review
- admin_traffic._get_bulk_spending: add func.abs() for SUBSCRIPTION_PAYMENT SUM
- get_user_total_spent_kopeks: move abs() from Python to SQL (per-row func.abs)
- referral_contest.total_outside: add abs() for mixed-type sum
- Revert func.abs() from generic by_type aggregation to preserve refund/withdrawal signs
2026-02-17 03:47:39 +03:00
Fringg 4247981c98 fix: normalize transaction amount signs across all aggregations
SUBSCRIPTION_PAYMENT transactions have inconsistent signs in DB
(some negative, some positive). Add func.abs()/abs() to all SUM
queries and display code to ensure correct totals regardless of sign.

Affected: admin statistics, referral contest stats, tariff revenue,
campaign stats, reporting service, admin renewal notifications.
2026-02-17 03:40:37 +03:00
Fringg c30972f6a7 fix: prevent negative amounts in spent display and balance history
SUBSCRIPTION_PAYMENT transactions are stored with negative amount_kopeks.
- get_user_total_spent_kopeks now returns abs() to fix "Потрачено: -155 ₽"
  and broken promo group threshold comparisons
- Balance history uses abs() before format_price to prevent "--85 ₽"
2026-02-17 03:36:56 +03:00
Egor 7628fb9f6e Merge pull request #2613 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.14.0
2026-02-16 19:26:11 +03:00
github-actions[bot] 4c48eadebc chore(main): release 3.14.0 2026-02-16 16:23:56 +00:00
Egor 6ea3860a2f Merge pull request #2612 from BEDOLAGA-DEV/dev
Dev
2026-02-16 19:23:30 +03:00
Fringg 1b8ef69a1b fix: NameError in set_user_devices_button — undefined action_text
Replaced undefined action_text with devices (the actual value being set).
Removed duplicate await callback.answer() call.
2026-02-16 19:09:52 +03:00
Fringg 9d710050ad feat: show all active webhook endpoints in startup log
Added missing webhook endpoints to the startup section:
Platega, CloudPayments, Kassa.ai, and RemnaWave webhook.
2026-02-16 19:08:49 +03:00
Fringg 491a7e1c42 fix: remove unused PaymentService from MonitoringService init
MonitoringService instantiated PaymentService() at module level during
import, triggering a debug log before structlog/logging were configured.
This caused [debug    ] with padded spaces (structlog default pad_level)
and appeared 7 seconds before the startup banner. The payment_service
attribute was never used in MonitoringService.
2026-02-16 19:02:57 +03:00
Fringg 7eb8d4e153 fix: force basicConfig to replace pre-existing handlers
logging.basicConfig() silently does nothing if the root logger already
has handlers. When import-time side effects trigger stdlib logging before
main() configures formatters, our ProcessorFormatter with pad_level=False
never gets applied — producing [debug    ] instead of [debug].
2026-02-16 18:49:39 +03:00
Fringg f63720467a refactor: improve log formatting — logger name prefix and table alignment
1. Add _prefix_logger_name processor that moves [module.name] before
   event text for consistent format: timestamp [level] [module] message
2. Fix startup summary table alignment by using display width calculation
   instead of len() — properly accounts for wide emoji and variation
   selectors that render as 2 terminal cells
2026-02-16 18:33:40 +03:00
Fringg 516be6e600 fix: sync support mode from cabinet admin to SupportSettingsService
Cabinet admin endpoint was setting settings.SUPPORT_SYSTEM_MODE directly
without updating SupportSettingsService JSON, causing bot to show stale
mode. Now routes through set_system_mode() which updates both stores.
2026-02-16 18:24:27 +03:00
Fringg 0807a9ff19 fix: sync SUPPORT_SYSTEM_MODE between SystemSettings and SupportSettings
When changing SUPPORT_SYSTEM_MODE via system settings admin panel, the
SupportSettingsService JSON cache was not updated, causing the old value
to take priority. Now both services stay in sync bidirectionally.
2026-02-16 18:22:44 +03:00
Fringg a93a32f3a7 fix: resolve MissingGreenlet error when accessing subscription.tariff
Add .selectinload(Subscription.tariff) chain to all User queries that
load subscriptions, preventing lazy loading of the tariff relationship
in async context. Also replace unsafe getattr(subscription, 'tariff')
with explicit async get_tariff_by_id() in handle_extend_subscription.
2026-02-16 17:54:43 +03:00
Egor 68de66f526 Merge pull request #2610 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.13.0
2026-02-16 10:12:33 +03:00
github-actions[bot] 15aba2b3db chore(main): release 3.13.0 2026-02-16 07:11:21 +00:00
Egor fa78fa6d09 Merge pull request #2609 from BEDOLAGA-DEV/dev
Dev
2026-02-16 10:10:52 +03:00
Fringg 11f8af003f fix: resolve exc_info for admin notifications, clean log formatting
- TelegramNotifierProcessor: resolve exc_info=True → sys.exc_info()
  tuple while still in except block, fixing "(no traceback available)"
- Use real exception type (e.g. TelegramBadRequest) instead of LogError
- Include user_id/username in admin notification context
- ConsoleRenderer: pad_level=False removes trailing spaces in [info]
- Strip [__main__] logger name from startup/timeline logs
2026-02-16 10:06:37 +03:00
Fringg 11ef714e0d fix: limit Rich traceback output to prevent console flood
RichTracebackFormatter defaults (show_locals=True, max_frames=100)
produced 5000+ line tracebacks on chained exceptions with aiogram.
Now: show_locals=False, max_frames=20, suppress aiogram/aiohttp frames.
2026-02-16 09:57:46 +03:00
Fringg 909a4039c4 fix: traceback in Telegram notifications + reduce log padding
- LoggingMiddleware: logger.error → logger.exception to include exc_info
  so TelegramNotifierProcessor can extract traceback for admin chat
- ConsoleRenderer: pad_event_to=0 to remove excessive whitespace
  in short event names (timeline markers like ┃, ┗)
2026-02-16 09:55:56 +03:00
Fringg bf646112df feat: colored console logs via structlog + rich + FORCE_COLOR
- Add rich dependency for colored tracebacks and console rendering
- Set FORCE_COLOR=1 in docker-compose for color output in containers
- Remove format_exc_info from processor chain — ConsoleRenderer now
  handles exc_info directly (Rich tracebacks on console, plain in files)
- Let ConsoleRenderer auto-detect colors via FORCE_COLOR env var
2026-02-16 09:43:41 +03:00
Fringg 8a6650e57c fix: suppress startup log noise (~350 lines → ~30)
- Suppress migration logger to WARNING during startup (main.py)
- Remove debug logs from get_traffic_packages() leaking before structlog init
- Downgrade handler registration logs to debug (start.py)
- Remove duplicate section headers from migration orchestrator
2026-02-16 09:34:17 +03:00
Fringg 25e8c9f8fc fix: use sync context manager for structlog bound_contextvars
bound_contextvars() returns a sync _GeneratorContextManager, not async.
Using `async with` caused TypeError crashing all web API requests.
2026-02-16 09:23:22 +03:00
Fringg 1f0fef114b refactor: complete structlog migration with contextvars, kwargs, and logging hardening
- Add ContextVarsMiddleware for automatic user_id/chat_id/username binding
  via structlog contextvars (aiogram) and http_method/http_path (FastAPI)
- Use bound_contextvars() context manager instead of clear_contextvars()
  to safely restore previous state instead of wiping all context
- Register ContextVarsMiddleware as outermost middleware (before GlobalError)
  so all error logs include user context
- Replace structlog.get_logger() with structlog.get_logger(__name__) across
  270 calls in 265 files for meaningful logger names
- Switch wrapper_class from BoundLogger to make_filtering_bound_logger()
  for pre-processor level filtering (performance optimization)
- Migrate 1411 %-style positional arg logger calls to structlog kwargs
  style across 161 files via AST script
- Migrate log_rotation_service.py from stdlib logging to structlog
- Add payment module prefixes to TelegramNotifierProcessor.IGNORED_LOGGER_PREFIXES
  and ExcludePaymentFilter.PAYMENT_MODULES to prevent payment data leaking
  to Telegram notifications and general log files
- Fix LoggingMiddleware: add from_user null-safety for channel posts,
  switch time.time() to time.monotonic() for duration measurement
- Remove duplicate logger assignments in purchase.py, config.py,
  inline.py, and admin/payments.py
2026-02-16 09:18:12 +03:00
Egor be6036e879 Merge pull request #2607 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.12.1
2026-02-16 07:32:42 +03:00
github-actions[bot] bba85a309a chore(main): release 3.12.1 2026-02-16 04:32:16 +00:00
Egor 448be6e512 Merge pull request #2606 from BEDOLAGA-DEV/dev
Dev
2026-02-16 07:31:48 +03:00
Fringg 871ceb866c fix: replace deprecated Query(regex=) with pattern= 2026-02-16 07:11:58 +03:00
Fringg 8e61fe4774 fix: handle TelegramBadRequest in ticket edit_message_text calls
Wrap all edit_message_text calls in ticket handlers with try/except
TelegramBadRequest fallback to message.answer(). Fixes crash when
the prompt message was deleted or has no text (e.g. photo message).
2026-02-16 07:09:06 +03:00
Fringg d4dfa235e5 chore: update all dependencies to latest stable versions
Security: cryptography 41.0→44.0+ (4 CVEs patched)
Major: redis 5.0→7.1, fastapi 0.115→0.129, bcrypt 4.2→5.0
Minor: sqlalchemy 2.0.46, alembic 1.18.4, asyncpg 0.31,
  aiosqlite 0.22, qrcode 8.0, packaging 26.0, pyjwt 2.11,
  yookassa 3.10, pyyaml 6.0.3
2026-02-16 06:59:48 +03:00
Fringg 97ec39aa80 fix: add promo code anti-abuse protections
- Rate-limit on brute-force: 5 failed attempts per 5 min blocks user
- Daily stacking limit: max 5 promo activations per 24h (in-memory + DB)
- Format validation: only alphanumeric/hyphen/underscore, 3-50 chars
2026-02-16 06:52:45 +03:00
Fringg 61a97220d3 fix: add /start burst rate-limit to prevent spam abuse
Sliding window limiter: max 3 /start calls per 60 seconds per user.
Runs before the general 0.5s throttle. Shows cooldown timer on block.
Lazy cleanup of start_buckets when size exceeds 500 entries.
2026-02-16 06:41:14 +03:00
Egor 2d04f2aa28 Merge pull request #2605 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.12.0
2026-02-16 02:20:45 +03:00
github-actions[bot] d6e79161e7 chore(main): release 3.12.0 2026-02-15 23:20:25 +00:00
Egor 45fd543206 Merge pull request #2604 from BEDOLAGA-DEV/dev
Dev
2026-02-16 02:20:02 +03:00
Fringg ba0a5e9abd fix: handle tariff_extend callback without period (back button crash)
The 'Back' button on tariff extend confirmation sends
tariff_extend:{id} without a period segment, which crashed
select_tariff_extend_period with IndexError on parts[2].
Now redirects to show_tariff_extend when period is missing.
2026-02-16 01:38:04 +03:00
Fringg d712ab8301 fix: remove redundant trial inactivity monitoring checks
Remnawave already sends user.not_connected webhooks, making the
monitoring service's 1h/24h trial inactivity checks redundant.
The monitoring checks caused false positives because they relied on
traffic_used_gb which may not be synced in real-time.

Removed:
- _check_trial_inactivity_notifications from monitoring cycle
- _send_trial_inactive_notification method
- trial_inactive_1h / trial_inactive_24h notification settings
- Admin UI toggles and preview buttons for these notifications
2026-02-16 00:58:24 +03:00
Fringg 1e2a7e3096 fix: webhook notification 'My Subscription' button uses unregistered callback_data
Changed callback_data from 'subscription' (no handler) to 'menu_subscription'
(registered handler) in _get_subscription_keyboard and _get_traffic_keyboard.
In cabinet mode the button opens a WebApp URL so the bug was invisible,
but in default MAIN_MENU_MODE the callback went unhandled.
2026-02-16 00:30:17 +03:00
Fringg 64a684cd2f fix: filter out traffic packages with zero price from purchase options 2026-02-15 23:32:15 +03:00
Fringg e4c207ecff chore: format files with ruff 2026-02-15 23:18:44 +03:00
Fringg 80914c1af7 fix: daily tariff subscriptions stuck in expired/disabled with no resume path
- Keyboard now shows "Возобновить" for disabled/expired daily tariffs
  instead of useless "Приостановить"
- resume_daily_subscription handles EXPIRED→ACTIVE (not only DISABLED)
- Pause handler detects inactive status and calls resume directly
- subscription_extend redirects daily tariffs to subscription info
  (daily tariffs have no period_prices, so extend page was empty)
2026-02-15 23:17:45 +03:00
Fringg e1822800ab fix: handle photo message in ticket creation flow
Ticket creation crashed with "there is no text in the message to edit"
when initiated from the tickets list (rendered as photo with logo).
2026-02-15 22:58:31 +03:00
Fringg 68773b7e77 feat: add per-button enable/disable toggle and custom labels per locale
- Add enabled flag to hide/show each button section in main menu
- Add per-locale custom labels (ru, en, ua, zh, fa) for button text
- Deep-copy nested labels dict in cache to prevent reference leaks
- Validate label entries from DB (type + locale key checks)
- Use selective merge in PATCH handler instead of blind .update()
2026-02-12 23:42:55 +03:00
Fringg 10538e7351 feat: add 'default' (no color) option for button styles
Allow admins to set buttons to Telegram's default style with no color
override. Refactors style resolution from or-chain to explicit if/elif/else
so that 'default' does not fall through to global config or hardcoded defaults.
2026-02-12 23:25:42 +03:00
Fringg a9687912df feat: add per-section button style and emoji customization via admin API
Add cabinet admin API for configuring button colors (primary/success/danger)
and custom emoji IDs per menu section (home, subscription, balance, referral,
support, info, admin). Styles are stored as JSON in system_settings and cached
in-process for fast resolution.

Style resolution chain: explicit param > per-section DB > global config > defaults.
2026-02-12 23:15:58 +03:00
Fringg 46c1a69456 fix: pre-validate CABINET_BUTTON_STYLE to prevent invalid values from suppressing per-section defaults 2026-02-12 22:43:30 +03:00
Fringg bf2b2f1c56 feat: add button style and emoji support for cabinet mode (Bot API 9.4)
- Upgrade aiogram to 3.25.0 for style/icon_custom_emoji_id support
- Add CABINET_BUTTON_STYLE config for global color override
- Per-section default styles: subscription (green), balance (blue),
  referral (green), admin (red), home (blue)
- Style priority: explicit > CABINET_BUTTON_STYLE > per-section default
- Add icon_custom_emoji_id pass-through for Premium bot owners
- Admin panel setting for button style with color picker
2026-02-12 22:34:38 +03:00
Fringg 9ac6da490d feat: add web admin button for admins in cabinet mode 2026-02-12 22:22:28 +03:00
Fringg ad87c5fb5e feat: rename MAIN_MENU_MODE=text to cabinet with deep-linking to frontend sections
- Rename mode from 'text' to 'cabinet' (text/text_only/minimal kept as aliases)
- Add build_cabinet_url() for joining MINIAPP_CUSTOM_URL with section paths
- Cabinet main menu now has section-specific buttons: subscription, balance,
  referral, support, info — each opens the corresponding cabinet page
- Add CALLBACK_TO_CABINET_PATH mapping for automatic deep-linking from
  callback_data to cabinet routes (/subscription, /balance, /referral, etc.)
- Unmapped callback_data gracefully falls back to regular Telegram callbacks
- Add startup validation warning when cabinet mode is active without MINIAPP_CUSTOM_URL
- Update admin broadcast buttons with section-specific routing
- Backward compatible: is_text_main_menu_mode() kept as alias for is_cabinet_mode()
2026-02-12 22:21:08 +03:00
Egor 7ac73e5745 Merge pull request #2600 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.11.0
2026-02-12 21:12:59 +03:00
github-actions[bot] 61be89743d chore(main): release 3.11.0 2026-02-12 18:12:13 +00:00
Egor d174d9a927 Merge pull request #2599 from BEDOLAGA-DEV/dev
Dev
2026-02-12 21:11:44 +03:00
Fringg 4048aebb9f chore: format models.py 2026-02-12 21:08:05 +03:00
Fringg bfd66c42c1 fix: add passive_deletes to Subscription relationships to prevent NOT NULL violation on cascade delete 2026-02-12 20:59:28 +03:00
Fringg 351c95bac1 chore: change SALES_MODE default to tariffs 2026-02-12 20:55:52 +03:00
Fringg 1d43ae5e25 fix: add startup warning for missing HAPP_CRYPTOLINK_REDIRECT_TEMPLATE in guide mode 2026-02-12 20:43:12 +03:00
Fringg 476b89fe8e feat: add startup warnings for missing HAPP_CRYPTOLINK_REDIRECT_TEMPLATE and MINIAPP_CUSTOM_URL 2026-02-12 20:38:33 +03:00
Fringg 14e13177b5 chore: change CONNECT_BUTTON_MODE default to miniapp_subscription 2026-02-12 20:35:34 +03:00
Fringg 760c833b74 fix: ticket creation crash and webhook PendingRollbackError
- tickets.py: remove ENABLE_LOGO_MODE branches that used edit_message_caption
  on text messages (prompt is always text, not photo with caption)
- webhook_service: add db.rollback() before retrying DB ops in _handle_user_deleted
  when subscription was cascade-deleted, catch PendingRollbackError alongside StaleDataError
2026-02-12 20:32:52 +03:00
Fringg 1a476c49c1 feat: add cabinet admin API for pinned messages management
- Full CRUD + broadcast/unpin/activate/deactivate endpoints
- Admin auth required on all endpoints (get_current_admin_user)
- Broadcast cooldown (60s) on all mass operation endpoints
- Cached Bot singleton to prevent aiohttp session leaks
- Guard against deleting active pinned messages (409 Conflict)
- Route ordering: /active/* before /{message_id}/* to prevent path conflicts
- Pydantic schemas with proper validation (file_id max_length=255)
2026-02-12 19:13:51 +03:00
Fringg 454b83138e fix: flood control handling in pinned messages and XSS hardening in HTML sanitizer
- Add retry loop with backoff to _unpin_message_for_user (max 3 attempts)
- Add TelegramRetryAfter handling in _send_and_pin_message (unpin + send phases)
- Fix missing failed_count increment when all broadcast retries exhaust (for/else)
- Remove dead code in unpin_active_pinned_message (unreachable TelegramRetryAfter catch)
- Harden sanitize_html: allowlist URI schemes (http/https/tg/mailto/tel), whitelist
  tag attributes, strip all attrs from tags without explicit whitelist, full HTML
  entity decoding via html.unescape
2026-02-12 19:13:40 +03:00
Fringg 2de438426a fix: suppress expired callback query error in AuthMiddleware
Catch TelegramBadRequest with "query is too old" before generic Exception handler
to prevent it from being logged as error and triggering error reports.
2026-02-12 18:43:16 +03:00
Egor 6039db997c Merge pull request #2597 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.10.3
2026-02-12 07:10:05 +03:00
github-actions[bot] 940959c951 chore(main): release 3.10.3 2026-02-12 04:06:02 +00:00
Egor e688110129 Merge pull request #2596 from BEDOLAGA-DEV/dev
Dev
2026-02-12 07:05:38 +03:00
Fringg 57dc1ff47f fix: resolve deadlock on server_squads counter updates and add webhook notification toggles
- Fix deadlock: enforce sorted lock ordering in add_user_to_servers/remove_user_from_servers
- Fix cross-call deadlock: add update_server_user_counts() for atomic add+remove in one sorted pass
- Fix deadlock in squad migration: use sorted dict iteration for counter updates
- Fix broken "Buy traffic" button: subscription_add_traffic → buy_traffic callback_data
- Add 12 webhook notification toggle settings (WEBHOOK_NOTIFY_*) with master toggle
- Add admin UI category "Уведомления от вебхуков" with hints in BotConfigurationService
- Add toggle check in _notify_user() respecting master and per-event settings
2026-02-12 06:47:26 +03:00
Fringg fc42916b10 fix: harden backup create/restore against serialization and constraint errors
- Backup creation: handle Decimal, float NaN/Inf, fallback for JSON column dumps
- Restore users: savepoint per INSERT to survive duplicate telegram_id/email/referral_code
- Restore associations: savepoint per INSERT to survive FK or duplicate constraint violations
- Restore table records: savepoint already added in prior commit
2026-02-12 03:41:24 +03:00
Fringg 5893874776 fix: handle unique constraint conflicts during backup restore without clear_existing 2026-02-12 03:37:36 +03:00
Egor 60305d8d5b Merge pull request #2595 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.10.2
2026-02-12 03:07:43 +03:00
github-actions[bot] 07ef3b46d9 chore(main): release 3.10.2 2026-02-12 00:07:06 +00:00
Egor f9d58e964c Merge pull request #2594 from BEDOLAGA-DEV/dev
Dev
2026-02-12 03:06:34 +03:00
Fringg d3c14ac303 fix: UnboundLocalError for get_logo_media in required_sub_channel_check 2026-02-12 02:56:14 +03:00
Fringg fda9f3beec fix: suppress bot-blocked-by-user error in AuthMiddleware 2026-02-12 02:53:05 +03:00
Fringg 27365b3c75 fix: handle time/date types in backup JSON serialization 2026-02-12 02:51:20 +03:00
Fringg 3dac332a9f chore: ruff format 7 files 2026-02-11 21:50:49 +03:00
Fringg c5124b97b6 fix: payment race conditions, balance atomicity, renewal rollback safety
- YooKassa: SELECT FOR UPDATE on payment row to prevent concurrent double-processing
- subtract_user_balance: row locking to prevent concurrent balance race conditions
- subtract_user_balance: transaction creation before commit for atomicity
- subscription renewal: compensating refund if extend_subscription fails after charge
- StaleDataError: use savepoint instead of full rollback to protect parent transaction
2026-02-11 21:49:37 +03:00
Fringg ee2e79db31 refactor: remove modem functionality from classic subscriptions
Remove all modem purchase/management code:
- Delete modem handler, service, and tests
- Remove modem button from keyboards and admin panel
- Remove modem pricing from calculations
- Remove modem REST API endpoint and schemas
- Remove modem decorator, config settings, and notification formatting
- Keep DB column and migration for backwards compatibility
2026-02-11 21:14:08 +03:00
Fringg d05ff678ab fix: HTML parse fallback, email change race condition, username length limit
- start.py: retry welcome message with parse_mode=None on TelegramBadRequest HTML parse error
- auth.py: handle IntegrityError race condition on email change, wrap email sending in try-except
- config.py: truncate RemnaWave username to 36 chars (API limit) instead of 64
2026-02-11 20:51:50 +03:00
Fringg fcaa9dfb27 fix: clean stale squad UUIDs from tariffs during server sync
When squads are deleted from the RemnaWave panel and servers are synced,
the bot cleaned subscription connected_squads but left stale UUIDs in
tariff.allowed_squads. This caused errors when users tried to purchase
or extend subscriptions with tariffs referencing deleted squads.

Now sync_with_remnawave also removes stale UUIDs from all tariffs.
2026-02-11 18:37:19 +03:00
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 640da34736 fix: remove DisplayNameRestrictionMiddleware
Blocking users based on display name patterns caused false positives
for legitimate users. Removed middleware registration from dispatcher.
2026-02-11 18:31:50 +03:00
Fringg 93bb8e0eb4 fix: allow email change for unverified emails
Unverified email users could not change their email (e.g. to fix a typo)
because the endpoint required email_verified=True. Now unverified emails
are replaced directly without code verification, and a new verification
email is sent to the updated address.
2026-02-11 18:28:52 +03:00
Fringg 7d9ced8f4f fix: delete subscription_servers before subscription to prevent FK violation
reset_user_subscription and reset_trial endpoints did not clean up
subscription_servers rows before deleting the subscription, causing
ForeignKeyViolationError on subscription_servers.subscription_id_fkey.

Also fixed the same missing cleanup in user_service.hard_delete_user.
2026-02-11 18:25:42 +03:00
Fringg b5998ea9d2 fix: use traffic topup config and add WATA 429 retry
- Cabinet API: use get_traffic_topup_packages() instead of
  get_traffic_packages() in classic mode endpoints (lines 622, 727, 2410)
  to prevent infinite free traffic exploit via initial-purchase packages
- WATA service: add retry logic for 429 rate limit responses with
  Retry-After parsing from header and response body, up to 2 retries,
  downgrade 429 from error to warning log level
2026-02-11 18:20:30 +03:00
Egor aabadf1ffd Merge pull request #2592 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.10.1
2026-02-11 06:11:43 +03:00
github-actions[bot] e5e5bb3354 chore(main): release 3.10.1 2026-02-11 03:11:02 +00:00
Egor ea41b0af7a Merge pull request #2591 from BEDOLAGA-DEV/dev
Dev
2026-02-11 06:10:38 +03:00
Fringg 3193ffbd1b fix: change CryptoBot URL priority to bot_invoice_url for Telegram opening 2026-02-11 05:50:43 +03:00
Egor 5da01cc6df Merge pull request #2590 from BEDOLAGA-DEV/main
w
2026-02-11 04:47:13 +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 6cec024e46 fix: use flush instead of commit in server counter functions
add_user_to_servers and remove_user_from_servers were calling
db.commit() internally, breaking transaction atomicity for all
callers that perform additional operations afterward. Changed to
db.flush() so the caller controls the commit boundary.
2026-02-11 04:15:50 +03:00
Fringg 2094886990 fix: address review issues in backup, updates, and webhook handlers
- backup: add DATE column parsing in restore, use is_file() in delete_backup
- updates: add missing callback.answer() in show_updates_menu early return
- webhook: add server counter decrement and SubscriptionServer cleanup on user deletion, use single commit
2026-02-11 04:09:39 +03:00
Fringg b0fd38d60c fix: clear subscription data when user deleted from Remnawave panel
Previously only status was set to expired and remnawave_uuid cleared.
Now also clears subscription_url, subscription_crypto_link,
remnawave_short_uuid, and connected_squads so the bot correctly
shows no active subscription after panel deletion.
2026-02-11 04:02:09 +03:00
Fringg 3a680b41b0 fix: suppress 'message is not modified' error in updates panel
- Remove dangling version_info['repo_url'] expression
- Handle 'message is not modified' in all three update handlers
  to prevent error screen on repeated button clicks
2026-02-11 03:47:30 +03:00
Fringg 02e40bd6f7 fix: expand backup coverage to all 68 models and harden restore
- Add 37 missing models to backup (payment providers, polls, contests,
  wheel, FAQ, promo offers, webhooks, configs, menu buttons, etc.)
- Add tariff_promo_groups and payment_method_promo_groups association tables
- Replace hardcoded association restore with generic handler
- Fix transaction atomicity: flush instead of commit in inner methods,
  remove inner rollback calls, single commit/rollback in outer handler
- Fix composite PK support for UserPromoGroup (was only detecting first PK)
- Fix duplicate insert bug when clear_existing=True and record already exists
- Add cabinet_refresh_tokens to clear list, fix support_audit_logs deletion order
- Add Time column parsing for ReferralContest.daily_summary_time
- Security: tarfile filter='data', path traversal protection in _restore_files
  and delete_backup, os.sep in startswith checks
2026-02-11 03:35:16 +03:00
Fringg 19dabf3851 fix: allow purchase when recalculated price is lower than cached
Only block purchase when the price increased (user would overpay).
When a promo discount activates between viewing price and confirming,
the recalculated price is lower — allow the purchase at the new price
instead of forcing the user to restart the checkout flow.
2026-02-11 02:30:40 +03:00
Fringg eaf3a07579 fix: use callback fallback when MINIAPP_CUSTOM_URL is not set
Only consider MINIAPP_CUSTOM_URL for miniapp buttons, not the
purchase-only MINIAPP_PURCHASE_URL which cannot display subscription
info and loads indefinitely. When no custom URL is configured, fall
back to regular callback_data so the bot shows subscription natively.
2026-02-11 01:58:40 +03:00
Fringg be1da976e1 fix: ignore 'message is not modified' on privacy policy decline
User clicking Decline twice produced the same edit_text causing
TelegramBadRequest. Silently ignore it and remove pointless retry.
2026-02-11 01:40:49 +03:00
Fringg a1ffd5bda6 fix: prevent cascading greenlet errors after sync rollback
After db.rollback() all ORM objects expire. Subsequent attribute access
triggers lazy load in async context causing greenlet_spawn errors for
every remaining user. Break the sync loop after rollback instead of
continuing with a corrupted session.

Also downgrade TelegramNetworkError to warning in channel_checker.
2026-02-11 01:39:39 +03:00
Fringg d58a80f3ea fix: handle StaleDataError in webhook when user already deleted
When a user is deleted via cabinet, RemnaWave sends user.disabled webhook
but the subscription row is already cascade-deleted. This caused
StaleDataError on commit + PendingRollbackError when logging user.id.

Save user_id before handler call and catch StaleDataError as warning.
2026-02-11 01:18:58 +03:00
Egor 45c7afe34c Update README.md 2026-02-11 01:03:58 +03:00
Fringg e43a8d6ce4 fix: downgrade Telegram timeout errors to warning in monitoring service
Add TelegramNetworkError handling before generic Exception catch in all
notification methods to prevent timeout errors from generating error
reports in chat. Timeouts are transient network issues, not bugs.
2026-02-10 23:11:48 +03:00
Fringg e94b93d0c1 fix: handle nullable traffic_limit_gb and end_date in subscription model
Add None-safety guards to Subscription model properties (is_active,
is_expired, should_be_expired, actual_status, days_left,
traffic_used_percent) and pricing handler comparisons to prevent
TypeError when nullable columns contain None values.
2026-02-10 20:35:42 +03:00
Egor 2ad26a9156 Merge pull request #2588 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.10.0
2026-02-10 07:59:27 +03:00
github-actions[bot] 3383b9c790 chore(main): release 3.10.0 2026-02-10 04:58:24 +00:00
Egor 6acaf18203 Merge pull request #2587 from BEDOLAGA-DEV/dev
Release: dev → main
2026-02-10 07:57:54 +03:00
Fringg 019fbc12b6 fix: webhook:close button not working due to channel check timeout
Channel checker middleware called bot.get_chat_member() which could
timeout (60s), causing callback.answer() to fail with "query too old".

Skip channel check for lightweight UI callbacks (webhook:close,
ban_notify:delete, noop). Also answer callback before delete attempt
and add fallback to remove keyboard if delete fails.
2026-02-10 07:54:24 +03:00
Fringg 5156d635f0 fix: sync subscription status from panel in user.modified webhook
When subscription was extended in panel, webhook updated end_date but
left status as expired. Now syncs ACTIVE/DISABLED status from panel
payload when end_date is in the future.
2026-02-10 07:49:10 +03:00
Fringg f77922522a fix: allow non-HTTP deep links in crypto link webhook updates
_is_valid_url only accepted http(s), silently dropping valid deep links
like happ://, vless://, ss:// from revoked webhook payloads.
Added _is_valid_link that accepts any URI scheme.
2026-02-10 07:41:32 +03:00
Fringg 0db00a8f90 style: format cryptobot.py with ruff 2026-02-10 07:33:42 +03:00
Fringg fe54640885 fix: add missing placeholders to Arabic SUBSCRIPTION_INFO template
Was just a header text without {status}, {type}, etc. placeholders,
causing KeyError when .format() was called.
2026-02-10 07:30:52 +03:00
Fringg ec8eaf52bf fix: downgrade transient API errors (502/503/504) to warning level
502/503/504 are transient errors that don't need ERROR reports in chat.
Also downgrade API connection test failure to warning.
2026-02-10 07:27:20 +03:00
Fringg fe5f5ded96 feat: add MULENPAY_WEBSITE_URL setting for post-payment redirect
Previously website_url was hardcoded to WEBHOOK_URL, redirecting users
to the webhook endpoint after payment. Now configurable via env var.
2026-02-10 07:25:58 +03:00
Fringg 2cb6d731e9 fix: stop CryptoBot webhook retry loop and save cabinet payments to DB
Cabinet was calling CryptoBotService.create_invoice() directly without
saving CryptoBotPayment to DB. When webhook arrived, payment lookup
failed and returned HTTP 400, causing infinite retries.

Now cabinet uses PaymentService.create_cryptobot_payment() (same as
miniapp) with proper USD conversion via currency_converter.

Also return HTTP 200 for unknown invoice_ids to stop retry spam.
2026-02-10 07:25:54 +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 8e85e244cb feat: handle errors.bandwidth_usage_threshold_reached_max_notifications webhook
Last remaining unhandled RemnaWave backend event — sends admin
notification when the bandwidth threshold notification limit is reached.
2026-02-10 06:34:20 +03:00
Fringg 43a326a98c feat: handle service.subpage_config_changed webhook event
Add admin notification when subscription page config is
created, updated or deleted in RemnaWave panel.
2026-02-10 06:32:52 +03:00
Fringg d9de15a5a0 feat: add close button to all webhook notifications
Add dismissible close button (✖️) to every webhook notification message.
Users can now close any webhook notification by tapping the button,
which deletes the message via webhook:close callback handler.
2026-02-10 06:22:17 +03:00
Fringg 17ce64037f fix: build composite device name from platform + hwid short suffix
Show "tag (platform)" when tag is set, "iOS (ab12cd34)" when only
platform and hwid available, or just platform as last resort.
2026-02-10 06:16:37 +03:00
Fringg 79793c47bb fix: extract device name from nested hwidUserDevice object
RemnaWave sends device info in data.hwidUserDevice, not top-level.
Try tag, deviceName, platform, hwid fields from nested object first.
2026-02-10 06:14:01 +03:00
Fringg 7091eb9c14 fix: add action buttons to webhook notifications and fix empty device names
- Add keyboard buttons to all webhook notifications: renew, connect,
  my subscription, buy traffic — context-appropriate per event type
- Extract device name from multiple possible payload fields (deviceName,
  tag, hwid, device, platform, name) with fallback to dash
- Log payload keys for device events to identify correct field names
2026-02-10 06:09:00 +03:00
Fringg dc1e96bbe9 fix: security and architecture fixes for webhook handlers
- Add html.escape() to all untrusted webhook data in admin and device
  notifications (prevents HTML/Telegram injection)
- Add public send_webhook_notification() and is_enabled property to
  AdminNotificationService (eliminates private method access)
- Add dedicated NotificationType enum values for device and not_connected
  events (fixes incorrect semantic mapping)
- Extend user resolution to handle nested user objects and userUuid for
  device-scope events
- Replace manual __anext__() DB session with AsyncSessionLocal context
  manager; skip DB session for admin-only events
- Replace deprecated datetime.utcnow() with datetime.now(UTC)
- Use db.flush() instead of db.commit() in handlers (router commits)
- Wrap _notify_user in try/except to prevent notification failures from
  rolling back successful DB mutations
2026-02-10 05:55:48 +03:00
Fringg 1e37fd9dd2 feat: add all remaining RemnaWave webhook events (node, service, crm, device)
Handle all 44 webhook events: admin alerts for node health (connection
lost/restored), service security (login attempts), CRM billing reminders,
plus user-facing device added/deleted and not_connected notifications
with localized messages across all 5 languages.
2026-02-10 05:47:35 +03:00
Fringg 9aa22af339 fix: use event field directly as event_name (already includes scope prefix)
RemnaWave sends event as "user.modified", not "modified".
Concatenating scope + event produced "user.user.modified" which
didn't match any handler keys.
2026-02-10 05:31:39 +03:00
Fringg 26637f0ae5 feat: unified notification delivery for webhook events (email + WS support)
- Replace direct bot.send_message with notification_delivery_service
- Email-only and OAuth users now receive webhook notifications via email/WS
- Add 10 new NotificationType enum values for webhook subscription events
- Map all webhook text_keys to NotificationType for unified routing
2026-02-10 05:16:59 +03:00
Fringg 6d67cad3e7 feat: add RemnaWave incoming webhooks for real-time subscription events
- Add FastAPI webhook endpoint with HMAC-SHA256 signature verification
- Handle 16 user events: expired, disabled, enabled, limited, traffic_reset,
  modified, deleted, revoked, created, expires_in_72h/48h/24h,
  expired_24h_ago, first_connected, bandwidth_threshold
- URL validation for subscription_url/subscription_crypto_link (XSS prevention)
- 64KB body size limit, 32-char minimum secret enforcement
- Sanitized percent value in bandwidth threshold notifications
- DB rollback on handler errors to prevent dirty session commits
- Localization for all 5 languages (ru, en, ua, zh, fa)
2026-02-10 05:13:39 +03:00
Fringg 90d9df8f0e fix: preserve payment initiation time in transaction created_at
Transaction created_at and completed_at showed identical timestamps
because webhook handlers created transactions with is_completed=True
in a single step. Now all 10 payment providers pass payment.created_at
to the transaction so created_at reflects when the user initiated
the payment, not when the webhook processed it.

Also: remove duplicate datetime import in inline.py, upgrade button
stats DB error logging from debug to warning, add index on
button_click_logs.button_type for analytics queries.
2026-02-10 04:26:23 +03:00
Egor ef654a09bb Merge pull request #2586 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.9.1
2026-02-10 04:05:23 +03:00
github-actions[bot] 74f3b388d8 chore(main): release 3.9.1 2026-02-10 01:04:57 +00:00
Egor 5af1f358b2 Merge pull request #2585 from BEDOLAGA-DEV/dev
Release: dev -> main
2026-02-10 04:04:30 +03:00
Fringg 994325360c fix: don't delete Heleket invoice message on status check
_process_heleket_payload deleted the invoice message on every call,
including manual "check status" presses. Now only deletes on final
statuses (paid, cancel, fail, etc.) so the payment UI stays visible
while the user is still waiting.

Also includes subscription fallback query fix (actual DB columns).
2026-02-10 03:50:21 +03:00
Fringg f0e7f8e3be fix: use actual DB columns for subscription fallback query
Subscription.is_active is a Python property, not a column — query
status/end_date/is_trial columns instead. Also restore subscription=None
initialization to avoid UnboundLocalError on line 112.
2026-02-10 03:44:34 +03:00
Fringg 40d8a6dc8b fix: safe HTML preview truncation and lazy-load subscription fallback
Rules editor crashed when preview truncated mid-HTML tag (e.g.
<blockquote> cut to <blockquo), causing Telegram parse error.
Strip HTML tags before truncating preview text.

Also fix MissingGreenlet in build_topup_success_keyboard: fall back
to a direct DB query instead of showing wrong button text.
2026-02-10 03:32:20 +03:00
Egor 6488dcfcb2 Merge pull request #2584 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.9.0
2026-02-09 23:08:05 +03:00
github-actions[bot] 9ec5f7f59e chore(main): release 3.9.0 2026-02-09 20:07:13 +00:00
Egor 0621a3febc Merge pull request #2582 from BEDOLAGA-DEV/dev
Release: remove auto-activation, Flask cleanup, production bug fixes
2026-02-09 22:42:36 +03:00
Fringg ebd6bee05e feat: allow tariff deletion with active subscriptions
Remove blocking check that prevented tariff deletion when subscriptions
exist. DB schema already supports SET NULL on tariff FK, so subscriptions
gracefully become "legacy" and users pick a new tariff on renewal.
Return affected_subscriptions count in API response.
2026-02-09 22:30:26 +03:00
Fringg 119f463c36 refactor: remove Flask, use FastAPI exclusively for all webhooks
Delete dead Flask-based PAL24 webhook server (app/external/pal24_webhook.py).
PAL24 webhooks already handled by unified FastAPI server on port 8080.

- Remove flask dependency from pyproject.toml and requirements.txt
- Remove PAL24_WEBHOOK_PORT config (unused, FastAPI uses shared port)
- Remove pal24_webhook module reference from log filter
- Update docs: webhook example rewritten from Flask to FastAPI
- Uninstall flask, werkzeug, blinker, itsdangerous
2026-02-09 21:54:15 +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
Egor 65ba50c2cf Merge pull request #2547 from DenyaBanan/patch-1
Fix 401 error
2026-02-09 21:10:04 +03:00
Egor cc54a7ad2f Merge pull request #2580 from xenral/main
feat(localization): add Persian (fa) locale support and wire it across app flows
2026-02-09 21:09:43 +03:00
PEDZEO 7b0403a307 feat: add lite mode functionality with endpoints for retrieval and update
Introduced a new feature for lite mode, including a GET endpoint to retrieve the current lite mode setting and a PATCH endpoint to update it. Added corresponding response and update models for lite mode management.
2026-02-09 18:18:56 +03:00
Fringg 142ff14a50 perf: cache logo file_id to avoid re-uploading on every message
After first logo upload, Telegram returns a file_id that can be reused
for all subsequent sends. This eliminates 3-4 second delay per message
caused by re-uploading the same file from disk every time.
2026-02-09 18:14:54 +03:00
Ali Morshedzadeh 29a3b395b6 feat: add Persian (fa) locale with complete translations
Translate all bot strings to Persian, including admin panel, user interface, payment flows, contests, monitoring, and promotional features. Add RTL text support and Persian-specific formatting for dates, numbers, and currency displays.
2026-02-09 18:24:28 +03:30
Fringg 49871f82f3 fix: prevent sync from overwriting end_date for non-ACTIVE panel users
sync_users_to_panel uses _safe_expire_at_for_panel which replaces past
end_dates with now+1min for expired subscriptions. When sync_users_from_panel
reads these artificial dates back, it treated them as legitimate "newer"
dates and overwrote all expired subscriptions' end_date to approximately
current time. This caused all subscription end dates to show as "just now"
after sync.

Fix: only update end_date from panel when the panel user status is ACTIVE.
For EXPIRED/DISABLED users, the panel date may be a _safe_expire_at artifact
and should not override the real expiry date in the local database.
2026-02-09 17:39:25 +03:00
Fringg efa3a5d457 refactor: remove "both" mode from BOT_RUN_MODE, keep only polling and webhook 2026-02-09 17:32:17 +03:00
Fringg 0b86f379b4 fix: nullify payment FK references before deleting transactions in user restoration
The user restoration flow deleted transactions without first clearing
foreign key references from payment tables (yookassa_payments,
cryptobot_payments, etc.) and referral_earnings. This caused
IntegrityError when a deleted user had payment records linked to
transactions.
2026-02-09 17:19:45 +03:00
Fringg 1cae7130bc fix: promo code max_uses=0 conversion and trial UX after promo activation
- Convert max_uses=0 to 999999 (unlimited) in cabinet and webapi routes,
  matching bot handler behavior. Fixes miniapp-created promo codes being
  immediately invalid due to is_valid check (current_uses < max_uses).
- Skip trial offer in post-registration keyboard when promo code already
  activated a subscription, showing "back to menu" button instead.
2026-02-09 17:13:11 +03:00
Fringg 45410168af fix: use selection.period.days instead of selection.period_days
PurchaseSelection dataclass has period: PurchasePeriodConfig (with .days),
not period_days. This caused admin notification to fail silently on every
subscription purchase from cabinet.
2026-02-09 16:45:36 +03:00
Ali Morshedzadeh 5482e609f8 Add initial Persian locale support and language handling updates 2026-02-09 16:53:50 +03:30
Fringg e79f598d17 fix: skip users with active subscriptions in admin inactive cleanup
Admin "Clear all" button was deleting inactive users regardless of
subscription status, destroying paid subscriptions. Now matches the
monitoring service behavior by checking is_active before deletion.
2026-02-09 05:53:30 +03:00
Egor 056070b6a4 Merge pull request #2578 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.8.0
2026-02-08 23:36:16 +03:00
github-actions[bot] 8b53c73ce8 chore(main): release 3.8.0 2026-02-08 20:35:58 +00:00
Egor e6ebf81752 Merge pull request #2577 from BEDOLAGA-DEV/dev
feat: admin panel enhancements & bug fixes
2026-02-08 23:35:17 +03:00
Fringg 11b8ab1959 feat: add admin updates endpoint for bot and cabinet releases
GET /cabinet/admin/updates/releases returns release history
and version info for both projects from GitHub API with caching.
2026-02-08 23:20:47 +03:00
Fringg 17e9259eb1 fix: include additional devices in tariff renewal price and display
Tariff renewal showed tariff.device_limit (default) instead of
subscription.device_limit (actual) and didn't add extra device
cost to the renewal price. Fixed in show_tariff_extend,
select_tariff_extend_period, and confirm_tariff_extend.
2026-02-08 23:01:11 +03:00
Fringg 02c30f8e7e feat: add system info endpoint for admin dashboard
Exposes bot version, Python version, uptime, total users and active
subscriptions via GET /cabinet/admin/stats/system-info.
2026-02-08 22:52:12 +03:00
Fringg 15c7cc2a58 feat: add server-side sorting for enrichment columns 2026-02-08 22:39:25 +03:00
Fringg f2dbab6171 feat: add enrichment data to CSV export
Extract _build_enrichment() helper, reuse in both GET /enrichment
endpoint and CSV export. CSV now includes: Connected Devices,
Total Spent (RUB), Sub Start, Sub End, Last Node columns.
2026-02-08 22:36:45 +03:00
Fringg 17af51ce0b fix: use correct pagination params (start/size) for bulk HWID devices
Remnawave API uses start/size (not take/skip) with default size=25.
Now fetches all devices with size=1000 per page. Remove debug logging.
2026-02-08 22:32:20 +03:00
Fringg 8f7fa76e6a fix: revert device pagination, add raw user data field discovery
Bulk device endpoint ignores take/skip params, causing duplicates.
Revert to single call. Add logging to discover extra fields in
panel user response that might include device count.
2026-02-08 22:26:06 +03:00
Fringg 4648a82da9 fix: paginate bulk device endpoint to fetch all HWID devices
The GET /api/hwid/devices endpoint returns only 25 devices by default.
Add take/skip pagination to fetch all devices across all pages.
2026-02-08 22:21:55 +03:00
Fringg 5be82f2d78 fix: add enrichment device mapping debug logs 2026-02-08 22:18:46 +03:00
Fringg 9e3aa23f69 chore: remove debug logging from enrichment endpoint 2026-02-08 22:14:35 +03:00
Fringg 46da31d89c fix: add debug logging for bulk device response structure 2026-02-08 22:11:54 +03:00
Fringg 5f219c33e6 fix: use bulk device endpoint instead of per-user calls
Replace O(users) per-user GET /api/hwid/devices/{uuid} calls
with single GET /api/hwid/devices bulk call to avoid rate limiting.
2026-02-08 22:06:15 +03:00
Fringg 94fcf20d17 fix: add email field to traffic table for OAuth/email users
Include user email in UserTrafficItem schema, search filter,
CSV export, and frontend display (shown below name when no
Telegram username exists).
2026-02-08 22:04:42 +03:00
Fringg 9d39901f78 fix: use per-user panel endpoints for reliable device counts and last node data
Replace bulk /api/hwid/devices and /api/subscriptions calls with
proven per-user endpoints: get_all_users() (paginated) for last
connected node and get_user_devices() with semaphore for device counts.
2026-02-08 22:01:32 +03:00
Fringg 5cf3f2f76e feat: add traffic usage enrichment endpoint with devices, spending, dates, last node
Add GET /admin/traffic/enrichment that returns per-user enrichment data
(connected devices, total spending, subscription dates, last connected node)
via bulk panel API calls with 5-min server-side cache.
2026-02-08 21:49:42 +03:00
Fringg 2f90f9134d feat: add admin traffic packages and device limit management
Add TrafficPurchaseItem schema, extend subscription info with traffic
purchases, add add_traffic/remove_traffic/set_device_limit actions,
extend tariff builder with device/traffic config fields.
2026-02-08 21:13:44 +03:00
Fringg c57de1081a feat: add admin device management endpoints
Add GET/DELETE endpoints for managing user devices from admin panel:
- GET /{user_id}/devices - list connected devices
- DELETE /{user_id}/devices/{hwid} - remove single device
- DELETE /{user_id}/devices - reset all devices
2026-02-08 20:49:04 +03:00
Fringg 33d5155a8d style: format schemas and remnawave_service with ruff 2026-02-08 20:39:22 +03:00
Fringg 9828ff0845 fix: read bot version from pyproject.toml when VERSION env is not set
Previously the bot only checked os.getenv('VERSION'), returning
'UNKNOW' when unset. Now falls back to importlib.metadata and
direct pyproject.toml parsing, so the version stays correct after
release-please updates it.
2026-02-08 20:38:17 +03:00
Fringg da6f746b09 feat: add endpoint for updating user referral commission percent
POST /{user_id}/referral-commission allows admins to set individual
referral commission percentage (0-100) or null for system default.
2026-02-08 20:29:53 +03:00
Fringg 165965d8ea fix: add email/UUID fallback for OAuth user panel sync
OAuth users registering via cabinet have no telegram_id, causing
panel sync failures. All RemnaWave panel lookups now use a 3-level
chain: UUID → telegram_id → email. Also pass email and user_id to
format_remnawave_username to generate unique panel usernames.
2026-02-08 19:55:34 +03:00
Egor e7e01ce9c8 Merge pull request #2576 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.7.2
2026-02-08 19:03:29 +03:00
github-actions[bot] c4c49571ec chore(main): release 3.7.2 2026-02-08 16:03:08 +00:00
Egor 4a63124818 Merge pull request #2575 from BEDOLAGA-DEV/dev
Release: dev → main
2026-02-08 19:02:40 +03:00
Fringg d6fa86b870 fix: remove dots from Remnawave username sanitization
Remnawave API only allows letters, numbers, underscores and dashes in
usernames. The sanitizer regex was also allowing dots, causing OAuth
users with email-based usernames (e.g. john.doe@gmail.com) to fail
subscription creation with "Validation failed: invalid_string".
2026-02-08 19:00:03 +03:00
Fringg 55d281b0e3 fix: handle FK violation in create_yookassa_payment when user is deleted
Catch IntegrityError on INSERT into yookassa_payments when user_id
references a deleted user. Rollback the session and return None instead
of letting the unhandled exception propagate. Protects all callers
(webhook restore, bot handlers, cabinet API, miniapp API).
2026-02-08 18:52:34 +03:00
Egor a42bc9b281 Merge pull request #2574 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.7.1
2026-02-08 18:03:31 +03:00
github-actions[bot] 5bc5567ab1 chore(main): release 3.7.1 2026-02-08 15:03:06 +00:00
Egor d88ca980ec Merge pull request #2573 from BEDOLAGA-DEV/dev
fix: release-please config — remove blocked workflow files
2026-02-08 18:02:46 +03:00
Fringg 0ef4f55304 fix: resolve merge conflict in release-please config 2026-02-08 18:02:20 +03:00
Fringg 5070bb34e8 fix: remove workflow files and pyproject.toml from release-please extra-files
GitHub Actions cannot modify .github/workflows/ files (403 "Resource not
accessible by integration"), causing "Error adding to tree" failure.
pyproject.toml is already handled natively by python release type.
Only Dockerfile needs the generic updater for x-release-please-version markers.
2026-02-08 18:00:59 +03:00
Egor 02d38d7891 Merge pull request #2572 from BEDOLAGA-DEV/dev
Release: dev → main
2026-02-08 17:55:51 +03:00
Fringg c46cc85144 style: format tariff.py with ruff 2026-02-08 17:54:07 +03:00
Fringg 071c23dd52 fix: resolve multiple production errors and performance issues
- tickets.py: guard against non-text messages in waiting_for_title FSM state
- payments.py: fix Wata webhook using wrong field name (order_id vs orderId),
  add full payload to error log
- tariff.py: stop overwriting admin tariff settings on every bot restart,
  sync_default_tariff_from_config now only creates if no tariff exists
- start.py: catch TelegramBadRequest specifically for "message is not modified"
  instead of bare except with useless retry
- admin/tickets.py: downgrade ticket notification log from error to warning
  for expected case of OAuth/email users without telegram_id
- pricing.py, countries.py, purchase.py: guard against expired FSM state
  causing KeyError on 'period_days'
- blacklist_service.py: add 5-min in-memory cache to is_user_blacklisted()
  to reduce DB load from per-request checks
- remnawave_service.py: fix "Session is closed" race condition — create
  new RemnaWaveAPI instance per get_api_client() call instead of reusing
  shared instance whose aiohttp session gets overwritten by parallel coroutines
2026-02-08 17:40:51 +03:00
Egor 5f3e426750 Merge pull request #2571 from BEDOLAGA-DEV/fix/hwid-reset-and-webhook-fk-check
fix: resolve HWID reset and webhook FK violation
2026-02-08 16:48:50 +03:00
Fringg a9eee19c95 fix: resolve HWID reset context manager bug and webhook FK violation
- Fix async context manager usage in sync_users: __aenter__() result
  was not assigned, so hwid_api_client held the context manager object
  instead of the actual API client, causing AttributeError on
  reset_user_devices()
- Add user existence check in _restore_missing_yookassa_payment before
  INSERT to prevent ForeignKeyViolationError when user_id from payment
  metadata no longer exists in users table
2026-02-08 16:48:07 +03:00
Fringg 552a8ff8d8 chore: fix release-please to auto-bump Dockerfile and workflow versions
- Switch release-please to manifest mode (config-file + manifest-file)
- Add Dockerfile and docker workflow files as generic extra-files
- Add x-release-please-version annotations for automatic version replacement
- Bump hardcoded v3.6.0 to v3.7.0 to match current release
2026-02-07 13:57:54 +03:00
Egor bec78beb25 Merge pull request #2569 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.7.0
2026-02-07 13:51:12 +03:00
github-actions[bot] a6561a4788 chore(main): release 3.7.0 2026-02-07 10:49:47 +00:00
Egor c49acc956f Merge pull request #2568 from BEDOLAGA-DEV/dev
chore: release bot updates
2026-02-07 13:49:14 +03:00
Egor 4c40b5b370 Merge pull request #2567 from BEDOLAGA-DEV/feat/traffic-filters-daterange
feat: traffic filters, date range & risk columns in CSV export
2026-02-07 13:30:34 +03:00
Fringg 7c1a142653 feat: add risk columns to traffic CSV export
- Add total_threshold_gb and node_threshold_gb to ExportCsvRequest
- Compute GB/day, risk level, risk ratio for each user when thresholds set
- CSV includes Total GB/day, Risk Level, Risk Ratio, Risk GB/day columns
2026-02-07 13:29:16 +03:00
Egor a161e2f904 Merge pull request #2566 from BEDOLAGA-DEV/feat/traffic-filters-daterange
feat: node/status filters + custom date range for traffic page
2026-02-07 11:54:54 +03:00
Fringg ad260d9fe0 feat: add node/status filters and custom date range to traffic page
- Add node filter: filter traffic by selected nodes, recalculate totals
- Add status filter: filter by subscription status (active/trial/expired/disabled)
- Add custom date range: support start_date/end_date params alongside period
- Refactor _aggregate_traffic to use date strings with stable 5-min cache keys
- Add cache eviction for expired entries to prevent memory leaks
- CSV export now respects all active filters and custom date range
- Extract _get_status helper, add _compute_date_range helper
2026-02-07 11:53:04 +03:00
Fringg 3fd3bce2cf Revert "Merge pull request #2565 from BEDOLAGA-DEV/feat/traffic-filters-devices"
This reverts commit ad6522f547, reversing
changes made to 61bb8fcafd.
2026-02-07 11:29:31 +03:00
Egor ad6522f547 Merge pull request #2565 from BEDOLAGA-DEV/feat/traffic-filters-devices
feat: add node/status filters, date range, devices to traffic page
2026-02-07 11:21:41 +03:00
Fringg 9ea533a864 feat: add node/status filters, custom date range, connected devices to traffic page
- Add node filter (comma-separated UUIDs) and status filter query params
- Add custom date range (start_date/end_date) as alternative to period
- Fetch connected device count per user via HWID API (semaphore=10)
- Cache key changed to (start_str, end_str) tuple for both modes
- CSV export now respects all active filters and date range
- Backend returns available_statuses and filtered nodes list
- Validate future dates, max 31-day range
2026-02-07 11:19:45 +03:00
Egor 61bb8fcafd Merge pull request #2564 from BEDOLAGA-DEV/fix/yookassa-cabinet-payment-db-record
fix: use PaymentService for cabinet YooKassa payments
2026-02-07 10:36:12 +03:00
Fringg ff5bba3fc5 fix: use PaymentService for cabinet YooKassa payments to save local DB record
Cabinet was calling YooKassaService.create_payment() directly, bypassing
PaymentService which saves the payment record to the local database.
When YooKassa webhook arrived, the payment was not found in the DB,
causing payment processing failures.

Now uses PaymentService.create_yookassa_payment() and
create_yookassa_sbp_payment() consistently with all other payment methods.
Also standardizes metadata key from 'type' to 'purpose' to match bot flow.
2026-02-07 10:35:08 +03:00
Egor cc1c8bacb4 Merge pull request #2563 from BEDOLAGA-DEV/fix/traffic-legacy-endpoint
fix: use legacy per-node endpoint for traffic aggregation
2026-02-07 10:06:22 +03:00
Fringg b707b7995b fix: use legacy per-node endpoint with correct response format 2026-02-07 10:05:49 +03:00
Egor a076dfb550 Merge pull request #2562 from BEDOLAGA-DEV/fix/traffic-node-users-parsing
fix: correct response parsing for non-legacy node-users endpoint
2026-02-07 10:01:07 +03:00
Fringg 91ac90c2ae fix: correct response parsing for non-legacy node-users endpoint 2026-02-07 10:00:29 +03:00
Egor b12544d3ea Merge pull request #2561 from BEDOLAGA-DEV/fix/traffic-429-rate-limit
fix: resolve 429 rate limiting on traffic page
2026-02-07 09:49:21 +03:00
Fringg 38018514dc style: apply ruff formatting 2026-02-07 09:48:54 +03:00
Fringg 924d6bc09c fix: resolve 429 rate limiting on traffic page
- Switch from per-user to per-node API strategy in _aggregate_traffic
  (O(nodes) calls instead of O(users), ~10 vs ~200 requests)
- Add retry with exponential backoff for 429 in _make_request
- Reduce concurrency limit from 20 to 5 to prevent request bursts
2026-02-07 09:46:59 +03:00
Egor 1021c2cdcd Merge pull request #2560 from BEDOLAGA-DEV/feat/traffic-tariff-filter
feat: tariff filter + fix traffic data aggregation
2026-02-07 09:32:15 +03:00
Fringg fa01819674 feat: add tariff filter, fix traffic data aggregation
- Switch from get_bandwidth_stats_node_users (broken UUID matching) to
  get_bandwidth_stats_user per user (same API as working detail page)
- Add tariff filter with available_tariffs in response
- Add concurrency-limited parallel per-user bandwidth stats fetching
2026-02-07 09:31:47 +03:00
Egor eeed2d6369 Merge pull request #2559 from BEDOLAGA-DEV/fix/traffic-sort-type-error
fix: handle mixed types in traffic sort
2026-02-07 09:14:30 +03:00
Fringg a194be0843 fix: handle mixed types in traffic sort for string fields
Sort by tariff_name/full_name crashed with TypeError when some values
were None (fallback to 0) mixed with strings. Use empty string fallback
for string fields with case-insensitive comparison.
2026-02-07 09:13:57 +03:00
Egor aa1cd3829c Merge pull request #2558 from BEDOLAGA-DEV/feat/admin-traffic-usage
feat: add admin traffic usage API
2026-02-07 09:06:06 +03:00
Fringg 6c2c25d2cc feat: add admin traffic usage API with per-node statistics
Add paginated GET /admin/traffic endpoint aggregating per-user traffic
across all nodes with server-side sorting, search, and 5-min in-memory
cache. Add POST /admin/traffic/export-csv to generate CSV and send
to admin via Telegram DM.
2026-02-07 09:04:52 +03:00
Egor 0b61c7fe48 Merge pull request #2557 from BEDOLAGA-DEV/fix/version-notification-html-tags
fix: close unclosed HTML tags in version notification
2026-02-07 08:21:50 +03:00
Fringg b6745508da fix: close unclosed HTML tags when truncating version notification
Telegram API rejects messages with mismatched HTML tags. When
truncate_for_blockquote cuts the description mid-way, it can leave
tags like <i>, <b> unclosed inside the blockquote. Telegram then
fails with "Unmatched end tag" error.

Add _close_open_tags helper that scans for unclosed tags and appends
closing tags in reverse order. Also ensure the total length with
closing tags still fits within the message budget.
2026-02-07 08:18:39 +03:00
Egor f5391c3159 Merge pull request #2556 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.6.0
2026-02-07 07:24:28 +03:00
github-actions[bot] 9a81932d2b chore(main): release 3.6.0 2026-02-07 04:23:45 +00:00
Egor 8b50fde9aa Merge pull request #2555 from BEDOLAGA-DEV/dev
chore: sync dev → main (v3.6.0)
2026-02-07 07:23:01 +03:00
Fringg 8b924df64f chore: bump version to 3.6.0 in Dockerfile and workflows 2026-02-07 07:15:15 +03:00
Egor 7102c50f52 Merge pull request #2554 from BEDOLAGA-DEV/feat/node-usage-30day-cache
feat: return 30-day daily breakdown for node usage
2026-02-07 06:51:04 +03:00
Fringg e4c65ca220 feat: return 30-day daily breakdown for node usage
Always fetch 30 days with daily_bytes per node and categories.
Frontend computes period totals locally without extra API calls.
Removes days query param.
2026-02-07 06:50:47 +03:00
Egor 557dbf3ebe Merge pull request #2553 from BEDOLAGA-DEV/fix/parse-bandwidth-series
fix: parse bandwidth stats series format for node usage
2026-02-07 06:42:08 +03:00
Fringg 462f7a99b9 fix: parse bandwidth stats series format for node usage
Response is {categories, series: [{uuid, name, countryCode, total}]}.
Parse series array instead of treating dict keys as node UUIDs.
2026-02-07 06:42:03 +03:00
Egor c68c4e5984 Merge pull request #2552 from BEDOLAGA-DEV/fix/node-usage-single-api-call
fix: reduce node usage to 2 API calls to avoid 429 rate limit
2026-02-07 06:37:18 +03:00
Fringg f00a051bb3 fix: reduce node usage to 2 API calls to avoid 429 rate limit
Per-node queries (8+ calls) hit Remnawave rate limit. Switch back to
single get_bandwidth_stats_user call with %Y-%m-%d date format (same
as traffic_monitoring_service). Add response logging to debug format.
Also optimize panel-info to use accessible-nodes instead of all-nodes.
2026-02-07 06:36:38 +03:00
Egor b94e3edf80 Merge pull request #2551 from BEDOLAGA-DEV/fix/node-usage-per-node-query
fix: query per-node legacy endpoint for user traffic breakdown
2026-02-07 06:30:10 +03:00
Fringg 51ca3e42b7 fix: query per-node legacy endpoint for user traffic breakdown
The /api/bandwidth-stats/users/{uuid} endpoint rejects date params.
Switch to querying each accessible node via the working legacy
endpoint /api/bandwidth-stats/nodes/{uuid}/users/legacy and finding
the user in the per-node results.
2026-02-07 06:29:44 +03:00
Egor 943e9a86aa Merge pull request #2550 from BEDOLAGA-DEV/fix/node-usage-accessible-nodes
fix: use accessible nodes API and fix date format for node usage
2026-02-07 06:22:45 +03:00
Fringg c4da591731 fix: use accessible nodes API and fix date format for node usage
- Add get_user_accessible_nodes() to fetch user's available nodes
- Fix date format from ISO datetime to date-only (Y-m-d) for bandwidth stats
- Show all accessible nodes (with zero traffic if no stats)
- Add country_code to node usage response
2026-02-07 06:22:07 +03:00
Egor 287a43ba65 Merge pull request #2549 from BEDOLAGA-DEV/feature/admin-user-detail-enhanced
feat: add panel info, node usage endpoints and campaign to user detail
2026-02-07 06:09:13 +03:00
Fringg 070321230b feat: add panel info, node usage endpoints and campaign to user detail
- Add campaign_name/campaign_id to UserDetailResponse
- Add GET /admin/users/{user_id}/panel-info endpoint (config, links, traffic, connection)
- Add GET /admin/users/{user_id}/node-usage endpoint (per-node traffic breakdown)
- Add UserPanelInfoResponse, UserNodeUsageItem, UserNodeUsageResponse schemas
2026-02-07 06:07:10 +03:00
Egor 8886d0dea2 Merge pull request #2548 from BEDOLAGA-DEV/feat/user-tickets-tab
feat: add user_id filter to admin tickets endpoint
2026-02-07 05:22:20 +03:00
Fringg d3819c492f feat: add user_id filter to admin tickets endpoint
Allow filtering tickets by user_id query parameter in GET /admin/tickets.
2026-02-07 05:21:22 +03:00
Egor 3cbb9ef024 Merge pull request #2546 from BEDOLAGA-DEV/feature/oauth-authorization
feat: OAuth 2.0 authorization (Google, Yandex, Discord, VK)
2026-02-07 02:37:46 +03:00
Fringg 41633af763 refactor: fix transaction boundaries, extract _finalize_oauth_login, replace deprecated datetime.utcnow 2026-02-07 02:35:55 +03:00
DenyaBanan 916ad9d567 Fix 401 error
If there is a token, the bot checks it anyway, and cannot connect to the remnawave panel.
2026-02-07 03:33:16 +04:00
Fringg ccd9ab02c5 refactor: remove duplicated helpers, import from auth.py 2026-02-07 02:31:56 +03:00
Fringg d0a9cfe6a9 refactor: replace dataclass with BaseModel for OAuthUserInfo 2026-02-07 02:29:01 +03:00
Fringg 333a3c5901 fix: increase OAuth HTTP timeout to 30s 2026-02-07 02:23:02 +03:00
Fringg 0de6418bca refactor: add strict typing to OAuth providers, replace urlencode with httpx params 2026-02-07 02:14:37 +03:00
Fringg e9b98b837a feat: migrate OAuth state storage from in-memory to Redis 2026-02-07 02:08:02 +03:00
Fringg 97be4afbff feat: add OAuth 2.0 authorization (Google, Yandex, Discord, VK)
- Add OAuth provider config vars and helpers to config.py
- Add google_id, yandex_id, discord_id, vk_id columns to User model
- Create OAuth provider service with state management and 4 providers
- Add CRUD functions for OAuth user lookup, linking, and creation
- Add 3 API endpoints: providers list, authorize URL, callback
- Add alembic migration and universal_migration support
- Fix trial disable logic to cover OAuth auth_types
2026-02-07 01:58:55 +03:00
Egor 9ca24efe43 Merge pull request #2545 from BEDOLAGA-DEV/feature/disposable-email-blocking
feat: block registration with disposable email addresses
2026-02-07 00:36:37 +03:00
Fringg 116c8453bb feat: block registration with disposable email addresses
Add DisposableEmailService that fetches ~72k disposable email domains
from github.com/disposable/disposable-email-domains into an in-memory
frozenset with 24h auto-refresh via asyncio background task.

Integrated into three email entry points in cabinet auth routes:
- POST /email/register (link email to Telegram account)
- POST /email/register/standalone (standalone email registration)
- POST /email/change (change existing email)

Controlled by DISPOSABLE_EMAIL_CHECK_ENABLED setting (default: true).
Falls back to allowing all emails if domain list fetch fails.
2026-02-07 00:34:11 +03:00
Egor 4e7438b9f9 Merge pull request #2544 from BEDOLAGA-DEV/feature/trial-disabled-for-user-type
feat: disable trial by user type (email/telegram/all)
2026-02-07 00:20:38 +03:00
Fringg c4794db1dd feat: add TRIAL_DISABLED_FOR setting to disable trial by user type
New setting allows granular control over trial availability:
- none: trial available for all (default)
- email: trial disabled for email users
- telegram: trial disabled for telegram users
- all: trial disabled for everyone

Enforced in bot handlers, cabinet API, and miniapp routes.
Automatically appears in admin panel as dropdown via CHOICES.
2026-02-07 00:19:25 +03:00
Fringg 1ffb8a5b85 fix: pass tariff object instead of tariff_id to set_tariff_promo_groups 2026-02-07 00:01:55 +03:00
Egor 7ab1a7b88d Merge pull request #2543 from BEDOLAGA-DEV/dev
chore: sync dev → main (v3.5.0)
2026-02-06 23:57:09 +03:00
Fringg e3f932afe4 chore: bump version to 3.5.0 in Dockerfile and workflows 2026-02-06 23:55:36 +03:00
Egor 5ca2f62854 Merge pull request #2542 from BEDOLAGA-DEV/main
chore: sync main → dev
2026-02-06 23:48:19 +03:00
c0mrade 8afe613451 Merge pull request #2541 from BEDOLAGA-DEV/release-please--branches--main
chore(main): release 3.5.0
2026-02-06 23:44:40 +03:00
github-actions[bot] 8de9c6e532 chore(main): release 3.5.0 2026-02-06 20:42:00 +00:00
Egor b69fcbde11 Merge pull request #2540 from BEDOLAGA-DEV/dev
Release 3.4.1
2026-02-06 23:33:38 +03:00
Fringg 44d6b6b266 chore: bump version to 3.4.1 2026-02-06 23:31:46 +03:00
c0mrade 4234769e92 revert: remove signature pop from HMAC validation
Telegram includes signature in the hash computation, so removing it
from the data-check-string breaks HMAC validation for all users.
2026-02-06 22:27:57 +03:00
c0mrade c2cabbee09 fix: restore unquote for user data parsing in telegram auth
parse_qsl does not fully decode nested URL-encoded JSON in the user
field, so unquote() is still needed before json.loads().
2026-02-06 22:13:32 +03:00
c0mrade 067b1b6716 chore: remove unused unquote import 2026-02-06 21:55:45 +03:00
c0mrade 5b64046137 fix: exclude signature field from Telegram initData HMAC validation
Telegram Bot API 8.0+ adds a `signature` field to WebApp initData.
Per the official spec, both `hash` and `signature` must be excluded
from the data-check-string before HMAC verification. Without this,
users with newer Telegram clients get a hash mismatch and 401.

Also remove redundant `unquote()` in telegram_auth.py — `parse_qsl`
already URL-decodes values, so the extra decode could corrupt user
data containing percent-like sequences.
2026-02-06 21:51:38 +03:00
c0mrade 085a61721a Merge pull request #2538 from BEDOLAGA-DEV/feat/tariff-sorting-dnd
feat: tariff reorder API endpoint
2026-02-06 17:45:27 +03:00
Fringg 4c2e11e64b feat: add tariff reorder API endpoint
Add PUT /cabinet/admin/tariffs/order endpoint for drag-and-drop
tariff sorting in admin cabinet. Move db.commit() from CRUD to
route level for consistency.
2026-02-06 17:42:01 +03:00
c0mrade 7c5f35b1cf Merge pull request #2539 from BEDOLAGA-DEV/feat/remnawave-original-config-format
Feat/remnawave original config format
2026-02-06 17:35:13 +03:00
Egor 561708b777 Merge pull request #2537 from BEDOLAGA-DEV/fix/blacklist-middleware
fix: enforce blacklist via middleware
2026-02-06 15:54:01 +03:00
Fringg 806a959662 style: format blacklist middleware 2026-02-06 15:52:19 +03:00
Fringg 966a599c2c fix: enforce blacklist via middleware instead of per-handler checks
Add BlacklistMiddleware for aiogram that blocks all message/callback/pre_checkout
from blacklisted users globally. Add blacklist check to cabinet API dependency.
Fix case-insensitive username matching. Remove 10 redundant manual checks from handlers.
2026-02-06 15:48:21 +03:00
c0mrade 0ed98c39b6 fix: improve button URL resolution and pass uiConfig to frontend
- Add {{HAPP_CRYPT3_LINK}} template support in _resolve_button_url
- Only resolve templates for subscriptionLink and copyButton, not external
- Always send subscriptionUrl and subscriptionCryptoLink (hideLink is display-only flag)
- Pass uiConfig from RemnaWave config for block renderer selection
2026-02-05 20:08:47 +03:00
c0mrade 095bc00b33 feat: pass platform-level fields from RemnaWave config to frontend
Preserve svgIconKey, displayName and other platform-level fields
instead of only forwarding apps array. Build platformNames from
RemnaWave displayName with English-only fallback.
2026-02-05 14:27:46 +03:00
c0mrade 43762ce8f4 feat: serve original RemnaWave config from app-config endpoint
- Return original blocks/svgLibrary instead of converting to steps
- Enrich apps with deepLink and buttons with resolvedUrl
- Add _resolve_button_url helper for template substitution
- Keep legacy file-based format as fallback
2026-02-05 08:29:57 +03:00
Egor 51752713b3 Merge pull request #2536 from BEDOLAGA-DEV/dev
Release v3.4.0
2026-02-05 07:49:30 +03:00
Fringg b6fc63e33c chore: bump version to 3.4.0
Update version references across all files:
- pyproject.toml
- Dockerfile
- docker-hub.yml
- docker-registry.yml
- .release-please-manifest.json
2026-02-05 07:49:02 +03:00
Egor 488d5c99f7 Merge pull request #2535 from BEDOLAGA-DEV/feat/release-workflows
feat(ci): add release-please and release workflows
2026-02-05 07:42:50 +03:00
Fringg 9151882245 feat(ci): add release-please and release workflows
- Add release-please workflow for automated changelog and version bumps
- Add release workflow with categorized changelog (features, fixes, perf)
- Include contributors section and diff stats in release notes
- Add Docker pull instructions in release body
- Configure changelog sections for conventional commits
2026-02-05 07:37:46 +03:00
Egor 02eca28bc0 Merge pull request #2534 from BEDOLAGA-DEV/feat/version-notification-redesign
feat(notifications): redesign version update notification
2026-02-05 07:32:46 +03:00
Fringg 3f7ca7be3a feat(notifications): redesign version update notification
- Add GitHub Markdown to Telegram HTML converter utility
- Place release description in blockquote expandable
- Auto-truncate description to fit 4096 char message limit
- Clean compact layout with clickable version link
- Convert markdown headers, bold, italic, code, links, strikethrough
2026-02-05 07:29:55 +03:00
Egor f7abe03dba Merge pull request #2533 from BEDOLAGA-DEV/fix/autopay-notification-cooldown
fix(autopay): add 6h cooldown for insufficient balance notifications
2026-02-05 07:18:51 +03:00
Fringg 992a5cb97f fix(autopay): add 6h cooldown for insufficient balance notifications
- Use Redis key with 6h TTL to prevent notification spam on each monitoring cycle
- Fallback to sending notification if Redis is unavailable
- Key auto-expires when user tops up balance and autopay succeeds
2026-02-05 07:17:25 +03:00
Egor 3d94e63c3c Merge pull request #2532 from BEDOLAGA-DEV/fix/daily-tariff-autopay
fix(autopay): exclude daily subscriptions from global autopay
2026-02-05 07:12:03 +03:00
Egor 79569510d2 Merge pull request #2531 from BEDOLAGA-DEV/fix/broadcast-stability
fix(broadcast): stabilize mass broadcast for 100k+ users
2026-02-05 07:12:01 +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
Fringg 13ebfdb5c4 fix(broadcast): stabilize mass broadcast for 100k+ users
- Add real-time progress bar with updates every 500 msgs / 5 sec
- Fix Telegram rate limiting: batch=25, delay=1.0s (~25 msg/sec)
- Add global flood_wait_until to prevent semaphore slot starvation
- Add parse_mode=HTML for web API broadcasts
- Separate error handling for FloodWait, Forbidden, BadRequest
- Convert ORM objects to scalars before long broadcast operations
- Add email recipients dataclass to prevent detached ORM state
2026-02-05 07:10:43 +03:00
Egor e8a413c3c3 Merge pull request #2530 from BEDOLAGA-DEV/fix/cabinet-promo-discounts
fix(cabinet): apply promo group discounts to addons and tariff switch
2026-02-05 06:30:00 +03:00
Fringg aa1d3289e1 fix(cabinet): apply promo group discounts to device/traffic purchase and tariff switch
- Add discount calculation for purchase_devices and get_device_price endpoints
- Fix traffic purchase discount to use period-aware calculation
- Apply period discount to tariff switch upgrade_cost
- Return discount info in API responses for frontend display
2026-02-05 06:26:17 +03:00
Egor 94a00ab269 Merge pull request #2529 from BEDOLAGA-DEV/fix/sqlalchemy-connection-closed
fix(broadcast): resolve SQLAlchemy connection closed errors
2026-02-05 05:49:11 +03:00
Fringg b8682adbbf fix(broadcast): resolve SQLAlchemy connection closed errors during long broadcasts
- Extract scalar values from ORM objects before long operations
- Create fresh DB sessions for persist operations with retry mechanism
- Replace ORM User objects with telegram_id integers in broadcast loops
- Update .gitignore to exclude Python cache, IDE files, and local configs

Fixes: InterfaceError "connection is closed" and MissingGreenlet errors
during mass message broadcasts
2026-02-05 05:42:31 +03:00
Egor cf10eeda53 Merge pull request #2528 from BEDOLAGA-DEV/main
Update docker-registry.yml
2026-02-05 05:04:32 +03:00
Egor 3cfac7e2dc Update docker-registry.yml 2026-02-05 05:04:00 +03:00
Egor 39e111c91b Merge pull request #2527 from BEDOLAGA-DEV/main
W
2026-02-05 04:55:04 +03:00
Egor ba42517808 Update README.md 2026-02-05 00:25:48 +03:00
Egor 13846d621a Update README.md 2026-02-05 00:25:07 +03:00
Egor e612e2f383 Merge pull request #2526 from BEDOLAGA-DEV/dev
Dev
2026-02-04 05:02:03 +03:00
Egor 1f524ccd80 Add files via upload 2026-02-04 04:51:35 +03:00
Egor 37bde2985e Add files via upload 2026-02-04 04:51:12 +03:00
Egor c6a5e0d4be Add files via upload 2026-02-04 04:50:38 +03:00
Egor 3985053636 Add files via upload 2026-02-04 04:49:37 +03:00
Egor 4cfb1dd38f Add files via upload 2026-02-04 04:49:14 +03:00
Egor 117a417ce0 Add files via upload 2026-02-04 04:48:49 +03:00
Egor a2e0474572 Add files via upload 2026-02-04 04:48:29 +03:00
Egor e992891691 Add files via upload 2026-02-04 04:48:01 +03:00
Egor 57cf8687d4 Add files via upload 2026-02-04 04:47:39 +03:00
Egor 27870bbdcb Update main.py 2026-02-04 04:47:24 +03:00
Egor 21d48078ed Merge pull request #2525 from BEDOLAGA-DEV/dev
Update admin_notification_service.py
2026-02-04 03:58:14 +03:00
Egor afb4f162d0 Update admin_notification_service.py 2026-02-04 03:55:59 +03:00
Egor 96d479780f Merge pull request #2524 from BEDOLAGA-DEV/dev
Update admin_promo_offers.py
2026-02-04 03:23:53 +03:00
Egor 2e0cd5d54c Update admin_promo_offers.py 2026-02-04 03:23:35 +03:00
Egor c4374ce483 Merge pull request #2523 from BEDOLAGA-DEV/dev
Dev
2026-02-04 03:05:46 +03:00
Egor bd1a0d4a4e Update wata.py 2026-02-04 03:05:22 +03:00
Egor 97f4cc0f7c Update subscription.py 2026-02-04 02:57:41 +03:00
Egor 3ebbb42096 Update inline.py 2026-02-04 02:57:12 +03:00
Egor 07ae7c2a7f Update traffic.py 2026-02-04 02:56:47 +03:00
Egor 5c3505aec9 Merge pull request #2522 from BEDOLAGA-DEV/dev
Update menu.py
2026-02-04 02:16:23 +03:00
Egor fffa231b7e Update menu.py 2026-02-04 02:15:45 +03:00
Egor f8db099d0f Merge pull request #2521 from BEDOLAGA-DEV/dev
Dev
2026-02-04 02:10:58 +03:00
Egor 9483517258 Add files via upload 2026-02-04 02:08:18 +03:00
Egor 0c0ab58236 Update promocode.py 2026-02-04 02:07:27 +03:00
Egor 92ec1219fa Add files via upload 2026-02-04 02:06:47 +03:00
Egor bf72e81d55 Update promocode_service.py 2026-02-04 02:06:13 +03:00
Egor 5a008e59a2 Merge pull request #2520 from BEDOLAGA-DEV/dev
Update subscription.py
2026-02-03 23:57:22 +03:00
Egor 61b8d586d3 Update subscription.py 2026-02-03 23:56:55 +03:00
Egor df62e2bd96 Merge pull request #2519 from BEDOLAGA-DEV/dev
Update subscription.py
2026-02-03 23:45:08 +03:00
Egor 07e8990ddb Update subscription.py 2026-02-03 23:44:15 +03:00
Egor 40fc4d7267 Merge pull request #2518 from BEDOLAGA-DEV/dev
Dev
2026-02-03 04:38:57 +03:00
Egor 5ffd3093ea Update users.py 2026-02-03 04:38:01 +03:00
Egor 01ac2c7ed0 Update admin_users.py 2026-02-03 04:37:25 +03:00
Egor 937a25aafd Update pyproject.toml 2026-02-03 04:29:27 +03:00
Egor aeee018a53 Merge pull request #2517 from BEDOLAGA-DEV/dev
Update subscription.py
2026-02-03 04:14:40 +03:00
Egor 5cef11f32b Update subscription.py 2026-02-03 04:14:15 +03:00
Egor 467f67907f Merge pull request #2516 from BEDOLAGA-DEV/dev
Dev
2026-02-03 03:58:59 +03:00
Egor 6d38531f42 Add files via upload 2026-02-03 03:58:31 +03:00
Egor 2dd057a911 Update subscription.py 2026-02-03 03:56:27 +03:00
Egor 4178e4b024 Add files via upload 2026-02-03 03:53:18 +03:00
Egor 21bcde26e5 Add files via upload 2026-02-03 03:52:56 +03:00
Egor 878606d745 Add files via upload 2026-02-03 03:52:29 +03:00
Egor 45a90876da Add files via upload 2026-02-03 03:52:08 +03:00
Egor bb4f496b21 Add files via upload 2026-02-03 03:50:33 +03:00
Egor 47c1de1cc8 Add files via upload 2026-02-03 03:50:05 +03:00
Egor f69156d7ee Update subscription.py 2026-02-03 03:43:51 +03:00
Egor c9d559e3f2 Update subscription.py 2026-02-03 03:41:18 +03:00
Egor e28a48853d Add files via upload 2026-02-03 03:40:08 +03:00
Egor b13da1f2e8 Add files via upload 2026-02-03 03:39:45 +03:00
Egor ba1bf677d6 Add files via upload 2026-02-03 03:39:21 +03:00
Egor ccdff05dca Add files via upload 2026-02-03 03:38:51 +03:00
Egor 03875b593e Add files via upload 2026-02-03 03:38:14 +03:00
Egor 06224d798d Add files via upload 2026-02-03 03:37:43 +03:00
Egor 966f436723 Merge pull request #2514 from BEDOLAGA-DEV/dev
Update cloudpayments.py
2026-02-03 03:32:10 +03:00
Egor 4941fe9469 Update cloudpayments.py 2026-02-03 03:31:48 +03:00
Egor fe56078481 Merge pull request #2513 from BEDOLAGA-DEV/dev
Update cloudpayments.py
2026-02-03 03:28:13 +03:00
Egor 39742499b8 Update cloudpayments.py 2026-02-03 03:27:53 +03:00
Egor d8207fa1f0 Merge pull request #2512 from BEDOLAGA-DEV/dev
Update cloudpayments.py
2026-02-03 03:23:48 +03:00
Egor 7eb302aab0 Update cloudpayments.py 2026-02-03 03:23:23 +03:00
Egor 8cb5da4f74 Merge pull request #2511 from BEDOLAGA-DEV/dev
Dev
2026-02-03 03:17:18 +03:00
Egor cad786f6ee Add files via upload 2026-02-03 03:15:34 +03:00
Egor 0adc7145a1 Update user_service.py 2026-02-03 03:14:39 +03:00
Egor d35f54a4db Merge pull request #2510 from BEDOLAGA-DEV/main
w
2026-02-03 03:14:01 +03:00
c0mrade 000d670869 Merge pull request #2506 from BEDOLAGA-DEV/fix/ticket-settings-route-order
fix: move /settings routes before /{ticket_id} to fix route matching
2026-02-02 09:01:30 +03:00
c0mrade 0c9b69deb0 fix: move /settings routes before /{ticket_id} to fix route matching
Static routes must be defined before dynamic routes in FastAPI.
Previously /settings was matched as ticket_id parameter causing parsing error.
2026-02-02 08:58:07 +03:00
Egor 63e31e84fc Merge pull request #2505 from BEDOLAGA-DEV/dev
Dev
2026-02-02 05:27:02 +03:00
Egor 1bd301f21a Add files via upload 2026-02-02 05:26:41 +03:00
Egor 3dbaf99733 Update inline.py 2026-02-02 05:26:09 +03:00
Egor 4380611bee Merge pull request #2504 from BEDOLAGA-DEV/dev
Update subscription.py
2026-02-02 05:18:52 +03:00
Egor 5aca466d72 Update subscription.py 2026-02-02 05:18:11 +03:00
Egor 86970f0398 Update subscription.py 2026-02-02 05:16:58 +03:00
c0mrade 733be09658 Merge pull request #2503 from BEDOLAGA-DEV/fix/promo-groups-async
fix: add refresh before assigning promo_groups to avoid async lazy lo…
2026-02-02 04:58:00 +03:00
c0mrade 5e75210c8b fix: add refresh before assigning promo_groups to avoid async lazy load error 2026-02-02 04:55:27 +03:00
Egor cb0ccc9c77 Merge pull request #2502 from BEDOLAGA-DEV/dev
Dev
2026-02-02 03:37:47 +03:00
Egor 078eebfbb1 Update tariffs.py 2026-02-02 03:37:21 +03:00
Egor 4049e0d9ff Update decorators.py 2026-02-02 03:36:38 +03:00
Egor 7bf7b942ba Merge pull request #2501 from BEDOLAGA-DEV/dev
Update blocked_users_service.py
2026-02-02 03:19:08 +03:00
Egor 4f1c14fda0 Update blocked_users_service.py 2026-02-02 03:18:46 +03:00
Egor 7bd6ae3c26 Merge pull request #2500 from BEDOLAGA-DEV/dev
Update blocked_users_service.py
2026-02-02 03:10:50 +03:00
Egor caeafc7abd Update blocked_users_service.py 2026-02-02 03:10:27 +03:00
Egor 4d249a3bc9 Merge pull request #2499 from BEDOLAGA-DEV/dev
Update blocked_users.py
2026-02-02 03:02:20 +03:00
Egor 1f26b522b4 Update blocked_users.py 2026-02-02 03:01:56 +03:00
Egor d1ed6c1b18 Merge pull request #2498 from BEDOLAGA-DEV/dev
Dev
2026-02-02 02:59:40 +03:00
Egor d4d89ec20d Update blocked_users.py 2026-02-02 02:59:17 +03:00
Egor 6a2fd5a7de Add files via upload 2026-02-02 02:58:22 +03:00
Egor f41c5a10b6 Update blocked_users.py 2026-02-02 02:57:29 +03:00
Egor 3e873a05a4 Update blocked_users_service.py 2026-02-02 02:56:58 +03:00
Egor c22f41cbf2 Merge pull request #2497 from BEDOLAGA-DEV/dev
Update blocked_users_service.py
2026-02-02 02:53:39 +03:00
Egor f3851b9ecc Update blocked_users_service.py 2026-02-02 02:53:10 +03:00
Egor 9a258744f2 Merge pull request #2496 from BEDOLAGA-DEV/dev
Dev
2026-02-02 02:50:14 +03:00
Egor 8780ae9407 Update blocked_users_service.py 2026-02-02 02:49:23 +03:00
Egor 3f886df44f Update blocked_users.py 2026-02-02 02:48:57 +03:00
Egor e3c6d4a5a1 Add files via upload 2026-02-02 02:47:49 +03:00
Egor c3215a1e54 Update bot.py 2026-02-02 02:47:00 +03:00
Egor fdd5a8aa6e Update admin.py 2026-02-02 02:46:39 +03:00
Egor c1792f487a Add files via upload 2026-02-02 02:46:03 +03:00
Egor f27f0f8bca Merge pull request #2495 from BEDOLAGA-DEV/dev
Update startup_notification_service.py
2026-02-02 02:21:02 +03:00
Egor c70ddfe157 Update startup_notification_service.py 2026-02-02 02:20:41 +03:00
Egor 554d776b77 Merge pull request #2494 from BEDOLAGA-DEV/dev
Dev
2026-02-02 02:08:12 +03:00
Egor 34ac9eb6ed Update global_error.py 2026-02-02 02:05:50 +03:00
Egor 6cc48d2872 Update startup_notification_service.py 2026-02-02 02:05:28 +03:00
Egor 9fc31c25b2 Update startup_notification_service.py 2026-02-02 02:00:01 +03:00
Egor 73585ebc82 Update global_error.py 2026-02-02 01:59:25 +03:00
Egor e9d3e9a2be Merge pull request #2493 from BEDOLAGA-DEV/dev
Update global_error.py
2026-02-02 01:43:28 +03:00
Egor 3e6e2f577c Update global_error.py 2026-02-02 01:43:05 +03:00
Egor 39c644b505 Merge pull request #2492 from BEDOLAGA-DEV/dev
Dev
2026-02-02 01:36:39 +03:00
Egor 62500a6369 Update startup_notification_service.py 2026-02-02 01:34:40 +03:00
Egor 9e16b56d9a Update global_error.py 2026-02-02 01:34:06 +03:00
Egor 9dfadcda72 Merge pull request #2491 from BEDOLAGA-DEV/dev
Update global_error.py
2026-02-02 01:19:08 +03:00
Egor e2afdc28f3 Update global_error.py 2026-02-02 01:18:28 +03:00
Egor 86bd24edd4 Merge pull request #2490 from BEDOLAGA-DEV/dev
Dev
2026-02-02 01:07:29 +03:00
Egor 2bda556c4b Update main.py 2026-02-02 01:07:06 +03:00
Egor 60724a0354 Update startup_notification_service.py 2026-02-02 01:05:30 +03:00
Egor 250edec20e Merge pull request #2489 from BEDOLAGA-DEV/dev
Dev
2026-02-02 00:56:21 +03:00
Egor 6b1e78f990 Update maintenance_service.py 2026-02-02 00:55:56 +03:00
Egor 56f784c8bf Update maintenance_service.py 2026-02-02 00:54:10 +03:00
Egor ce822ead2b Update maintenance_service.py 2026-02-02 00:51:13 +03:00
Egor e606c1d4d5 Update startup_notification_service.py 2026-02-02 00:50:51 +03:00
Egor c204194b8b Update main.py 2026-02-02 00:50:01 +03:00
Egor 5a878239f3 Add files via upload 2026-02-02 00:49:29 +03:00
Egor 08aa8dabfd Merge pull request #2488 from BEDOLAGA-DEV/dev
Update subscription.py
2026-02-02 00:34:18 +03:00
Egor 20ed6071e2 Update subscription.py 2026-02-02 00:33:59 +03:00
Egor 8d34a4b3d2 Merge pull request #2487 from BEDOLAGA-DEV/dev
Dev
2026-02-02 00:28:21 +03:00
Egor 94a9528397 Update subscription.py 2026-02-02 00:27:51 +03:00
Egor 403052a840 Update tariff_purchase.py 2026-02-02 00:27:21 +03:00
Egor bb8e5bb6ca Update admin_notification_service.py 2026-02-02 00:26:53 +03:00
Egor 11ee8764a6 Merge pull request #2486 from BEDOLAGA-DEV/dev
Update admin_notification_service.py
2026-02-02 00:18:02 +03:00
Egor f9be0e6315 Update admin_notification_service.py 2026-02-02 00:17:20 +03:00
Egor 9e56c56528 Update admin_notification_service.py 2026-02-02 00:11:28 +03:00
Egor 85cf96b813 Merge pull request #2485 from BEDOLAGA-DEV/dev
Dev
2026-02-01 18:34:17 +03:00
Egor c16eee4ef2 Add files via upload 2026-02-01 18:33:12 +03:00
Egor b6bd2625c2 Update subscription.py 2026-02-01 18:32:29 +03:00
Egor 020343cdf8 Merge pull request #2484 from BEDOLAGA-DEV/dev
Dev
2026-02-01 18:11:23 +03:00
Egor c07fffd809 Update tariff_purchase.py 2026-02-01 18:10:59 +03:00
Egor afaeeaf7f1 Update subscription.py 2026-02-01 18:10:22 +03:00
Egor e946cc7354 Merge pull request #2483 from BEDOLAGA-DEV/dev
Dev
2026-02-01 17:28:42 +03:00
Egor bf6a966668 Update subscription.py 2026-02-01 17:28:21 +03:00
Egor 7f12fa7003 Update devices.py 2026-02-01 17:27:44 +03:00
Egor 5f6ef5993c Merge pull request #2482 from BEDOLAGA-DEV/dev
Dev
2026-02-01 17:22:07 +03:00
Egor f1ac67e511 Update devices.py 2026-02-01 17:18:00 +03:00
Egor 48f9f606aa Update subscription.py 2026-02-01 17:17:02 +03:00
Egor 7d9d1b0a6f Update inline.py 2026-02-01 17:16:28 +03:00
Egor afadf7160c Merge pull request #2481 from BEDOLAGA-DEV/main
w
2026-02-01 16:50:38 +03:00
Egor b546fbd1cc Merge pull request #2452 from Gy9vin/main
реф система и другое
2026-02-01 16:45:33 +03:00
Egor b8f1785783 Delete migrations/.DS_Store 2026-02-01 16:44:15 +03:00
gy9vin 7ee8c8ff4d Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2026-02-01 14:41:56 +03:00
gy9vin 551112d2d9 make fix 2026-02-01 14:41:45 +03:00
Mikhail e9dc9630b2 Merge branch 'BEDOLAGA-DEV:main' into main 2026-02-01 14:38:39 +03:00
Egor b068c1fb12 Merge pull request #2480 from BEDOLAGA-DEV/dev
Dev
2026-02-01 12:34:47 +03:00
Egor 9f66e176f7 Add files via upload 2026-02-01 12:34:24 +03:00
Egor c66bad99f0 Update devices.py 2026-02-01 12:33:57 +03:00
Egor f6a29760a9 Merge pull request #2479 from BEDOLAGA-DEV/dev
Dev
2026-02-01 11:29:14 +03:00
Egor d7e1b8fd5d Update user.py 2026-02-01 11:28:36 +03:00
Egor 54e9175bdf Update Dockerfile 2026-02-01 11:25:42 +03:00
gy9vin f581b10e19 fix 2026-02-01 11:23:42 +03:00
gy9vin 1ae6ea18b7 Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2026-02-01 11:18:59 +03:00
gy9vin bea6c02d89 kassa ai 2026-02-01 11:18:54 +03:00
Mikhail 153083d791 Merge branch 'main' into main 2026-02-01 11:11:23 +03:00
Egor 80538b39ac Update Dockerfile 2026-02-01 01:10:51 +03:00
Egor 205f9e8e3c Update docker-registry.yml 2026-02-01 01:10:17 +03:00
Egor 97ccfd3af0 Update docker-hub.yml 2026-02-01 01:10:03 +03:00
Egor 6288d3fb7f Merge pull request #2478 from BEDOLAGA-DEV/dev
Dev
2026-02-01 00:54:44 +03:00
Egor d611eecece Update user.py 2026-02-01 00:54:17 +03:00
Egor 779cccffe6 Update tribute.py 2026-02-01 00:53:50 +03:00
Egor 04144dc7a5 Merge pull request #2477 from BEDOLAGA-DEV/dev
Update subscription.py
2026-01-31 21:28:51 +03:00
Egor b7bfdbb485 Update subscription.py 2026-01-31 21:28:35 +03:00
Egor 21b7c039b7 Merge pull request #2476 from BEDOLAGA-DEV/dev
Dev
2026-01-31 21:15:22 +03:00
Egor dc7d2eb02a Add files via upload 2026-01-31 21:13:54 +03:00
Egor 6c26d5c7f8 Update texts.py 2026-01-31 21:13:04 +03:00
Egor 06e99d5a43 Merge pull request #2475 from BEDOLAGA-DEV/dev
Dev
2026-01-31 20:49:48 +03:00
Egor a7712c7151 Add files via upload 2026-01-31 20:46:25 +03:00
Egor 418d329b75 Update subscription_auto_purchase_service.py 2026-01-31 20:45:55 +03:00
Egor a4d5b8067c Merge pull request #2474 from BEDOLAGA-DEV/dev
Update subscription.py
2026-01-31 20:34:27 +03:00
Egor f61ee0f64a Update subscription.py 2026-01-31 20:33:39 +03:00
Egor 841b1e4c52 Merge pull request #2473 from BEDOLAGA-DEV/dev
Dev
2026-01-31 20:16:36 +03:00
Egor 927ec91e0e Update admin_users.py 2026-01-31 20:12:58 +03:00
Egor 9cc2a285dc Update user.py 2026-01-31 20:12:25 +03:00
Egor f11173d5aa Merge pull request #2472 from BEDOLAGA-DEV/dev
Dev
2026-01-31 19:52:58 +03:00
Egor 7bd5d13cc8 Update websocket.py 2026-01-31 19:50:47 +03:00
Egor c30e22e1b1 Update subscription_auto_purchase_service.py 2026-01-31 19:50:03 +03:00
Egor ffff91466e Merge pull request #2471 from BEDOLAGA-DEV/dev
Dev
2026-01-31 19:42:07 +03:00
Egor a7669d0f35 Update devices.py 2026-01-31 19:41:16 +03:00
Egor 1371f21d17 Update subscription_auto_purchase_service.py 2026-01-31 19:40:18 +03:00
Egor ec553d3334 Update subscription.py 2026-01-31 19:39:28 +03:00
Egor 638644d1e9 Update subscription.py 2026-01-31 19:02:30 +03:00
Egor 8ae6ef5cb8 Merge pull request #2470 from BEDOLAGA-DEV/dev
Update universal_migration.py
2026-01-31 18:13:59 +03:00
Egor 1092301767 Update universal_migration.py 2026-01-31 18:13:42 +03:00
Egor 365f75447f Update universal_migration.py 2026-01-31 18:12:53 +03:00
Egor 2e3dbaa18c Merge pull request #2469 from BEDOLAGA-DEV/dev
Dev
2026-01-31 17:50:21 +03:00
Egor 68df186f72 Update admin_broadcasts.py 2026-01-31 17:50:00 +03:00
Egor 8d3bedefb0 Update broadcast_service.py 2026-01-31 17:49:30 +03:00
Egor 701a4d51de Update universal_migration.py 2026-01-31 17:49:02 +03:00
Egor fbb45c10c1 Update main.py 2026-01-31 17:47:43 +03:00
Egor e4f182ffc6 Update broadcasts.py 2026-01-31 17:47:00 +03:00
Egor fa94042284 Update admin_broadcasts.py 2026-01-31 17:46:37 +03:00
Egor b258715cc1 Update broadcast_service.py 2026-01-31 17:45:59 +03:00
Egor 4e9f01d439 Add files via upload 2026-01-31 17:45:19 +03:00
Egor 5dad41953a Merge pull request #2468 from BEDOLAGA-DEV/dev
Update channel_checker.py
2026-01-31 17:10:40 +03:00
Egor dd9b33af83 Update channel_checker.py 2026-01-31 17:10:04 +03:00
Egor fbf2325a42 Merge pull request #2467 from BEDOLAGA-DEV/dev
Dev
2026-01-31 17:06:05 +03:00
Egor 11eb27437b Update devices.py 2026-01-31 17:05:35 +03:00
Egor 1bb5ef85aa Update inline.py 2026-01-31 17:04:59 +03:00
Egor 35c5d78963 Merge pull request #2466 from BEDOLAGA-DEV/dev
Dev
2026-01-31 16:58:57 +03:00
Egor 38ff15e794 Update subscription.py 2026-01-31 16:58:32 +03:00
Egor 2992dfbada Update subscription_service.py 2026-01-31 16:58:01 +03:00
Egor a1e5a71ad3 Merge pull request #2465 from BEDOLAGA-DEV/dev
Update subscription_auto_purchase_service.py
2026-01-31 15:22:36 +03:00
Egor 28dbe3dca7 Update subscription_auto_purchase_service.py 2026-01-31 15:22:11 +03:00
gy9vin 4f77ece187 Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2026-01-30 23:43:29 +03:00
gy9vin 56a69fa1ba правки 2026-01-30 23:43:26 +03:00
Mikhail 5c94bda60a Merge branch 'BEDOLAGA-DEV:main' into main 2026-01-30 23:41:34 +03:00
gy9vin b8d0e6eefb Новый фильтр и кричиеский баг
Теперь при подписке на канал:
  -  Обычные пользователи — подписка реактивируется
  - 🚫 Заблокированные — пропуск с логом, подписка НЕ активируется
2026-01-30 23:40:46 +03:00
Egor 49b48164fd Merge pull request #2464 from BEDOLAGA-DEV/dev
Update monitoring_service.py
2026-01-30 23:02:46 +03:00
Egor f688c74aee Update monitoring_service.py 2026-01-30 23:02:00 +03:00
Egor fe42548dd7 Merge pull request #2462 from BEDOLAGA-DEV/dev
Dev
2026-01-30 21:05:05 +03:00
Egor 7000cd5bc2 Update balance.py 2026-01-30 21:04:46 +03:00
Egor e3901c8d39 Add files via upload 2026-01-30 21:04:10 +03:00
Egor 23f72dc4ec Merge pull request #2461 from BEDOLAGA-DEV/dev
Dev
2026-01-30 20:44:07 +03:00
Egor 55d817bcad Update user_service.py 2026-01-30 20:43:45 +03:00
Egor 8a9994e539 Update user_service.py 2026-01-30 20:41:42 +03:00
Egor f050a62bc6 Merge pull request #2460 from BEDOLAGA-DEV/main
w
2026-01-30 20:40:52 +03:00
c0mrade e26464ddad Merge pull request #2459 from BEDOLAGA-DEV/feat/websocket-subscription-balance-notifications
feat/websocket subscription balance notifications
2026-01-30 20:12:45 +03:00
c0mrade 3263606702 fix: resolve circular import with lazy websocket imports
Move websocket notification imports inside functions to avoid
circular dependency when module is loaded.
2026-01-30 19:17:25 +03:00
c0mrade 86350424d5 feat(websocket): add real-time notifications for subscription and balance events
- Import and call notify_user_subscription_renewed in auto-extend flows
- Import and call notify_user_subscription_activated for new subscriptions
- Add WebSocket notifications to _auto_purchase_tariff and _auto_purchase_daily_tariff
- Add WebSocket notifications to auto_activate_subscription_after_topup
- Add notify_user_balance_topup call in payment common mixin
2026-01-30 19:04:44 +03:00
Egor d2ade1d9ed Merge pull request #2457 from BEDOLAGA-DEV/dev
Update subscription.py
2026-01-30 18:17:05 +03:00
Egor cc47cea268 Update subscription.py 2026-01-30 18:16:49 +03:00
Egor 6f420264f8 Merge pull request #2456 from BEDOLAGA-DEV/dev
Update user_cart_service.py
2026-01-30 17:47:39 +03:00
Egor 5949460572 Update user_cart_service.py 2026-01-30 17:46:55 +03:00
Egor 4330775d01 Merge pull request #2454 from BEDOLAGA-DEV/dev
Dev
2026-01-30 16:58:59 +03:00
Egor fa5c217dd0 Update heleket.py 2026-01-30 16:58:40 +03:00
Egor aa270c9ab4 Update subscription_auto_purchase_service.py 2026-01-30 16:58:12 +03:00
Mikhail b7af25644a Merge branch 'BEDOLAGA-DEV:main' into main 2026-01-30 16:40:25 +03:00
Egor 8b742082a4 Merge pull request #2453 from BEDOLAGA-DEV/dev
Dev
2026-01-30 16:09:42 +03:00
Egor 8078a4e64d Update remnawave_service.py 2026-01-30 16:09:13 +03:00
Egor 79f2cc0da5 Update .env.example 2026-01-30 16:07:47 +03:00
Egor 0c769ac16d Update config.py 2026-01-30 16:06:28 +03:00
Egor 25aba75413 Update user.py 2026-01-30 16:06:06 +03:00
Egor 9afe370a98 Add files via upload 2026-01-30 16:05:36 +03:00
Egor 6202801793 Update auth.py 2026-01-30 16:03:34 +03:00
Egor 4d48418b2c Update auth.py 2026-01-30 15:59:26 +03:00
Egor a21dfa75f0 Update email_service.py 2026-01-30 15:59:00 +03:00
Egor e09d9b6607 Update email_verification.py 2026-01-30 15:58:12 +03:00
Mikhail e312767247 Merge branch 'main' into main 2026-01-30 09:36:50 +03:00
gy9vin 1dfa243736 Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2026-01-30 09:35:23 +03:00
gy9vin e0d667df28 fix реф системы! фишки конкурсной систем! проверка логов по рефералам и начисления бонусов 2026-01-30 09:35:17 +03:00
Egor 68a734051d Merge pull request #2451 from BEDOLAGA-DEV/dev
Update remnawave_service.py
2026-01-29 02:03:15 +03:00
Egor 3f43371e60 Update remnawave_service.py 2026-01-29 02:02:59 +03:00
Egor cb8d233a16 Merge pull request #2450 from BEDOLAGA-DEV/dev
Dev
2026-01-29 01:29:57 +03:00
Egor d95aa7ca5c Rename SubscriptionResponse to SubscriptionData 2026-01-29 01:03:01 +03:00
Egor f7fc7d5cb0 Refactor subscription endpoint to return SubscriptionStatusResponse 2026-01-29 01:02:40 +03:00
Egor 5d6d3b962b Update remnawave_service.py 2026-01-29 01:02:18 +03:00
Egor 6bf8f85c80 Merge pull request #2449 from BEDOLAGA-DEV/dev
Improve payload management and subscription validation
2026-01-29 00:09:25 +03:00
Egor 0a254b1903 Improve payload management and subscription validation
Refactor payload handling and user subscription check logic.
2026-01-29 00:07:52 +03:00
Egor 9f33331618 Merge pull request #2448 from BEDOLAGA-DEV/dev
Dev
2026-01-28 20:17:18 +03:00
Egor 595ecff396 Update payment_method_config_service.py 2026-01-28 20:16:58 +03:00
Egor ad96e8951d Merge pull request #2447 from BEDOLAGA-DEV/main
ц
2026-01-28 20:16:17 +03:00
Mikhail 385e1b4287 Merge pull request #2446 from Gy9vin/main
fix
2026-01-28 13:55:37 +03:00
Mikhail 6551ac1fe9 Merge branch 'main' into main 2026-01-28 13:55:24 +03:00
Egor 327ba81d25 Merge pull request #2445 from BEDOLAGA-DEV/dev
Update remnawave_service.py
2026-01-28 12:48:51 +03:00
Egor bf65e16d4d Update remnawave_service.py 2026-01-28 12:48:29 +03:00
Egor 9cf24deb93 Update remnawave_service.py 2026-01-28 12:47:25 +03:00
Egor 3791f1db5a Merge pull request #2444 from BEDOLAGA-DEV/dev
Dev
2026-01-28 11:59:11 +03:00
Egor 0c3070a0cc Add Kassa AI payment method support 2026-01-28 11:56:02 +03:00
Egor a37ec7a308 Update payment_method_config_service.py 2026-01-28 11:55:29 +03:00
Egor b161a8604e Merge pull request #2443 from BEDOLAGA-DEV/dev
Dev
2026-01-28 11:46:47 +03:00
Egor 1e93f24f78 Add files via upload 2026-01-28 11:46:12 +03:00
Egor f8cd3076e9 Add files via upload 2026-01-28 11:43:22 +03:00
Egor e557504309 Implement panel_datetime_to_naive_utc function
Add function to convert panel datetime to naive UTC.
2026-01-28 11:42:45 +03:00
Egor 4602f72030 Update remnawave_service.py 2026-01-28 11:41:40 +03:00
Egor d811321808 Merge pull request #2442 from BEDOLAGA-DEV/dev
Dev
2026-01-28 11:07:08 +03:00
Egor dffb637e8d Update remnawave_service.py 2026-01-28 11:06:51 +03:00
Egor 32129bebc0 Merge pull request #2441 from BEDOLAGA-DEV/main
w
2026-01-28 11:06:01 +03:00
gy9vin dd5ee45ab5 Keep local customs over main 2026-01-27 23:51:07 +03:00
gy9vin 95b7152c05 касса и прочее 2026-01-27 23:47:39 +03:00
Egor aa093a074a Delete miniapp directory 2026-01-27 18:37:07 +03:00
Egor 2796cd0a1e Update Dockerfile 2026-01-27 18:28:13 +03:00
Egor 3d0497211a Update version number to 3.2.0 in workflow 2026-01-27 18:27:59 +03:00
Egor d489c3bbfd Update versioning scheme to 3.2.0 2026-01-27 18:27:29 +03:00
Egor c634456fb8 Merge pull request #2440 from BEDOLAGA-DEV/dev
Dev
2026-01-27 16:48:16 +03:00
Egor 4086824a11 Add logger initialization in email_template_overrides.py 2026-01-27 16:47:32 +03:00
Egor ea512ff153 Update test_kassa_ai_notifications.py 2026-01-27 16:47:02 +03:00
Egor c8d1254203 Fix string quotes in test_kassa_ai_notifications.py 2026-01-27 16:45:18 +03:00
Egor 66773261bc Simplify total_before_discount calculation
Refactor total_before_discount calculation for clarity.
2026-01-27 16:44:30 +03:00
Egor 4b908ce3cf Update messages.py 2026-01-27 16:43:51 +03:00
Egor 0131b39861 Update email_template_overrides.py 2026-01-27 16:43:11 +03:00
Egor 9217d1fefa Merge pull request #2439 from BEDOLAGA-DEV/main
ц
2026-01-27 16:41:05 +03:00
Egor 3eefbbf48f Merge pull request #2438 from BEDOLAGA-DEV/dev
Update messages.py
2026-01-27 16:40:46 +03:00
Egor 0bfe665b70 Add files via upload 2026-01-27 16:40:27 +03:00
Egor a85ac342ed Update messages.py 2026-01-27 16:38:13 +03:00
Egor a7f6008995 Merge pull request #2431 from Gy9vin/main
Окончалтельный фикс простой покупки!
2026-01-27 16:14:36 +03:00
Egor b07cbaabd5 Merge pull request #2437 from BEDOLAGA-DEV/dev
Update admin_stats.py
2026-01-27 16:14:19 +03:00
Egor affca76ec0 Update admin_stats.py 2026-01-27 16:13:14 +03:00
Egor ef3491fb22 Merge pull request #2436 from BEDOLAGA-DEV/dev
Update pricing_utils.py
2026-01-27 16:06:36 +03:00
Egor 67a75235fd Update pricing_utils.py 2026-01-27 16:06:13 +03:00
Egor 26922b942f Merge pull request #2435 from BEDOLAGA-DEV/dev
Update notification.py
2026-01-27 15:15:40 +03:00
Egor 866f89aea4 Update notification.py 2026-01-27 15:15:24 +03:00
Egor 75c4dea603 Merge pull request #2434 from BEDOLAGA-DEV/dev
Dev
2026-01-27 14:30:35 +03:00
Egor e85a2a58cf Update middleware.py 2026-01-27 14:29:40 +03:00
Egor 9a4acf2016 Adjust database connection pool settings 2026-01-27 14:29:13 +03:00
Egor 1ea513b3b5 Update websocket.py 2026-01-27 14:28:45 +03:00
Egor c912d6a4de Merge pull request #2433 from BEDOLAGA-DEV/dev
Dev
2026-01-27 14:17:19 +03:00
Egor d18945d0ee Update referral_contest.py 2026-01-27 01:38:42 +03:00
Egor c5c8eb880f Update universal_migration.py 2026-01-27 01:37:18 +03:00
Egor 282ba43b42 Add files via upload 2026-01-27 01:36:47 +03:00
Egor 6ce42357c5 Add files via upload 2026-01-27 01:36:18 +03:00
Egor 13bb03ac91 Add files via upload 2026-01-27 01:34:28 +03:00
Egor 2f58d35c80 Add files via upload 2026-01-27 01:33:35 +03:00
Egor 021918dd99 Update branding.py 2026-01-27 01:16:54 +03:00
Egor eb1dd5aa12 Update menu.py 2026-01-27 00:58:03 +03:00
Egor 545365d923 Update photo_message.py 2026-01-27 00:57:30 +03:00
Egor 0ce3e44058 Update photo_message.py 2026-01-27 00:52:11 +03:00
Egor a8b51f4aee Update photo_message.py 2026-01-27 00:46:13 +03:00
Egor 0efae905bc Update email_template_overrides.py 2026-01-27 00:35:55 +03:00
Egor c1f2c4c066 Add files via upload 2026-01-27 00:25:21 +03:00
Egor 93004b7636 Add files via upload 2026-01-27 00:24:50 +03:00
Egor 7a42d34bc9 Update notification_delivery_service.py 2026-01-27 00:23:50 +03:00
Egor 0aa9fc3723 Merge pull request #2432 from BEDOLAGA-DEV/dev
Dev
2026-01-26 23:28:44 +03:00
Egor e7850a3777 Update subscription.py 2026-01-26 23:21:26 +03:00
Egor c8e8087d69 Update tariff_purchase.py 2026-01-26 23:20:08 +03:00
Egor 89b958c726 Update subscription_auto_purchase_service.py 2026-01-26 23:19:37 +03:00
Egor 6bb22b76f7 Update subscription.py 2026-01-26 23:19:02 +03:00
Mikhail b5df07c7a7 Merge branch 'main' into main 2026-01-26 23:15:04 +03:00
gy9vin dd423efe08 Окончалтельный фикс простой покупки! 2026-01-26 23:10:51 +03:00
Egor 7019799f4c Add files via upload 2026-01-26 22:37:32 +03:00
Egor 441bc44a24 Add files via upload 2026-01-26 22:36:48 +03:00
Egor 84b933a0e4 Add files via upload 2026-01-26 22:36:13 +03:00
Egor 7d69e466d0 Update main.py 2026-01-26 22:35:33 +03:00
Egor cca3563422 Merge pull request #2430 from BEDOLAGA-DEV/dev
Update universal_migration.py
2026-01-26 22:07:04 +03:00
Egor aaf258fbad Update universal_migration.py 2026-01-26 22:06:46 +03:00
Egor d6ab9f6092 Merge pull request #2429 from BEDOLAGA-DEV/dev
Dev
2026-01-26 22:00:37 +03:00
Egor caa19331ac Add files via upload 2026-01-26 21:58:14 +03:00
Egor e9af145934 Add files via upload 2026-01-26 21:57:44 +03:00
Egor a7abce9a4e Add files via upload 2026-01-26 21:57:08 +03:00
Egor d01492f982 Update universal_migration.py 2026-01-26 21:55:56 +03:00
Egor 37567c0090 Add files via upload 2026-01-26 21:55:13 +03:00
Egor 25b1d7cf69 Merge pull request #2428 from BEDOLAGA-DEV/main
ц
2026-01-26 21:54:39 +03:00
Egor 990a1ddc66 Merge pull request #2426 from Gy9vin/main
Фикс
2026-01-26 21:12:51 +03:00
Egor 01eaa8bbd5 Merge pull request #2427 from BEDOLAGA-DEV/dev
Update purchase.py
2026-01-26 21:11:40 +03:00
Egor da09be3af7 Update purchase.py 2026-01-26 21:11:24 +03:00
gy9vin c188ff805e Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2026-01-26 21:06:59 +03:00
Egor e71e2bbaa0 Merge pull request #2425 from BEDOLAGA-DEV/dev
Dev
2026-01-26 21:04:14 +03:00
Egor 5f5ea6b1ef Update purchase.py 2026-01-26 21:03:49 +03:00
gy9vin 94c9b6232e Фикс простой прокупки 2026-01-26 20:38:30 +03:00
Egor 36acd7a66a Update balance.py 2026-01-26 20:34:18 +03:00
Egor 2e86380e2c Merge pull request #2424 from BEDOLAGA-DEV/dev
Update subscription_service.py
2026-01-26 20:26:45 +03:00
Egor 82d24eea5b Update subscription_service.py 2026-01-26 20:26:23 +03:00
Egor 8306fa63c0 Merge pull request #2423 from BEDOLAGA-DEV/dev
Update universal_migration.py
2026-01-26 20:01:40 +03:00
Egor f85097698a Update universal_migration.py 2026-01-26 20:01:05 +03:00
Egor f7928e68e5 Merge pull request #2422 from BEDOLAGA-DEV/dev
Dev
2026-01-26 19:20:48 +03:00
Egor 5aac3481a0 Update payment_verification_service.py 2026-01-26 19:20:16 +03:00
Egor 715520320d Add files via upload 2026-01-26 19:13:59 +03:00
Egor b636aec03a Merge pull request #2421 from BEDOLAGA-DEV/main
w
2026-01-26 19:07:15 +03:00
Egor 59f05efcb3 Merge pull request #2419 from Gy9vin/main
Багфиксы и плюшки для Кассааи
2026-01-26 19:05:41 +03:00
Egor a3fafc6dfc Merge pull request #2418 from BEDOLAGA-DEV/c0mrade/setup-pre-commit
с0mrade/setup pre commit
2026-01-26 19:05:15 +03:00
Egor d0ad9f6e2e Merge pull request #2420 from BEDOLAGA-DEV/dev
Dev
2026-01-26 19:04:16 +03:00
Egor 0d84e0ba8f Add files via upload 2026-01-26 19:03:16 +03:00
Egor 964b7c19b4 Update admin_stats.py 2026-01-26 18:43:32 +03:00
Egor b3391139f1 Update traffic_monitoring_service.py 2026-01-26 18:42:58 +03:00
gy9vin 0d9498f169 Багфиксы и плюшки для Кассааи 2026-01-26 12:45:08 +03:00
c0mrade 1b212cc8d6 ci: add ruff lint workflow and fix formatting 2026-01-25 19:31:00 +03:00
c0mrade bd18e6c187 Merge pull request #2417 from BEDOLAGA-DEV/email
Email
2026-01-25 18:33:44 +03:00
c0mrade 02f8826132 fix(config): make SMTP credentials optional for servers without AUTH 2026-01-25 14:43:59 +03:00
c0mrade 989da445be fix(email): handle SMTP servers without AUTH support 2026-01-25 14:35:51 +03:00
Egor ac892cc899 Update subscription.py 2026-01-25 13:39:47 +03:00
Egor f8564f353f Merge pull request #2415 from BEDOLAGA-DEV/email
Email
2026-01-25 13:30:35 +03:00
Egor 99c60793b8 Update remnawave_api.py 2026-01-25 13:29:52 +03:00
Egor af45f1aac0 Update dependencies.py 2026-01-25 13:29:26 +03:00
Egor b797a93105 Update notification_delivery_service.py 2026-01-25 13:28:59 +03:00
Egor 4f84dc6324 Update database.py 2026-01-25 13:28:28 +03:00
Egor 91102d66f9 Merge pull request #2413 from BEDOLAGA-DEV/email
Email
2026-01-25 12:34:19 +03:00
Egor 4eb6e035db Update subscription.py 2026-01-25 12:34:02 +03:00
Egor d7ac622ddc Update cloudpayments_service.py 2026-01-25 12:28:48 +03:00
Egor df91ac51a9 Update payments.py 2026-01-25 12:27:56 +03:00
Egor 658b48f154 Merge pull request #2412 from BEDOLAGA-DEV/email
Email
2026-01-25 11:55:22 +03:00
Egor 3c47dab510 Update payments.py 2026-01-25 11:55:09 +03:00
Egor e612e38e46 Update cloudpayments.py 2026-01-25 11:54:14 +03:00
Egor 5d3af39137 Add files via upload 2026-01-25 11:53:40 +03:00
Egor 6f40cdd09c Update user.py 2026-01-25 11:52:24 +03:00
Egor df189dcf17 Update user_service.py 2026-01-25 11:33:58 +03:00
Egor e7a82a7e6e Add files via upload 2026-01-25 11:32:48 +03:00
Egor c990a10c5b Update auth.py 2026-01-25 11:32:11 +03:00
Egor 52a19f884f Update auth.py 2026-01-25 11:25:33 +03:00
Egor fc0e7a3347 Update auth.py 2026-01-25 11:20:14 +03:00
Egor 832deccfe6 Update auth.py 2026-01-25 11:01:46 +03:00
Egor d80983ec25 Update auth.py 2026-01-25 10:58:12 +03:00
Egor 7ab108a74d Update auth.py 2026-01-25 10:52:37 +03:00
Egor 5d66cc21bb Update remnawave_api.py 2026-01-25 10:52:13 +03:00
Egor 294810fb94 Update auth.py 2026-01-25 10:35:59 +03:00
Egor 45edbd53d0 Add files via upload 2026-01-25 10:35:18 +03:00
Egor b547bea807 Update remnawave_api.py 2026-01-25 10:34:51 +03:00
Egor d6f4ea1d43 Update config.py 2026-01-25 09:56:00 +03:00
Egor 1b1cc7312d Update auth.py 2026-01-25 09:55:30 +03:00
Egor 9dec4186ed Update .env.example 2026-01-25 09:44:49 +03:00
Egor 9578a91a9e Add files via upload 2026-01-25 09:43:49 +03:00
Egor 7b42bfd02d Update config.py 2026-01-25 09:43:15 +03:00
Egor 41fb6b0f9b Update .env.example 2026-01-25 09:23:54 +03:00
Egor 182b9c47cf Update auth.py 2026-01-25 09:23:22 +03:00
Egor 8b492d7ebb Update auth.py 2026-01-25 09:22:56 +03:00
Egor 5677fca06f Update auth.py 2026-01-25 08:43:00 +03:00
Egor 9a32a108c4 Update auth.py 2026-01-25 08:42:03 +03:00
Egor 98677b90d0 Merge pull request #2411 from BEDOLAGA-DEV/chore/setup-uv-ruff
Chore/setup uv ruff
2026-01-24 17:55:17 +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 6c12dd8ce7 Merge pull request #2407 from BEDOLAGA-DEV/dev5
Dev5
2026-01-24 12:07:40 +03:00
Egor 345f3c0f1f Update payments.py 2026-01-24 12:07:08 +03:00
Egor 8c7a6ebc2b Update cloudpayments_service.py 2026-01-24 12:06:47 +03:00
Egor b5f563f80b Update cloudpayments.py 2026-01-24 12:05:51 +03:00
Egor d155493b7a Merge pull request #2406 from BEDOLAGA-DEV/dev5
Dev5
2026-01-24 11:53:05 +03:00
Egor e1b0863642 Update payment_verification_service.py 2026-01-24 11:52:16 +03:00
Egor 9ff8cfab5d Update cloudpayments.py 2026-01-24 11:51:58 +03:00
Egor f0ab05e02b Merge pull request #2405 from BEDOLAGA-DEV/dev5
Update cloudpayments.py
2026-01-24 11:36:21 +03:00
Egor 7fd6450180 Update cloudpayments.py 2026-01-24 11:35:59 +03:00
Egor 5b9b5a4eed Merge pull request #2404 from BEDOLAGA-DEV/dev5
Update cloudpayments.py
2026-01-24 11:31:56 +03:00
Egor f44a59f365 Update cloudpayments.py 2026-01-24 11:31:43 +03:00
Egor 73446e0360 Merge pull request #2403 from BEDOLAGA-DEV/dev5
Update cloudpayments.py
2026-01-24 11:28:22 +03:00
Egor 7d64abf6f8 Update cloudpayments.py 2026-01-24 11:28:05 +03:00
Egor 328183d942 Merge pull request #2402 from BEDOLAGA-DEV/dev5
Dev5
2026-01-24 11:24:49 +03:00
Egor 34105f8e97 Update daily_subscription_service.py 2026-01-24 11:24:16 +03:00
Egor 7e37bc4409 Update subscription.py 2026-01-24 11:23:28 +03:00
Egor e12b19099f Merge pull request #2401 from BEDOLAGA-DEV/dev5
Dev5
2026-01-24 11:13:45 +03:00
Egor 890c219d90 Update universal_migration.py 2026-01-24 11:13:30 +03:00
Egor c27128aa30 Update models.py 2026-01-24 11:12:42 +03:00
Egor cd80164bee Update user.py 2026-01-24 09:56:06 +03:00
Egor c0032c1c0d Merge pull request #2399 from BEDOLAGA-DEV/dev5
Update user.py
2026-01-24 09:51:53 +03:00
Egor 3d9a8c39dc Update user.py 2026-01-24 09:51:13 +03:00
Egor cc5aa4278d Update .env.example 2026-01-23 11:30:08 +03:00
Egor fe73128a9e Update config.py 2026-01-23 11:29:50 +03:00
Egor c9cbb81054 Add files via upload 2026-01-23 11:29:08 +03:00
Egor 7e16d0edee Add files via upload 2026-01-23 11:28:32 +03:00
Egor 80e4cdb791 Add files via upload 2026-01-23 11:27:30 +03:00
Egor 37797ba3f6 Add files via upload 2026-01-23 11:26:42 +03:00
Egor 334130e587 Add files via upload 2026-01-23 11:25:38 +03:00
Egor 1ce729629d Add files via upload 2026-01-23 11:24:27 +03:00
Egor 0a0fc48463 Add files via upload 2026-01-23 11:23:51 +03:00
Egor b576cb4486 Add files via upload 2026-01-23 11:22:31 +03:00
Egor e79f86e5ec Merge pull request #2398 from BEDOLAGA-DEV/main
ц
2026-01-23 04:58:05 +03:00
Egor 0b31d7b27f Update Dockerfile 2026-01-23 03:55:00 +03:00
Egor bd245076a5 Update docker-registry.yml 2026-01-23 03:54:28 +03:00
Egor fd2e032205 Update docker-hub.yml 2026-01-23 03:54:17 +03:00
Egor fcf84aa41e Merge pull request #2397 from BEDOLAGA-DEV/dev5
Update subscription.py
2026-01-23 03:46:28 +03:00
Egor db01725582 Update subscription.py 2026-01-23 03:45:50 +03:00
Egor 9269770703 Merge pull request #2396 from BEDOLAGA-DEV/dev5
Update subscription.py
2026-01-23 00:36:42 +03:00
Egor e91cc23156 Update subscription.py 2026-01-23 00:36:25 +03:00
Egor ffc9453b76 Merge pull request #2395 from BEDOLAGA-DEV/dev5
Update purchase.py
2026-01-22 23:25:04 +03:00
Egor 3a9404c349 Update purchase.py 2026-01-22 23:23:25 +03:00
Egor de2f3de28a Merge pull request #2394 from BEDOLAGA-DEV/dev5
Update admin_promo_offers.py
2026-01-22 23:08:48 +03:00
Egor 25318c1c41 Update admin_promo_offers.py 2026-01-22 23:08:19 +03:00
Egor c233ba8a8c Merge pull request #2393 from BEDOLAGA-DEV/dev5
Dev5
2026-01-22 22:39:19 +03:00
Egor 2a82b037d8 Add files via upload 2026-01-22 22:39:01 +03:00
Egor 67083980a3 Update payment_service.py 2026-01-22 22:38:31 +03:00
Egor 05f65af8e9 Merge pull request #2392 from BEDOLAGA-DEV/dev5
Dev5
2026-01-22 22:34:24 +03:00
Egor 085459dfd3 Update transaction.py 2026-01-22 22:34:09 +03:00
Egor 65af46cdae Update reporting_service.py 2026-01-22 22:33:40 +03:00
Egor f218852f5f Merge pull request #2391 from BEDOLAGA-DEV/main
w
2026-01-22 22:33:00 +03:00
Egor 6635666112 Merge pull request #2390 from Gy9vin/main
fix(referral): исправить потерю реферальных кодов при обязательной по…
2026-01-22 22:00:27 +03:00
Egor 83f9d05fe3 Update payments.py 2026-01-22 21:59:10 +03:00
gy9vin d47a65c29f fix(referral): исправить потерю реферальных кодов при обязательной подписке на канал
Проблема: у некоторых пользователей реферальный код из deep link терялся,
  потому что pending_start_payload сохранялся только в FSM state, который
  мог быть недоступен (state=None) в edge cases.
                                                            Исправления:
  - Добавлен Redis fallback для хранения payload (TTL 1 час)
  - _capture_start_payload() теперь сохраняет в FSM state И в Redis
  - cmd_start() и required_sub_channel_check() проверяют Redis если FSM state
пуст
  - Добавлено логирование warning при state=None
  - Изменён уровень лога успешного сохранения с debug на info

  Изменённые файлы:
  - app/middlewares/channel_checker.py — Redis-функции и улучшенное логирование
  - app/handlers/start.py — Redis fallback в обработчиках

  Добавлены тесты:
  - tests/middlewares/test_channel_checker_payload.py (14 тестов)
2026-01-22 21:54:32 +03:00
Egor 626c67a7a7 Update balance.py 2026-01-22 21:52:43 +03:00
Egor e9c6ea9fc9 Update payments.py 2026-01-22 21:44:53 +03:00
Egor 318dda9e04 Update cloudpayments_service.py 2026-01-22 21:44:13 +03:00
Egor c73b0433b9 Merge pull request #2387 from BEDOLAGA-DEV/dev5
Dev5
2026-01-22 16:09:27 +03:00
Egor 0c2293fef2 Update remnawave_service.py 2026-01-22 16:08:55 +03:00
Egor 9f5971563b Merge pull request #2386 from BEDOLAGA-DEV/main
w
2026-01-22 16:06:54 +03:00
Egor 5930506972 Merge pull request #2379 from Gy9vin/main
feat(payments): добавить KassaAI как отдельную платёжную систему
2026-01-21 16:12:00 +03:00
Egor 6b6d79257e Merge pull request #2383 from BEDOLAGA-DEV/dev5
Dev5
2026-01-21 15:43:56 +03:00
Egor 86c2092eff Update subscription.py 2026-01-21 15:43:29 +03:00
Egor 7bd838f0b0 Update subscription_checker.py 2026-01-21 15:42:13 +03:00
Egor 5563314718 Add files via upload 2026-01-21 15:41:33 +03:00
Egor db69af159b Merge pull request #2382 from BEDOLAGA-DEV/main
w
2026-01-21 15:22:48 +03:00
Egor 4a16bcbccf Update auth.py 2026-01-21 15:03:15 +03:00
Egor 8dec623f2d Update README.md 2026-01-21 11:49:53 +03:00
Egor 0cb714b3a9 Update Dockerfile 2026-01-21 10:36:42 +03:00
Egor 2c3c4ba09c Update docker-registry.yml 2026-01-21 10:36:27 +03:00
Egor 48c6c8dd63 Update docker-hub.yml 2026-01-21 10:36:15 +03:00
Egor d01dd47d57 Merge pull request #2380 from BEDOLAGA-DEV/dev5
Update purchase.py
2026-01-21 10:13:19 +03:00
Egor d51d51db55 Update purchase.py 2026-01-21 10:09:27 +03:00
Mikhail 060ae9decf Merge branch 'BEDOLAGA-DEV:main' into main 2026-01-21 09:49:12 +03:00
Egor 275c797566 Merge pull request #2378 from BEDOLAGA-DEV/dev5
Update balance.py
2026-01-21 09:32:05 +03:00
Egor d9a4af341e Update balance.py 2026-01-21 09:31:43 +03:00
Egor a4f337a502 Merge pull request #2377 from BEDOLAGA-DEV/dev5
Update yookassa.py
2026-01-21 09:27:40 +03:00
Egor 1f55d76459 Update yookassa.py 2026-01-21 09:27:17 +03:00
Egor 2760a744db Merge pull request #2376 from BEDOLAGA-DEV/dev5
Update promo.py
2026-01-21 08:21:17 +03:00
Egor f169c08275 Update promo.py 2026-01-21 08:21:02 +03:00
Egor c69b371c53 Merge pull request #2375 from BEDOLAGA-DEV/dev5
Update promo.py
2026-01-21 08:12:34 +03:00
Egor a45d667c89 Update promo.py 2026-01-21 08:12:17 +03:00
Egor 894e4e02b2 Merge pull request #2374 from BEDOLAGA-DEV/dev5
Dev5
2026-01-21 07:56:30 +03:00
Egor c289b96f1a Update subscription_purchase_service.py 2026-01-21 07:56:04 +03:00
Egor 6425cfb0fb Merge pull request #2373 from BEDOLAGA-DEV/main
ц
2026-01-21 07:35:10 +03:00
Egor a56daca368 Update balance.py 2026-01-21 07:34:25 +03:00
Egor d0628eebda Update config.py 2026-01-21 07:33:54 +03:00
Egor 6a36504699 Merge pull request #2372 from BEDOLAGA-DEV/dev5
Update wheel_service.py
2026-01-21 07:04:31 +03:00
Egor 8db061553f Update wheel_service.py 2026-01-21 07:03:07 +03:00
Egor 7eb8750d0f Merge pull request #2371 from BEDOLAGA-DEV/dev5
Update subscription.py
2026-01-21 06:46:40 +03:00
Egor ae7f63aed0 Update subscription.py 2026-01-21 06:46:07 +03:00
Egor c18b4a3cbb Merge pull request #2370 from BEDOLAGA-DEV/dev5
Dev5
2026-01-21 05:55:28 +03:00
Egor c0cada8fb5 Add files via upload 2026-01-21 05:54:54 +03:00
Egor 1117a1dd34 Merge pull request #2369 from BEDOLAGA-DEV/main
w
2026-01-21 05:16:41 +03:00
Egor abd312dacc Merge pull request #2368 from Gy9vin/main
feat(monitoring): добавить настройки мониторинга трафика в админку
2026-01-21 05:14:36 +03:00
gy9vin 7aa64521d2 feat(payments): добавить KassaAI как отдельную платёжную систему
Новая платёжка KassaAI (api.fk.life) работает параллельно с Freekassa.

  Добавлено:
  - app/services/kassa_ai_service.py — API-сервис
  - app/database/crud/kassa_ai.py — CRUD-операции
  - app/services/payment/kassa_ai.py — KassaAiPaymentMixin
  - app/handlers/balance/kassa_ai.py — хендлеры пополнения

  Изменено:
  - config.py — настройки KASSA_AI_*
  - models.py — PaymentMethod.KASSA_AI, модель KassaAiPayment
  - payment_service.py — подключён KassaAiPaymentMixin
  - webserver/payments.py — webhook /kassa-ai-webhook
  - keyboards/inline.py — кнопка KassaAI
  - handlers/balance/main.py — регистрация хендлеров
  - universal_migration.py — миграция таблицы kassa_ai_payments
  - system_settings_service.py — настройки в админке
  - .env.example — примеры переменных

  Способы оплаты: 44=СБП, 36=Карты РФ, 43=SberPay
2026-01-20 19:09:27 +03:00
Mikhail b99ff79920 Merge branch 'BEDOLAGA-DEV:main' into main 2026-01-20 17:20:46 +03:00
gy9vin dff723aede feat(monitoring): добавить настройки мониторинга трафика в админку
- Добавлена кнопка "⚙️ Настройки трафика" в меню мониторинга
  - Добавлен UI для управления быстрой и суточной проверками трафика
  - Можно включать/выключать проверки, менять пороги и интервалы
  - Настройки сохраняются в БД через BotConfigurationService
  - Добавлены SETTING_HINTS с описаниями параметров
2026-01-20 17:19:57 +03:00
Egor 86097b300e Merge pull request #2367 from BEDOLAGA-DEV/dev5
Dev5
2026-01-20 16:57:18 +03:00
Egor f6b795e555 Update miniapp.py 2026-01-20 16:56:59 +03:00
Egor 7719d035a1 Update dependencies.py 2026-01-20 16:56:07 +03:00
Egor 33e11fb25a Update database.py 2026-01-20 16:55:35 +03:00
Egor fcdda41541 Merge pull request #2366 from BEDOLAGA-DEV/dev5
Update subscription.py
2026-01-20 16:44:59 +03:00
Egor c5183f5a9f Update subscription.py 2026-01-20 16:44:38 +03:00
Egor f200f90150 Merge pull request #2365 from BEDOLAGA-DEV/dev5
Dev5
2026-01-20 14:45:45 +03:00
Egor e42421d2ff Update dependencies.py 2026-01-20 14:28:35 +03:00
Egor c783884ace Update miniapp.py 2026-01-20 14:27:37 +03:00
Egor 6ca1bae6f8 Merge pull request #2364 from BEDOLAGA-DEV/dev5
Update freekassa_service.py
2026-01-20 13:18:45 +03:00
Egor e1aeff55d7 Update freekassa_service.py 2026-01-20 13:18:14 +03:00
Egor 10107964ba Merge pull request #2363 from BEDOLAGA-DEV/dev5
Dev5
2026-01-20 13:06:16 +03:00
Egor ade2794d52 Update start.py 2026-01-20 13:05:45 +03:00
Egor a462657f96 Merge pull request #2362 from BEDOLAGA-DEV/main
ц
2026-01-20 13:04:40 +03:00
Egor 91af4a3818 Update Dockerfile 2026-01-20 08:04:44 +03:00
Egor 05f29c25ec Update docker-registry.yml 2026-01-20 08:04:30 +03:00
Egor 5b851f1047 Update docker-hub.yml 2026-01-20 08:04:08 +03:00
Egor fac258a40d Merge pull request #2361 from BEDOLAGA-DEV/dev5
Update subscription.py
2026-01-20 06:37:30 +03:00
Egor d92071e8aa Update subscription.py 2026-01-20 06:37:04 +03:00
Egor f6c9304a40 Merge pull request #2360 from BEDOLAGA-DEV/dev5
Dev5
2026-01-20 06:23:22 +03:00
Egor b994a5ffd6 Add files via upload 2026-01-20 06:23:00 +03:00
Egor 0413a0ee6a Update purchase.py 2026-01-20 06:22:24 +03:00
Egor 1fc8d38c70 Merge pull request #2359 from BEDOLAGA-DEV/dev5
Update subscription.py
2026-01-20 05:39:59 +03:00
Egor f50fbe232d Update subscription.py 2026-01-20 05:39:36 +03:00
Egor 80e1b68863 Merge pull request #2358 from BEDOLAGA-DEV/dev5
Dev5
2026-01-20 02:35:07 +03:00
Egor 4f54ffcc2a Update subscription.py 2026-01-20 02:34:35 +03:00
Egor 6fed2542eb Merge pull request #2357 from BEDOLAGA-DEV/main
w
2026-01-20 02:33:50 +03:00
Egor c331c33321 Merge pull request #2356 from BEDOLAGA-DEV/dev5
Dev5
2026-01-20 02:20:14 +03:00
PEDZEO 338ee832ea Add fullscreen settings endpoints and models to branding.py 2026-01-20 02:17:35 +03:00
Egor b7a05f7cd1 Update miniapp.py 2026-01-20 02:14:42 +03:00
Egor dd396aa16d Update miniapp.py 2026-01-20 02:14:10 +03:00
Egor 814d224359 Update subscription.py 2026-01-20 02:13:34 +03:00
Egor 95ab0236d9 Update subscription.py 2026-01-20 02:13:01 +03:00
Egor 4fbe07919c Merge pull request #2355 from BEDOLAGA-DEV/dev5
Dev5
2026-01-20 01:46:57 +03:00
Egor 1752f52197 Update miniapp.py 2026-01-20 01:39:50 +03:00
Egor 5fe37e57a6 Update subscription.py 2026-01-20 01:39:09 +03:00
PEDZEO da9997609b Add custom logging configuration to WebAPIServer to reduce WebSocket spam 2026-01-20 01:30:17 +03:00
Egor 92b7c0b602 Merge pull request #2354 from BEDOLAGA-DEV/main
ц
2026-01-20 01:24:16 +03:00
Egor 44b3a0dfab Merge pull request #2353 from BEDOLAGA-DEV/dev5
Update subscription_auto_purchase_service.py
2026-01-20 01:23:34 +03:00
Egor b3bbd48723 Update subscription_auto_purchase_service.py 2026-01-20 01:23:06 +03:00
Egor e51afc6bcf Merge pull request #2352 from BEDOLAGA-DEV/dev5
Dev5
2026-01-20 01:02:27 +03:00
Egor 0ae70d702e Update purchase.py 2026-01-20 01:00:43 +03:00
Egor 722b800f1d Update subscription_purchase_service.py 2026-01-20 00:59:55 +03:00
Egor cd9287236e Update subscription.py 2026-01-20 00:58:58 +03:00
Egor 18e8e38855 Update miniapp.py 2026-01-20 00:58:24 +03:00
Egor a63d587aad Update subscription_utils.py 2026-01-20 00:54:45 +03:00
Egor aba2df927d Update tariff_purchase.py 2026-01-20 00:53:56 +03:00
Egor d78f85735b Update remnawave_api.py 2026-01-20 00:52:59 +03:00
PEDZEO a7e0f52e27 Merge pull request #2351 from BEDOLAGA-DEV/test 2026-01-20 00:41:18 +03:00
Egor b9ca73a306 Update subscription.py 2026-01-20 00:41:09 +03:00
Egor c26ccb8e96 Update subscription_purchase_service.py 2026-01-20 00:40:22 +03:00
PEDZEO 38bf8633b7 Merge branch 'test' of https://github.com/Fr1ngg/remnawave-bedolaga-telegram-bot into test 2026-01-20 00:38:29 +03:00
PEDZEO 73d52f2047 Adjust logging levels for WebSocket connections to reduce verbosity 2026-01-20 00:38:23 +03:00
Egor d781290652 Merge pull request #2350 from BEDOLAGA-DEV/dev5
Dev5
2026-01-20 00:28:33 +03:00
Egor 9d453283ec Update global_error.py 2026-01-20 00:28:16 +03:00
Egor 98d01cff49 Update message_patch.py 2026-01-20 00:27:50 +03:00
Egor 255c623143 Merge pull request #2349 from BEDOLAGA-DEV/dev5
Dev5
2026-01-20 00:20:20 +03:00
Egor 2d69d98d81 Update subscription_renewal_service.py 2026-01-20 00:19:26 +03:00
Egor 8ad2d50b25 Add files via upload 2026-01-20 00:18:57 +03:00
Egor 372654683a Merge pull request #2348 from BEDOLAGA-DEV/main
w
2026-01-20 00:17:42 +03:00
Egor 6fd470a02f Merge pull request #2347 from BEDOLAGA-DEV/dev5
Dev5
2026-01-19 23:58:03 +03:00
Egor cb4f79dd6e Update monitoring_service.py 2026-01-19 23:57:45 +03:00
Egor b38e06383d Update user.py 2026-01-19 23:57:03 +03:00
Egor 5523c6bf76 Merge pull request #2346 from BEDOLAGA-DEV/dev5
Dev5
2026-01-19 23:47:01 +03:00
Egor 57981b69c7 Update server_squad.py 2026-01-19 23:46:41 +03:00
PEDZEO 6a3e716ad2 Refactor logging levels in websocket.py files to use debug instead of info and warning for connection attempts and token validation. 2026-01-19 23:46:03 +03:00
Egor c21804f8db Add files via upload 2026-01-19 23:45:53 +03:00
Egor 3937bbffc9 Merge pull request #2345 from BEDOLAGA-DEV/dev5
Update auth.py
2026-01-19 23:36:06 +03:00
Egor 70441da7de Update auth.py 2026-01-19 23:35:12 +03:00
Egor df2626adae Merge pull request #2344 from BEDOLAGA-DEV/dev5
Update subscription.py
2026-01-19 23:17:18 +03:00
Egor 9bffeb4151 Update subscription.py 2026-01-19 23:17:00 +03:00
Egor 8524e2c023 Merge pull request #2343 from BEDOLAGA-DEV/dev5
Dev5
2026-01-19 23:06:38 +03:00
Egor 3553ff615d Update subscription.py 2026-01-19 23:06:21 +03:00
Egor ca0682e48f Merge pull request #2342 from BEDOLAGA-DEV/main
w
2026-01-19 22:52:58 +03:00
Egor 1e1c0e89bc Update subscription.py 2026-01-19 22:51:57 +03:00
Egor 93227b7f41 Update yookassa.py 2026-01-19 22:49:58 +03:00
Egor 0a51e4d9ea Merge pull request #2339 from BEDOLAGA-DEV/dev5
Update branding.py
2026-01-19 10:22:50 +03:00
Egor 9e69b0cf22 Update branding.py 2026-01-19 10:17:33 +03:00
Egor aaaaa25231 Merge pull request #2338 from BEDOLAGA-DEV/dev5
Update admin_promocodes.py
2026-01-19 09:32:03 +03:00
Egor 10fea329ad Update admin_promocodes.py 2026-01-19 09:31:41 +03:00
Egor 408c5c520e Merge pull request #2337 from BEDOLAGA-DEV/dev5
Update admin_stats.py
2026-01-19 09:17:15 +03:00
Egor 6775b06b2e Update admin_stats.py 2026-01-19 08:51:48 +03:00
Egor 9460c86f7a Merge pull request #2336 from BEDOLAGA-DEV/dev5
Dev5
2026-01-19 07:53:16 +03:00
Egor f8d7b3288c Update cloudpayments.py 2026-01-19 07:52:54 +03:00
Egor bd6498fb73 Update subscription.py 2026-01-19 07:52:16 +03:00
Egor cdb3507a56 Update tariff_purchase.py 2026-01-19 06:26:15 +03:00
Egor 0b18c16f47 Update subscription_auto_purchase_service.py 2026-01-19 06:25:30 +03:00
Egor f452434b13 Merge pull request #2335 from BEDOLAGA-DEV/main
w
2026-01-19 06:24:22 +03:00
PEDZEO e6e688a395 fix(routes): reorder notification and ticket routers to prevent route conflicts
- Moved the notifications router to be included before the tickets router to avoid conflicts.
- Updated comments for clarity regarding the order of router inclusion.
2026-01-19 01:30:31 +03:00
PEDZEO b1206a84c7 feat(notifications): enhance notification security and ownership checks
- Added ownership verification for user notifications to ensure only the rightful owner can mark them as read.
- Implemented checks to confirm that admin notifications are correctly identified before allowing them to be marked as read.
- Introduced a new method to retrieve notifications by ID in the TicketNotificationCRUD for improved data handling.
2026-01-19 00:39:36 +03:00
PEDZEO 63e45e12de Merge pull request #2334 from BEDOLAGA-DEV/test
feat(notifications): implement ticket notifications for users and admins
2026-01-19 00:34:03 +03:00
PEDZEO 792ff22471 Merge branch 'main' into test 2026-01-19 00:33:21 +03:00
PEDZEO 346806bce0 feat(notifications): integrate WebSocket notifications for ticket replies and new tickets
- Added WebSocket notifications for admins on new ticket creation and user replies.
- Implemented notification handling in the ticket management routes.
- Enhanced error logging for notification failures.
2026-01-19 00:28:57 +03:00
PEDZEO 5630e99812 Merge branch 'main' of https://github.com/Fr1ngg/remnawave-bedolaga-telegram-bot 2026-01-19 00:03:43 +03:00
PEDZEO 67c3dba1cc feat(notifications): implement ticket notifications for users and admins
- Added a new TicketNotification model to handle notifications for ticket events.
- Implemented user and admin notifications for new tickets and replies in the cabinet.
- Introduced settings to enable or disable notifications for users and admins.
- Enhanced ticket settings to include notification preferences.
- Integrated WebSocket notifications for real-time updates.
2026-01-19 00:02:41 +03:00
Egor c1e901ba5e Merge pull request #2333 from BEDOLAGA-DEV/dev5
Update auth.py
2026-01-18 23:34:02 +03:00
Egor b6f2052464 Update auth.py 2026-01-18 23:33:45 +03:00
PEDZEO c63db708cc feat(tickets): notify admins on new ticket creation and replies
- Added functionality to notify admins when a new ticket is created.
- Implemented notification for admins when a user replies to a ticket.
- Included error handling for notification failures.
2026-01-18 23:23:46 +03:00
Egor 3fc702ec65 Merge pull request #2332 from BEDOLAGA-DEV/dev5
Dev5
2026-01-18 22:15:37 +03:00
Egor 0aff94de74 Update main.py 2026-01-18 22:15:03 +03:00
Egor d8c60ce19f Merge pull request #2331 from BEDOLAGA-DEV/main
w
2026-01-18 22:14:34 +03:00
Egor f3995c7ca8 Merge pull request #2330 from DrillUser/patch-1
+убрать очепятку
2026-01-18 21:31:22 +03:00
Egor 1330f394bb Merge pull request #2328 from Gy9vin/main
fix(contests): исправлены критические баги системы конкурсов
2026-01-18 21:31:01 +03:00
Vladislav ec27d63f70 +убрать очепятку 2026-01-18 14:09:04 +03:00
gy9vin 78d785f83f fix(contests): исправлены критические баги системы конкурсов
- Исправлен вызов get_active_rounds в админ-панели (передавалось 2 параметра вместо 1)
- Обновлены кнопки редактирования призов с prize_days на prize_type/prize_value
- Мигрирован Cabinet API с устаревшего prize_days на новые поля
- Добавлена поддержка нескольких типов призов (дни, баланс, кастом)
- Обновлена документация API конкурсов
2026-01-18 10:15:45 +03:00
Egor 04bb20c1e7 Update Dockerfile 2026-01-18 07:33:22 +03:00
Egor 7fdf2dcd51 Update docker-registry.yml 2026-01-18 07:33:13 +03:00
Egor 6d5462b084 Update docker-hub.yml 2026-01-18 07:32:52 +03:00
Egor 956b90e95e Merge pull request #2327 from BEDOLAGA-DEV/dev5
Dev5
2026-01-18 06:01:18 +03:00
Egor 15e7725cf7 Update tariff.py 2026-01-18 05:47:59 +03:00
Egor 4205eed54f Update admin_tariffs.py 2026-01-18 05:46:50 +03:00
Egor 921ae25dd3 Merge pull request #2326 from BEDOLAGA-DEV/main
w
2026-01-18 05:43:05 +03:00
Egor cee4139a64 Update README.md 2026-01-17 19:49:19 +03:00
Egor 92339ec55a Merge pull request #2323 from libkitdev/main
feat(promocodes): добавить тип DISCOUNT для одноразовых процентных скидок
2026-01-17 19:45:10 +03:00
Egor 3372736fa3 Merge pull request #2325 from BEDOLAGA-DEV/dev5
Dev5
2026-01-17 10:52:16 +03:00
Egor cd0ce908a1 Add files via upload 2026-01-17 10:31:40 +03:00
Egor b7f8469895 Add files via upload 2026-01-17 10:31:21 +03:00
Egor 8a96dbd224 Merge pull request #2324 from BEDOLAGA-DEV/dev5
Add files via upload
2026-01-17 10:05:56 +03:00
Egor 840c954203 Add files via upload 2026-01-17 10:05:30 +03:00
libkit 8b6683302d feat(localization): добавить тексты для DISCOUNT промокодов
Добавлены переводы на все 4 языка (ru, en, ua, zh):
- ADMIN_PROMOCODE_TYPE_DISCOUNT - название типа в админке
- PROMOCODE_ACTIVE_DISCOUNT_EXISTS - ошибка при конфликте скидок

Тексты описывают функционал одноразовой процентной скидки.
2026-01-17 11:25:51 +05:00
libkit 7a351d3028 feat(keyboards): добавить кнопку типа DISCOUNT в меню промокодов
Кнопка "💸 Одноразовая скидка" в меню выбора типа промокода.
2026-01-17 11:23:08 +05:00
libkit 5610a91866 feat(admin): добавить UI для создания DISCOUNT промокодов
Добавлена полная поддержка DISCOUNT типа в админке:
- Тип "💸 Одноразовая скидка" в селекторе
- Флоу создания: код → процент (1-100) → макс использований → срок промокода (дни) → срок скидки (часы)
- Валидация процента скидки (1-100)
- Валидация срока действия скидки (0-8760 часов)
- Отображение в списках и странице управления
- Новый стейт setting_discount_hours для ввода срока скидки
2026-01-17 11:22:32 +05:00
libkit 0858388b18 feat(handlers): добавить обработку ошибки active_discount_exists
Пользователь получает понятное сообщение при попытке
активировать промокод когда уже есть активная скидка.
2026-01-17 11:19:24 +05:00
libkit 1793775fe8 feat(services): реализовать логику активации DISCOUNT промокодов
Добавлена обработка нового типа промокода DISCOUNT:
- Проверка конфликта с активными скидками пользователя
- Запись скидки в профиль (promo_offer_discount_percent, promo_offer_discount_expires_at)
- Обработка срока действия скидки (0 часов = бессрочно до первой покупки)
- Логирование активации и ошибок
- Выброс ValueError при попытке активировать скидку при наличии активной
2026-01-17 11:18:46 +05:00
libkit ff45a3e28d feat(models): добавить тип DISCOUNT в PromoCodeType
Добавлен новый тип промокода для одноразовых скидок.
Использует существующие поля без изменения схемы БД:
- balance_bonus_kopeks для хранения процента скидки (1-100)
- subscription_days для хранения срока действия скидки в часах (0-8760)
2026-01-17 11:17:30 +05:00
Egor a59252fbb1 Merge pull request #2322 from BEDOLAGA-DEV/dev5
Dev5
2026-01-17 08:51:55 +03:00
Egor 44a410babf Add files via upload 2026-01-17 08:50:47 +03:00
Egor 19a1d93a15 Update balance.py 2026-01-17 08:41:15 +03:00
Egor 64fe45fcfc Update balance.py 2026-01-17 08:40:37 +03:00
Egor 6d2b16f180 Merge pull request #2321 from BEDOLAGA-DEV/dev5
Update admin_users.py
2026-01-17 06:51:53 +03:00
Egor 1f138aa772 Update admin_users.py 2026-01-17 06:51:20 +03:00
Egor 65f5e31540 Merge pull request #2320 from BEDOLAGA-DEV/dev5
Update admin_users.py
2026-01-17 06:40:27 +03:00
Egor ca4252c9cb Update admin_users.py 2026-01-17 06:40:12 +03:00
Egor ee9682320f Merge pull request #2319 from BEDOLAGA-DEV/dev5
Update admin_users.py
2026-01-17 06:35:27 +03:00
Egor 15386ad4d8 Update admin_users.py 2026-01-17 06:35:08 +03:00
Egor d93db9b199 Merge pull request #2318 from BEDOLAGA-DEV/dev5
Dev5
2026-01-17 06:29:35 +03:00
Egor a54f5347a8 Update users.py 2026-01-17 06:28:42 +03:00
Egor c121855078 Update admin_users.py 2026-01-17 06:28:10 +03:00
Egor c870df4923 Merge pull request #2317 from BEDOLAGA-DEV/dev5
Update admin_users.py
2026-01-17 06:21:31 +03:00
Egor 8956fff7d7 Update admin_users.py 2026-01-17 06:21:14 +03:00
Egor de782e54ce Merge pull request #2316 from BEDOLAGA-DEV/dev5
Dev5
2026-01-17 06:11:46 +03:00
Egor 35b900dfe4 Add files via upload 2026-01-17 05:57:40 +03:00
Egor c1b70436b7 Add files via upload 2026-01-17 05:57:10 +03:00
Egor 5ecdfa14bd Merge pull request #2315 from BEDOLAGA-DEV/dev5
Обновление кампаний
2026-01-17 05:36:17 +03:00
Egor fd68c1c99f Add files via upload 2026-01-17 05:24:12 +03:00
Egor 0e339450f8 Add files via upload 2026-01-17 05:23:44 +03:00
Egor 1eadbfe3f8 Update campaigns.py 2026-01-17 05:14:23 +03:00
Egor bf0627a301 Update campaigns.py 2026-01-17 05:08:14 +03:00
Egor 274f8701a2 Update states.py 2026-01-17 05:06:07 +03:00
Egor ea4570ba71 Update campaigns.py 2026-01-17 05:05:42 +03:00
Egor 5f39821652 Update admin.py 2026-01-17 05:05:12 +03:00
Egor 26c78b6814 Update campaigns.py 2026-01-17 05:04:01 +03:00
Egor 3e1abcbd51 Update campaigns.py 2026-01-17 05:03:32 +03:00
Egor cd6f9a3296 Update campaign_service.py 2026-01-17 05:02:54 +03:00
Egor 73e4009c35 Update start.py 2026-01-17 05:02:07 +03:00
Egor 08d202161c Update campaign.py 2026-01-17 05:01:12 +03:00
Egor c4cde5efa2 Add files via upload 2026-01-17 05:00:47 +03:00
Egor e0868bca18 Merge pull request #2314 from BEDOLAGA-DEV/dev5
Add files via upload
2026-01-17 04:37:48 +03:00
Egor 248cc51e73 Add files via upload 2026-01-17 04:35:37 +03:00
Egor 322ad3b5e4 Merge pull request #2313 from BEDOLAGA-DEV/dev5
Dev5
2026-01-17 03:32:54 +03:00
Egor 63fd318290 Update auth.py 2026-01-17 03:32:10 +03:00
Egor c0e3e329af Update main.py 2026-01-17 03:31:39 +03:00
Egor f5b6f75cf7 Merge pull request #2312 from BEDOLAGA-DEV/dev5
Dev5
2026-01-17 03:28:42 +03:00
Egor e3fb2ec854 Update purchase.py 2026-01-17 03:28:29 +03:00
Egor 8b83f3d08b Update tickets.py 2026-01-17 03:28:01 +03:00
Egor 2493684e71 Merge pull request #2311 from BEDOLAGA-DEV/dev5
Update message_patch.py
2026-01-17 03:12:31 +03:00
Egor acfad93d93 Update message_patch.py 2026-01-17 03:12:15 +03:00
Egor 9bc1a66422 Merge pull request #2310 from BEDOLAGA-DEV/dev5
Update happ.py
2026-01-17 03:07:37 +03:00
Egor 0e4f9c1ce0 Update happ.py 2026-01-17 03:07:06 +03:00
Egor 58b28d9eb7 Merge pull request #2309 from BEDOLAGA-DEV/dev5
Dev5
2026-01-17 03:02:57 +03:00
Egor 94320d4217 Add files via upload 2026-01-17 03:02:28 +03:00
Egor 44592602dc Update links.py 2026-01-17 03:00:13 +03:00
Egor 84702e16df Update stats_service.py 2026-01-17 02:59:28 +03:00
Egor ec1870ef8f Merge pull request #2308 from BEDOLAGA-DEV/dev5
Update purchase.py
2026-01-17 02:54:56 +03:00
Egor 35dc9cf3e2 Update purchase.py 2026-01-17 02:54:40 +03:00
Egor 08fe4df226 Merge pull request #2307 from BEDOLAGA-DEV/dev5
Update config.py
2026-01-17 02:51:22 +03:00
Egor 17b442ad07 Update config.py 2026-01-17 02:49:14 +03:00
Egor 9cfc1e46ac Merge pull request #2306 from BEDOLAGA-DEV/dev5
Add files via upload
2026-01-17 02:46:24 +03:00
Egor c59b823df2 Add files via upload 2026-01-17 02:45:46 +03:00
Egor 6bbfd0caac Merge pull request #2305 from BEDOLAGA-DEV/dev5
Update pricing.py
2026-01-17 02:42:22 +03:00
Egor 39fed57876 Update pricing.py 2026-01-17 02:41:59 +03:00
Egor ed0ae70ff4 Merge pull request #2304 from BEDOLAGA-DEV/dev5
Dev5
2026-01-17 02:38:27 +03:00
Egor c0062b1ca3 Update promocode.py 2026-01-17 02:38:11 +03:00
Egor 5bdb06a280 Update main.py 2026-01-17 02:37:43 +03:00
Egor a42a884eb6 Update purchase.py 2026-01-17 02:37:16 +03:00
Egor 8726e33665 Add files via upload 2026-01-17 02:36:33 +03:00
Egor ba7eb8a1e8 Merge pull request #2303 from BEDOLAGA-DEV/dev5
Dev5
2026-01-17 02:35:39 +03:00
Egor 4599801f83 Update pricing.py 2026-01-17 02:35:23 +03:00
Egor a5f17b6802 Add files via upload 2026-01-17 02:03:06 +03:00
Egor c804505361 Add files via upload 2026-01-17 02:02:40 +03:00
Egor 3de9937442 Merge pull request #2302 from BEDOLAGA-DEV/dev5
clear logs
2026-01-17 01:51:04 +03:00
Egor 782d910f25 Add files via upload 2026-01-17 01:50:34 +03:00
Egor ac87d47bf3 Add files via upload 2026-01-17 01:49:56 +03:00
Egor 3dc7a80d87 Merge pull request #2301 from BEDOLAGA-DEV/dev5
fuck db sessions
2026-01-17 01:33:07 +03:00
Egor c61cd0b42e Update texts.py 2026-01-17 01:19:12 +03:00
Egor 5fcc202542 Add files via upload 2026-01-17 01:18:02 +03:00
Egor 1b4758cdbf Update monitoring.py 2026-01-17 01:16:50 +03:00
Egor 5cb0ce3030 Add files via upload 2026-01-17 01:16:10 +03:00
Egor e7bd52463d Add files via upload 2026-01-17 01:15:28 +03:00
Egor c1f035b13d Add files via upload 2026-01-17 01:14:57 +03:00
Egor 8d888f3e56 Merge pull request #2300 from BEDOLAGA-DEV/main
w
2026-01-17 01:04:26 +03:00
PEDZEO 1a990bd776 Refactor settings handling in AdminBanSystem to improve response parsing
- Introduced a new helper function `_parse_setting_response` to streamline the parsing of settings responses from the API.
- Updated the `get_settings`, `get_setting`, `set_setting`, and `toggle_setting` endpoints to utilize the new parsing function, enhancing code readability and maintainability.
- Improved handling of settings data formats, allowing for both detailed metadata and simple values.
2026-01-16 21:04:48 +03:00
PEDZEO b0f83f3534 Новые вкладки в AdminBanSystem:
1. Traffic (Трафик) - статистика трафика, топ пользователей по трафику, последние нарушения
  2. Reports (Отчёты) - отчёты за период (6h, 12h, 24h, 48h, 72h), статистика активных пользователей и IP, топ нарушителей
  3. Settings (Настройки) - управление настройками системы банов, группировка по категориям, переключатели для bool, ввод для int
  4. Health (Здоровье) - статус системы (healthy/degraded/unhealthy), аптайм, статус компонентов
2026-01-16 20:51:28 +03:00
PEDZEO 723a49f1f1 Fix stats mapping: uptime from tcp_metrics, agents count from connected_nodes
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 19:25:20 +03:00
PEDZEO e31c9118b3 ● Готово! Исправил маппинг для нод и агентов. 2026-01-16 19:21:31 +03:00
PEDZEO 7ef416eff2 Implement logging for Ban System API checks and add endpoint for raw stats retrieval
- Added logging for Ban System API status checks, including whether the system is enabled and its configured URL.
- Introduced a new endpoint `/stats/raw` to fetch raw statistics from the Ban System API for debugging purposes.
- Enhanced logging to capture raw stats response for better monitoring.
2026-01-16 18:51:19 +03:00
PEDZEO 29d0190a05 Исправил маппинг полей. 2026-01-16 18:41:21 +03:00
Egor 5eec0aa1a0 Update balance.py 2026-01-16 18:13:25 +03:00
Egor 02ae44a594 Merge pull request #2298 from Gy9vin/main
Мониторинг трафика v2
2026-01-16 17:56:10 +03:00
Egor b9801614f3 Update subscription.py 2026-01-16 17:51:28 +03:00
Egor 0ea1076761 Update subscription.py 2026-01-16 17:36:28 +03:00
gy9vin 94cd06302a Фиксы UI 2026-01-16 15:58:22 +03:00
gy9vin 5a64dbf209 feat(payments): добавить режим яркого промпта активации подписки
- Реализован режим SHOW_ACTIVATION_PROMPT_AFTER_TOPUP для яркого уведомления пользователей
  - При пополнении баланса отправляется внимание-привлекающее сообщение с восклицательными знаками
  - Динамические кнопки в зависимости от статуса подписки:
    * Активная платная подписка: "🔄 Продлить" + "📱 Изменить устройства"
    * Нет подписки/истекла/триал: "🔥 Активировать подписку"
  - Убраны дублирующие уведомления из yookassa.py (строка 851)
  - Убраны дублирующие уведомления из subscription_auto_purchase_service.py (строки 755, 918)
  - Режим включается через SHOW_ACTIVATION_PROMPT_AFTER_TOPUP=true в .env

  Файлы:
  - app/services/payment/common.py: добавлена логика яркого промпта
  - app/services/payment/yookassa.py: отключено старое уведомление для корзины
  - app/services/subscription_auto_purchase_service.py: отключены 2 блока старых уведомлений
2026-01-16 15:29:44 +03:00
PEDZEO b392a99f56 Интеграция системы мониторинга банов 2026-01-16 15:17:02 +03:00
gy9vin 07417a4877 фикс 2026-01-16 14:28:39 +03:00
gy9vin 1c2dca2c65 fix(traffic): исправлены критические баги мониторинга трафика v2
- Исправлен баг с пустым snapshot {} (не распознавался как существующий)
- Исправлено игнорирование комментариев в TRAFFIC_MONITORED_NODES
- Добавлено исключение пользователей по UUID (TRAFFIC_EXCLUDED_USER_UUIDS)
- Добавлены названия нод в уведомления о превышении трафика
- Улучшено логирование: кулдаун, фильтры, исключённые пользователи
- Исправлен баг с блокировкой имён типа "Сейтмеметов" (ложное срабатывание на "тме")
- Разрешён конфликт слияния в display_name_restriction.py

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-16 12:19:29 +03:00
gy9vin ab492f3aef Мониторинг и исправления защиты имени пользователя! 2026-01-16 12:18:04 +03:00
Mikhail 1c7ed68674 Merge branch 'main' into main 2026-01-16 12:16:23 +03:00
Egor fed3fda83e Merge pull request #2297 from BEDOLAGA-DEV/dev5
Сброс трафика на тарифах
2026-01-16 08:51:09 +03:00
Egor 8db459e206 Update admin_tariffs.py 2026-01-16 08:50:34 +03:00
Egor 4f3a849d03 Update tariffs.py 2026-01-16 08:50:08 +03:00
Egor 9eec5ef9c7 Update monitoring_service.py 2026-01-16 08:40:52 +03:00
Egor 7106c89711 Update subscription.py 2026-01-16 08:40:01 +03:00
Egor fd947bc562 Update subscription_service.py 2026-01-16 08:36:37 +03:00
Egor b088328439 Update tariffs.py 2026-01-16 08:36:08 +03:00
Egor dcaf2b8103 Update tariff.py 2026-01-16 08:35:26 +03:00
Egor 1024a88d19 Add files via upload 2026-01-16 08:34:56 +03:00
Egor d98baf23aa Merge pull request #2296 from BEDOLAGA-DEV/main
w
2026-01-16 08:34:23 +03:00
Egor 192f014180 Update Dockerfile 2026-01-16 08:34:01 +03:00
Egor 7f6be1c8f0 Update docker-registry.yml 2026-01-16 08:33:48 +03:00
Egor cfe780122b Update docker-hub.yml 2026-01-16 08:33:36 +03:00
Egor 4b7dcbbca4 Update subscription.py 2026-01-16 07:25:00 +03:00
Egor 81bda22cb7 Update tariffs.py 2026-01-16 06:29:22 +03:00
Egor 9230efcd31 Update admin_tariffs.py 2026-01-16 06:29:00 +03:00
Egor 7cacc73187 Update tariff.py 2026-01-16 06:18:20 +03:00
Egor 53d1828d54 Update admin_tariffs.py 2026-01-16 06:17:44 +03:00
Egor 31fbccca26 Update tariff_purchase.py 2026-01-16 06:12:36 +03:00
Egor dbf4c1f521 Update users.py 2026-01-16 06:12:01 +03:00
Egor a089947aee Update subscription.py 2026-01-16 06:11:34 +03:00
Egor 1337339d23 Update tariffs.py 2026-01-16 06:03:32 +03:00
Egor 0a3f67a1f0 Update tariffs.py 2026-01-16 06:02:47 +03:00
Egor 1c1a15984e Update subscription.py 2026-01-16 06:02:22 +03:00
Egor e22e786c88 Update tariff.py 2026-01-16 06:01:50 +03:00
Egor a32e3fc582 Add files via upload 2026-01-16 06:01:23 +03:00
Egor a7303d765f Update states.py 2026-01-16 06:00:50 +03:00
Egor 4f66e947b9 Update subscription.py 2026-01-16 05:30:01 +03:00
Egor 46efd56e20 Update subscription.py 2026-01-16 05:21:00 +03:00
Egor 2c124f1343 Update subscription.py 2026-01-16 05:13:25 +03:00
Egor 68ce06e97e Update subscription.py 2026-01-16 05:06:54 +03:00
Egor 577d731adb Merge pull request #2295 from BEDOLAGA-DEV/dev5
Dev5
2026-01-16 04:58:38 +03:00
Egor f2e25fe585 Update admin_apps.py 2026-01-16 04:57:54 +03:00
Egor 65c087aefb Update system_settings_service.py 2026-01-16 04:57:04 +03:00
Egor be9d7290cb Update config.py 2026-01-16 04:56:34 +03:00
Egor 9d431bc576 Merge pull request #2294 from BEDOLAGA-DEV/main
w
2026-01-16 04:56:13 +03:00
Egor 0e907d80fa Update balance.py 2026-01-16 04:16:20 +03:00
Egor 192381d148 Update balance.py 2026-01-16 04:10:11 +03:00
Egor 73bf9b757a Update balance.py 2026-01-16 04:09:46 +03:00
Egor 0a67a55c5e Add files via upload 2026-01-16 03:59:49 +03:00
Egor 3ef4183650 Update admin_stats.py 2026-01-16 03:52:35 +03:00
Egor 365bcd15a5 Update admin_stats.py 2026-01-16 03:35:41 +03:00
Egor 6483b37bd3 Update admin_stats.py 2026-01-16 03:28:47 +03:00
Egor ec9eaf4271 Update subscription_conversion.py 2026-01-16 03:28:01 +03:00
Egor 1c03cd8425 Update admin_stats.py 2026-01-16 03:19:21 +03:00
Egor 176d17fe40 Update subscription_conversion.py 2026-01-16 03:18:53 +03:00
Egor 4e69e0ea0f Add files via upload 2026-01-16 02:24:46 +03:00
Egor e33995c446 Update admin_tickets.py 2026-01-16 02:15:39 +03:00
Egor a72e029d1d Update balance.py 2026-01-16 01:59:54 +03:00
Egor d07390f379 Update subscription.py 2026-01-16 01:42:36 +03:00
Egor 4278a84231 Merge pull request #2293 from BEDOLAGA-DEV/dev5
Update referral.py
2026-01-16 01:16:48 +03:00
Egor 088236e136 Update referral.py 2026-01-16 01:16:16 +03:00
Egor 53db561909 Merge pull request #2292 from BEDOLAGA-DEV/dev5
Dev5
2026-01-16 00:59:50 +03:00
Egor 6d2cb32e5f Update subscription.py 2026-01-16 00:58:44 +03:00
Egor 7b23c61703 Add files via upload 2026-01-16 00:57:38 +03:00
Egor 12f592a3dc Merge pull request #2291 from BEDOLAGA-DEV/dev5
Dev5
2026-01-16 00:52:39 +03:00
Egor 9422b9421f Update miniapp.py 2026-01-16 00:51:53 +03:00
Egor 5b7fdff186 Update traffic.py 2026-01-16 00:50:59 +03:00
Egor 395646168d Update subscription.py 2026-01-16 00:50:03 +03:00
Egor 572584710c Merge pull request #2290 from BEDOLAGA-DEV/dev5
Dev5
2026-01-16 00:20:48 +03:00
Egor 23f0be4915 Update info.py 2026-01-15 18:43:34 +03:00
Egor 79904b58a9 Update config.py 2026-01-15 18:42:23 +03:00
Egor bba3b478f5 Merge pull request #2289 from BEDOLAGA-DEV/dev5
Dev5
2026-01-15 17:59:47 +03:00
Egor 829da095e0 Update balance.py 2026-01-15 17:59:21 +03:00
Egor 8bafcc89f5 Update balance.py 2026-01-15 17:58:52 +03:00
Egor f7563dc57c Merge pull request #2288 from BEDOLAGA-DEV/dev5
Dev5
2026-01-15 17:42:58 +03:00
Egor a80f6f8700 Add files via upload 2026-01-15 17:42:17 +03:00
Egor 2e77c5b74e Update miniapp.py 2026-01-15 17:34:39 +03:00
Egor 75108682cc Update miniapp.py 2026-01-15 17:34:16 +03:00
Egor 7113a381c5 Add files via upload 2026-01-15 17:33:28 +03:00
Egor 26865059b8 Update traffic.py 2026-01-15 17:32:20 +03:00
Egor c4382ff69d Add files via upload 2026-01-15 17:31:39 +03:00
Egor 13770a01c6 Add files via upload 2026-01-15 17:31:15 +03:00
Egor a2a09c8914 Update menu.py 2026-01-15 17:02:04 +03:00
Egor bcd3c26843 Update subscription_auto_purchase_service.py 2026-01-15 17:01:35 +03:00
Egor 7f65d398bf Update models.py 2026-01-15 16:56:19 +03:00
PEDZEO a53219525f Merge pull request #2284 from BEDOLAGA-DEV/buttons
Enhance ban notification system with delete functionality and improve…
2026-01-14 14:56:43 +03:00
PEDZEO c868ef3b69 Enhance ban notification system with delete functionality and improved message formatting
- Added a new handler to delete ban notifications upon user interaction.
- Introduced a delete button in ban notifications for better user experience.
- Updated ban notification messages to include node information more prominently.
- Refactored the BanNotificationService to send messages with the delete button included.
2026-01-14 14:50:00 +03:00
PEDZEO 34b87cba88 Merge pull request #2283 from BEDOLAGA-DEV/buttons
Enhance ban notification messages and service to include node informa…
2026-01-14 14:10:24 +03:00
PEDZEO 3aa5e304c3 Enhance ban notification messages and service to include node information
- Updated ban notification messages to provide detailed reasons for account bans, including node information.
- Refactored the BanNotificationService to safely format messages with optional node details.
- Modified API routes and schemas to support the inclusion of node names in ban notifications.
2026-01-14 14:03:09 +03:00
Egor 4b338b3ce2 Update subscription.py 2026-01-14 09:35:16 +03:00
Egor ba4c41a689 Update subscription.py 2026-01-14 09:22:54 +03:00
Egor e4c4b11d74 Update subscription.py 2026-01-14 09:17:49 +03:00
Egor 5fa4cf78c0 Update subscription.py 2026-01-14 09:00:20 +03:00
Egor d2c2f3ced0 Update subscription.py 2026-01-14 08:59:46 +03:00
Egor 7a65dd7fb6 Update branding.py 2026-01-14 08:17:57 +03:00
Egor e33e8bcc2d Update subscription.py 2026-01-14 07:38:59 +03:00
PEDZEO b49031ea72 Merge pull request #2282 from BEDOLAGA-DEV/buttons
Add ban notification messages and refactor notification service
2026-01-14 07:33:02 +03:00
PEDZEO c02c5472a5 Update BanNotificationRequest schema to include new notification type for mobile network bans 2026-01-14 07:31:09 +03:00
PEDZEO 243eef066c Add ban notification messages and refactor notification service
- Introduced new ban notification messages for device limit, WiFi, and mobile network violations in the configuration.
- Refactored the BanNotificationService to utilize the new messages from the configuration for sending notifications.
- Added a new method to handle mobile network ban notifications.
- Updated API routes to support the new notification type for mobile network bans.
2026-01-14 07:25:09 +03:00
PEDZEO e82b6cd4c0 Merge pull request #2281 from BEDOLAGA-DEV/buttons
Add tariff period selection for custom traffic in subscription flow
2026-01-14 06:52:09 +03:00
PEDZEO e1d3363122 Implement discount calculation for custom tariff periods in subscription flow
- Added logic to calculate and apply discounts based on the selected tariff period.
- Updated state management to store discount percentages for custom days and traffic changes.
- Enhanced the tariff price calculation to incorporate discounts when confirming selections.
- Modified the tariff preview to display applicable discounts for better user clarity.
2026-01-14 06:50:19 +03:00
PEDZEO 25623ea211 Add tariff period selection for custom traffic in subscription flow
- Introduced a new function to generate a keyboard for selecting tariff periods with custom traffic.
- Enhanced the tariff price calculation logic to separate period and traffic pricing.
- Updated the custom tariff preview formatting to reflect changes in pricing structure.
- Implemented a new handler for processing the selection of tariff periods with custom traffic.
2026-01-14 06:44:36 +03:00
PEDZEO 3557c8c285 Merge pull request #2280 from BEDOLAGA-DEV/buttons
Implement custom days and traffic handling in subscription purchase flow
2026-01-14 06:41:05 +03:00
PEDZEO 84abf529de Implement custom days and traffic handling in subscription purchase flow
- Added new states for selecting custom days and traffic in the subscription process.
- Enhanced the tariff purchase handler to support custom days and traffic adjustments.
- Introduced new functions for formatting and displaying custom tariff previews.
- Updated the ban notification service to include a new notification type for WiFi bans.
- Modified API routes and schemas to accommodate the new notification type and its parameters.
2026-01-14 06:37:59 +03:00
Egor 48effb5087 Update subscription.py 2026-01-14 06:32:51 +03:00
Egor 237bd24fb3 Update subscription.py 2026-01-14 06:32:24 +03:00
Egor 6bea51b6dc Update config.py 2026-01-14 04:14:29 +03:00
Egor 834c542a57 Update yookassa.py 2026-01-14 04:13:02 +03:00
Egor 9c2b17af3b Update subscription.py 2026-01-14 04:12:18 +03:00
Egor c9d1a6bb55 Update stars_payments.py 2026-01-14 04:11:44 +03:00
Egor a174943bcc Update subscription.py 2026-01-14 03:35:48 +03:00
Egor b651867aac Add files via upload 2026-01-14 03:05:04 +03:00
Egor 10b5b37c48 Update wheel_service.py 2026-01-14 02:52:56 +03:00
Egor f19445bcf1 Update pricing.py 2026-01-14 02:52:22 +03:00
Egor 171b4e2ab4 Update main.py 2026-01-14 02:51:57 +03:00
Egor a1ab2f3727 Update tariff.py 2026-01-14 02:39:58 +03:00
Egor 58eae42eee Add files via upload 2026-01-13 16:51:19 +03:00
Egor 6937bcbc3d Update pricing.py 2026-01-13 16:30:52 +03:00
Egor 4730cf30e9 Update config.py 2026-01-13 16:30:27 +03:00
Egor ce7d7a206c Update config.py 2026-01-13 16:24:48 +03:00
Egor fe4e261115 Merge pull request #2275 from BEDOLAGA-DEV/buttons
Buttons
2026-01-13 03:33:39 +03:00
Egor 38613722b3 Merge pull request #2274 from SayonaraQ/fix/tickets-timezone
Fix ticket timestamps: render in local timezone
2026-01-13 03:29:00 +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 eac299d0bd Update backup_service.py 2026-01-13 01:37:46 +03:00
Egor 31241a6f01 Update backup_service.py 2026-01-13 01:31:02 +03:00
Egor e5faaa6c6f Update index.html 2026-01-13 01:27:07 +03:00
SayonaraQ 96384cfdcf Fix ticket timestamps: render in local timezone 2026-01-13 01:09:03 +03:00
Egor 91f75acb77 Update balance.py 2026-01-13 01:07:46 +03:00
Egor 11167d532b Add files via upload 2026-01-13 01:07:12 +03:00
Egor 70e747b866 Add files via upload 2026-01-13 01:06:13 +03:00
Egor 87f909d9bc Update admin.py 2026-01-13 01:05:36 +03:00
Egor 808bc2d40b Update miniapp.py 2026-01-13 01:04:50 +03:00
Egor 2f06285f69 Update messages.py 2026-01-13 00:53:08 +03:00
Egor 7fb7116101 Update messages.py 2026-01-13 00:52:02 +03:00
Egor 9d1b4bcb54 Update users.py 2026-01-13 00:22:32 +03:00
Egor 1583511854 Update tariff_purchase.py 2026-01-13 00:22:04 +03:00
Egor 45d7c2f659 Merge pull request #2273 from BEDOLAGA-DEV/dev5
Dev5
2026-01-13 00:08:04 +03:00
Egor e92b14391b Update config.py 2026-01-13 00:07:09 +03:00
Egor 61cc2a72cd Update display_name_restriction.py 2026-01-13 00:06:42 +03:00
Egor 9b3a39b13f Update balance.py 2026-01-12 23:53:04 +03:00
Egor 1b51886dd1 Update yookassa.py 2026-01-12 23:51:39 +03:00
Egor cd5116e62f Merge pull request #2272 from BEDOLAGA-DEV/dev5
Update messages.py
2026-01-12 23:31:50 +03:00
Egor a9499337a0 Update messages.py 2026-01-12 23:31:28 +03:00
Egor 2745b015d7 Update miniapp.py 2026-01-12 23:25:32 +03:00
PEDZEO 8e44db357a Enhance _message_to_response function to include media_file_id in the response 2026-01-12 22:26:47 +03:00
PEDZEO ac5850746e Merge pull request #2271 from BEDOLAGA-DEV/main
merge main
2026-01-12 22:25:49 +03:00
Egor c36d51be30 Update index.html 2026-01-12 20:06:37 +03:00
Egor e9a9b85791 Update index.html 2026-01-12 20:03:47 +03:00
Egor 43548fdb27 Update index.html 2026-01-12 20:00:28 +03:00
Egor 4e3b6a081c Update index.html 2026-01-12 19:48:17 +03:00
Egor a2380b937c Update index.html 2026-01-12 19:44:07 +03:00
Egor fe9feaf65d Update miniapp.py 2026-01-12 19:43:38 +03:00
Egor cec597cfd9 Update miniapp.py 2026-01-12 19:34:04 +03:00
Egor 40f1312d0b Update backup_service.py 2026-01-12 19:29:03 +03:00
Egor e4d54677fa Update miniapp.py 2026-01-12 19:25:25 +03:00
Egor f59614f14f Update index.html 2026-01-12 19:24:53 +03:00
Egor c42444429e Update index.html 2026-01-12 19:22:18 +03:00
Egor 7692e85ef0 Update index.html 2026-01-12 19:17:16 +03:00
Egor 5fdbb6fe7e Merge pull request #2270 from BEDOLAGA-DEV/dev5
Daily Tariffs / Bug fixs / promocode fixs / db dublicate session fix
2026-01-12 19:06:54 +03:00
Egor 26f3d4e052 Update purchase.py 2026-01-12 18:57:50 +03:00
Egor fab17702c5 Update miniapp.py 2026-01-12 18:57:13 +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 eb40d8f48a Update miniapp.py 2026-01-12 18:43:54 +03:00
Egor e987b25e6b Add files via upload 2026-01-12 18:26:54 +03:00
Egor 25f2a9507d Update index.html 2026-01-12 18:26:00 +03:00
Egor db54b01f04 Update subscription.py 2026-01-12 18:16:59 +03:00
Egor df17f2be4a Update index.html 2026-01-12 18:13:02 +03:00
Egor 26e242cac7 Update subscription.py 2026-01-12 18:12:14 +03:00
Egor bcef64bafa Update miniapp.py 2026-01-12 18:11:21 +03:00
Egor 97711ac735 Update index.html 2026-01-12 18:01:34 +03:00
Egor 0ac2a7a62b Update miniapp.py 2026-01-12 17:58:50 +03:00
Egor c350195bfc Update miniapp.py 2026-01-12 17:58:25 +03:00
Egor 6e8c9bda30 Update channel_checker.py 2026-01-12 17:39:58 +03:00
Egor ae94ed1dcf Update subscription_checker.py 2026-01-12 17:36:31 +03:00
Egor d9514ac00e Add files via upload 2026-01-12 17:33:52 +03:00
Egor a9e56504a7 Update menu.py 2026-01-12 17:33:11 +03:00
Egor 0f8a367b24 Add files via upload 2026-01-12 17:26:16 +03:00
Egor 09bb52f8e5 Add files via upload 2026-01-12 17:25:47 +03:00
Egor 0903f42da9 Add files via upload 2026-01-12 17:20:55 +03:00
Egor 3839f6f709 Add files via upload 2026-01-12 17:20:13 +03:00
Egor 0759657185 Update purchase.py 2026-01-12 17:00:05 +03:00
Egor 71ff89ca55 Update monitoring_service.py 2026-01-12 16:56:00 +03:00
Egor 030acf07a4 Update tariff_purchase.py 2026-01-12 16:47:52 +03:00
Egor 891b388799 Add files via upload 2026-01-12 16:41:36 +03:00
Egor 92a6231b6f Update tariff_purchase.py 2026-01-12 16:40:42 +03:00
Egor 7aac2fadf7 Update tariff_purchase.py 2026-01-12 16:33:47 +03:00
Egor 640a80953f Update subscription.py 2026-01-12 16:31:00 +03:00
Egor 2090da3603 Update inline.py 2026-01-12 16:30:24 +03:00
Egor 62bec70db9 Update daily_subscription_service.py 2026-01-12 16:29:59 +03:00
Egor 8c5a385f14 Update tariff_purchase.py 2026-01-12 16:29:31 +03:00
Egor 78c44a1e00 Update tariff_purchase.py 2026-01-12 16:19:17 +03:00
Egor 1c23538b71 Update tariff_purchase.py 2026-01-12 16:14:14 +03:00
Egor 4967c7ff7d Update daily_subscription_service.py 2026-01-12 16:05:31 +03:00
Egor 2b1a20e373 Update purchase.py 2026-01-12 15:59:22 +03:00
Egor 6fc3dd0e35 Update purchase.py 2026-01-12 15:49:25 +03:00
Egor 7c4471a510 Update inline.py 2026-01-12 15:48:51 +03:00
Egor 24666dd155 Update tariffs.py 2026-01-12 15:48:20 +03:00
Egor 42978e2a37 Update inline.py 2026-01-12 15:27:37 +03:00
Egor 22884b5cdd Update purchase.py 2026-01-12 15:27:05 +03:00
Egor 785eabaa47 Update tariffs.py 2026-01-12 15:26:20 +03:00
Egor 538c002f8f Add files via upload 2026-01-12 15:25:47 +03:00
Egor 472ef37490 Add files via upload 2026-01-12 15:25:25 +03:00
Egor 9e4fa9defe Add files via upload 2026-01-12 15:24:59 +03:00
Egor 49bd69f987 Add files via upload 2026-01-12 15:24:17 +03:00
Egor e15aed6c19 Update main.py 2026-01-12 15:23:27 +03:00
Egor 2e4e62d324 Update index.html 2026-01-12 14:31:13 +03:00
Egor b7137c9498 Merge pull request #2261 from evansvl/main
Fix formatting and improve readability in README.md; update configuration tables and enhance descriptions for better clarity.
2026-01-12 13:58:06 +03:00
PEDZEO 15f6108674 feat(tariffs): добавлена поддержка докупки трафика и улучшения тарифов
- Реализована возможность докупки трафика для тарифов с новыми параметрами: traffic_topup_enabled, traffic_topup_packages и max_topup_traffic_gb.
- Обновлены схемы и маршруты для управления тарифами и трафиком.
- Добавлены новые эндпоинты для работы с докупкой трафика в мини-приложении.
- Обновлены настройки и логика для проверки доступности докупки трафика в зависимости от тарифа.
- Внедрены улучшения в обработку платежей через Freekassa.

Обновлён .env.example с новыми параметрами для режима тарифов.
2026-01-12 07:47:35 +03:00
PEDZEO 0e24a5505c feat(subscription): добавлены новые функции для управления тарифами и трафиком
- Обновлены схемы и маршруты для поддержки покупки тарифов и управления трафиком.
- Реализована синхронизация тарифов и серверов из RemnaWave при запуске.
- Добавлены новые параметры в тарифы: server_traffic_limits и allow_traffic_topup.
- Обновлены настройки и логика для проверки доступности докупки трафика в зависимости от тарифа.
- Внедрены новые эндпоинты для работы с колесом удачи и обработка платежей через Stars.

Обновлён .env.example с новыми параметрами для режима продаж подписок.
2026-01-12 07:41:10 +03:00
PEDZEO ffbb879752 Merge pull request #2264 from BEDOLAGA-DEV/main
main
2026-01-12 07:38:37 +03:00
evansvl 8f1b71408e Fix formatting and improve readability in README.md; update configuration tables and enhance descriptions for better clarity. 2026-01-11 06:11:11 +03:00
Egor 62a8e6cdc6 Merge pull request #2260 from evansvl/main
Enhance Freekassa payment handling and improve Docker Compose configuration
2026-01-11 05:59:11 +03:00
Egor a18cfd0147 Update tariff_purchase.py 2026-01-11 05:57:01 +03:00
Egor 2619db3f40 Update miniapp.py 2026-01-11 05:56:24 +03:00
Egor fea2283d88 Update miniapp.py 2026-01-11 05:53:44 +03:00
Egor 479a2b8344 Update tariff_purchase.py 2026-01-11 05:52:59 +03:00
Egor 453577b448 Update miniapp.py 2026-01-11 05:47:56 +03:00
evansvl b5234f3265 Enhance Freekassa payment handling and improve Docker Compose configuration 2026-01-11 05:45:09 +03:00
evansvl edb335ee52 Reduce Freekassa API logging verbosity 2026-01-11 05:44:43 +03:00
Egor 0333720fca Update index.html 2026-01-11 05:21:27 +03:00
Egor 76b521879e Update miniapp.py 2026-01-11 05:21:03 +03:00
Egor 4a24dbe267 Update miniapp.py 2026-01-11 05:20:41 +03:00
Egor fdd40ed923 Update miniapp.py 2026-01-11 05:14:25 +03:00
Egor b2b48b8bde Merge pull request #2259 from evansvl/main
Add Freekassa webhook handling and configuration options
2026-01-11 05:12:56 +03:00
Egor 10f9622df7 Update index.html 2026-01-11 05:08:43 +03:00
Egor 1586a3fe9a Update miniapp.py 2026-01-11 05:08:21 +03:00
Egor d4556038cc Update miniapp.py 2026-01-11 05:07:54 +03:00
evansvl a54a12825e Add Freekassa webhook handling and configuration options 2026-01-11 05:06:07 +03:00
Egor efae4b0c44 Update miniapp.py 2026-01-11 05:01:36 +03:00
Egor cda70afdef Update miniapp.py 2026-01-11 04:57:32 +03:00
Egor ead8266e0e Update index.html 2026-01-11 04:56:54 +03:00
Egor daf8214c40 Update index.html 2026-01-11 04:54:13 +03:00
Egor 9dacd3be24 Update miniapp.py 2026-01-11 04:51:06 +03:00
Egor a7fa36ca9b Update index.html 2026-01-11 04:50:15 +03:00
Egor fae72d7107 Update index.html 2026-01-11 04:42:33 +03:00
Egor f94c1437e4 Update index.html 2026-01-11 04:31:57 +03:00
Egor a8d167ac9a Update index.html 2026-01-11 04:27:18 +03:00
Egor 8b9ff3a32b Merge pull request #2258 from BEDOLAGA-DEV/dev5
Dev5
2026-01-11 04:12:46 +03:00
Egor 8482e4caad Update index.html 2026-01-11 04:09:47 +03:00
Egor b2577d5973 Update inline.py 2026-01-11 04:09:19 +03:00
Egor 752abfc6b5 Update tariff_purchase.py 2026-01-11 04:08:48 +03:00
Egor b213f7deb4 Update miniapp.py 2026-01-11 04:08:11 +03:00
Egor 7dfbd833bb Update miniapp.py 2026-01-11 04:07:42 +03:00
Egor 83812e1d4c Merge pull request #2257 from BEDOLAGA-DEV/main
w
2026-01-11 04:00:43 +03:00
Egor 21b2add7ac Update miniapp.py 2026-01-11 03:40:33 +03:00
Egor 1f52c39fed Update miniapp.py 2026-01-11 03:33:07 +03:00
Egor b9c9a82b6f Update miniapp.py 2026-01-11 03:28:46 +03:00
Egor 0a0f59ea24 Update miniapp.py 2026-01-11 03:22:07 +03:00
Egor aa6935464b Update universal_migration.py 2026-01-11 03:04:57 +03:00
Egor f50d6fc28a Merge pull request #2256 from BEDOLAGA-DEV/dev5
Dev5
2026-01-11 03:00:42 +03:00
Egor 3656f0181c Update tariffs.py 2026-01-11 02:59:48 +03:00
Egor 7c3b3188c1 Update states.py 2026-01-11 02:59:16 +03:00
Egor fc7d3d1823 Update index.html 2026-01-11 02:58:40 +03:00
Egor 3117d02c2f Update miniapp.py 2026-01-11 02:58:08 +03:00
Egor c2fe9f082f Update miniapp.py 2026-01-11 02:57:41 +03:00
Egor ce66c08e1a Update tariff.py 2026-01-11 02:56:46 +03:00
Egor c58faff2df Update models.py 2026-01-11 02:56:14 +03:00
Egor cb6aa4bad4 Merge pull request #2255 from BEDOLAGA-DEV/main
ц
2026-01-11 02:55:55 +03:00
Egor 11a35e1058 Update index.html 2026-01-11 02:28:20 +03:00
Egor d51cb4a02d Merge pull request #2254 from BEDOLAGA-DEV/dev5
Update miniapp.py
2026-01-11 02:21:25 +03:00
Egor deae83d2cd Update miniapp.py 2026-01-11 02:20:43 +03:00
Egor 0ad0462afb Merge pull request #2253 from BEDOLAGA-DEV/dev5
Dev5
2026-01-11 02:13:35 +03:00
Egor ca5f9af325 Update miniapp.py 2026-01-11 02:13:03 +03:00
Egor db98b20118 Update index.html 2026-01-11 02:12:22 +03:00
Egor 66cd99e2a8 Merge pull request #2252 from BEDOLAGA-DEV/dev5
Update index.html
2026-01-11 02:01:23 +03:00
Egor 217df39e10 Update index.html 2026-01-11 02:00:59 +03:00
Egor 752850e56b Update Dockerfile 2026-01-11 00:08:34 +03:00
Egor 6a1eb3a530 Update docker-registry.yml 2026-01-11 00:08:24 +03:00
Egor 2b89748384 Update docker-hub.yml 2026-01-11 00:08:14 +03:00
Egor 638c60b39b Merge pull request #2251 from BEDOLAGA-DEV/dev5
Update index.html
2026-01-10 22:13:37 +03:00
Egor f27b6c55fd Update index.html 2026-01-10 22:12:51 +03:00
Egor e5c1d4166a Merge pull request #2250 from BEDOLAGA-DEV/dev5
Update miniapp.py
2026-01-10 21:58:46 +03:00
Egor 34a5b0345f Update miniapp.py 2026-01-10 21:58:04 +03:00
Egor c9f67e6db3 Merge pull request #2249 from BEDOLAGA-DEV/dev5
Update change tariffs logic / Traffic buy / Freekassa updates / ux updates
2026-01-10 21:46:33 +03:00
Egor 8eaec9b032 Add files via upload 2026-01-10 21:44:17 +03:00
Egor 39c3ec9ed4 Add files via upload 2026-01-10 21:43:29 +03:00
Egor a598237465 Update index.html 2026-01-10 21:37:17 +03:00
Egor c5a35cd254 Update miniapp.py 2026-01-10 21:36:31 +03:00
Egor c7a51915c9 Update miniapp.py 2026-01-10 21:35:59 +03:00
Egor 29725d6028 Update index.html 2026-01-10 21:31:41 +03:00
Egor 60846ad06b Update miniapp.py 2026-01-10 21:29:55 +03:00
Egor 7a86cb6010 Update miniapp.py 2026-01-10 21:25:03 +03:00
Egor 16e70bff46 Update miniapp.py 2026-01-10 21:14:40 +03:00
Egor 4c947a3de9 Update miniapp.py 2026-01-10 21:14:06 +03:00
Egor 2c4b77ff8c Update inline.py 2026-01-10 21:05:58 +03:00
Egor e6676720f2 Update inline.py 2026-01-10 20:57:49 +03:00
Egor 83769df0ee Update tariff_purchase.py 2026-01-10 20:52:25 +03:00
Egor b2e00ecbbe Update user_service.py 2026-01-10 20:48:42 +03:00
Egor 7ea906bd1e Update tariff_purchase.py 2026-01-10 20:41:59 +03:00
Egor 744428e4f6 Update tariff.py 2026-01-10 20:37:40 +03:00
Egor 5d1d561882 Update subscription.py 2026-01-10 20:33:55 +03:00
Egor 69f4fd2b2a Update tariffs.py 2026-01-10 20:32:57 +03:00
Egor 8690d5fa8e Update traffic.py 2026-01-10 20:32:20 +03:00
Egor 209ce2c25a Update universal_migration.py 2026-01-10 20:30:47 +03:00
Egor 90d090a048 Update models.py 2026-01-10 20:30:30 +03:00
Egor e66944e2bf Update inline.py 2026-01-10 20:29:53 +03:00
Egor 57e4ccea28 Update states.py 2026-01-10 20:29:22 +03:00
Egor 011f4428e2 Update config.py 2026-01-10 19:41:18 +03:00
Egor 4d62fa946b Update freekassa_service.py 2026-01-10 19:40:56 +03:00
Egor fc9552a1bf Add files via upload 2026-01-10 18:38:58 +03:00
Egor af5401a393 Update freekassa_service.py 2026-01-10 18:38:20 +03:00
Egor 3685af771e Update miniapp.py 2026-01-10 18:28:48 +03:00
Egor bc7470b39d Update subscription.py 2026-01-10 18:20:35 +03:00
Egor cd0a25abec Update users.py 2026-01-10 18:17:10 +03:00
Mikhail 553e8e1ecd Merge branch 'BEDOLAGA-DEV:main' into main 2026-01-10 00:47:40 +03:00
gy9vin 6e1d671df2 feat(traffic): добавлен новый мониторинг трафика v2 с проверкой дельты и snapshot
Новый функционал:
- Быстрая проверка (TRAFFIC_FAST_CHECK_*) — отслеживает дельту трафика за интервал через snapshot
- Суточная проверка (TRAFFIC_DAILY_CHECK_*) — анализирует трафик за 24 часа через bandwidth API
- Фильтрация по нодам (TRAFFIC_MONIT
2026-01-10 00:47:23 +03:00
Egor b482c76a5c Merge pull request #2248 from BEDOLAGA-DEV/dev5
Dev5
2026-01-09 19:31:47 +03:00
Egor 4e6d5b4716 Update subscription.py 2026-01-09 19:30:53 +03:00
Egor 879650c2e4 Update webhook_server.py 2026-01-09 13:11:40 +03:00
Egor d9ce09b3bf Update ru.json 2026-01-08 23:14:40 +03:00
Egor 678bd18509 Merge pull request #2247 from BEDOLAGA-DEV/main
ц
2026-01-08 23:14:18 +03:00
Egor 805e3847b9 Merge pull request #2234 from Gy9vin/main
Обновки
2026-01-08 14:43:22 +03:00
gy9vin eaeb6def51 feat(config): добавлено предупреждение после пополнения и обновлён .env.example
Новый функционал:
- SHOW_ACTIVATION_PROMPT_AFTER_TOPUP — показывает предупреждение с кнопками
  "Активировать", "Продлить", "Добавить устройства" после пополнения баланса,
  если подписка не активна (режим для новичков)

Обновлён .env.example (+138 строк):
- Redis: CART_TTL_SECONDS
- Remnawave: AUTO_SYNC_*, TRIAL_USER_TAG, PAID_SUBSCRIPTION_USER_TAG
- Трафик: BUY_TRAFFIC_BUTTON_VISIBLE, PRICE_TRAFFIC_UNLIMITED
- Автопродление: ENABLE_AUTOPAY
- Конкурсы: REFERRAL_CONTESTS_ENABLED
- YooKassa: TRUSTED_PROXY_NETWORKS
- Mulenpay: DISPLAY_NAME, IFRAME_EXPECTED_ORIGIN, DISPLAY_NAME_BANNED_KEYWORDS
- Platega: DISPLAY_NAME
- WATA: PUBLIC_KEY_CACHE_SECONDS, PUBLIC_KEY_URL
- CloudPayments: API_URL, WIDGET_URL, RETURN_URL
- Интерфейс: MENU_LAYOUT_ENABLED, MINIAPP_PURCHASE_URL, HAPP_DOWNLOAD_LINK_PC
- Web API: WORKERS, TITLE, VERSION, TOKEN_HASH_ALGORITHM, REQUEST_LOGGING,
  EXTERNAL_ADMIN_TOKEN, EXTERNAL_ADMIN_TOKEN_BOT_ID

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-08 11:16:52 +03:00
gy9vin 4c1ebd9f61 Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2026-01-08 11:00:38 +03:00
gy9vin 51b88068bd fix(payment): добавлен параметр bot в auto_activate_subscription_after_topup
- Передача bot через getattr(self, "bot", None) во всех платёжных провайдерах
  - Добавлена отправка предупреждений пользователю при отключенной автоактивации
  - Добавлены предупреждения о необходимости активации подписки после пополнения
2026-01-08 11:00:34 +03:00
Mikhail f25ed360fc Merge branch 'BEDOLAGA-DEV:main' into main 2026-01-08 08:12:45 +03:00
Egor 75b1fff791 Delete docs/web-api-analysis-and-suggestions.md 2026-01-08 04:55:31 +03:00
Egor 4ed23caa68 Update README.md 2026-01-08 04:41:31 +03:00
Egor 098e297e3a Update README.md 2026-01-08 04:40:39 +03:00
Egor 20315cf88f Update README.md 2026-01-08 04:37:18 +03:00
Egor 28c953c5ae Update Dockerfile 2026-01-08 03:45:21 +03:00
Egor 685305bff2 Update docker-registry.yml 2026-01-08 03:45:09 +03:00
Egor 927eb1d240 Update docker-hub.yml 2026-01-08 03:44:57 +03:00
Egor c767473184 Merge pull request #2246 from BEDOLAGA-DEV/dev5
Freekassa fix / campaign fix
2026-01-08 03:30:28 +03:00
Egor 744e5c1453 Update campaign_service.py 2026-01-08 03:28:49 +03:00
Egor 5eb581c68e Update .env.example 2026-01-08 03:19:32 +03:00
Egor cf53801408 Update freekassa.py 2026-01-08 03:18:56 +03:00
Egor 4e59d0a071 Update freekassa_service.py 2026-01-08 03:18:31 +03:00
Egor c31de445b9 Update config.py 2026-01-08 03:18:03 +03:00
Egor cc3f78c2f8 Update subscription.py 2026-01-08 03:07:31 +03:00
Egor 5eae547cb2 Update tariff_purchase.py 2026-01-08 02:57:50 +03:00
Egor 7e8e0c1617 Update tariff_purchase.py 2026-01-08 02:54:31 +03:00
Egor 250b8d95fb Update tariff_purchase.py 2026-01-08 02:45:26 +03:00
Egor 28e868fb09 Merge pull request #2245 from BEDOLAGA-DEV/main
ц
2026-01-08 02:44:47 +03:00
Egor 45e9a29b4e Update index.html 2026-01-08 02:36:25 +03:00
Egor 8a52b34760 Update index.html 2026-01-08 02:26:36 +03:00
Egor 464df9689e Update index.html 2026-01-08 01:33:36 +03:00
Egor 6191a7a395 Update index.html 2026-01-08 01:25:27 +03:00
Egor 233f6c3490 Update index.html 2026-01-08 01:02:18 +03:00
Egor 0e5b115d64 Update index.html 2026-01-08 00:52:25 +03:00
Egor 69bf99f3a6 Merge pull request #2244 from BEDOLAGA-DEV/dev5
Update index.html
2026-01-07 18:36:05 +03:00
Egor dae5c07318 Update index.html 2026-01-07 18:35:43 +03:00
Egor d53bf4ae29 Merge pull request #2243 from BEDOLAGA-DEV/dev5
Update index.html
2026-01-07 17:53:10 +03:00
Egor 50dd5a5fb3 Update index.html 2026-01-07 17:52:50 +03:00
Egor 9595026d3d Merge pull request #2242 from BEDOLAGA-DEV/dev5
Api update / Miniapp fix
2026-01-07 17:39:27 +03:00
Egor 571018982f Update index.html 2026-01-07 17:35:30 +03:00
Egor cfdfe1ccd1 Update miniapp.py 2026-01-07 17:34:39 +03:00
Egor d9f0d6496d Update miniapp.py 2026-01-07 17:33:56 +03:00
Egor 0eba4cfc8f Update remnawave_api.py 2026-01-07 17:25:06 +03:00
gy9vin 6392033579 fix(referral): обновлены методы отправки уведомлений админам
- Заменён метод send_notification на send_to_admins в AdminNotificationService
  - Исправлена настройка NOTIFICATIONS_CHAT_ID на ADMIN_NOTIFICATIONS_CHAT_ID для отправки в топик
2026-01-07 17:00:34 +03:00
gy9vin 2607ee4d0a fix(referral-withdrawal): исправления тестового режима вывода
1. Исправлена кнопка "Профиль" после тестового начисления
     - callback изменён с admin_user_{id} на admin_user_manage_{id}

  2. Исправлена логика расчёта доступного баланса
     - Добавлен метод get_first_referral_earning_date()
     - Добавлен метод get_user_spending_after_first_earning()
     - Теперь учитываются только траты ПОСЛЕ первого реф. начисления
     - Старые траты больше не уменьшают доступный реферальный баланс

  3. Добавлен bypass cooldown в тестовом режиме
     - При REFERRAL_WITHDRAWAL_TEST_MODE=true 30-дневный cooldown пропускается
2026-01-07 16:05:42 +03:00
gy9vin 3299d47b11 merge: resolve conflict in universal_migration.py 2026-01-07 15:05:14 +03:00
gy9vin 4afefcafa4 Добавлена система вывода реферального баланса
Новая функциональность вывода средств:
  - config.py: добавлены настройки вывода (минимальная сумма, кулдаун, анализ подозрительности, тестовый режим)
  - models.py: добавлена модель WithdrawalRequest с полями для заявок, анализа рисков и обработки админ
2026-01-07 14:54:50 +03:00
Mikhail c582e1b0c6 Merge branch 'BEDOLAGA-DEV:main' into main 2026-01-07 14:24:08 +03:00
Egor 3eb84338a4 Merge pull request #2241 from BEDOLAGA-DEV/dev5
Tariffs
2026-01-07 05:14:30 +03:00
Egor 127a609d6b Update .env.example 2026-01-07 05:12:18 +03:00
Egor 528944f649 Update tariff_purchase.py 2026-01-07 05:06:25 +03:00
Egor 48fa739ca7 Update tariff_purchase.py 2026-01-07 04:48:27 +03:00
Egor 07e50f449f Update tariff_purchase.py 2026-01-07 04:40:09 +03:00
Egor 47433d905e Update admin.py 2026-01-07 04:30:54 +03:00
Egor b096003683 Update tariff_purchase.py 2026-01-07 04:26:31 +03:00
Egor 5814bbc920 Update tariff_purchase.py 2026-01-07 04:18:46 +03:00
Egor fdffe7ae35 Update traffic.py 2026-01-07 04:08:33 +03:00
Egor 917fa84838 Update service.py 2026-01-07 04:07:52 +03:00
Egor 9631f340c1 Update config.py 2026-01-07 03:58:44 +03:00
Egor 61fe7f0be4 Update inline.py 2026-01-07 03:49:31 +03:00
Egor a8c54c4d3b Update miniapp.py 2026-01-07 03:48:49 +03:00
Egor db7e6cf8f8 Add files via upload 2026-01-07 03:48:02 +03:00
Egor 9690436b9f Update tariffs.py 2026-01-07 03:47:28 +03:00
Egor fefc46e5c4 Update miniapp.py 2026-01-07 03:38:52 +03:00
Egor 14fc1f58af Update states.py 2026-01-07 03:38:13 +03:00
Egor f933992883 Update purchase.py 2026-01-07 03:31:56 +03:00
Egor fdc382f309 Update tariffs.py 2026-01-07 03:31:17 +03:00
Egor 0ef3e32c15 Update miniapp.py 2026-01-07 03:20:58 +03:00
Egor 9c870ffc70 Update purchase.py 2026-01-07 03:20:17 +03:00
Egor 6ce87698bc Update tariff.py 2026-01-07 03:19:32 +03:00
Egor 60a38d3ea6 Add files via upload 2026-01-07 03:18:46 +03:00
Egor 5355f41bef Update states.py 2026-01-07 03:06:11 +03:00
Egor 0fac84aa7d Update tariffs.py 2026-01-07 03:05:31 +03:00
Egor b4e472b873 Add files via upload 2026-01-07 03:04:44 +03:00
Egor 6c0c3f1b79 Update inline.py 2026-01-07 03:03:55 +03:00
Egor 203405438f Update tariff.py 2026-01-07 03:03:18 +03:00
Egor a38c12eaa6 Add files via upload 2026-01-07 03:02:47 +03:00
Egor e48ebca91e Update inline.py 2026-01-07 02:55:26 +03:00
Egor e32bf5f2c4 Add files via upload 2026-01-07 02:54:47 +03:00
Egor fbb7d6c4ab Update tariffs.py 2026-01-07 02:45:42 +03:00
Egor 29f967469f Update tariff_purchase.py 2026-01-07 02:42:07 +03:00
Egor 541d3c903d Update subscription_auto_purchase_service.py 2026-01-07 02:37:30 +03:00
Egor f19e2b2a34 Update ru.json 2026-01-07 02:36:43 +03:00
Egor 3d0050139c Refactor personal discount retrieval in tariff_purchase 2026-01-07 02:36:02 +03:00
Egor 0b677e4205 Update tariffs.py 2026-01-07 02:35:27 +03:00
Egor 71dac493d8 Update tariffs.py 2026-01-07 02:29:37 +03:00
Egor fc1528532e Update index.html 2026-01-07 02:25:48 +03:00
Egor 48cb19170b Update miniapp.py 2026-01-07 02:24:30 +03:00
Egor 1af1919a14 Update miniapp.py 2026-01-07 02:23:58 +03:00
Egor 5d864d0286 Introduce tariff creation and editing states
Added states for creating and editing tariffs.
2026-01-07 02:23:21 +03:00
Egor a448a2c450 Add files via upload 2026-01-07 02:22:36 +03:00
Egor e301d49657 Add tariffs button to admin keyboard 2026-01-07 02:21:42 +03:00
Egor 738216cf9f Add tariff change button for tariff mode 2026-01-07 02:21:15 +03:00
Egor 7b6f646d7e Update bot.py 2026-01-07 02:20:49 +03:00
Egor 3150349ffa Update config.py 2026-01-07 02:17:18 +03:00
Egor b50478eda0 Add files via upload 2026-01-07 02:16:33 +03:00
Egor cff00eb515 Add files via upload 2026-01-07 02:16:00 +03:00
Egor a981bf2ae0 Add files via upload 2026-01-07 02:15:16 +03:00
Egor 031c2b683b Add files via upload 2026-01-07 02:14:41 +03:00
Egor 72d2501be5 Merge pull request #2240 from BEDOLAGA-DEV/dev5
Update start.py
2026-01-06 22:59:30 +03:00
Egor 69ff87ab31 Update start.py 2026-01-06 22:57:21 +03:00
Egor e4fce0f430 Merge pull request #2239 from BEDOLAGA-DEV/dev5
Update start.py
2026-01-06 22:51:38 +03:00
Egor 5fb0699dcb Update start.py 2026-01-06 22:51:18 +03:00
Egor 965ae9d1d8 Merge pull request #2238 from BEDOLAGA-DEV/revert-2237-revert-2236-dev5
Revert "Revert "Frekassa""
2026-01-06 22:43:11 +03:00
Egor 23b64ffb2a Revert "Revert "Frekassa"" 2026-01-06 22:43:01 +03:00
Egor 9868c5de0f Merge pull request #2237 from BEDOLAGA-DEV/revert-2236-dev5
Revert "Frekassa"
2026-01-06 22:40:45 +03:00
Egor aeaaa54920 Revert "Frekassa" 2026-01-06 22:40:35 +03:00
Egor fb25032284 Merge pull request #2236 from BEDOLAGA-DEV/dev5
Frekassa
2026-01-06 21:43:35 +03:00
Egor 3e0661da39 Update index.html 2026-01-06 21:02:20 +03:00
Egor 7ab9fe9ad2 Update .env.example 2026-01-06 21:01:56 +03:00
Egor 7c846c2f83 Update miniapp.py 2026-01-06 21:01:20 +03:00
Egor 163f55ec14 Update config.py 2026-01-06 21:00:04 +03:00
Egor 2c8e67ac82 Implement Freekassa webhook handler
Added support for Freekassa webhook handling and logging.
2026-01-06 20:59:38 +03:00
Egor e9ce583eb2 Add files via upload 2026-01-06 20:59:02 +03:00
Egor 416908aea4 Add files via upload 2026-01-06 20:58:36 +03:00
Egor 6223a5d63a Update bot_configuration.py 2026-01-06 20:57:55 +03:00
Egor 53a10c0640 Add files via upload 2026-01-06 20:56:44 +03:00
Egor 7c2408209d Add files via upload 2026-01-06 20:54:46 +03:00
Egor 9fbc3a8312 Add FreekassaPayment model for payment processing 2026-01-06 20:54:18 +03:00
Egor dff08cbad2 Add create_freekassa_payments_table function 2026-01-06 20:53:55 +03:00
Egor a2379b9be1 Delete FreekassaPayment model and related code
Removed FreekassaPayment class and its related fields.
2026-01-06 20:53:32 +03:00
Egor 12dc9ccbaa Update models.py 2026-01-06 20:51:46 +03:00
gy9vin 8342e8fe35 Ручной запуск мониторинга трафика
Ручная проверка в админке (monitoring.py):
  - Новая кнопка "📊 Проверка трафика" в меню мониторинга
  - Проверяет всех юзеров с активной подпиской
  - Показывает результат: сколько проверено, сколько превышений
  - Отправляет уведомления админам при превышении
2026-01-04 21:21:05 +03:00
Mikhail 03d30dd5c0 Merge branch 'BEDOLAGA-DEV:main' into main 2026-01-04 21:15:40 +03:00
gy9vin 27512825ae Улучшение системы мониторинга трафика
Изменения в traffic_monitoring_service.py:

  1. Добавлен импорт get_db — для получения сессии БД внутри цикла
  2. Добавлен set_bot() — для установки бота
  3. Изменён start_monitoring() — не требует db и bot как параметры
  4. Добавлен кэш уведомлений — защита от спама (1 уведомление в 24ч на юзера)
  5. Добавлена очистка кэша — удаляет записи старше 48ч

  Изменения в main.py:

  1. Импорт traffic_monitoring_scheduler
  2. Переменная traffic_monitoring_task
  3. set_bot() при старте
  4. Stage "Мониторинг трафика" с логированием интервала и порога
  5. Секция "Активные фоновые сервисы" — добавлен статус
  6. Перезапуск при ошибке в основном цикле
  7. Остановка в блоке finally

  ---
  Как включить

  В .env на сервере:

  TRAFFIC_MONITORING_ENABLED=true
  TRAFFIC_THRESHOLD_GB_PER_DAY=10.0
  TRAFFIC_MONITORING_INTERVAL_HOURS=1
  SUSPICIOUS_NOTIFICATIONS_TOPIC_ID=14

  После перезагрузки бота увидишь в логах:

  📊 Мониторинг трафика
     ├ Интервал проверки: 1 ч
     ├ Порог трафика: 10.0 ГБ/сутки
     └  Мониторинг трафика запущен
2026-01-04 21:15:29 +03:00
Egor 4b74ae12ad Merge pull request #2233 from BEDOLAGA-DEV/main
w
2026-01-04 17:24:01 +03:00
PEDZEO 258a4a5cb4 Merge pull request #2230 from BEDOLAGA-DEV/buttons
Buttons
2026-01-03 14:41:17 +03:00
Egor 2cd2147464 Merge pull request #2231 from Gy9vin/main
Фиксы
2026-01-02 19:26:52 +03:00
Mikhail c5efc7ce06 Merge branch 'BEDOLAGA-DEV:main' into main 2026-01-02 19:25:34 +03:00
gy9vin 9cd5d8e0b9 Фикс промокодов 2026-01-02 19:23:52 +03:00
Egor 31d538fbcf Merge pull request #2229 from Gy9vin/main
Фиксы
2026-01-02 19:01:26 +03:00
gy9vin 2156f630dc Добавлена опция "только для первой покупки" в промокоды
- models.py: добавлено поле first_purchase_only в PromoCode
- universal_migration.py: миграция для добавления колонки first_purchase_only
- promocodes.py: добавлен хендлер toggle_promocode_first_purchase, отображение статуса в управлении промокодом
- promocode.py: обработка ошибки "not
2026-01-02 16:40:04 +03:00
gy9vin 917ca69b1d фикс 2026-01-02 16:20:42 +03:00
gy9vin d524088bb8 Обязательная подписка на канал Доработка 2026-01-02 16:14:40 +03:00
PEDZEO 9bd1944ba3 fix platega inv 2026-01-02 12:16:36 +03:00
PEDZEO c41979bda6 fix 2026-01-02 00:48:08 +03:00
PEDZEO 0813d585d2 docs: add cabinet settings to .env.example
Add configuration options for personal cabinet:
- CABINET_ENABLED, JWT settings, CORS origins
- Email verification settings
- SMTP configuration for email sending

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-02 00:23:05 +03:00
PEDZEO 3f74005068 feat: add cabinet columns migration
Add automatic migration for cabinet (personal account) columns:
- email, email_verified, email_verified_at
- password_hash, email_verification_token/expires
- password_reset_token/expires, cabinet_last_login

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 23:58:47 +03:00
PEDZEO 6b69ec750e feat: add cabinet (personal account) backend API
- Add JWT authentication for cabinet users
- Add Telegram WebApp authentication
- Add subscription management endpoints
- Add balance and transactions endpoints
- Add referral system endpoints
- Add tickets support for cabinet
- Add webhooks and websocket for real-time updates
- Add email verification service

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 23:20:20 +03:00
gy9vin 5a5a18d80d Фикс промокодов
Пагинация списка промокодов:
     - promocodes.py: добавлен хендлер show_promocodes_list_page
     - Зарегистрирован для admin_promo_list_page_*
2026-01-01 22:59:12 +03:00
gy9vin 4bebff5c4a fix(auto-activation): исправлен парсинг AVAILABLE_SUBSCRIPTION_PERIODS
Ошибка: код итерировал по строке "14,30,60,90,180,360" посимвольно,
  что приводило к ValueError: invalid literal for int() with base 10: ','

  Заменено на settings.get_available_subscription_periods() который
  корректно парсит строку в список [14, 30, 60, 90, 180, 360].
2026-01-01 22:55:01 +03:00
Mikhail e2ae7dd34d Merge branch 'BEDOLAGA-DEV:main' into main 2026-01-01 22:48:27 +03:00
gy9vin e15728e369 Fix простой покупки 2026-01-01 22:47:40 +03:00
Egor ecaf270e04 Merge pull request #2228 from yazhog/main
Новые коды НДС для Юкассы
2025-12-31 14:07:48 +04:00
Egor 08e864e5ea Merge pull request #2227 from Gy9vin/main
Фиксы по старому функционалу)
2025-12-31 14:06:16 +04:00
yazhog 97655b8616 Merge pull request #47 from yazhog/codex/add-new-yookassa_vat_code-to-api
Add YooKassa VAT codes 7–12 to settings and document them in .env.example
2025-12-31 12:01:35 +03:00
yazhog 800d589afa Document YooKassa VAT codes in env example 2025-12-31 12:00:48 +03:00
gy9vin ff51a984ef fix Параметризация callback_data в get_back_keyboard + поддержка модема в уведомлениях
1. app/keyboards/inline.py
  - Добавлен параметр callback_data: str = "back_to_menu" в get_back_keyboard()
  - Позволяет использовать кнопку "Назад" с разными callback'ами

2. app/services/admin_notification_service.py
  - Добавлен тип "modem" в update_types с заголовком "📡 ИЗМЕНЕНИЕ МОД
2025-12-31 10:16:14 +03:00
gy9vin a4072237cc fix(nalogo): защита от дублирования чеков + очередь ручной проверки
ПРОБЛЕМА:
  При таймауте после успешной авторизации чек мог быть создан на сервере
  nalog.ru, но ответ не возвращался. Бот добавлял чек в очередь повторной
  отправки → создавался дубликат.

  РЕШЕНИЕ:
  1. Разделена обработка ошибок на два этапа:
     - Аутентификация не прошла → чек точно не создан → в очередь
     - Таймаут при создании → чек МОГ быть создан → НЕ в очередь

  2. Новая очередь `nalogo:pending_verification` для чеков требующих
     ручной проверки (когда таймаут после успешной авторизации)

  3. Кнопка в админке: Мониторинг → Статистика → "⚠️ Проверить (N)"
     - Показывает список чеков с суммой, датой, payment_id
     - " Создан" — чек найден в налоговой, убираем из очереди
     - "🔄 Отправить" — чек НЕ найден, отправляем повторно
     - "🗑 Очистить всё" — после полной сверки с lknpd.nalog.ru

  4. Таймаут увеличен с 10 до 30 секунд (NALOGO_TIMEOUT)

  5. Атомарная защита от race condition через cache.setnx()

  Изменённые файлы:
  - app/utils/cache.py — добавлен метод setnx()
  - app/services/nalogo_service.py — разделение ошибок, pending_verification
  - app/services/nalogo_queue_service.py — статус pending в get_status()
  - app/handlers/admin/monitoring.py — UI для ручной проверки
2025-12-31 01:25:47 +03:00
gy9vin ac83273a22 Фиксы 2025-12-31 00:07:33 +03:00
gy9vin 073d96fb27 fix Новый фильтр "Готовы к продлению"
1. Добавлен .unique() — предотвращает дубликаты при JOIN с подписками
  2. Лимит 20 → 10 — соответствует хендлеру и другим фильтрам
2025-12-30 23:16:42 +03:00
gy9vin 8e6082ce15 fix Черный список, мониторинг суточно графика по регламенту
Исправленные файлы:

  1. app/services/traffic_monitoring_service.py — удалены неиспользуемые импорты Decimal, aiohttp
  2. app/services/blacklist_service.py — удалён неиспользуемый импорт re
  3. app/database/crud/user.py:998 — создана отсутствующая функция get_users_with_active_subscriptions:
  async def get_users_with_active_subscriptions(db: AsyncSession) -> List[User]:
  3. Функция:
    - Возвращает пользователей с активными подписками
    - Фильтрует по remnawave_uuid IS NOT NULL (нужен для API Remnawave)
    - Проверяет end_date > now и status == ACTIVE
2025-12-30 23:11:54 +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
gy9vin 096b4d4fe3 fix Отправка сообщения пользователю из карточки
1. app/handlers/admin/users.py
  - Добавлен параметр parse_mode="HTML" в send_message для поддержки HTML-форматирования
  - Добавлен вызов await state.clear() при ошибке BadRequest для очистки состояния FSM
2025-12-30 22:48:15 +03:00
gy9vin 9dd3299744 fix Скрытие кнопок пополнения через env
1. app/config.py
  - Добавлен метод is_quick_amount_buttons_enabled() для централизации логики

  2. 9 файлов в app/handlers/balance/:
  - main.py — 1 замена
  - cryptobot.py — 2 замены
  - stars.py — 2 замены
  - yookassa.py — 4 замены
  - pal24.py — 1 замена
  - platega.py — 1 замена
  - mulenpay.py — 1 замена
  - wata.py — 1 замена
  - heleket.py — 1 замена

  Было (12 раз):
  if settings.YOOKASSA_QUICK_AMOUNT_SELECTION_ENABLED and not settings.DISABLE_TOPUP_BUTTONS:

  Стало:
  if settings.is_quick_amount_buttons_enabled():
2025-12-30 22:40:43 +03:00
gy9vin bc19ec32bb fix Реализация корзины пользователя! запоминает настройки подписки после пополнения баланса 2025-12-30 22:35:54 +03:00
gy9vin 720f0ecb60 fix Скрытие кнопки партнёрки через env 2025-12-30 22:29:06 +03:00
gy9vin a9fd4c2466 fix Модульная структура платежки 2025-12-30 22:22:56 +03:00
gy9vin 5aa9b6ddb3 fix Исправление уведомления пользователя о поступлении денег на счет 2025-12-30 22:18:44 +03:00
gy9vin 180cba4561 fix Расширение фильтров 2025-12-30 22:14:09 +03:00
gy9vin 25dc7ff624 fix Добавлена фильтрация пользователей по балансу 2025-12-30 22:07:26 +03:00
gy9vin 1233d38fe1 fix Добавлена функция покупки подписки администратором с преобразованием триала в безлимитную подписку 2025-12-30 21:54:02 +03:00
gy9vin d60ebaef41 Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2025-12-30 21:50:42 +03:00
gy9vin dd86014667 Fix Добавление кнопок пополнения с суммой подписки 2025-12-30 21:50:36 +03:00
Mikhail bb8beff511 Merge branch 'BEDOLAGA-DEV:main' into main 2025-12-30 21:47:07 +03:00
Egor b276d764a3 Update Python version argument to v2.9.4 2025-12-30 19:28:19 +04:00
Egor ee78ab0932 Update docker-registry.yml 2025-12-30 19:28:03 +04:00
Egor e9daa76d7e Update docker-hub.yml 2025-12-30 19:27:52 +04:00
Egor 780c3956fa Merge pull request #2226 from BEDOLAGA-DEV/dev5
Новый режим покупки фикс+докупка со сбросом при продлении
2025-12-30 18:53:30 +04:00
Egor e582802e39 Update payment link generation to use async method 2025-12-30 18:51:55 +04:00
Egor d13b20d380 Update cloudpayments_service.py 2025-12-30 18:51:21 +04:00
Egor 5918f296ff Update inline.py 2025-12-30 18:33:18 +04:00
Egor 2f1ef8a60d Update pricing.py 2025-12-30 18:16:35 +04:00
Egor cefb6602f7 Refactor selectable logic in ensurePurchaseTrafficSelection 2025-12-30 18:15:50 +04:00
Egor b6503f9af9 Update miniapp.py 2025-12-30 18:15:02 +04:00
Egor 76f465e0f6 Update subscription.py 2025-12-30 18:13:18 +04:00
Egor 63ec894615 Update inline.py 2025-12-30 18:11:56 +04:00
Egor c9c25613af Add new traffic selection mode option 2025-12-30 18:10:08 +04:00
Egor 6ecaa406aa Update subscription_purchase_service.py 2025-12-30 18:09:11 +04:00
Egor 22c8f73eac Update traffic limit handling in subscription service
Refactor traffic limit assignment logic for subscriptions.
2025-12-30 18:08:32 +04:00
Egor d4bc7d0b51 Update subscription_renewal_service.py 2025-12-30 18:08:03 +04:00
Egor aa3c9231b0 Update subscription_service.py 2025-12-30 18:07:39 +04:00
Egor bce05d4bc4 Implement traffic limit reset on subscription renewal
Added logic to handle traffic limit reset during subscription renewal based on fixed traffic settings.
2025-12-30 18:05:26 +04:00
Egor f107109091 Update traffic.py 2025-12-30 18:04:54 +04:00
Egor 826a554d55 Update config.py 2025-12-30 17:56:40 +04:00
Egor fd5801839c Merge pull request #2225 from BEDOLAGA-DEV/main
w
2025-12-30 17:55:46 +04:00
gy9vin 8843d86d9b Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2025-12-30 11:34:46 +03:00
gy9vin 449f82d538 refactor(auto-purchase): перезагрузка пользователя после списания баланса для восстановления связей
- Добавлен get_user_by_id в импорты
- Перезагрузка user через get_user_by_id после subtract_user_balance
- Восстановление связи user_promo_groups, сбрасываемой после db.refresh() в payment-сервисах
- Добавлен мок get_user_by_id в тесте
2025-12-30 11:34:41 +03:00
Egor abce475ccc Merge pull request #2223 from Gy9vin/main
Отправка чеков со временем
2025-12-30 09:47:45 +04:00
gy9vin 22129ecbec минификс в отладке конкурсов 2025-12-30 02:15:52 +03:00
gy9vin 2a2a3daaae fix(contests): исправление статистики реферальных конкурсов
Основные исправления:
  - Фильтрация событий по дате регистрации реферала (occurred_at)
    в период конкурса (start_at - end_at)
  - Лидерборд теперь показывает правильные числа (было 21, стало 11)
  - Разделение DEPOSIT и SUBSCRIPTION_PAYMENT в статистике:
    - Основная метрика: покупки подписок (SUBSCRIPTION_PAYMENT)
    - Информационно: пополнения баланса (DEPOSIT)

  Новый функционал:
  - Кнопка "🔍 Отладка" для просмотра транзакций конкурса
  - Разбивка сумм по типам в детальной статистике
  - Кнопки "Назад" в синхронизации и отладке
  - Логирование дат фильтрации в синхронизации

  Также исправлено:
  - NaloGO: защита от дублирования чеков в очереди
    (проверка nalogo:created и nalogo:queued в Redis)
2025-12-30 02:08:23 +03:00
gy9vin ac94d5d708 Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2025-12-30 00:39:50 +03:00
gy9vin d10ccc4844 refactor(nalogo): улучшение системы чеков NaloGO
Сохранение времени оплаты:
  - Добавлен параметр operation_time в create_receipt()
  - Чеки из очереди создаются с оригинальным временем платежа
  - Парсинг created_at из Redis очереди

  Защита от дублей (3 уровня):
  - Проверка transaction.receipt_uuid перед созданием
  - Redis ключ nalogo:created:{payment_id} с TTL 30 дней
  - Сохранение receipt_uuid в транзакцию после создания

  Бесконечные повторы:
  - Убрано удаление чеков после 10 попыток
  - Чеки остаются в очереди до успешной отправки

  Обработка ошибок:
  - Добавлена обработка 500 и "внутренняя ошибка" как временной недоступности

  Сверка чеков:
  - Заменена API сверка на сверку по логам (logs/current/payments.log)
  - Кнопка "Без чеков" → "Сверка чеков" с прямым показом сверки
  - Исправлена навигация кнопок "Назад"
2025-12-30 00:39:00 +03:00
Mikhail de733a5f08 Merge branch 'BEDOLAGA-DEV:main' into main 2025-12-29 22:15:48 +03:00
gy9vin 4cab3f5ed4 Отправка чеков со временем 2025-12-29 22:15:07 +03:00
Egor 26b85b16b5 Merge pull request #2220 from BEDOLAGA-DEV/main
w
2025-12-29 10:35:52 +04:00
Egor ea770c32e8 Merge pull request #2218 from Gy9vin/main
Апдейты
2025-12-28 17:23:04 +03:00
gy9vin 23f8bdfbec feat(restrictions): добавить систему ограничений пользователей
Добавлена возможность ограничивать пользователям:
  - Пополнение баланса (restriction_topup)
  - Покупку/продление подписки (restriction_subscription)

  Изменения:
  - models.py: добавлены поля restriction_topup, restriction_subscription,
    restriction_reason и property has_restrictions
  - universal_migration.py: миграция для новых полей
  - admin/users.py: меню управления ограничениями в карточке пользователя
  - keyboards/admin.py: клавиатура ограничений с toggle-кнопками
  - states.py: состояние editing_user_restriction_reason

  Проверки ограничений добавлены на двух уровнях:
  - start_*_payment: при выборе метода оплаты
  - process_*_payment_amount: при создании платежа

  Затронутые провайдеры: stars, yookassa, mulenpay, wata, pal24,
  cryptobot, heleket, platega, tribute, cloudpayments

  При ограничении пользователь видит причину и кнопку "Обжаловать",
  ведущую на контакт поддержки из настроек.
2025-12-28 13:32:04 +03:00
gy9vin a362ef9f25 refactor(nalogo): восстановить описание чеков из настроек и использовать локальную библиотеку
- Добавлено восстановление описания чека из настроек при обработке очереди
- Передача telegram_user_id и amount_kopeks через всю цепочку создания чеков
- Переход на локальную исправленную версию библ
2025-12-28 04:58:05 +03:00
gy9vin 1b736b381d refactor(nalogo): упростить настройку чеков и использовать локальное время
- Удалена избыточная настройка NALOGO_RECEIPTS_ENABLED
- Удален эндпоинт /settings/support/nalogo_receipts_enabled
- Удалены методы is_nalogo_receipts_enabled и set_nalogo_receipts_enabled из SupportSettingsService
- Упрощена логика создания чеков
2025-12-27 19:29:04 +03:00
gy9vin d343a317ee feat(logging): добавить систему ротации логов
- Ежедневная ротация в 00:00 с архивацией в tar.gz
  - Разделение по уровням: info.log, warning.log, error.log
  - Отдельный payments.log для платежных операций
  - Отправка архивов в Telegram-канал бекапов
  - Автоочистка архивов старше 7 дней (настраивается)
  - Переключатель LOG_ROTATION_ENABLED (по умолчанию выключен)
2025-12-27 19:02:28 +03:00
Egor 3fc9e63653 Merge pull request #2208 from Gy9vin/fix
Исправление уязвимостей и багов в конкурсах
2025-12-27 16:20:18 +03:00
Mikhail 9f12462871 Merge branch 'main' into fix 2025-12-27 15:54:07 +03:00
Egor e293470c14 Merge pull request #2217 from D4nilKO/promo-campaing-trial-fix
Fix campaign subscription logic: use trial instead of paid
2025-12-27 11:17:21 +03:00
Egor 6322e970ef Merge pull request #2216 from BEDOLAGA-DEV/main
w
2025-12-27 10:55:00 +03:00
PEDZEO 8a40d54c03 Merge pull request #2215 from BEDOLAGA-DEV/BACKUP
Add backup management endpoints
2025-12-27 05:18:15 +03:00
PEDZEO 0264c24743 Enhance backup upload validation
- Added checks for safe filename to prevent directory traversal attacks.
- Updated file type validation to use the sanitized filename.
- Implemented path resolution to ensure uploaded files are within the backup directory.
2025-12-27 05:16:08 +03:00
PEDZEO 1aade85fc9 Add backup management endpoints
- Implemented download, restore, upload and delete functionalities for backups.
- Added corresponding request and response schemas for backup operations.
- Enhanced security checks to prevent unauthorized access to backup files.
2025-12-27 04:33:13 +03:00
PEDZEO a5874a9873 Merge pull request #2214 from BEDOLAGA-DEV/BACKUP
Add support for password-protected backup archives
2025-12-27 04:13:22 +03:00
PEDZEO 6f9dc45e16 Update BackupService to check for temporary zip path instead of password for captioning 2025-12-27 04:11:08 +03:00
PEDZEO 34db5a0d28 Add support for password-protected backup archives
- Updated .env.example to include BACKUP_ARCHIVE_PASSWORD variable.
- Added pyzipper to requirements.txt for ZIP file encryption.
- Modified Settings class in config.py to handle BACKUP_ARCHIVE_PASSWORD.
- Enhanced BackupService to create and send password-protected ZIP archives if a password is provided.
2025-12-27 03:58:48 +03:00
Dxnil 34517427b0 test 2025-12-27 03:05:48 +03:00
gy9vin cad9abd8bd feat(payments): умная автоактивация подписки после пополнения + округление цен
Добавлена функция умной автоактивации подписки после пополнения баланса:

  - Новая настройка AUTO_ACTIVATE_AFTER_TOPUP_ENABLED в .env
  - Функция auto_activate_subscription_after_topup() в subscription_auto_purchase_service.py:
    - Автоматически продлевает истёкшую подписку с теми же параметрами
    - Создаёт новую подписку с дефолтными параметрами если подписки нет
    - Проверяет достаточность баланса перед активацией
    - Интеграция с RemnaWave API
    - Уведомления пользователю и админам

  - Интеграция во все 9 платёжных провайдеров:
    - Stars, CryptoBot, YooKassa, CloudPayments
    - WATA, Platega, Pal24, MulenPay, Tribute

  - Исправлен handle_activate_button в menu.py:
    - Полная переработка с интеграцией RemnaWave
    - Корректная работа с балансом и транзакциями
    - Использование SubscriptionRenewalService

  Добавлено округление цен при отображении:

  - Новая настройка PRICE_ROUNDING_ENABLED в .env
  - Логика: ≤50 коп → вниз, >50 коп → вверх
  - Применяется везде: пополнения, партнёрки, скидки, промогруппы
2025-12-26 23:38:46 +03:00
gy9vin bf9728352e feat(subscription): улучшение UX выбора серверов и устройств
- Кнопки устройств теперь в один столбец (вместо 2 колонок)
  - Автоматический предвыбор бесплатных серверов (price_kopeks == 0)
  - Вывод описания сквадов в тексте сообщения над кнопками

  Изменённые файлы:
  - keyboards/inline.py: get_devices_keyboard в 1 столбец
  - handlers/subscription/countries.py: хелперы _get_preselected_free_countries и _build_countries_selection_text
  - handlers/subscription/purchase.py, traffic.py, autopay.py: применение новой логики
2025-12-26 22:15:34 +03: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 64ffffdf90 fix(traffic): исправлен баг с бесплатным переключением трафика
При наличии докупленного трафика (например 250 + 10 ГБ = 260 ГБ)
  система округляла текущий пакет до ближайшего (500 ГБ) и позволяла
  бесплатно переключиться на него.

  Исправления:
  - confirm_switch_traffic: используется базовый трафик для расчёта цены
  - get_traffic_switch_keyboard: добавлен параметр base_traffic_gb
  - handle_switch_traffic: показывает информацию о докупленном трафике
  - execute_switch_traffic: сбрасывает purchased_traffic_gb при переключении
2025-12-26 11:18:16 +03:00
gy9vin e71a3c1af7 feat(referral): топ рефереров по периодам в админ-панели
Добавлена возможность просмотра топа рефереров за неделю/месяц
   с сортировкой по количеству приглашённых или по заработку:

   - get_top_referrers_by_period() в crud/referral.py
   - Интерактивные кнопки выбора периода и критерия сортировки
   - Топ-20 рефереров с медалями для первых трёх мест
2025-12-26 09:11:08 +03:00
gy9vin 265d2b907b fix(devices): сброс устройств при уменьшении лимита
При уменьшении лимита устройств подключённые устройства не удалялись,
   позволяя пользователю продолжать использовать их бесплатно.

   Исправления:
   - execute_change_devices: сброс всех устройств через API если
     подключённых больше чем новый лимит
   - confirm_change_devices: предупреждение пользователя о сбросе
     устройств перед подтверждением
   - Уведомление о количестве сброшенных устройств в результате
2025-12-26 09:00:56 +03:00
gy9vin 54ffe3e126 feat(transactions): добавлен параметр payment_method для ручных пополнений баланса
Добавлена поддержка указания способа оплаты при пополнении баланса:

- add_user_balance(): новый параметр payment_method для передачи в транзакцию
- add_user_balance_by_id(): поддержка payment_method
- UserService: ручные пополнения админом пом
2025-12-26 08:53:08 +03:00
gy9vin 7e3d7d4771 refactor(referral): извлечена lambda в именованную функцию для пагинации списка рефералов
Заменена inline lambda на handle_referral_list_page() для улучшения читаемости:

- Извлечение номера страницы из callback.data
- Вызов show_detailed_referral_list() с параметром page
- Улучшена читаемость кода обработчика пагинации
2025-12-26 08:39:59 +03:00
gy9vin 05bfd89a02 ```
feat(tickets): добавлены уведомления админам об ответах пользователей на тикеты

Реализована функция notify_admins_about_ticket_reply() для оповещения администраторов:

- Уведомление отправляется после успешного добавления ответа пользователя
- Формат уведомления включает ID тикета, заголовок
2025-12-26 08:31:36 +03:00
gy9vin 3bf540427e feat(nalogo): расширена проверка временных ошибок для очереди чеков
Добавлены проверки сетевых ошибок и таймаутов в _is_service_unavailable():

- Проверка типа исключения (timeout, readtimeout, connecttimeout)
- Проверка сетевых ошибок (connectionerror, connecterror)
- Проверка текста ошибки на наличие "timeout"
- Обновлён docstring мет
2025-12-26 00:27:34 +03:00
gy9vin bf6dc3991a feat(trial): платный триал с выбором метода оплаты
Реализована система платного триала с гибким выбором способа оплаты:

- Автоопределение платности: если TRIAL_ACTIVATION_PRICE > 0, триал автоматически платный
- TRIAL_PAYMENT_ENABLED теперь опционален (для обратной совместимости)
- Добавлена функция create
2025-12-26 00:03:08 +03:00
Mikhail fb9405cccd Merge branch 'BEDOLAGA-DEV:main' into main 2025-12-25 23:56:04 +03:00
gy9vin 0b34e90372 feat(migrations): добавлены миграции для модема, трафика и призов конкурсов
Добавлены миграции для новых функций:

- migrate_contest_templates_prize_columns(): миграция prize_days → prize_type + prize_value
- add_subscription_modem_enabled_column(): колонка modem_enabled в subscriptions
- add_subscription_purchased_traffic_column(): колонка purchased_traffic_gb в subscriptions
- Обновлён check
2025-12-25 23:29:02 +03:00
Egor 04e83814b4 Merge pull request #2213 from BEDOLAGA-DEV/dev5
CloudPayments
2025-12-25 23:09:44 +03:00
gy9vin 0df3018703 feat(nalogo): система очереди чеков с отложенной отправкой
Реализована отказоустойчивая система отправки чеков в налоговую:

  - Добавлен NalogoQueueService для фоновой обработки очереди чеков
  - При недоступности nalog.ru (503) чеки сохраняются в Redis
  - Автоматическая повторная отправка с настраиваемым интервалом
  - Защита от DDoS: задержка между чеками (NALOGO_QUEUE_RECEIPT_DELAY)
  - Уведомления админам в топик при проблемах и успешной разгрузке

  Изменения в файлах:
  - app/services/nalogo_queue_service.py: новый фоновый сервис
  - app/services/nalogo_service.py: методы очереди, определение 503
  - app/utils/cache.py: lpush/rpop/llen/lrange для Redis List
  - app/handlers/admin/monitoring.py: статистика чеков в админке
  - app/config.py: NALOGO_QUEUE_* и ADMIN_NOTIFICATIONS_NALOG_TOPIC_ID
  - main.py: интеграция запуска/остановки сервиса

  Новые ENV переменные:
  - ADMIN_NOTIFICATIONS_NALOG_TOPIC_ID
  - NALOGO_QUEUE_CHECK_INTERVAL (300с)
  - NALOGO_QUEUE_RECEIPT_DELAY (3с)
  - NALOGO_QUEUE_MAX_ATTEMPTS (10)
2025-12-25 23:01:49 +03:00
Egor 8eb2be15ff Update index.html 2025-12-25 21:11:13 +03:00
Egor 648fba6e2a Update miniapp.py 2025-12-25 21:10:15 +03:00
Egor 3df8d0cb24 Update bot_configuration.py 2025-12-25 21:09:18 +03:00
Egor a59a15af7f Update inline.py 2025-12-25 21:07:42 +03:00
Egor c919953219 Add files via upload 2025-12-25 21:07:00 +03:00
Egor 5e6baac07e Add files via upload 2025-12-25 21:05:49 +03:00
Egor 42b06ea8bc Add files via upload 2025-12-25 21:05:10 +03:00
Egor 07ded3710c Add files via upload 2025-12-25 21:04:10 +03:00
Egor 7d0977066b Add files via upload 2025-12-25 21:03:14 +03:00
Egor d8e57ab766 Add files via upload 2025-12-25 21:01:58 +03:00
Egor 83cb1ec823 Add files via upload 2025-12-25 21:01:11 +03:00
gy9vin da46e39c61 refactor(modem): рефакторинг модуля управления модемом
Рефакторинг архитектуры управления модемом:

- Создан сервис app/services/modem_service.py:
  - ModemService с бизнес-логикой подключения/отключения
  - ModemError enum для типизации ошибок
  - ModemPriceInfo, ModemOperationResult dataclass'ы
  - Константы MODEM_WARNING_DAYS_* для уровней предупреждений
2025-12-25 18:44:27 +03:00
gy9vin 86dd18fbe7 refactor(contests): доработка ежедневных конкурсов
Рефакторинг архитектуры ежедневных конкурсов:

- Создан модуль app/services/contests/ с новой архитектурой:
  - enums.py: GameType, RoundStatus, PrizeType enum классы
  - games.py: паттерн Стратегия для 7 типов игр
  - attempt_service.py: ContestAttemptService для атомарных операций

- Упрощён handlers/contests.py:
  - Удалены отдельные _render_* функции (заменены на стратегии)
  - Логика обработки попыток вынесена в ContestAttemptService
  - Уменьшено с 523 до 342 строк (-35%)

- Обновлён contest_rotation_service.py:
  - Заменена if-elif цепочка на get_game_strategy().build_payload()
  - Используются enum классы вместо магических строк

- Исправлен handlers/admin/daily_contests.py:
  - prize_days → prize_type/prize_value (соответствие модели БД)
  - Обновлены EDITABLE_FIELDS и отображение приза

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-25 18:09:11 +03:00
gy9vin 21f34a9b08 fix(contests): блокировка повторных ответов в текстовых играх
- Создание попытки сразу при показе вопроса (cipher/emoji/anagram)
- Проверка attempt.answer is not None для блокировки повторного ответа
- Обновление существующей попытки вместо создания новой
- Добавлена функция update_attempt() в CRUD
2025-12-25 15:00:30 +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
Mikhail 1e64b65586 Merge branch 'BEDOLAGA-DEV:main' into main 2025-12-25 14:26:35 +03:00
gy9vin 90c3df6331 Добавлен функционал подключения модема к подписке
Изменения:
- Добавлены настройки модема в .env.example и config.py (MODEM_ENABLED, MODEM_PRICE_PER_MONTH, MODEM_PERIOD_DISCOUNTS)
- Добавлено поле modem_enabled в модель Subscription
- Реализован модуль handlers/subscription/modem.py с обработчиками подключения/отключения модема
- Добавлено управ
2025-12-25 14:26:15 +03:00
Egor b9ea5a80ac Merge pull request #2212 from BEDOLAGA-DEV/dev5
Update subscription_service.py
2025-12-25 11:00:00 +03:00
Egor 40d6514dee Update subscription_service.py 2025-12-25 10:59:35 +03:00
Egor 4a2b254d99 Merge pull request #2211 from BEDOLAGA-DEV/dev5
Dev5
2025-12-25 09:45:07 +03:00
Egor 6c740ad984 Update purchase.py 2025-12-25 09:35:49 +03:00
Egor 929a8d5fa9 Update purchase.py 2025-12-25 09:09:46 +03:00
Egor b0bf5131d4 Update subscription_service.py 2025-12-25 09:09:12 +03:00
Egor ef8d9fe1ff Update subscription_purchase_service.py 2025-12-24 23:15:37 +03:00
Egor d57e0743a1 Update tickets.py 2025-12-24 23:06:22 +03:00
Egor 664cbff1ce Update tickets.py 2025-12-24 23:05:52 +03:00
Egor 6ea52bf406 Update messages.py 2025-12-24 22:46:04 +03:00
Mikhail 0ddf24125b Merge branch 'BEDOLAGA-DEV:main' into main 2025-12-24 16:17:29 +03:00
Egor f5a533e407 Merge pull request #2210 from BEDOLAGA-DEV/dev5
Dev5
2025-12-24 15:30:46 +03:00
Egor dd87b4d408 Update database.py 2025-12-24 14:44:02 +03:00
Egor 2c6c7056e8 Update subscriptions.py 2025-12-24 11:16:00 +03:00
Egor 8a10b96fef Update users.py 2025-12-24 11:15:40 +03:00
Egor c0a85bad84 Merge pull request #2209 from BEDOLAGA-DEV/dev5
Dev5
2025-12-23 22:09:46 +03:00
Egor fbfc00586c Update purchase.py 2025-12-23 21:03:13 +03:00
Egor 5723c3b379 Update purchase.py 2025-12-23 20:37:01 +03:00
Egor f1be66d1a5 Update inline.py 2025-12-23 20:35:42 +03:00
gy9vin b3cdd3c03a Расширение функционала конкурсов: разнообразие наград, напоминания, многоязычность
Изменения:
- ContestTemplate: prize_days заменен на prize_type и prize_value для поддержки разных типов наград (days, balance, custom)
- _award_prize: обновлена логика выдачи призов для всех типов наград
- DEFAULT_TEMPLATES: обновлены для использования prize_type/prize_value
- upsert_template: обновлена сигнатура для новых полей
- _announce_round_start: добавлена локализация и напоминания о конкурсах
- handle_text_answer: исправлена гонка условий с атомарным инкрементом победителей
- Локализация: добавлены ключи CONTEST_START_ANNOUNCEMENT, CONTEST_PRIZE, DAYS, CONTEST_WINNERS, CONTEST_ATTEMPTS, CONTEST_ELIGIBILITY, REMINDER, CONTEST_REMINDER_TEXT в ru.json и en.json
- API схемы: обновлены ContestTemplateResponse и ContestTemplateUpdateRequest

Требуется миграция БД для новых колонок prize_type и prize_value.
2025-12-23 19:15:40 +03:00
gy9vin 01afce002a Исправление уязвимостей и багов в конкурсах
- Добавлена защита от спама: rate limiting для попыток (1 попытка/3-5 сек)
- Усилена валидация входных данных: функция _validate_callback_data для безопасного парсинга callback.data
- Перепроверка авторизации: статус подписки проверяется на каждом шаге
- Атомарные операции победителей: использование select with_for_update для предотвращения гонок условий
- Улучшено логирование: добавлены логи попыток и побед для аудита
- Добавлена кнопка 'Назад' в игру 'Блиц' для предотвращения застревания пользователей
- Исправлены отступы и ошибки линтера в _render_blitz

Все изменения направлены на повышение безопасности, стабильности и UX конкурсов.
2025-12-23 18:59:44 +03:00
Egor 63a9c1afd1 Update inline.py 2025-12-23 16:09:58 +03:00
Egor 0c9f667cd8 Merge pull request #2207 from BEDOLAGA-DEV/dev5
Dev5
2025-12-23 11:57:02 +03:00
Egor dc428baa6a Update subscription.py 2025-12-23 11:53:52 +03:00
Egor f65aa6a82d Update remnawave_service.py 2025-12-23 11:53:11 +03:00
Egor c986b127a7 Merge pull request #2206 from BEDOLAGA-DEV/dev5
w
2025-12-23 11:29:16 +03:00
Egor 94a7a5fce8 Update remnawave_service.py 2025-12-23 11:28:37 +03:00
Egor f07bbe0fd0 Update remnawave_api.py 2025-12-23 11:27:57 +03:00
Egor 46f61dbc57 Update config.py 2025-12-23 11:27:33 +03:00
Egor 41502cadcd Merge pull request #2205 from BEDOLAGA-DEV/dev5
Update remnawave_api.py
2025-12-23 11:18:46 +03:00
Egor aa5e6841f8 Update remnawave_api.py 2025-12-23 11:18:22 +03:00
Egor 8a98a7ee84 Merge pull request #2204 from BEDOLAGA-DEV/dev5
Update config.py
2025-12-23 11:09:26 +03:00
Egor e1d6c73557 Update config.py 2025-12-23 11:08:50 +03:00
Egor b4d66bd34d Merge pull request #2203 from BEDOLAGA-DEV/dev5
Update photo_message.py
2025-12-23 02:19:18 +03:00
Egor 1496ec901d Update photo_message.py 2025-12-23 02:17:31 +03:00
Egor 78ce6bd428 Merge pull request #2202 from BEDOLAGA-DEV/dev5
Update remnawave_service.py
2025-12-23 00:54:44 +03:00
Egor 9ec52dcf95 Update remnawave_service.py 2025-12-23 00:54:01 +03:00
Egor 80a13e6b71 Merge pull request #2201 from BEDOLAGA-DEV/dev5
fix
2025-12-22 22:46:27 +03:00
Egor 9231f770a3 Update payment_utils.py 2025-12-22 22:45:21 +03:00
Egor f8ba587e5c Add files via upload 2025-12-22 22:43:51 +03:00
Egor 9280eecf4c Update Dockerfile 2025-12-22 19:40:19 +03:00
Egor a36b15e8ad Update docker-registry.yml 2025-12-22 19:40:09 +03:00
Egor 3e833f8a8c Update docker-hub.yml 2025-12-22 19:39:57 +03:00
Egor 48044b56c1 Merge pull request #2200 from BEDOLAGA-DEV/dev5
platega change name
2025-12-22 19:36:09 +03:00
Egor 3dab9df26c Update platega.py 2025-12-22 19:33:09 +03:00
Egor 65da3a57a7 Update inline.py 2025-12-22 19:32:36 +03:00
Egor 791482a8a1 Update system_settings_service.py 2025-12-22 19:32:06 +03:00
Egor 7b03f3e553 Update payment_verification_service.py 2025-12-22 19:31:32 +03:00
Egor 47698882fa Update payments.py 2025-12-22 19:30:52 +03:00
Egor 2c4a55f7c7 Update config.py 2025-12-22 19:30:13 +03:00
Egor f8053e14c3 Merge pull request #2199 from BEDOLAGA-DEV/main
w
2025-12-22 17:43:38 +03:00
Egor 2073d42fa8 Merge pull request #2198 from BEDOLAGA-DEV/dev5
fix: add trafic button
2025-12-22 17:08:20 +03:00
Egor 076eb89760 Update menu.py 2025-12-22 15:53:56 +03:00
Egor 34878a2ef3 Merge pull request #2197 from BEDOLAGA-DEV/dev5
Caddy Token auth
2025-12-22 15:33:36 +03:00
Egor 6ae573ed48 Update .env.example 2025-12-22 15:32:38 +03:00
Egor 482c42e9bf Update README.md 2025-12-22 15:30:57 +03:00
Egor 66092af999 Update maintenance_service.py 2025-12-22 15:29:46 +03:00
Egor c7eabdf90e Update remnawave_service.py 2025-12-22 15:29:21 +03:00
Egor ee6f4b35b0 Update subscription_service.py 2025-12-22 15:29:02 +03:00
Egor 7aea87a227 Update remnawave_api.py 2025-12-22 15:28:23 +03:00
Egor a2b039d092 Update config.py 2025-12-22 15:28:02 +03:00
Egor f2d2c0a8a4 Merge pull request #2196 from BEDOLAGA-DEV/dev5
Remnawave Api Update / Pinned Massages
2025-12-22 15:18:18 +03:00
Egor ea3033a088 Update validators.py 2025-12-22 15:11:23 +03:00
Egor 07f445b485 Update pinned_messages.py 2025-12-22 15:01:26 +03:00
Egor a94cb355aa Add files via upload 2025-12-22 14:56:16 +03:00
Egor 9f14ae67da Update __init__.py 2025-12-22 14:48:14 +03:00
Egor 44247dee03 Update app.py 2025-12-22 14:47:40 +03:00
Egor c66af415d5 Add files via upload 2025-12-22 14:46:51 +03:00
Egor 6b2d7618a7 Add files via upload 2025-12-22 14:45:27 +03:00
Egor 866fa56f5b Add files via upload 2025-12-22 14:43:58 +03:00
Egor ea48036010 Update messages.py 2025-12-22 14:43:22 +03:00
Egor 4077b2a032 Update admin.py 2025-12-22 14:42:52 +03:00
Egor a69500ce91 Update states.py 2025-12-22 14:42:23 +03:00
Egor 9a1e57a764 Update remnawave_service.py 2025-12-22 14:08:44 +03:00
Egor 88657dd3e2 Update remnawave_service.py 2025-12-22 14:03:33 +03:00
Egor 85d4c9c208 Add files via upload 2025-12-22 13:57:37 +03:00
Egor 2bda60cd18 Update messages.py 2025-12-22 13:56:52 +03:00
Egor 73e5e1b5a3 Update pinned_message_service.py 2025-12-22 13:56:15 +03:00
Egor 3f1b65b602 Update 7a3c0b8f5b84_add_send_before_menu_to_pinned_messages.py 2025-12-22 13:55:43 +03:00
Egor fa7dd7434b Update 1b2e3d4f5a6b_add_pinned_start_mode_and_user_last_pin.py 2025-12-22 13:55:18 +03:00
Egor 0243d3a2ba Merge pull request #2195 from BEDOLAGA-DEV/i1s5hb-bedolaga/add-pinned-message-feature-in-admin-menu
Add one-time pinned message delivery mode
2025-12-22 13:32:48 +03:00
Egor 0951c9f6dd Add one-time pinned message delivery mode 2025-12-22 13:32:34 +03:00
Egor 6891cc1f36 Merge pull request #2194 from BEDOLAGA-DEV/revert-2192-kbzjuf-bedolaga/add-pinned-message-feature-in-admin-menu
Revert "Add start delivery frequency toggle for pinned messages"
2025-12-22 13:32:16 +03:00
Egor dbe805662a Revert "Add start delivery frequency toggle for pinned messages" 2025-12-22 13:32:07 +03:00
Egor cd5c293b71 Merge pull request #2192 from BEDOLAGA-DEV/kbzjuf-bedolaga/add-pinned-message-feature-in-admin-menu
Add start delivery frequency toggle for pinned messages
2025-12-22 13:28:58 +03:00
Egor 58e789b094 Merge pull request #2193 from BEDOLAGA-DEV/revert-2191-wc3pdx-bedolaga/add-pinned-message-feature-in-admin-menu
Revert "Add admin option to remove pinned message"
2025-12-22 13:28:50 +03:00
Egor 3fd48807d1 Revert "Add admin option to remove pinned message" 2025-12-22 13:28:40 +03:00
Egor 76b32ea4fe Add one-time pinned message option for /start 2025-12-22 13:28:08 +03:00
Egor 60670e44a2 Merge pull request #2191 from BEDOLAGA-DEV/wc3pdx-bedolaga/add-pinned-message-feature-in-admin-menu
Add admin option to remove pinned message
2025-12-22 13:14:24 +03:00
Egor 69f1b91ce7 Add admin control to remove pinned message 2025-12-22 13:14:01 +03:00
Egor c78313b5db Merge pull request #2190 from BEDOLAGA-DEV/revert-2189-h29si7-bedolaga/add-pinned-message-feature-in-admin-menu
Revert "Prevent duplicate unknown command message after /start"
2025-12-22 13:13:27 +03:00
Egor 55a7ec6b11 Revert "Prevent duplicate unknown command message after /start" 2025-12-22 13:13:18 +03:00
Egor 41d94cd8e7 Merge pull request #2189 from BEDOLAGA-DEV/h29si7-bedolaga/add-pinned-message-feature-in-admin-menu
Prevent duplicate unknown command message after /start
2025-12-22 13:00:53 +03:00
Egor 2422f56137 Avoid unknown handler after /start commands 2025-12-22 13:00:17 +03:00
Egor bb7b95c971 Merge pull request #2188 from BEDOLAGA-DEV/revert-2187-6r14me-bedolaga/add-pinned-message-feature-in-admin-menu
Revert "Add pinned message placement control and reduce broadcast throttling"
2025-12-22 13:00:02 +03:00
Egor a17344858b Revert "Add pinned message placement control and reduce broadcast throttling" 2025-12-22 12:59:52 +03:00
Egor a45dd70531 Merge pull request #2187 from BEDOLAGA-DEV/6r14me-bedolaga/add-pinned-message-feature-in-admin-menu
Add pinned message placement control and reduce broadcast throttling
2025-12-22 12:49:05 +03:00
Egor 2bcda34f1c Add pinned message placement control and fix throttling broadcast 2025-12-22 12:48:21 +03:00
Egor ac698b3a74 Merge pull request #2186 from BEDOLAGA-DEV/revert-2185-1li4we-bedolaga/add-pinned-message-feature-in-admin-menu
Revert "Add position control for pinned messages"
2025-12-22 12:47:19 +03:00
Egor e52a47bfb3 Revert "Add position control for pinned messages" 2025-12-22 12:47:10 +03:00
Egor 47d7bdd632 Merge pull request #2185 from BEDOLAGA-DEV/1li4we-bedolaga/add-pinned-message-feature-in-admin-menu
Add position control for pinned messages
2025-12-22 12:42:12 +03:00
Egor f7be2911cd Add position control for pinned messages 2025-12-22 12:41:43 +03:00
Egor 104cf899ee Merge pull request #2184 from BEDOLAGA-DEV/revert-2183-b72kym-bedolaga/add-pinned-message-feature-in-admin-menu
Revert "Support media attachments in pinned messages"
2025-12-22 12:30:15 +03:00
Egor 6f0e3c0bfd Revert "Support media attachments in pinned messages" 2025-12-22 12:30:06 +03:00
Egor 09d8261cbf Merge pull request #2183 from BEDOLAGA-DEV/b72kym-bedolaga/add-pinned-message-feature-in-admin-menu
Support media attachments in pinned messages
2025-12-22 12:18:48 +03:00
Egor 3c9580dc30 Add pinned messages to universal migration 2025-12-22 12:18:32 +03:00
Egor 1d72419243 Merge pull request #2181 from BEDOLAGA-DEV/dev5
fix: promo info button in menu
2025-12-22 11:50:49 +03:00
Egor ae420a592a Update menu.py 2025-12-22 11:47:42 +03:00
Egor a2586d88e1 Merge pull request #2179 from D4nilKO/main
chore: sync subscription with Remnawave on creation/replacement
2025-12-21 20:25:13 +03:00
Dxnil 0b61878de8 chore: sync subscription with Remnawave on creation/replacement 2025-12-21 17:53:16 +03:00
Egor 5ad9fd8ae7 Update Dockerfile 2025-12-21 08:25:31 +03:00
Egor f9cfaa4bc1 Update docker-registry.yml 2025-12-21 08:25:21 +03:00
Egor e1cc7a2e23 Update docker-hub.yml 2025-12-21 08:25:10 +03:00
Egor 7a0faa4b0a Merge pull request #2177 from BEDOLAGA-DEV/dev5
Remnawave 2.4.0+ Api Update, Menu layout Api, Partners Stats Api, Yookassa 22%
2025-12-21 08:13:51 +03:00
Egor a87d067133 Update exported_at to use timezone-aware datetime 2025-12-21 08:08:07 +03:00
Egor 42759854c2 Use timezone-aware datetime for calculations 2025-12-21 08:07:31 +03:00
Egor b2027df7f3 Replace deprecated datetime.utcnow() with _utcnow()
Replaced deprecated datetime.utcnow() with a custom _utcnow() function to return current UTC time as naive datetime.
2025-12-21 08:06:52 +03:00
Egor ce865a9b2a Update start.py 2025-12-21 08:05:53 +03:00
Egor 7dcd11b964 Update contests.py 2025-12-21 07:53:20 +03:00
Egor 6482284cd8 Use configured timezone for contest scheduling
Refactor time handling to use configured timezone for scheduling.
2025-12-21 07:52:35 +03:00
Egor 7f8fbf069b Update referral_contest_service.py 2025-12-21 07:52:00 +03:00
Egor 3e6064756e Update contests.py 2025-12-21 07:51:21 +03:00
Egor 1d1a9e0d78 Add tables for menu layout history and button clicks 2025-12-21 07:18:52 +03:00
Egor bc6e57765e Use UTC for registration days calculation 2025-12-21 07:18:31 +03:00
Egor 16031023cb Change datetime from now() to utcnow() 2025-12-21 07:17:52 +03:00
Egor 151ce092b9 Enhance button stats middleware with builtin callbacks
Added a set of known builtin callback data for button statistics logging.
2025-12-21 07:16:55 +03:00
Egor 01d3659ad2 Update stats_service.py 2025-12-21 07:16:24 +03:00
Egor 7dd0f5f7b0 Improve button configuration and logging
Refactor button construction and configuration handling.
2025-12-21 07:16:06 +03:00
Egor cfd79f4b23 Update partner_stats_service.py 2025-12-21 07:15:39 +03:00
PEDZEO 0cd355a878 Merge pull request #2175 from BEDOLAGA-DEV/buttons
Buttons
2025-12-21 05:02:45 +03:00
Egor 344ff65710 Merge pull request #2173 from Gy9vin/main
Юкасса сдк обновление
2025-12-21 04:52:41 +03:00
PEDZEO 1b47f2aa99 Remove unused imports from partner_stats_service.py to streamline the code and improve readability. 2025-12-21 04:38:42 +03:00
PEDZEO 1d01a77457 Add global partner statistics endpoints and enhance partner-related schemas; implement detailed stats retrieval for referrers and daily statistics. 2025-12-21 04:35:58 +03:00
PEDZEO aa669fa3cd Refactor logging in ButtonStatsMiddleware and cleanup debug endpoints in menu_layout; streamline button click logging and enhance error handling. 2025-12-21 04:05:26 +03:00
Egor e487776510 Update remnawave_service.py 2025-12-21 03:40:00 +03:00
Egor 9d038f7443 Update remnawave_api.py 2025-12-21 03:38:41 +03:00
PEDZEO 02ebcd368e Improve logging in get_top_users to include detailed user data and streamline response item creation 2025-12-21 03:15:25 +03:00
PEDZEO 7e1a2998af Add debug_stats endpoint to expose raw button click log data and enhance logging for user_id checks in get_top_users 2025-12-21 03:10:41 +03:00
Egor 0a5383eb80 Update LICENSE 2025-12-21 02:54:58 +03:00
PEDZEO 763d8f2aaa Enhance logging in get_stats_by_button_type to include total record count in button_click_logs and update stats logging to info level for better visibility. 2025-12-21 02:54:40 +03:00
PEDZEO ce11ec7c0e Enhance ButtonStatsMiddleware with improved logging and error handling; log middleware activation status based on MENU_LAYOUT_ENABLED setting. 2025-12-21 02:17:40 +03:00
PEDZEO 1bb0a5c000 Refactor MenuLayoutStatsService to return hourly statistics as a complete list for all 24 hours, ensuring counts default to 0 when no data exists for a given hour. 2025-12-21 01:14:04 +03:00
gy9vin 2cb6dfb4aa Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2025-12-21 00:38:14 +03:00
gy9vin 837473b274 Апи для детальной статистики по конкурсу рефералов 2025-12-21 00:38:08 +03:00
gy9vin aab32299ac Детальная статистика по конкурсу рефералов. 2025-12-21 00:19:13 +03:00
PEDZEO 2a3f1bac76 Refactor MenuLayoutStatsService to create a dictionary for quick access to weekday statistics, ensuring all weekdays are returned with a count of 0 if no data exists. 2025-12-20 23:33:35 +03:00
PEDZEO f4ed274623 Merge branch 'buttons' of https://github.com/Fr1ngg/remnawave-bedolaga-telegram-bot into buttons 2025-12-20 21:56:36 +03:00
PEDZEO 32c28aedea Enhance MenuLayoutStatsService to include daily, weekly, and monthly click statistics for buttons, improving analytics capabilities in the menu layout. 2025-12-20 21:56:33 +03:00
PEDZEO 69927a4db2 Improve error handling and logging in MenuLayout statistics endpoints; change button click log ordering to descending. 2025-12-20 21:50:13 +03:00
gy9vin bdc1df737b Фикс автопродления и Фиксы конкурсов 2025-12-20 14:57:38 +03:00
gy9vin c8c79ea807 Улучшение реферального конкурса! 2025-12-20 14:32:26 +03:00
PEDZEO d75fc0c60f Add statistics endpoints in MenuLayoutService for button clicks, including by type, hour, weekday, top users, period comparison, and user click sequences 2025-12-20 03:32:34 +03:00
PEDZEO 931b282f5b Enhance button handling in MenuLayoutService to improve connect button identification and URL management 2025-12-20 03:27:31 +03:00
PEDZEO 10bc00d429 Merge pull request #2174 from BEDOLAGA-DEV/buttons
Buttons
2025-12-20 02:55:59 +03:00
PEDZEO dd24b7ffde Add ButtonStatsMiddleware for automatic button click logging in bot setup 2025-12-20 02:42:40 +03:00
PEDZEO 5fa627bd7f Refactor subscription days calculation and update autopay property naming in main menu keyboard 2025-12-20 02:31:52 +03:00
PEDZEO b8671ef07d Refactor subscription days variable usage in MenuLayoutService to improve clarity and consistency 2025-12-20 02:29:41 +03:00
PEDZEO 7a30aa23dc Update subscription parameter naming in main menu keyboard function 2025-12-20 02:23:55 +03:00
PEDZEO a87d52f2bc Update subscription placeholder naming in menu layout and adjust context variable accordingly 2025-12-20 02:15:51 +03:00
PEDZEO 5919cfff16 Refactor referral data retrieval and update subscription placeholder naming in menu layout 2025-12-20 01:55:26 +03:00
PEDZEO e743689b34 Enhance main menu keyboard functionality by adding user data support and subscription details retrieval 2025-12-20 01:40:23 +03:00
PEDZEO 37dd5ede9f fix 2025-12-19 23:27:00 +03:00
Mikhail 930aabc166 Merge branch 'BEDOLAGA-DEV:main' into main 2025-12-19 17:42:58 +03:00
gy9vin f70ad92efe Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2025-12-19 17:42:10 +03:00
gy9vin 01fd7a317d НДС 22 2025-12-19 17:42:03 +03:00
Egor 507df0af33 Merge pull request #2172 from BEDOLAGA-DEV/d2pxq4-bedolaga/fix-missing-localization-key-for-ru
Add missing Buy Traffic localization key
2025-12-19 07:28:16 +03:00
PEDZEO af91423dec Merge pull request #2171 from BEDOLAGA-DEV/buttons
Buttons
2025-12-19 07:27:44 +03:00
Egor 893ff0e8f1 Add missing Buy Traffic localization key 2025-12-19 07:27:27 +03:00
Egor cde838864f Merge pull request #2170 from BEDOLAGA-DEV/main
w
2025-12-19 07:23:40 +03:00
Egor 2eb2661848 Merge pull request #2167 from BEDOLAGA-DEV/dev5
Dev5
2025-12-19 07:23:00 +03:00
Egor d7a935906e Merge pull request #2168 from Gy9vin/main
Фиксы
2025-12-19 07:22:42 +03:00
PEDZEO b81400105f Add button open mode and webapp url 2025-12-19 04:02:58 +03:00
PEDZEO 8c3e71bdfd Fix menu layout update conversions 2025-12-19 03:22:44 +03:00
PEDZEO 025d50675f test 2025-12-19 02:14:57 +03:00
Mikhail 5f540d907e Merge branch 'BEDOLAGA-DEV:main' into main 2025-12-18 17:51:05 +03:00
gy9vin c6175255a5 фикс кнопок конкурсов 2025-12-18 17:50:36 +03:00
gy9vin 71facd9624 Активация подписки после пополнения баланса! 2025-12-18 08:45:59 +03:00
Egor 89a5f5c6f7 Merge pull request #2166 from BEDOLAGA-DEV/j0zhkm-bedolaga/add-subscription-management-for-users-who-unsubscribed
Add toggle for trial deactivation on channel unsubscribe
2025-12-18 03:23:14 +03:00
Egor 7b60be1ec7 Add toggle for trial deactivation on channel unsubscribe 2025-12-18 03:04:13 +03:00
Egor ed314ca19b Merge pull request #2165 from Gy9vin/main
Фиксы, правки и хотелки
2025-12-18 00:16:25 +03:00
Mikhail 0b714893e7 Merge branch 'BEDOLAGA-DEV:main' into main 2025-12-18 00:14:20 +03:00
gy9vin 5ca0f5fc27 Еще правки 2025-12-18 00:13:57 +03:00
Egor 31fa7b7072 Merge pull request #2164 from BEDOLAGA-DEV/main
ц
2025-12-17 20:23:29 +03:00
Egor 86d7003c33 Merge pull request #2161 from Gy9vin/main
Кнопка конкурсов + прототип налоговой. не трогайте налоговую еще!!!
2025-12-17 19:13:32 +03:00
Egor 753d77b4c2 Merge pull request #2162 from Vysokostnyi/main
Добавлено передача telegram_user_id в описание платежа
2025-12-17 19:13:05 +03:00
Vysokostnyi 4add298aab Добавлено передача telegram_user_id в описание платежа 2025-12-16 02:41:58 +03:00
gy9vin e76f2f3d50 Кнопка конкурсов + прототип налоговой. не трогайте налоговую еще!!! 2025-12-16 00:59:23 +03:00
Egor dcb0002f4a Merge pull request #2160 from Gy9vin/main
Конкурсные
2025-12-15 22:58:21 +03:00
gy9vin 332c20fc45 Merge branch 'main' of https://github.com/Gy9vin/remnawave-bedolaga-telegram-bot 2025-12-15 21:36:23 +03:00
gy9vin 305a3c4490 Фиксы по конкурсам. 2025-12-15 21:34:56 +03:00
Mikhail a9ecd5f620 Merge branch 'BEDOLAGA-DEV:main' into main 2025-12-15 20:05:03 +03:00
gy9vin 2f0594e361 Конкурсная система. 2025-12-15 20:04:39 +03:00
Egor 65b36c3a5f Merge pull request #2159 from BEDOLAGA-DEV/revert-2158-c8yqa8-bedolaga/add-subscription-settings-for-happ_cryptolink
Revert "Add limited Happ cryptolink support"
2025-12-15 11:12:22 +03:00
Egor f8ef2b9f5a Revert "Add limited Happ cryptolink support" 2025-12-15 11:12:14 +03:00
Egor 70a283d1f1 Merge pull request #2158 from BEDOLAGA-DEV/c8yqa8-bedolaga/add-subscription-settings-for-happ_cryptolink
Add limited Happ cryptolink support
2025-12-15 11:00:54 +03:00
Egor f2a5032f15 Refresh Happ link before displaying subscription 2025-12-15 11:00:39 +03:00
Egor 0f5fcdd067 Merge pull request #2157 from BEDOLAGA-DEV/revert-2156-2gz1mq-bedolaga/add-subscription-settings-for-happ_cryptolink
Revert "Add limited Happ cryptolink support"
2025-12-15 11:00:26 +03:00
Egor 80388be54f Revert "Add limited Happ cryptolink support" 2025-12-15 11:00:17 +03:00
Egor 47f0b77138 Merge pull request #2156 from BEDOLAGA-DEV/2gz1mq-bedolaga/add-subscription-settings-for-happ_cryptolink
Add limited Happ cryptolink support
2025-12-15 10:41:18 +03:00
Egor 162e7da350 Add cooldown for Happ device reset links 2025-12-15 10:40:59 +03:00
Egor 07e1e08b1d Merge pull request #2154 from BEDOLAGA-DEV/revert-2153-49fvja-bedolaga/add-web-admin-button-for-admins
Revert "Add admin web panel miniapp toggle"
2025-12-15 07:24:51 +03:00
Egor fc955bd3b2 Revert "Add admin web panel miniapp toggle" 2025-12-15 07:24:41 +03:00
Egor 1b504063d2 Merge pull request #2153 from BEDOLAGA-DEV/49fvja-bedolaga/add-web-admin-button-for-admins
Add admin web panel miniapp toggle
2025-12-15 07:19:01 +03:00
Egor 174f9b8517 Add admin web panel miniapp toggle 2025-12-15 07:18:45 +03:00
Egor 3706d5ceb4 Merge pull request #2152 from BEDOLAGA-DEV/main
w
2025-12-14 19:35:39 +03:00
Egor 3577054d79 Merge pull request #2151 from Gy9vin/main
Коркурсная система + АПИ
2025-12-14 19:32:41 +03:00
gy9vin afd4fe8d1d Конкурсы +АПИ 2025-12-14 14:37:29 +03:00
gy9vin 1409a0ab8d Конкурсы 2025-12-14 01:38:22 +03:00
Egor 9df8ca52d6 Merge pull request #2150 from BEDOLAGA-DEV/dev5
Dev5
2025-12-12 08:54:47 +03:00
Egor 0902efc007 Merge pull request #2149 from BEDOLAGA-DEV/9ks456-bedolaga/fix-url-validation-error-in-bot
Restrict blacklist URL input to waiting state
2025-12-12 08:52:51 +03:00
Egor 0b4fea02a1 Restrict blacklist URL input to waiting state 2025-12-12 08:52:36 +03:00
Egor 01580aae74 Merge pull request #2148 from BEDOLAGA-DEV/dev5
Dev5
2025-12-12 06:58:03 +03:00
Egor 7e022a1eca Merge pull request #2147 from BEDOLAGA-DEV/om94g5-bedolaga/update-subscription-link-display
Wrap Happ CryptoLink subscription link in blockquote
2025-12-12 06:56:36 +03:00
Egor f31c64602c Wrap Happ CryptoLink subscription link in blockquote 2025-12-12 06:55:58 +03:00
Egor f193b0bfcf Update Python version argument to v2.9.1 2025-12-12 06:29:18 +03:00
Egor b961529001 Update version to v2.9.1 in docker-registry.yml 2025-12-12 06:29:09 +03:00
Egor afa172f3cc Update docker-hub.yml 2025-12-12 06:28:52 +03:00
Egor 8be1d7e423 Delete app/handlers/.DS_Store 2025-12-12 06:10:15 +03:00
Egor 8c4db0a0e6 Delete app/.DS_Store 2025-12-12 06:09:46 +03:00
Egor 1e56e4eaa6 Merge pull request #2146 from BEDOLAGA-DEV/main
w
2025-12-12 06:08:29 +03:00
Egor a8da98c35e Update docker-compose.yml 2025-12-12 06:07:54 +03:00
Egor 7ca6942443 Rename vpn_logo (1).png to vpn_logo.png 2025-12-12 06:07:06 +03:00
Egor 3f97d22a76 Add files via upload 2025-12-12 06:06:42 +03:00
Egor e3dccf2c1b Merge pull request #2144 from Gy9vin/main
Обновки
2025-12-12 06:04:37 +03:00
Egor d0e25fff3d Merge pull request #2145 from BEDOLAGA-DEV/dev5
Dev5
2025-12-12 06:03:41 +03:00
Egor 3699d248b1 Add enrich_happ_links parameter to get_all_users 2025-12-12 05:59:58 +03:00
Egor bffbf3ea39 Update remnawave_api.py 2025-12-12 05:59:01 +03:00
gy9vin e869c9b167 Обновление env 2025-12-11 23:21:12 +03:00
gy9vin 0b2b109e86 Минификсы 2025-12-11 23:11:23 +03:00
gy9vin 5dd586e0b2 Новый фильтр Готовы к продлению 2025-12-11 22:42:37 +03:00
gy9vin c9de084efa Фикс корзины 2025-12-11 22:25:42 +03:00
gy9vin 81b3c7ed3f черный список + фиксы 2025-12-11 10:56:14 +03:00
gy9vin 80785f22b0 Черный список, мониторинг суточно графика по регламенту 2025-12-10 19:13:52 +03:00
Egor b1cb368bf6 Merge pull request #2139 from BEDOLAGA-DEV/main
w
2025-12-10 02:21:37 +03:00
Egor 9fc977ace3 Merge pull request #2132 from remnawave-contrib/ivan-nginx-platega-min
Reduce minimum amount for Platega transactions from 10000 to 100 kope…
2025-12-10 02:16:49 +03:00
Egor 47acd37449 Merge pull request #2133 from remnawave-contrib/ivan-nginx-health-check
fix: healthcheck command to include API key in requests
2025-12-10 02:16:08 +03:00
Egor d7fa956f58 Merge pull request #2138 from BEDOLAGA-DEV/dev5
Dev5
2025-12-10 02:14:54 +03:00
Egor 98164c2083 Merge pull request #2137 from BEDOLAGA-DEV/g0wcwm-bedolaga/fix-api-issue-with-faq-status-editing
Fix FAQ status route matching
2025-12-10 02:10:00 +03:00
Egor 81f5ce429e Fix FAQ status route matching 2025-12-10 02:09:46 +03:00
Egor 5a3bded4a8 Merge pull request #2136 from BEDOLAGA-DEV/revert-2134-dfg5t2-bedolaga/fix-api-issue-with-faq-status-editing
Revert "Handle FAQ status update without request body"
2025-12-10 02:09:00 +03:00
Egor 2743a845bd Revert "Handle FAQ status update without request body" 2025-12-10 02:08:51 +03:00
Egor 7c222c0aed Merge pull request #2135 from BEDOLAGA-DEV/dev5
Dev5
2025-12-09 23:49:34 +03:00
Egor 3222c82b46 Merge pull request #2134 from BEDOLAGA-DEV/dfg5t2-bedolaga/fix-api-issue-with-faq-status-editing
Handle FAQ status update without request body
2025-12-09 23:49:16 +03:00
Egor 9f0f3a367c Handle FAQ status update without request body 2025-12-09 23:48:54 +03:00
Ivan.Nginx f702356f48 fix: healthcheck command to include API key in requests 2025-12-09 03:14:24 +03:00
Ivan.Nginx 48d799e312 Reduce minimum amount for Platega transactions from 10000 to 100 kopeks (from 100 to 1 rub) 2025-12-09 00:59:29 +03:00
Egor 7c05b36b9d Update Python version to 2.9.0 in Dockerfile 2025-12-08 04:35:25 +03:00
Egor b398eecbeb Update versioning scheme to v2.9.0 2025-12-08 04:35:13 +03:00
Egor 5ab80b09a1 Update docker-hub.yml 2025-12-08 04:34:58 +03:00
Egor 535b92d43b Merge pull request #2129 from BEDOLAGA-DEV/dev5
Обновление Api Remnawave под версию 2.3.0 + Возможность установить таги для триалов и платных подписок + Правки Web Api
2025-12-08 04:28:00 +03:00
Egor cbaddd65e0 Merge pull request #2128 from BEDOLAGA-DEV/revert-2127-xs3s5d-bedolaga/add-ability-to-assign-internal-squads
Revert "Support user-specific internal squads"
2025-12-08 04:24:04 +03:00
Egor 136cae68f1 Revert "Support user-specific internal squads" 2025-12-08 04:23:57 +03:00
Egor 38abf49af9 Merge pull request #2127 from BEDOLAGA-DEV/xs3s5d-bedolaga/add-ability-to-assign-internal-squads
Support user-specific internal squads
2025-12-08 04:20:37 +03:00
Egor 799243a988 Support user-specific internal squads 2025-12-08 04:20:21 +03:00
Egor 6d024716c7 Merge pull request #2126 from BEDOLAGA-DEV/revert-2125-8z51jt-bedolaga/add-support-for-assigning-internal-squads
Revert "Add internal squad management for users and trials"
2025-12-08 04:17:14 +03:00
Egor 0892f494d9 Revert "Add internal squad management for users and trials" 2025-12-08 04:17:05 +03:00
Egor 42b67bdc47 Merge pull request #2125 from BEDOLAGA-DEV/8z51jt-bedolaga/add-support-for-assigning-internal-squads
Add internal squad management for users and trials
2025-12-08 04:15:35 +03:00
Egor 6c41263511 Add internal squad management for users and trials 2025-12-08 04:15:18 +03:00
Egor 1aab9550ce Merge pull request #2124 from BEDOLAGA-DEV/42kgo8-bedolaga/fix-squads-functionality-in-bot-api
Fix RemnaWave squad creation success flag
2025-12-08 04:00:58 +03:00
Egor d596b19d96 Fix RemnaWave squad creation success flag 2025-12-08 04:00:42 +03:00
Egor 0863e3023d Merge pull request #2123 from BEDOLAGA-DEV/revert-2122-mbdf7a-bedolaga/fix-squads-functionality-in-bot-api
Revert "Fix RemnaWave squad inbound serialization"
2025-12-08 04:00:31 +03:00
Egor 1ef2e1264f Revert "Fix RemnaWave squad inbound serialization" 2025-12-08 04:00:22 +03:00
Egor c40806a5a3 Merge pull request #2122 from BEDOLAGA-DEV/mbdf7a-bedolaga/fix-squads-functionality-in-bot-api
Fix RemnaWave squad inbound serialization
2025-12-08 03:52:53 +03:00
Egor 841c288313 Fix serialization of squad inbounds 2025-12-08 03:52:38 +03:00
Egor cd1a4a4a6e Merge pull request #2121 from BEDOLAGA-DEV/0w5so9-bedolaga/fix-critical-error-in-show_node_details
Bind refreshed callbacks to bot
2025-12-08 03:34:10 +03:00
Egor e9e61f4892 Bind refreshed callbacks to bot 2025-12-08 03:33:56 +03:00
Egor 167cddcd2f Merge pull request #2120 from BEDOLAGA-DEV/revert-2119-hcism8-bedolaga/fix-critical-error-in-show_node_details
Revert "Fix node details refresh callback usage"
2025-12-08 03:33:07 +03:00
Egor 5b4c597e9b Revert "Fix node details refresh callback usage" 2025-12-08 03:32:58 +03:00
Egor 0cb1c9b580 Merge pull request #2119 from BEDOLAGA-DEV/hcism8-bedolaga/fix-critical-error-in-show_node_details
Fix node details refresh callback usage
2025-12-08 03:26:46 +03:00
Egor ff4471a22a Fix node details refresh callback usage 2025-12-08 03:26:32 +03:00
Egor 93d7bd74a3 Merge pull request #2118 from BEDOLAGA-DEV/revert-2117-sifkp4-bedolaga/fix-critical-error-in-show_node_details
Revert "Fix callback reuse after node actions"
2025-12-08 03:26:22 +03:00
Egor c770948c1f Revert "Fix callback reuse after node actions" 2025-12-08 03:26:14 +03:00
Egor 2e1a6faec1 Merge pull request #2117 from BEDOLAGA-DEV/sifkp4-bedolaga/fix-critical-error-in-show_node_details
Fix callback reuse after node actions
2025-12-08 03:24:26 +03:00
Egor 0031c9e2e0 Fix callback reuse after node actions 2025-12-08 03:24:13 +03:00
Egor 637d2a07e0 Merge pull request #2116 from BEDOLAGA-DEV/udkyiq-bedolaga/expand-remnawave-node-statistics
Expand Remnawave node statistics
2025-12-08 03:19:36 +03:00
Egor 988ffbebdb Expand Remnawave node statistics 2025-12-08 03:19:23 +03:00
Egor 5a795a2ae2 Update remnawave_api.py 2025-12-08 03:13:16 +03:00
Egor 9b6cd74dbf Update remnawave_api.py 2025-12-08 03:01:21 +03:00
Egor daa2f13ca3 Merge pull request #2114 from BEDOLAGA-DEV/qhbf7v-bedolaga/add-custom-tag-feature-for-trial-users
Add configurable RemnaWave user tags for trial and paid subscriptions
2025-12-08 02:46:32 +03:00
Egor 386b9ae998 Add configurable user tags for trial and paid subscriptions 2025-12-08 02:44:53 +03:00
Egor e64854dc48 Update remnawave_api.py 2025-12-08 01:42:03 +03:00
Egor 23eed94009 Add functions to extract traffic bytes from user data 2025-12-08 01:32:23 +03:00
Egor f04ffa58e4 Update remnawave_api.py 2025-12-08 01:31:42 +03:00
Egor fc45db6f3c Merge pull request #2112 from BEDOLAGA-DEV/dev5
Dev5
2025-12-06 17:31:03 +03:00
Egor b8874772be Merge pull request #2111 from BEDOLAGA-DEV/8ioop5-bedolaga/add-api-endpoint-for-statistics
Add full statistics API endpoint
2025-12-06 16:14:52 +03:00
Egor d8c7793a26 Merge pull request #2110 from BEDOLAGA-DEV/dev5
Dev5
2025-12-06 15:34:35 +03:00
Egor 10d08d5b40 Add full statistics API endpoint 2025-12-06 15:32:01 +03:00
Egor b07a889826 Merge pull request #2109 from BEDOLAGA-DEV/ffowe2-bedolaga/-api
Add promo offer broadcast endpoint
2025-12-06 15:28:12 +03:00
Egor a24b4c72e9 Add promo offer broadcast endpoint 2025-12-06 15:21:54 +03:00
Egor 5e1d00ad0d Merge pull request #2108 from belousotroll/fix-calculating-tg-starts-amount
Fix calculating tg starts amount
2025-12-06 06:24:52 +03:00
belousotroll d33ebb1453 Merge branch 'BEDOLAGA-DEV:main' into fix-calculating-tg-starts-amount 2025-12-05 21:54:46 +07:00
Egor 7a2bcf3d2f Merge pull request #2107 from BEDOLAGA-DEV/dev5
Dev5
2025-12-05 10:22:44 +03:00
Egor dbb68582e4 Merge pull request #2106 from BEDOLAGA-DEV/gpower-bedolaga/add-telegram-id-support-to-promo-offers-api
Add Telegram ID support to promo offers API
2025-12-05 10:18:34 +03:00
Egor 479b9bc384 Add telegram id support for promo offers 2025-12-05 09:56:03 +03:00
Egor 73f3987481 Merge pull request #2105 from BEDOLAGA-DEV/dev5
Dev5
2025-12-03 07:30:06 +03:00
Egor 8b38f1e37d Merge pull request #2104 from BEDOLAGA-DEV/axy4i1-bedolaga/fix-telegram-api-error-in-show_balance_menu
Handle balance menu for YooKassa SBP QR and add Heleket localization keys
2025-12-03 07:29:43 +03:00
Egor 6976129972 Handle balance menu edits for SBP invoices and add Heleket locales 2025-12-03 07:29:01 +03:00
belousotroll 207e4673c0 Merge branch 'BEDOLAGA-DEV:main' into fix-calculating-tg-starts-amount 2025-11-30 20:30:14 +07:00
belousotroll 160ff7ff9f fix: calculating telegram starts amount 2025-11-30 19:29:29 +07:00
Egor 6c7c57138d Merge pull request #2099 from BEDOLAGA-DEV/dev5
Dev5
2025-11-29 09:52:18 +03:00
Egor 12b5a39194 Update subscription_purchase_service.py 2025-11-29 09:50:35 +03:00
Egor 7678150e6a Update subscription_auto_purchase_service.py 2025-11-29 09:50:05 +03:00
Egor 99e35cae4c Merge pull request #2098 from BEDOLAGA-DEV/dev5
Dev5
2025-11-28 23:02:44 +03:00
Egor af313a12ed Add files via upload 2025-11-28 23:00:08 +03:00
Egor 71d18287fe Add files via upload 2025-11-28 22:59:27 +03:00
Egor 6b24b69b53 Merge pull request #2097 from BEDOLAGA-DEV/dev5
Update menu.py
2025-11-28 21:28:54 +03:00
Egor 9528457b89 Update menu.py 2025-11-28 21:27:11 +03:00
Egor 69322640c5 Merge pull request #2096 from BEDOLAGA-DEV/dev5
Update purchase.py
2025-11-28 21:17:51 +03:00
Egor 3c0703b599 Update purchase.py 2025-11-28 21:13:49 +03:00
Egor d14aa5bd8a Update README.md 2025-11-28 06:42:43 +03:00
Egor baa5da243e Merge pull request #2095 from BEDOLAGA-DEV/dev5
Dev5
2025-11-28 06:24:37 +03:00
Egor fff01d1ce3 Update validators.py 2025-11-28 06:23:55 +03:00
Egor 52c8442423 Merge pull request #2094 from BEDOLAGA-DEV/revert-2093-acgzuy-bedolaga/fix-unsupported-html-tag-parsing-error
Revert "Remove blockquote markup to prevent Telegram parse errors"
2025-11-28 06:02:16 +03:00
Egor 150f9e741a Revert "Remove blockquote markup to prevent Telegram parse errors" 2025-11-28 06:02:08 +03:00
Egor 4ae2234b7f Merge pull request #2093 from BEDOLAGA-DEV/acgzuy-bedolaga/fix-unsupported-html-tag-parsing-error
Remove blockquote markup to prevent Telegram parse errors
2025-11-28 06:00:48 +03:00
Egor 71366a8133 Remove blockquote markup to prevent Telegram parse errors 2025-11-28 06:00:32 +03:00
Egor fb6cda2c63 Merge pull request #2092 from BEDOLAGA-DEV/revert-2091-ndvrn0-bedolaga/fix-unsupported-html-tag-parsing-error
Revert "Harden message send fallback for invalid HTML"
2025-11-28 06:00:25 +03:00
Egor 2d4f9da9a7 Revert "Harden message send fallback for invalid HTML" 2025-11-28 06:00:16 +03:00
Egor 7a39abe05c Merge pull request #2091 from BEDOLAGA-DEV/ndvrn0-bedolaga/fix-unsupported-html-tag-parsing-error
Harden message send fallback for invalid HTML
2025-11-28 05:51:20 +03:00
Egor 79659ec5fe Harden message send fallback for invalid HTML 2025-11-28 05:51:05 +03:00
Egor a3457d5853 Merge pull request #2090 from BEDOLAGA-DEV/revert-2089-pmhwx5-bedolaga/fix-unsupported-html-tag-parsing-error
Revert "Improve fallback on Telegram parse errors"
2025-11-28 05:50:59 +03:00
Egor 0392aa5b45 Revert "Improve fallback on Telegram parse errors" 2025-11-28 05:50:50 +03:00
Egor 2c68d9ded9 Merge pull request #2089 from BEDOLAGA-DEV/pmhwx5-bedolaga/fix-unsupported-html-tag-parsing-error
Improve fallback on Telegram parse errors
2025-11-28 05:49:24 +03:00
Egor a437ebd65b Improve fallback on Telegram parse errors 2025-11-28 05:49:04 +03:00
Egor e2323755de Merge pull request #2088 from BEDOLAGA-DEV/revert-2087-lyaqkf-bedolaga/fix-unsupported-html-tag-parsing-error
Revert "Handle Telegram parse errors gracefully"
2025-11-28 05:48:57 +03:00
Egor 5e23920723 Revert "Handle Telegram parse errors gracefully" 2025-11-28 05:48:48 +03:00
Egor 5e45fc1285 Merge pull request #2087 from BEDOLAGA-DEV/lyaqkf-bedolaga/fix-unsupported-html-tag-parsing-error
Handle Telegram parse errors gracefully
2025-11-28 05:43:41 +03:00
Egor ff1556ffcd Handle parse errors with plain text fallback 2025-11-28 05:43:23 +03:00
Egor 549e8fa332 Merge pull request #2086 from BEDOLAGA-DEV/revert-2085-aoflna-bedolaga/fix-unsupported-html-tag-parsing-error
Revert "Ensure photo replies default to HTML parse mode"
2025-11-28 05:43:15 +03:00
Egor 8a7fb598fa Revert "Ensure photo replies default to HTML parse mode" 2025-11-28 05:43:06 +03:00
Egor 521c364fbb Merge pull request #2085 from BEDOLAGA-DEV/aoflna-bedolaga/fix-unsupported-html-tag-parsing-error
Ensure photo replies default to HTML parse mode
2025-11-28 05:41:40 +03:00
Egor db60f5c5ba Ensure photo replies default to HTML parse mode 2025-11-28 05:41:24 +03:00
Egor affc07985e Merge pull request #2084 from BEDOLAGA-DEV/4drat9-bedolaga/fix-empty-page-on-/redoc
Ensure ReDoc loads reliably
2025-11-28 04:00:35 +03:00
Egor 2761255e65 Ensure ReDoc loads reliably 2025-11-28 03:58:59 +03:00
Egor 53988c319b Update Dockerfile 2025-11-28 03:21:48 +03:00
Egor 777ea3b99b Update docker-registry.yml 2025-11-28 03:21:34 +03:00
Egor 672ce18f38 Update docker-hub.yml 2025-11-28 03:21:20 +03:00
Egor aafcec2716 Merge pull request #2083 from BEDOLAGA-DEV/dev5
Dev5
2025-11-28 03:03:03 +03:00
Egor 4e5b607288 Merge pull request #2082 from BEDOLAGA-DEV/ycxgll-bedolaga/restore-reverse-sync-button-in-remnawave
Recover missing RemnaWave users during panel sync
2025-11-28 03:00:24 +03:00
Egor aae85683a0 Recover missing RemnaWave users during panel sync 2025-11-28 03:00:09 +03:00
Egor 9971c43218 Merge pull request #2081 from BEDOLAGA-DEV/revert-2080-jq66gt-bedolaga/restore-reverse-sync-button-in-remnawave
Revert "Handle RemnaWave status validation changes"
2025-11-28 02:59:49 +03:00
Egor b4370e9a34 Revert "Handle RemnaWave status validation changes" 2025-11-28 02:59:41 +03:00
Egor 101e27acd6 Merge pull request #2080 from BEDOLAGA-DEV/jq66gt-bedolaga/restore-reverse-sync-button-in-remnawave
Handle RemnaWave status validation changes
2025-11-28 02:53:30 +03:00
Egor 5b9002896e Handle RemnaWave status validation changes 2025-11-28 02:53:13 +03:00
Egor e8ac14b0b7 Merge pull request #2079 from BEDOLAGA-DEV/revert-2078-lw4oi2-bedolaga/restore-reverse-sync-button-in-remnawave
Revert "Align RemnaWave sync with new status and expiration rules"
2025-11-28 02:52:57 +03:00
Egor 7cd6c3acb7 Revert "Align RemnaWave sync with new status and expiration rules" 2025-11-28 02:52:47 +03:00
Egor 7e7795fc4e Merge pull request #2078 from BEDOLAGA-DEV/lw4oi2-bedolaga/restore-reverse-sync-button-in-remnawave
Align RemnaWave sync with new status and expiration rules
2025-11-28 02:49:23 +03:00
Egor 1f75413abd Handle RemnaWave API status and expire constraints 2025-11-28 02:48:49 +03:00
Egor 3c6d674ce5 Merge pull request #2077 from BEDOLAGA-DEV/revert-2076-7uxban-bedolaga/restore-reverse-sync-button-in-remnawave
Revert "Add reverse remnawave sync with batched upload"
2025-11-28 02:48:37 +03:00
Egor 92efc52f7e Revert "Add reverse remnawave sync with batched upload" 2025-11-28 02:48:28 +03:00
Egor c558f69d62 Merge pull request #2076 from BEDOLAGA-DEV/7uxban-bedolaga/restore-reverse-sync-button-in-remnawave
Add reverse remnawave sync with batched upload
2025-11-28 02:39:55 +03:00
Egor 168cb5ea38 Add reverse remnawave sync with batched upload 2025-11-28 02:34:50 +03:00
Egor 6a48cc687c Merge pull request #2075 from BEDOLAGA-DEV/r3w3lo-bedolaga/fix-bot-crash-due-to-html-tags
Avoid unescaping attribute entities in sanitizer
2025-11-28 02:30:54 +03:00
Egor 9a5b0553c6 Avoid unescaping attribute entities in sanitizer 2025-11-28 02:22:39 +03:00
Egor 7515964599 Merge pull request #2074 from BEDOLAGA-DEV/revert-2072-ywwhae-bedolaga/fix-bot-crash-due-to-html-tags
Revert "Improve HTML sanitization for menu messages"
2025-11-28 02:12:41 +03:00
Egor bf5e0ecd4f Revert "Improve HTML sanitization for menu messages" 2025-11-28 02:12:32 +03:00
Egor 6d058beade Merge pull request #2072 from BEDOLAGA-DEV/ywwhae-bedolaga/fix-bot-crash-due-to-html-tags
Improve HTML sanitization for menu messages
2025-11-28 01:35:35 +03:00
Egor 91f557e357 Improve HTML sanitization for menu messages 2025-11-28 01:31:53 +03:00
Egor 8e6c594a7b Merge pull request #2071 from BEDOLAGA-DEV/revert-2069-k72cch-bedolaga/fix-bot-crash-due-to-html-tags
Revert "Validate HTML in user messages"
2025-11-28 01:31:47 +03:00
Egor 94cc04703b Revert "Validate HTML in user messages" 2025-11-28 01:31:39 +03:00
Egor 9ac621cebd Merge pull request #2069 from BEDOLAGA-DEV/k72cch-bedolaga/fix-bot-crash-due-to-html-tags
Validate HTML in user messages
2025-11-28 01:06:50 +03:00
Egor 5d9f6064d6 Validate user message HTML 2025-11-28 01:00:15 +03:00
Egor 010be14379 Merge pull request #2068 from BEDOLAGA-DEV/dev5
Dev5
2025-11-28 00:18:54 +03:00
Egor d864c80457 Merge pull request #2067 from BEDOLAGA-DEV/80cp2x-bedolaga/fix-cryptobot-notification-error
Handle missing greenlet when building topup keyboard
2025-11-28 00:11:37 +03:00
Egor ac04284d85 Handle lazy subscription access in checkout resume 2025-11-28 00:11:15 +03:00
Egor e1377ad7a0 Merge pull request #2066 from BEDOLAGA-DEV/dev5
Dev5
2025-11-28 00:03:34 +03:00
Egor 6c7bbba7ed Merge pull request #2065 from BEDOLAGA-DEV/78k0ik-bedolaga/filter-out-pricing-logs-from-bot
Reduce noisy price calculation logging
2025-11-27 23:57:00 +03:00
Egor 7a70a90d63 Reduce noisy price calculation logging 2025-11-27 23:55:54 +03:00
Egor 58187cecdb Merge pull request #2064 from BEDOLAGA-DEV/dev5
Dev5
2025-11-27 23:46:46 +03:00
Egor 649a358560 Merge pull request #2063 from BEDOLAGA-DEV/a812lu-bedolaga/fix-manual-status-check-error-in-payment-service
Refresh promo groups before platega finalize
2025-11-27 23:42:38 +03:00
Egor e0f1f221df Refresh promo groups before platega finalize 2025-11-27 23:38:16 +03:00
Egor 1342236b23 Merge pull request #2062 from BEDOLAGA-DEV/rq2kdr-bedolaga/fix-attributeerror-in-cryptobotpayment
Fix CryptoBot saved cart notifications
2025-11-27 23:33:02 +03:00
Egor 61681b393e Fix CryptoBot saved cart notifications 2025-11-27 23:28:53 +03:00
Egor 20a36fe869 Update README.md 2025-11-27 21:30:29 +03:00
Egor a4fe68bf2a Merge pull request #2061 from BEDOLAGA-DEV/dev5
Dev5
2025-11-25 10:09:29 +03:00
Egor 827cdd7805 Merge pull request #2060 from BEDOLAGA-DEV/9h699c-bedolaga/fix-telegram-flood-control-issue
Add retry when persisting broadcast results after DB disconnect
2025-11-25 10:02:44 +03:00
Egor 2479167073 Merge pull request #2059 from BEDOLAGA-DEV/y8nxh1-bedolaga/fix-payment-verification-service-error
Avoid lazy loading during Platega payment finalization
2025-11-25 10:00:13 +03:00
Egor 5cc8f7869f Add retry when persisting broadcast results after DB disconnect 2025-11-25 09:59:07 +03:00
Egor 330ace039b Avoid lazy loading during Platega payment finalization 2025-11-25 09:57:11 +03:00
Egor 36ad95dfef Merge pull request #2058 from BEDOLAGA-DEV/dev5
Dev5
2025-11-25 06:41:03 +03:00
Egor a7d564b7d1 Update README.md 2025-11-25 06:40:42 +03:00
Egor 4582daa1d1 Update docker-compose.local.yml 2025-11-25 06:38:14 +03:00
Egor c440274c32 Merge pull request #2057 from BEDOLAGA-DEV/dev5
Dev5
2025-11-25 04:59:59 +03:00
Egor a02b2f163b Merge pull request #2056 from BEDOLAGA-DEV/bedolaga-5s9q2y
Serve miniapp app-config and fix maintenance schema
2025-11-25 04:32:34 +03:00
Egor f5a6dbdeec Serve miniapp app-config and fix maintenance schema 2025-11-25 04:26:54 +03:00
Egor 282bf3aa11 Merge pull request #2055 from BEDOLAGA-DEV/revert-2053-bedolaga-1xcsyw
Revert "Block miniapp during maintenance mode"
2025-11-25 04:26:22 +03:00
Egor d302e02b0a Revert "Block miniapp during maintenance mode" 2025-11-25 04:26:12 +03:00
Egor da554736ba Merge pull request #2054 from BEDOLAGA-DEV/dev5
Dev5
2025-11-25 04:10:40 +03:00
Egor aefbc21033 Merge pull request #2053 from BEDOLAGA-DEV/bedolaga-1xcsyw
Block miniapp during maintenance mode
2025-11-25 04:03:15 +03:00
Egor add0fb4fbe Block miniapp during maintenance mode 2025-11-25 03:58:10 +03:00
Egor f1bec83a6f Merge pull request #2052 from BEDOLAGA-DEV/revert-2051-bedolaga-612jbk
Revert "Improve miniapp app-config loading fallback"
2025-11-25 03:58:02 +03:00
Egor a9e15a7cc1 Revert "Improve miniapp app-config loading fallback" 2025-11-25 03:57:52 +03:00
Egor 53c0f17200 Merge pull request #2051 from BEDOLAGA-DEV/bedolaga-612jbk
Improve miniapp app-config loading fallback
2025-11-25 03:46:46 +03:00
Egor 0c5a28d1c3 Improve miniapp app-config loading fallback 2025-11-25 03:46:23 +03:00
Egor cedb6b4cc4 Merge pull request #2050 from BEDOLAGA-DEV/revert-2048-bedolaga-myk79e
Revert "Show maintenance notice in miniapp"
2025-11-25 03:45:55 +03:00
Egor 5c7ec8c4a2 Revert "Show maintenance notice in miniapp" 2025-11-25 03:45:46 +03:00
Egor 3bb2a055e7 Merge pull request #2049 from BEDOLAGA-DEV/dev5
Dev5
2025-11-25 03:29:19 +03:00
Egor b117df126a Merge pull request #2048 from BEDOLAGA-DEV/bedolaga-myk79e
Show maintenance notice in miniapp
2025-11-25 03:13:40 +03:00
Egor 610a39e322 Show maintenance notice in miniapp 2025-11-25 03:12:30 +03:00
Egor 71fca0ccf8 Merge pull request #2046 from BEDOLAGA-DEV/dev5
Dev5
2025-11-25 02:49:53 +03:00
Egor 2568cf086a Merge pull request #2045 from BEDOLAGA-DEV/0dm6a3-bedolaga/fix-broadcast-message-failure-on-large-lists
Handle large broadcast status updates and cancellations
2025-11-25 02:42:34 +03:00
Egor ae453279bf Handle late cancellation finalization 2025-11-25 02:38:17 +03:00
Egor bdb04ab91b Merge pull request #2042 from BEDOLAGA-DEV/dev5
Dev5
2025-11-25 02:16:49 +03:00
Egor 3636cd27b6 Merge pull request #2041 from BEDOLAGA-DEV/q8dwo9-bedolaga/add-user-balance-to-promocode-notifications
Ensure balance fields exposed in subscription events API
2025-11-25 02:13:47 +03:00
Egor 04279542c5 Ensure balance fields exposed in subscription events API 2025-11-25 02:10:33 +03:00
Egor c7666274b8 Merge pull request #2040 from BEDOLAGA-DEV/revert-2039-uqw8rl-bedolaga/add-user-balance-to-promocode-notifications
Revert "Add balance details to promocode notifications"
2025-11-25 02:06:33 +03:00
Egor 5b27b8834d Revert "Add balance details to promocode notifications" 2025-11-25 02:06:23 +03:00
Egor 4b506cde0c Merge pull request #2039 from BEDOLAGA-DEV/uqw8rl-bedolaga/add-user-balance-to-promocode-notifications
Add balance details to promocode notifications
2025-11-25 02:05:23 +03:00
Egor 121d254fc0 Add balance details to promocode notifications 2025-11-25 02:03:16 +03:00
Egor 515c9dc8b1 Merge pull request #2038 from BEDOLAGA-DEV/dev5
Апи для сообщений в меню и приветственного текста и доп уведомления
2025-11-25 02:00:46 +03:00
Egor 4e03fa1b71 Merge pull request #2037 from BEDOLAGA-DEV/7z2yaf-bedolaga/fix-text-field-key-mismatch-in-updater
Fix welcome text patch text field mapping
2025-11-25 01:53:20 +03:00
Egor 80752c3004 Fix welcome text update payload mapping 2025-11-25 01:53:01 +03:00
Egor a11d37ef96 Merge pull request #2036 from BEDOLAGA-DEV/1docjs-bedolaga/add-notifications-to-api
Add notification events for balances and promotions
2025-11-25 01:51:45 +03:00
Egor 14c89c7aab Expand notification events 2025-11-25 01:43:07 +03:00
Egor b09b47fa49 Merge pull request #2034 from BEDOLAGA-DEV/2westv-bedolaga/expand-bot-api-for-welcome-text
Handle missing creator on welcome text creation
2025-11-25 01:25:57 +03:00
Egor 49b8a96a84 Handle missing creator on welcome text creation 2025-11-25 01:25:41 +03:00
Egor 6f800ac60b Merge pull request #2033 from BEDOLAGA-DEV/revert-2031-vb0a8m-bedolaga/expand-bot-api-for-welcome-text
Revert "Handle missing creator on user message creation"
2025-11-25 01:24:02 +03:00
Egor 46dfb59f3d Revert "Handle missing creator on user message creation" 2025-11-25 01:23:54 +03:00
Egor d5bbb9f14a Merge pull request #2031 from BEDOLAGA-DEV/vb0a8m-bedolaga/expand-bot-api-for-welcome-text
Handle missing creator on user message creation
2025-11-25 01:19:15 +03:00
Egor 7c52811750 Merge pull request #2032 from BEDOLAGA-DEV/revert-2030-j1ummj-bedolaga/expand-bot-api-for-welcome-text
Revert "Expose admin APIs for welcome texts and menu messages"
2025-11-25 01:19:01 +03:00
Egor 2d4b46afbd Revert "Expose admin APIs for welcome texts and menu messages" 2025-11-25 01:18:45 +03:00
Egor 83093236fc Handle missing creator on user message creation 2025-11-25 01:18:03 +03:00
Egor 3881e7d1d5 Merge pull request #2030 from BEDOLAGA-DEV/j1ummj-bedolaga/expand-bot-api-for-welcome-text
Expose admin APIs for welcome texts and menu messages
2025-11-25 01:08:09 +03:00
Egor 1c3dbd57c5 Add API endpoints for welcome texts and menu messages 2025-11-25 01:06:05 +03:00
Egor 6f1275f291 Merge pull request #2029 from BEDOLAGA-DEV/dev5
Апи для партнерки
2025-11-25 00:58:14 +03:00
Egor cfc48ea061 Merge pull request #2028 from BEDOLAGA-DEV/vinuia-bedolaga/expand-bot-api-for-partner-section
Fix referrer listing filter for partners API
2025-11-25 00:54:20 +03:00
Egor 2679172ae4 Fix referrer query predicate 2025-11-25 00:54:05 +03:00
Egor 6a0c276454 Merge pull request #2027 from BEDOLAGA-DEV/revert-2026-fvbx51-bedolaga/expand-bot-api-for-partner-section
Revert "Fix partner routes referral imports"
2025-11-25 00:52:21 +03:00
Egor 5872e3bd3c Revert "Fix partner routes referral imports" 2025-11-25 00:52:09 +03:00
Egor f6041ab055 Merge pull request #2026 from BEDOLAGA-DEV/fvbx51-bedolaga/expand-bot-api-for-partner-section
Fix partner routes referral imports
2025-11-25 00:45:37 +03:00
Egor b5c5da552d Fix partner routes referral imports 2025-11-25 00:45:23 +03:00
Egor c093ef95ed Merge pull request #2025 from BEDOLAGA-DEV/revert-2024-f0fpo3-bedolaga/expand-bot-api-for-partner-section
Revert "Add API endpoint to update user referral commission"
2025-11-25 00:45:07 +03:00
Egor d376a25e64 Revert "Add API endpoint to update user referral commission" 2025-11-25 00:44:56 +03:00
Egor 4ec926d072 Merge pull request #2024 from BEDOLAGA-DEV/f0fpo3-bedolaga/expand-bot-api-for-partner-section
Add API endpoint to update user referral commission
2025-11-25 00:42:20 +03:00
Egor 65a7df4549 Allow updating referral commission per user via API 2025-11-25 00:42:05 +03:00
Egor 57c252dcbf Merge pull request #2023 from BEDOLAGA-DEV/revert-2022-76qz7l-bedolaga/expand-bot-api-for-partner-section
Revert "Add API to update referrer commission percent"
2025-11-25 00:41:28 +03:00
Egor 9b74b40794 Revert "Add API to update referrer commission percent" 2025-11-25 00:41:19 +03:00
Egor 0b028e1f13 Merge pull request #2022 from BEDOLAGA-DEV/76qz7l-bedolaga/expand-bot-api-for-partner-section
Add API to update referrer commission percent
2025-11-25 00:40:08 +03:00
Egor 337b948fda Add API to update referrer commission percent 2025-11-25 00:39:50 +03:00
Egor 5de187c6cd Merge pull request #2021 from BEDOLAGA-DEV/dev5
Dev5
2025-11-25 00:27:50 +03:00
Egor 7150204c71 Merge pull request #2020 from BEDOLAGA-DEV/0i4s7o-bedolaga/update-bot-api-for-notifications
Add user details to subscription event API responses
2025-11-25 00:24:58 +03:00
Egor 3d44403318 Add user info to subscription event API 2025-11-25 00:24:32 +03:00
Egor 812f3e983c Merge pull request #2018 from BEDOLAGA-DEV/dev5
Dev5
2025-11-24 08:27:34 +03:00
Egor 7549e571fe Merge pull request #2017 from BEDOLAGA-DEV/7pp9bw-bedolaga/add-setting-to-disable-support-balance-top-up
Add setting to disable support balance top-ups
2025-11-24 08:25:55 +03:00
Egor 9d3f096be0 Add toggle for support top-ups 2025-11-24 08:17:23 +03:00
Egor fd40cd3ba6 Merge pull request #2016 from BEDOLAGA-DEV/dev5
Dev5
2025-11-24 08:12:05 +03:00
Egor 1ba566f30f Merge pull request #2015 from BEDOLAGA-DEV/mz6u7a-bedolaga/fix-subscription-notification-api
Rollback DB session on subscription event logging errors
2025-11-24 07:59:39 +03:00
Egor 9b9d17b8e7 Rollback session after subscription event logging failure 2025-11-24 07:55:52 +03:00
Egor 3fee600db0 Merge pull request #2012 from BEDOLAGA-DEV/revert-2011-rrpx8s-bedolaga/add-referral-income-withdrawal-feature
Revert "Debit balance when closing referral withdrawals"
2025-11-24 07:30:05 +03:00
Egor fbb1091f8b Revert "Debit balance when closing referral withdrawals" 2025-11-24 07:29:57 +03:00
Egor 8513d67a78 Merge pull request #2011 from BEDOLAGA-DEV/rrpx8s-bedolaga/add-referral-income-withdrawal-feature
Debit balance when closing referral withdrawals
2025-11-24 07:22:18 +03:00
Egor 45ce615fbe Debit balance when closing referral withdrawal requests 2025-11-24 07:21:39 +03:00
Egor 2ab4ca5b09 Merge pull request #2010 from BEDOLAGA-DEV/revert-2009-so9oqv-bedolaga/add-referral-income-withdrawal-feature
Revert "Harden referral withdrawal template formatting"
2025-11-24 07:21:04 +03:00
Egor b229dc22ba Revert "Harden referral withdrawal template formatting" 2025-11-24 07:20:56 +03:00
Egor bf49a5c1d5 Merge pull request #2009 from BEDOLAGA-DEV/so9oqv-bedolaga/add-referral-income-withdrawal-feature
Harden referral withdrawal template formatting
2025-11-24 07:11:04 +03:00
Egor 27b6e974ab Initialize texts in admin referral stats handler 2025-11-24 07:06:14 +03:00
Egor 9f00b56be0 Merge pull request #2002 from BEDOLAGA-DEV/j33on7-bedolaga/add-individual-referral-percentage-in-user-edit
Add universal migration for referral commission column
2025-11-24 05:35:46 +03:00
Egor 05177bff92 Chain referral commission migration to latest head 2025-11-24 05:35:37 +03:00
Egor f40f233562 Add universal migration for referral commission column 2025-11-24 05:27:04 +03:00
Egor d3a351aeba Merge pull request #1992 from BEDOLAGA-DEV/dd57ir-bedolaga/fix-validation-error-in-system-stats-response
Handle fractional uptime values in system stats
2025-11-24 05:23:15 +03:00
Egor fb76d30457 Merge pull request #2001 from BEDOLAGA-DEV/revert-2000-main
Revert "Обратная синхронизация remnawave"
2025-11-24 01:20:25 +03:00
Egor afba2137d1 Revert "Обратная синхронизация remnawave" 2025-11-24 01:20:17 +03:00
Egor 9ef3ca1831 Merge pull request #2000 from Gy9vin/main
Обратная синхронизация remnawave
2025-11-24 01:14:20 +03:00
gy9vin 65ae2f5c48 Обратная синхронизация 2025-11-24 00:09:58 +03:00
Egor 2686dcd30a Merge pull request #1998 from BEDOLAGA-DEV/dev5
Dev5
2025-11-23 06:40:08 +03:00
Egor 6bc125a2f4 Merge pull request #1997 from BEDOLAGA-DEV/w16jb9-bedolaga/add-admin-panel-for-pricing-limits
Fix admin pricing callbacks for base discount settings
2025-11-23 06:37:00 +03:00
Egor 29c6e296df Escape promo discount format hint for HTML 2025-11-23 06:36:44 +03:00
Egor 3d1d064af7 Merge pull request #1996 from BEDOLAGA-DEV/revert-1995-efy4mi-bedolaga/add-admin-panel-for-pricing-limits
Revert "Fix admin pricing callbacks for base discount settings"
2025-11-23 06:36:02 +03:00
Egor ccf1f8a71d Revert "Fix admin pricing callbacks for base discount settings" 2025-11-23 06:35:53 +03:00
Egor b83a8c9df0 Merge pull request #1995 from BEDOLAGA-DEV/efy4mi-bedolaga/add-admin-panel-for-pricing-limits
Fix admin pricing callbacks for base discount settings
2025-11-23 06:29:56 +03:00
Egor a7bd94f394 Shorten admin pricing callback payloads 2025-11-23 06:29:33 +03:00
Egor 96787c27d3 Merge pull request #1994 from BEDOLAGA-DEV/revert-1993-arxkfd-bedolaga/add-admin-panel-for-pricing-limits
Revert "Add base promo group discount controls to admin pricing"
2025-11-23 06:29:11 +03:00
Egor e99c731e27 Revert "Add base promo group discount controls to admin pricing" 2025-11-23 06:29:03 +03:00
Egor 4a4b5bd8ef Merge pull request #1993 from BEDOLAGA-DEV/arxkfd-bedolaga/add-admin-panel-for-pricing-limits
Add base promo group discount controls to admin pricing
2025-11-23 06:18:05 +03:00
Egor 9d27f1aa6b Add base promo group discount controls to admin pricing 2025-11-23 06:17:45 +03:00
Egor fb010038f1 Ensure uptime seconds parsed as integer 2025-11-23 06:08:33 +03:00
Egor 700f86fe38 Merge pull request #1991 from BEDOLAGA-DEV/dev5
Dev5
2025-11-23 06:00:33 +03:00
Egor 582a8b9615 Merge pull request #1990 from BEDOLAGA-DEV/bedolaga
Apply base promo discounts to all order components
2025-11-23 05:55:48 +03:00
Egor 7c9dfc352c Apply base promo discounts to all order components 2025-11-23 05:51:30 +03:00
Egor b86d549695 Merge pull request #1989 from BEDOLAGA-DEV/dev5
Dev5
2025-11-23 04:46:13 +03:00
Egor 577f6dfd8e Merge pull request #1988 from BEDOLAGA-DEV/bedolaga-dtalt2
Add subscription events table to universal migration
2025-11-23 04:37:53 +03:00
Egor eab4cce251 Add subscription events universal migration 2025-11-23 04:33:44 +03:00
Egor 7a099ab255 Merge pull request #1987 from BEDOLAGA-DEV/dev5
Dev5
2025-11-23 04:19:34 +03:00
Egor 9fa67f61f3 Merge pull request #1986 from BEDOLAGA-DEV/bedolaga/add-/upload-endpoint-for-file-uploads-lowg6q
Proxy media downloads without exposing bot token
2025-11-23 04:19:03 +03:00
Egor 86ebff4948 Serve proxy media with detected content type 2025-11-23 04:09:04 +03:00
Egor 821ac4668f Merge pull request #1983 from BEDOLAGA-DEV/main
w
2025-11-23 03:23:33 +03:00
Egor d0280f0ab9 Merge pull request #1980 from belousotroll/add-policy-page
Add policy page at registration stage
2025-11-23 03:22:49 +03:00
belousotroll ceb45b4c0b add policy page at registration stage 2025-11-22 21:30:11 +07:00
Egor 85ea3d97ef Update README.md 2025-11-22 02:36:04 +03:00
Egor 5640041e45 Update README.md 2025-11-22 02:35:17 +03:00
Egor 1357ddc1fe Update README.md 2025-11-22 02:34:29 +03:00
Egor 0765dae178 Update README.md 2025-11-22 02:31:48 +03:00
Egor 81f2e20c08 Update README.md 2025-11-22 02:29:35 +03:00
Egor b27d34ec92 Update README.md 2025-11-22 02:24:59 +03:00
Egor e7fbbd579c Merge pull request #1977 from remnawave-contrib/ivan-nginx-manual-update
docs: update manual update instructions
2025-11-22 00:11:22 +03:00
Ivan.Nginx 7a2a82fa87 docs: update manual update instructions 2025-11-21 10:25:02 +03:00
Egor c3c105619b Update Dockerfile 2025-11-21 07:02:11 +03:00
Egor 01e575676f Update docker-registry.yml 2025-11-21 07:01:57 +03:00
Egor b53a43fcc6 Update docker-hub.yml 2025-11-21 07:01:41 +03:00
Egor 6a8ff1c1b4 Merge pull request #1976 from BEDOLAGA-DEV/dev5
Dev5
2025-11-21 06:36:35 +03:00
Egor 451ab514cc Merge pull request #1975 from BEDOLAGA-DEV/bedolaga/remove-unnecessary-chat-messages-after-balance-refill-d1pv7w
Clean up CryptoBot prompt messages
2025-11-21 06:33:34 +03:00
Egor c8b6830704 Clean up CryptoBot amount prompts 2025-11-21 06:32:34 +03:00
Egor 74ee7149c5 Merge pull request #1974 from BEDOLAGA-DEV/revert-1972-bedolaga/remove-unnecessary-chat-messages-after-balance-refill-675m3k
Revert "Fix Tribute payment prompt formatting"
2025-11-21 06:32:23 +03:00
Egor 506b96dec4 Revert "Fix Tribute payment prompt formatting" 2025-11-21 06:32:13 +03:00
Egor 927d4230a2 Merge pull request #1973 from BEDOLAGA-DEV/dev5
Dev5
2025-11-21 06:08:36 +03:00
Egor 69ff737b72 Merge pull request #1972 from BEDOLAGA-DEV/bedolaga/remove-unnecessary-chat-messages-after-balance-refill-675m3k
Fix Tribute payment prompt formatting
2025-11-21 06:05:50 +03:00
Egor d0114a1f29 Fix Tribute payment prompt editing 2025-11-21 06:03:35 +03:00
Egor f92a0fd88b Merge pull request #1971 from BEDOLAGA-DEV/revert-1969-bedolaga/remove-unnecessary-chat-messages-after-balance-refill-xitbxf
Revert "Reject YooKassa webhooks lacking payment id"
2025-11-21 06:03:14 +03:00
Egor e7478cc1e1 Revert "Reject YooKassa webhooks lacking payment id" 2025-11-21 06:03:04 +03:00
Egor 5814f9757d Merge pull request #1970 from BEDOLAGA-DEV/dev5
Dev5
2025-11-21 05:40:12 +03:00
Egor cb7b9a9e22 Merge pull request #1969 from BEDOLAGA-DEV/bedolaga/remove-unnecessary-chat-messages-after-balance-refill-xitbxf
Reject YooKassa webhooks lacking payment id
2025-11-21 05:34:23 +03:00
Egor 6dc525dd72 Handle missing YooKassa payment ids gracefully 2025-11-21 05:26:42 +03:00
Egor 409c8c161b Merge pull request #1968 from BEDOLAGA-DEV/revert-1967-bedolaga/remove-unnecessary-chat-messages-after-balance-refill-skti1r
Revert "Handle YooKassa webhook payloads without payment ids"
2025-11-21 05:26:31 +03:00
Egor 78db3a1e77 Revert "Handle YooKassa webhook payloads without payment ids" 2025-11-21 05:26:21 +03:00
Egor d0c5ff19e1 Merge pull request #1967 from BEDOLAGA-DEV/bedolaga/remove-unnecessary-chat-messages-after-balance-refill-skti1r
Handle YooKassa webhook payloads without payment ids
2025-11-21 05:17:43 +03:00
Egor 6a29765ddf Handle YooKassa webhooks without payment ids 2025-11-21 05:17:09 +03:00
Egor 95147fbe03 Merge pull request #1964 from BEDOLAGA-DEV/revert-1963-bedolaga/remove-unnecessary-chat-messages-after-balance-refill-fbz95w
Revert "Clean up Platega and YooKassa invoices after payment"
2025-11-21 04:49:30 +03:00
Egor 0137321d24 Revert "Clean up Platega and YooKassa invoices after payment" 2025-11-21 04:49:17 +03:00
Egor 0521306699 Merge pull request #1963 from BEDOLAGA-DEV/bedolaga/remove-unnecessary-chat-messages-after-balance-refill-fbz95w
Clean up Platega and YooKassa invoices after payment
2025-11-21 04:18:23 +03:00
Egor 2a10e7d2c7 Clean up Platega and YooKassa invoices after payment 2025-11-21 04:18:03 +03:00
Egor e78e9e1a4d Merge pull request #1962 from BEDOLAGA-DEV/revert-1960-bedolaga/remove-unnecessary-chat-messages-after-balance-refill-v2ldtf
Revert "Clean up Platega and YooKassa prompts"
2025-11-21 04:17:22 +03:00
Egor 29d0b54b04 Revert "Clean up Platega and YooKassa prompts" 2025-11-21 04:17:13 +03:00
Egor 64fe3fdbb7 Merge pull request #1960 from BEDOLAGA-DEV/bedolaga/remove-unnecessary-chat-messages-after-balance-refill-v2ldtf
Clean up Platega and YooKassa prompts
2025-11-21 04:02:54 +03:00
Egor 04edca175e Merge pull request #1961 from BEDOLAGA-DEV/revert-1959-bedolaga/remove-unnecessary-chat-messages-after-balance-refill-s863sv
Revert "Clean up Telegram Stars payment flow"
2025-11-21 04:02:38 +03:00
Egor 840091cb05 Revert "Clean up Telegram Stars payment flow" 2025-11-21 04:02:28 +03:00
Egor 473c3704cf Clean up Platega and YooKassa prompts 2025-11-21 04:02:22 +03:00
Egor af630b22c9 Merge pull request #1959 from BEDOLAGA-DEV/bedolaga/remove-unnecessary-chat-messages-after-balance-refill-s863sv
Clean up Telegram Stars payment flow
2025-11-21 03:27:06 +03:00
Egor 29fe2f2016 Clean up Telegram Stars payment flow 2025-11-21 03:26:34 +03:00
Egor cd5691640e Merge pull request #1958 from BEDOLAGA-DEV/revert-1957-bedolaga/remove-unnecessary-chat-messages-after-balance-refill
Revert "Clean up Telegram Stars top-up messages"
2025-11-21 03:26:03 +03:00
Egor 77c217f9ad Revert "Clean up Telegram Stars top-up messages" 2025-11-21 03:25:55 +03:00
Egor 9e963569bc Merge pull request #1957 from BEDOLAGA-DEV/bedolaga/remove-unnecessary-chat-messages-after-balance-refill
Clean up Telegram Stars top-up messages
2025-11-21 03:24:32 +03:00
Egor c7114ec359 Clean up Telegram Stars top-up messages 2025-11-21 03:24:17 +03:00
Egor b9586ad72a Merge pull request #1956 from BEDOLAGA-DEV/revert-1955-bedolaga/remove-unnecessary-messages-after-balance-update-vvw9nt
Revert "Clean up Telegram Stars top-up messages"
2025-11-21 03:18:19 +03:00
Egor b6e333127c Revert "Clean up Telegram Stars top-up messages" 2025-11-21 03:18:10 +03:00
Egor 6ea2c2cceb Merge pull request #1955 from BEDOLAGA-DEV/bedolaga/remove-unnecessary-messages-after-balance-update-vvw9nt
Clean up Telegram Stars top-up messages
2025-11-21 03:16:40 +03:00
Egor af42377c3b Clean up Telegram Stars top-up messages 2025-11-21 03:16:24 +03:00
Egor 82881a4c45 Merge pull request #1954 from BEDOLAGA-DEV/revert-1953-bedolaga/remove-unnecessary-messages-after-balance-update
Revert "Clean up Telegram Stars payment messages"
2025-11-21 03:16:12 +03:00
Egor 70d50e9c47 Revert "Clean up Telegram Stars payment messages" 2025-11-21 03:16:04 +03:00
Egor ddb5c01026 Merge pull request #1953 from BEDOLAGA-DEV/bedolaga/remove-unnecessary-messages-after-balance-update
Clean up Telegram Stars payment messages
2025-11-21 03:14:41 +03:00
Egor e287adcb84 Clean up Telegram Stars payment messages 2025-11-21 03:14:25 +03:00
Egor 83d041c13b Merge pull request #1952 from BEDOLAGA-DEV/bedolaga/fix-auto-renewal-calculation-error
Fix autopay renewal pricing for promo groups
2025-11-20 23:13:12 +03:00
Egor 545c5fd749 Eager load promo groups for autopay renewals 2025-11-20 23:12:49 +03:00
Egor 7f0e2de7c4 Merge pull request #1951 from BEDOLAGA-DEV/bedolaga/fix-subscription-check-service-errors
Handle missing channel link in subscription check
2025-11-20 23:06:53 +03:00
Egor 1fdf1e49a3 Handle missing channel link in subscription check 2025-11-20 23:06:34 +03:00
Egor 08f82ee511 Merge pull request #1950 from BEDOLAGA-DEV/bedolaga-q76r4i
Fix trial reset cleanup
2025-11-20 22:58:04 +03:00
Egor fba217b87f Fix trial reset by clearing server links 2025-11-20 22:49:57 +03:00
Egor 6668a18ad3 Merge pull request #1949 from BEDOLAGA-DEV/revert-1948-bedolaga-uhav33
Revert "Add admin trial reset controls"
2025-11-20 22:46:40 +03:00
Egor 11c239f46c Revert "Add admin trial reset controls" 2025-11-20 22:46:30 +03:00
Egor ac62dee279 Merge pull request #1948 from BEDOLAGA-DEV/bedolaga-uhav33
Add admin trial reset controls
2025-11-20 22:34:27 +03:00
Egor 29a17a7876 Add admin trial reset controls 2025-11-20 22:33:43 +03:00
Egor 694c934612 Merge pull request #1947 from BEDOLAGA-DEV/dev5
Dev5
2025-11-20 22:11:23 +03:00
Egor c01d2bfcd7 Update README.md 2025-11-20 22:09:07 +03:00
Egor b3708f99c0 Merge pull request #1943 from BEDOLAGA-DEV/bedolaga/fix-subscription-check-error-on-double-click
Handle repeat device selection without redundant updates
2025-11-20 18:39:46 +03:00
Egor f651f921aa Handle repeat device selection without redundant updates 2025-11-20 18:39:25 +03:00
Egor ada6845036 Merge pull request #1938 from BEDOLAGA-DEV/dev5
Dev5
2025-11-20 17:58:46 +03:00
Egor d33b259537 Merge pull request #1936 from BEDOLAGA-DEV/bedolaga/fix-email-dispatch-limit-to-100000-users-yvuqli
Throttle broadcast sending for large campaigns
2025-11-20 17:31:23 +03:00
Egor 3c2ed147ca Merge pull request #1937 from BEDOLAGA-DEV/revert-1934-bedolaga/fix-email-dispatch-limit-to-100000-users
Revert "Remove broadcast recipient limit"
2025-11-20 17:31:07 +03:00
Egor d46e88c2b5 Revert "Remove broadcast recipient limit" 2025-11-20 17:30:56 +03:00
Egor 1477491e6e Throttle broadcast speed for large campaigns 2025-11-20 17:30:30 +03:00
Egor 647dc0bd7c Merge pull request #1935 from BEDOLAGA-DEV/dev5
Dev5
2025-11-20 15:47:45 +03:00
Egor f6a45993e9 Merge pull request #1934 from BEDOLAGA-DEV/bedolaga/fix-email-dispatch-limit-to-100000-users
Remove broadcast recipient limit
2025-11-20 15:47:24 +03:00
Egor 0766320411 Fetch all broadcast users in batches 2025-11-20 15:36:38 +03:00
Egor 5ebf113fd6 Merge pull request #1915 from BEDOLAGA-DEV/dev4
Dev4
2025-11-20 01:30:14 +03:00
Egor 2005d103f8 Merge pull request #1914 from BEDOLAGA-DEV/bedolaga/fix-balance-top-up-through-method-10
Handle Platega description byte limit
2025-11-20 01:20:05 +03:00
Egor 3935813336 Trim Platega descriptions by byte length 2025-11-20 01:16:25 +03:00
Egor ec71fa78c0 Merge pull request #1913 from BEDOLAGA-DEV/bedolaga/fix-subscription-channel-error
Handle duplicate channel subscription prompts
2025-11-20 01:12:44 +03:00
Egor cd2b0a2d67 Handle duplicate channel subscription messages 2025-11-20 01:10:28 +03:00
Egor 68d502804f Merge pull request #1911 from BEDOLAGA-DEV/dev4
Dev4
2025-11-18 01:17:55 +03:00
Egor afbd343442 Merge pull request #1910 from BEDOLAGA-DEV/bedolaga/fix-subscription-creation-api-error-uklgqk
Preserve autopay and device limits during subscription replacement
2025-11-18 01:17:37 +03:00
Egor 991e5a3112 Preserve zero device limit when replacing trials 2025-11-18 01:14:43 +03:00
Egor 7d9de6ca5d Merge pull request #1906 from BEDOLAGA-DEV/dev4
Dev4
2025-11-18 00:28:35 +03:00
Egor 562bb69082 Merge pull request #1905 from BEDOLAGA-DEV/bedolaga/expand-bot-api-functionality
Expand admin API for polls, logs, and tickets
2025-11-18 00:27:49 +03:00
Egor a02416c78b Add poll sending and ticket API enhancements 2025-11-18 00:22:46 +03:00
Egor 81f56008d4 Delete install_bot.sh 2025-11-16 12:04:21 +03:00
Egor 43a7039479 Merge pull request #1904 from Fr1ngg/dev4
Dev4
2025-11-15 01:46:45 +03:00
Egor a9f3904524 Merge pull request #1903 from Fr1ngg/bedolaga/fix-ru-cards-payment-processing-error
Limit Platega description length
2025-11-15 00:59:45 +03:00
Egor 9136c7cfe3 Limit Platega description length 2025-11-15 00:56:11 +03:00
Egor 5595846929 Merge pull request #1902 from Fr1ngg/dev4
Dev4
2025-11-14 01:32:49 +03:00
Egor 9ebe2971bf Merge pull request #1901 from Fr1ngg/bedolaga/fix-402-error-in-subscription-renewal-endpoint
Fix renewal mixed payment logic
2025-11-14 01:31:06 +03:00
Egor fadea75314 Fix renewal mixed payment logic 2025-11-14 01:30:31 +03:00
Egor a2009cae39 Merge pull request #1899 from Fr1ngg/dev4
Allow trial users to renew from miniapp
2025-11-14 01:17:04 +03:00
Egor 0187adb6f9 Merge pull request #1898 from Fr1ngg/bedolaga/fix-trial-subscription-error-in-miniapp
Enable trial subscriptions to renew via miniapp
2025-11-14 01:16:00 +03:00
Egor 302a028873 Allow trial users to renew from miniapp 2025-11-14 00:15:43 +03:00
Egor 77c9c19806 Merge pull request #1897 from Fr1ngg/dev4
Dev4
2025-11-13 23:37:04 +03:00
Egor 724da2545e Merge pull request #1896 from Fr1ngg/main
w
2025-11-13 23:36:46 +03:00
Egor 079af66d9f Merge pull request #1895 from Fr1ngg/bedolaga/fix-subscription-purchase-failure-with-platega
Fix Platega quick amount selection flow
2025-11-13 23:36:23 +03:00
Egor e701d234f0 Fix Platega quick amount selection flow 2025-11-13 23:33:07 +03:00
Egor 1b111975bb Update config.py 2025-11-12 16:41:37 +03:00
Egor c874425e0e Merge pull request #1890 from DOFER998/c0mrade/refactor-subtract-balance-logging
refactor: improve logging level for balance subtraction debug info
2025-11-12 16:28:09 +03:00
c0mrade c6c112fd17 refactor: improve logging level for balance subtraction debug info 2025-11-12 10:21:28 +03:00
Egor 57d924e3ba Merge pull request #1889 from Fr1ngg/dev4
Доп языки + фиксы
2025-11-12 05:38:34 +03:00
Egor 9d5b9ebf82 Add files via upload 2025-11-12 05:28:39 +03:00
Egor 354358e860 Create fail.html 2025-11-12 05:28:25 +03:00
Egor 327c9d52d2 Create succes.html 2025-11-12 05:27:59 +03:00
Egor c03051614d Merge pull request #1888 from Fr1ngg/revert-1887-bedolaga/activate-trial-automatically-after-payment-le7ksb
Revert "Enable automatic trial activation after balance top-up"
2025-11-12 05:24:24 +03:00
Egor ac9e5cd908 Revert "Enable automatic trial activation after balance top-up" 2025-11-12 05:24:14 +03:00
Egor 585bb56a99 Merge pull request #1887 from Fr1ngg/bedolaga/activate-trial-automatically-after-payment-le7ksb
Enable automatic trial activation after balance top-up
2025-11-12 04:45:20 +03:00
Egor 8f33eb0cc6 Enable automatic trial activation after balance top-up 2025-11-12 04:45:03 +03:00
Egor 71515a87de Merge pull request #1886 from Fr1ngg/revert-1885-bedolaga/activate-trial-automatically-after-payment
Revert "feat: auto activate paid trials after balance top-up"
2025-11-12 04:44:54 +03:00
Egor 0a4ede8f79 Revert "feat: auto activate paid trials after balance top-up" 2025-11-12 04:44:46 +03:00
Egor 040b33b541 Merge pull request #1885 from Fr1ngg/bedolaga/activate-trial-automatically-after-payment
feat: auto activate paid trials after balance top-up
2025-11-12 04:34:06 +03:00
Egor 5c3484ee28 feat: auto activate paid trials after balance top-up 2025-11-12 04:27:33 +03:00
Egor ef309c3101 Merge pull request #1884 from Fr1ngg/bedolaga/fix-trial-subscription-display-issue
Fix trial subscription status display in menu
2025-11-12 03:09:46 +03:00
Egor 51dad7936b Fix trial subscription status display in menu 2025-11-12 03:03:34 +03:00
Egor 097734b31d Merge pull request #1883 from Fr1ngg/bedolaga/fix-user-deletion-foreign-key-violation
Handle Platega payments when deleting users
2025-11-12 02:47:54 +03:00
Egor 7185fde9bc Handle Platega payments when deleting users 2025-11-12 02:47:37 +03:00
Egor 75f2cdb04b Update remnawave.py 2025-11-12 02:41:44 +03:00
Egor d3c445ed2d Merge pull request #1882 from Fr1ngg/bedolaga/fix-webhook-issue-with-heleket
Fix Heleket webhook signature verification
2025-11-12 02:40:34 +03:00
Egor 804f088435 Fix Heleket webhook signature verification 2025-11-11 16:41:58 +03:00
Egor 6c1b70e796 Merge pull request #1881 from Fr1ngg/bedolaga/fix-403-error-on-subscription-renewal-endpoint-n1nsij
Handle CryptoBot renewal payload fallbacks
2025-11-11 13:13:14 +03:00
Egor a3532e5878 Handle CryptoBot renewal payload fallbacks 2025-11-11 13:06:10 +03:00
Egor a8c1b32912 Merge pull request #1880 from Fr1ngg/revert-1877-bedolaga/fix-403-error-on-subscription-renewal-endpoint
Revert "Allow expired miniapp subscriptions to load renewal options"
2025-11-11 12:22:29 +03:00
Egor 20b0c8a0e2 Revert "Allow expired miniapp subscriptions to load renewal options" 2025-11-11 12:22:15 +03:00
Egor bc18692d75 Merge pull request #1877 from Fr1ngg/bedolaga/fix-403-error-on-subscription-renewal-endpoint
Allow expired miniapp subscriptions to load renewal options
2025-11-11 10:46:42 +03:00
Egor c05ecf1ecd Allow expired subscriptions to access renewal options 2025-11-11 10:42:33 +03:00
Egor 8381fc52f1 Merge pull request #1876 from Fr1ngg/bedolaga/add-default-localization-support-for-flags-cen8qi
Fix dynamic traffic price recalculation in localization
2025-11-11 10:33:33 +03:00
Egor a697ffa8f1 Fix dynamic traffic localization prices 2025-11-11 10:28:09 +03:00
Egor 4eb36fab6d Merge pull request #1875 from Fr1ngg/revert-1873-bedolaga/add-default-localization-support-for-flags-ocds8i
Revert "Add dynamic localization support for UA and ZH languages"
2025-11-11 10:27:19 +03:00
Egor 4b0780b549 Revert "Add dynamic localization support for UA and ZH languages" 2025-11-11 10:27:10 +03:00
Egor 1befc2982a Merge pull request #1873 from Fr1ngg/bedolaga/add-default-localization-support-for-flags-ocds8i
Add dynamic localization support for UA and ZH languages
2025-11-11 09:10:15 +03:00
Egor df1f225405 Populate dynamic prices and support text for new locales 2025-11-11 09:07:02 +03:00
Egor df6feca53c Add files via upload 2025-11-11 08:37:03 +03:00
Egor bd41efb974 Merge pull request #1869 from Fr1ngg/main
w
2025-11-11 08:34:18 +03:00
Egor a1216bface Update README.md 2025-11-11 08:32:07 +03:00
Egor e0969b315a Merge pull request #1868 from remnawave-contrib/ivan-nginx-readme-make
Added «make» installation command to Readme
2025-11-11 08:30:06 +03:00
Ivan.Nginx 395bccf4e5 Merge branch 'Fr1ngg:main' into main 2025-11-11 08:23:02 +03:00
Ivan.Nginx f6e5cfce54 Merge pull request #2 from remnawave-contrib/ivan-nginx-readme-add-make-installation
Update installation instructions for 'make' command
2025-11-11 08:22:16 +03:00
Ivan.Nginx a26e89147b Update installation instructions for 'make' command 2025-11-11 08:21:34 +03:00
Egor 4396020177 Merge pull request #1867 from Fr1ngg/dev4
[FEAT] Add integration metadata for miniapp payment methods
2025-11-11 08:16:20 +03:00
Egor e2c89ec19e Merge pull request #1866 from Fr1ngg/bedolaga/extend-api-for-payment-method-integration-types
[FEAT] Add integration metadata for miniapp payment methods
2025-11-11 08:15:06 +03:00
Egor 68c125ba14 feat: expose integration metadata for miniapp payments 2025-11-11 08:11:42 +03:00
Egor 8c794fc91c Update README.md 2025-11-11 07:42:15 +03:00
Egor efbe8475df Update README.md 2025-11-11 07:41:43 +03:00
Egor 7835e02d5c Merge pull request #1860 from Gy9vin/main
Апи поиск в боте по тгID
2025-11-11 02:08:32 +03:00
Mikhail 21a5499af8 Merge branch 'Fr1ngg:main' into main 2025-11-10 13:54:03 +03:00
gy9vin dd85db071a Апи поиск в боте по тгID 2025-11-10 13:53:21 +03:00
Egor 813193102c Update Dockerfile 2025-11-10 06:28:50 +03:00
Egor 42112d6c8a Update docker-registry.yml 2025-11-10 06:28:40 +03:00
Egor dfe5e36fe0 Update docker-hub.yml 2025-11-10 06:28:31 +03:00
Egor b5d4a54e97 Update README.md 2025-11-10 06:22:26 +03:00
Egor 1eaf7204ce Merge pull request #1859 from Fr1ngg/dev4
fix #1849 Round CryptoBot top-up amounts up to whole rubles
2025-11-10 06:13:51 +03:00
Egor 8cc37dc439 Merge pull request #1858 from Fr1ngg/bedolaga/fix-webhook-handler-error-in-cryptobot-i1csym
Round CryptoBot top-up amounts up to whole rubles
2025-11-10 06:11:42 +03:00
Egor ccafb18122 Round CryptoBot top-up amounts up to whole rubles 2025-11-10 06:11:18 +03:00
Egor 654b132ae6 Merge pull request #1857 from Fr1ngg/revert-1855-bedolaga/fix-webhook-handler-error-in-cryptobot
Revert "Refactor CryptoBot notifications to avoid transaction rollback"
2025-11-10 06:11:05 +03:00
Egor 815fa0560c Revert "Refactor CryptoBot notifications to avoid transaction rollback" 2025-11-10 06:10:54 +03:00
Egor c4d19810a4 Merge pull request #1856 from Fr1ngg/dev4
fix
2025-11-10 06:05:55 +03:00
Egor 9fbb32eb5b Merge pull request #1855 from Fr1ngg/bedolaga/fix-webhook-handler-error-in-cryptobot
Refactor CryptoBot notifications to avoid transaction rollback
2025-11-10 05:59:09 +03:00
Egor 3ce3cde859 Refactor CryptoBot notifications to avoid transaction rollback 2025-11-10 05:53:26 +03:00
Egor 4e71dcd2b1 Merge pull request #1853 from Fr1ngg/dev4
Update Pal24 callback handling and SBP link fallback
2025-11-10 05:33:11 +03:00
Egor acf21fa6d2 Merge pull request #1852 from Fr1ngg/bedolaga/update-requirements.txt-and-fix-pal24-webhook
Update Pal24 callback handling and SBP link fallback
2025-11-10 05:29:04 +03:00
Egor f2b724a78d Adjust Pal24 callback handling and SBP link fallback 2025-11-10 05:26:02 +03:00
Egor 03473360c1 Merge pull request #1851 from Fr1ngg/dev4
Dev4
2025-11-10 04:30:16 +03:00
Egor 27dc68be41 Merge pull request #1850 from Fr1ngg/bedolaga/fix-webhook-bot-error-handling
Prevent maintenance monitoring from crashing without RemnaWave URL
2025-11-10 04:26:35 +03:00
Egor b15d78f8af Handle missing RemnaWave config in maintenance monitoring 2025-11-10 04:25:52 +03:00
Egor d232d14937 Merge pull request #1848 from Fr1ngg/dev4
fix migration on new bases
2025-11-10 04:13:19 +03:00
Egor 927d469db2 Merge pull request #1847 from Fr1ngg/bedolaga/fix-database-migration-crash-on-first-bot-launch
Handle missing tables when creating indexes during init_db
2025-11-10 04:06:46 +03:00
Egor e20e9e7cec Fix init_db index creation on fresh databases 2025-11-10 04:06:28 +03:00
Egor 0f097c3108 Merge pull request #1830 from Gy9vin/main
Фикс простой покупки!
2025-11-10 03:37:31 +03:00
gy9vin eaa3c80d59 Фикс простой покупки! 2025-11-09 21:55:58 +03:00
Egor 0c49eddfde Merge pull request #1828 from Gy9vin/main
Фикс проверки зачисления платежа юкассы(защита от дублирования)
2025-11-09 20:09:15 +03:00
gy9vin 33882f1e93 Фикс проверки зачисления платежа юкассы(защита от дублирования) 2025-11-09 18:31:39 +03:00
Egor f94666b68d Merge pull request #1826 from Fr1ngg/dev4
Dev4
2025-11-09 10:29:27 +03:00
Egor d32a49f801 Merge pull request #1825 from Fr1ngg/bedolaga/fix-bulk_update-to-include-where-clause
Fix bulk_update to target records by primary key
2025-11-09 10:29:11 +03:00
Egor 9596f82ea6 Fix bulk_update to target records by primary key 2025-11-09 10:28:47 +03:00
Egor 0e3fdf7d61 Merge pull request #1824 from Fr1ngg/dev4
Razgonchik
2025-11-09 10:24:57 +03:00
Egor 54cfec6029 Merge pull request #1823 from Fr1ngg/bedolaga/fix-repeated-yookassa-deposits-y7sxo6
Ensure YooKassa retries finish pending credits
2025-11-09 10:13:20 +03:00
Egor 9e88eae416 Ensure YooKassa retries finish pending credits 2025-11-09 10:13:01 +03:00
Egor 8d32efac73 Merge pull request #1822 from Fr1ngg/revert-1821-bedolaga/fix-repeated-yookassa-deposits
Revert "Prevent double processing of YooKassa payments"
2025-11-09 10:04:02 +03:00
Egor 9f07b6007e Revert "Prevent double processing of YooKassa payments" 2025-11-09 10:03:54 +03:00
Egor 2fb3b6c5dc Merge pull request #1821 from Fr1ngg/bedolaga/fix-repeated-yookassa-deposits
Prevent double processing of YooKassa payments
2025-11-09 10:03:38 +03:00
Egor 0637576425 Prevent double processing of YooKassa payments 2025-11-09 10:00:17 +03:00
Egor ee7a445610 Update database.py 2025-11-09 09:46:40 +03:00
Egor ba4c7ee7ac Update database.py 2025-11-09 09:43:26 +03:00
Egor 4da169eb0f Merge pull request #1819 from Fr1ngg/bedolaga/fix-health-endpoints-for-sqlite-nullpool
Handle missing pool metrics for NullPool
2025-11-09 09:40:53 +03:00
Egor 28937abab4 Handle missing pool metrics for NullPool 2025-11-09 09:40:08 +03:00
Egor b1dcf2779e Update database.py 2025-11-09 09:25:59 +03:00
Egor 3219062ce2 Update database.py 2025-11-09 09:22:36 +03:00
Egor 2ac72951f8 Merge pull request #1818 from Fr1ngg/bedolaga/add-health-and-metrics-endpoints-to-fastapi
Add database health and pool metrics endpoints
2025-11-09 09:17:35 +03:00
Egor cefb8cba78 Add database health and pool metrics endpoints 2025-11-09 09:17:18 +03:00
Egor e869655028 Update database.py 2025-11-09 09:11:47 +03:00
Egor ae03ede209 Merge pull request #1817 from Fr1ngg/dev4
Dev
2025-11-09 08:34:49 +03:00
Egor a72bb25ea2 Update database.py 2025-11-09 08:30:38 +03:00
Egor 0b22bc7056 Merge pull request #1815 from Fr1ngg/bedolaga/-nullpool-queuepool-wh494i
Handle optional Pal24 metadata fields
2025-11-09 08:24:26 +03:00
Egor cde84ff20b Handle optional Pal24 metadata fields 2025-11-09 08:23:01 +03:00
Egor f76114d7dc Update database.py 2025-11-09 08:17:43 +03:00
Egor 9708a56fd7 Update database.py 2025-11-09 08:14:41 +03:00
Egor a360337660 Merge pull request #1813 from Fr1ngg/dev4
фикс бекапов/восстановления
2025-11-09 07:39:18 +03:00
Egor 9f78335651 Merge pull request #1812 from Fr1ngg/bedolaga/improve-backup-and-restore-mechanism-1wazcg
Avoid duplicate association errors during restore
2025-11-09 07:31:17 +03:00
Egor ef8142a99b Skip duplicate squad promo associations during restore 2025-11-09 07:30:54 +03:00
Egor 06d51f9fcf Merge pull request #1811 from Fr1ngg/revert-1810-bedolaga/improve-backup-and-restore-mechanism-gn1h90
Revert "Handle PostgreSQL backups without pg_dump"
2025-11-09 07:30:41 +03:00
Egor 4d94347179 Revert "Handle PostgreSQL backups without pg_dump" 2025-11-09 07:30:31 +03:00
Egor 2f6aa0b1e6 Merge pull request #1810 from Fr1ngg/bedolaga/improve-backup-and-restore-mechanism-gn1h90
Handle PostgreSQL backups without pg_dump
2025-11-09 07:23:11 +03:00
Egor 536a58d4d3 Handle PostgreSQL backups without pg_dump 2025-11-09 07:22:50 +03:00
Egor 62f7c07059 Merge pull request #1809 from Fr1ngg/revert-1808-bedolaga/improve-backup-and-restore-mechanism
Revert "Refactor backup pipeline to use archive dumps"
2025-11-09 07:22:10 +03:00
Egor 0648edb3c4 Revert "Refactor backup pipeline to use archive dumps" 2025-11-09 07:21:56 +03:00
Egor 9b6c235424 Merge pull request #1808 from Fr1ngg/bedolaga/improve-backup-and-restore-mechanism
Refactor backup pipeline to use archive dumps
2025-11-09 07:12:18 +03:00
Egor 2fc35950cf Refactor backup system with archive dumps 2025-11-09 07:12:01 +03:00
Egor d2a5d74239 Merge pull request #1807 from Fr1ngg/dev4
Dev4
2025-11-09 07:06:24 +03:00
Egor 6b04c6748e Merge pull request #1806 from Fr1ngg/bedolaga/add-trial-activation-funds-check
Prefill top-up amount for paid trial activation
2025-11-09 06:58:03 +03:00
Egor 10b44cbdb7 Prefill top-up amount for paid trial activation 2025-11-09 06:51:50 +03:00
Egor dde04c716c Merge pull request #1805 from Fr1ngg/bedolaga/fix-variable-loading-for-minimum-sum
Adjust Platega top-up prompt to show configured limits
2025-11-09 06:44:55 +03:00
Egor 819f19a7ea Update Platega prompt to use configured limits 2025-11-09 06:44:23 +03:00
Egor e7201597ab Merge pull request #1804 from Fr1ngg/bedolaga/fix-pall24-payment-method-issue
Fix Pal24 SBP link handling after status checks
2025-11-09 06:35:54 +03:00
Egor ea61aa7053 Fix Pal24 SBP link handling after status checks 2025-11-09 06:31:02 +03:00
Egor 14546a8485 Merge pull request #1803 from Fr1ngg/bedolaga/add-ip-validation-for-yookassa-webhooks
Handle Cloudflare proxied YooKassa webhooks
2025-11-09 06:22:17 +03:00
Egor f55455761f Trust Cloudflare headers for YooKassa webhooks 2025-11-09 06:21:40 +03:00
Egor b1a7767827 Merge pull request #1802 from Fr1ngg/revert-1801-bedolaga/add-server-category-feature-to-admin-panel-ltnwjl
Revert "Fix server category button routing in admin panel"
2025-11-09 05:55:16 +03:00
Egor 43c04b7e64 Revert "Fix server category button routing in admin panel" 2025-11-09 05:55:07 +03:00
Egor add679cf6f Merge pull request #1801 from Fr1ngg/bedolaga/add-server-category-feature-to-admin-panel-ltnwjl
Fix server category button routing in admin panel
2025-11-09 05:49:00 +03:00
Egor ee173190a0 Fix category edit menu callback 2025-11-09 05:48:45 +03:00
Egor a6e21b47f6 Merge pull request #1800 from Fr1ngg/revert-1799-bedolaga/add-server-category-feature-to-admin-panel-fwofd2
Revert "Fix category pricing to ignore full squads"
2025-11-09 05:40:56 +03:00
Egor cd627e5840 Revert "Fix category pricing to ignore full squads" 2025-11-09 05:40:47 +03:00
Egor fc096e6867 Merge pull request #1799 from Fr1ngg/bedolaga/add-server-category-feature-to-admin-panel-fwofd2
Fix category pricing to ignore full squads
2025-11-09 05:33:29 +03:00
Egor b591844c4e Fix category pricing to ignore full squads 2025-11-09 05:33:13 +03:00
Egor 9557acb546 Merge pull request #1798 from Fr1ngg/revert-1797-bedolaga/add-server-category-feature-to-admin-panel
Revert "Ensure server category selection skips full squads"
2025-11-09 05:31:20 +03:00
Egor 1fa6e75bd3 Revert "Ensure server category selection skips full squads" 2025-11-09 05:31:09 +03:00
Egor 8965e43a55 Merge pull request #1797 from Fr1ngg/bedolaga/add-server-category-feature-to-admin-panel
Ensure server category selection skips full squads
2025-11-09 05:24:50 +03:00
Egor 8e7a6beece Ensure category auto-selection respects capacity 2025-11-09 05:23:58 +03:00
Egor e9f4fd8007 Merge pull request #1796 from Fr1ngg/revert-1793-bedolaga/implement-server-grouping-system-for-vpn-bot
Revert "Add server group backend selection logic"
2025-11-09 04:54:55 +03:00
Egor a991c59d58 Revert "Add server group backend selection logic" 2025-11-09 04:54:47 +03:00
Egor dd0624adf8 Merge pull request #1795 from Fr1ngg/revert-1794-bedolaga/check-functionality-for-server-grouping
Revert "Fix autopurchase server selection and RemnaWave stats handling"
2025-11-09 04:54:31 +03:00
Egor ab51cbe96a Revert "Fix autopurchase server selection and RemnaWave stats handling" 2025-11-09 04:54:24 +03:00
Egor 2f7a08deb0 Merge pull request #1794 from Fr1ngg/bedolaga/check-functionality-for-server-grouping
Fix autopurchase server selection and RemnaWave stats handling
2025-11-09 04:50:50 +03:00
Egor a0fa7f986b Fix autopurchase server selection and RemnaWave stats handling 2025-11-09 04:50:32 +03:00
Egor b2d3eebe39 Merge pull request #1793 from Fr1ngg/bedolaga/implement-server-grouping-system-for-vpn-bot
Add server group backend selection logic
2025-11-09 04:39:54 +03:00
Egor a043fc0e46 feat: add backend support for server groups 2025-11-09 04:36:33 +03:00
Egor d6eec8787e Merge pull request #1792 from Fr1ngg/bedolaga/fix-payment-methods-display-for-platega.io
Add Platega payment option to balance top-up list
2025-11-09 03:31:21 +03:00
Egor 95eee42047 Добавить Platega в список пополнения 2025-11-09 03:30:49 +03:00
Egor c673d6db4f Merge pull request #1790 from Fr1ngg/dev4
Dev4
2025-11-08 18:58:33 +03:00
Egor bb32a63d48 Merge pull request #1789 from Fr1ngg/bedolaga/fix-null-value-constraint-in-promo_groups
Fix default promo group creation with priority column
2025-11-08 18:58:13 +03:00
Egor af5acb272c Fix default promo group creation with priority column 2025-11-08 18:57:53 +03:00
Egor 5cd5ac8710 Merge pull request #1788 from Fr1ngg/revert-1787-dev4
Revert "Dev4"
2025-11-08 12:05:27 +03:00
Egor 8bb58b44b3 Revert "Dev4" 2025-11-08 12:05:12 +03:00
Egor 511ecd506f Merge pull request #1787 from Fr1ngg/dev4
Dev4
2025-11-08 11:38:41 +03:00
Egor 62fc014bc3 Restore json serialization helper for YooKassa webhook tests 2025-11-08 11:38:18 +03:00
Egor 961f564274 Merge pull request #1786 from Fr1ngg/bedolaga/fix-webhook-ip-verification-for-lcydgf
Remove YooKassa IP filtering from webhooks
2025-11-08 11:27:53 +03:00
Egor 984870c78c Remove YooKassa IP filtering from webhooks 2025-11-08 11:27:37 +03:00
Egor 6196c135d2 Merge pull request #1785 from Fr1ngg/revert-1782-bedolaga/fix-webhook-ip-verification-for-w66vvd
Revert "Verify YooKassa webhooks against API"
2025-11-08 11:27:23 +03:00
Egor bf1b8315a8 Revert "Verify YooKassa webhooks against API" 2025-11-08 11:27:13 +03:00
Egor b7eabcf7e7 Merge pull request #1784 from Fr1ngg/revert-1783-dev4
Revert "Dev4"
2025-11-08 11:08:55 +03:00
Egor e83ebc4f02 Revert "Dev4" 2025-11-08 11:08:47 +03:00
Egor 1a4758f4cc Merge pull request #1783 from Fr1ngg/dev4
Dev4
2025-11-08 11:04:08 +03:00
Egor b80e8b3804 Merge pull request #1782 from Fr1ngg/bedolaga/fix-webhook-ip-verification-for-w66vvd
Verify YooKassa webhooks against API
2025-11-08 11:00:49 +03:00
Egor e036173670 Verify YooKassa webhooks against API 2025-11-08 11:00:28 +03:00
Egor bd728c6466 Merge pull request #1781 from Fr1ngg/revert-1777-bedolaga/fix-webhook-ip-verification-for
Revert "Handle Cloudflare forwarded IPs for YooKassa webhooks"
2025-11-08 10:58:48 +03:00
Egor e3aec310a3 Revert "Handle Cloudflare forwarded IPs for YooKassa webhooks" 2025-11-08 10:58:34 +03:00
Egor 1c59ce601e Merge pull request #1780 from Fr1ngg/revert-1779-dev4
Revert "da eb tvoyu mat' kakoy pidoras delal etu ukassu "
2025-11-08 10:58:21 +03:00
Egor 0563f7524f Revert "da eb tvoyu mat' kakoy pidoras delal etu ukassu " 2025-11-08 10:58:12 +03:00
Egor cedbe07759 Merge pull request #1779 from Fr1ngg/dev4
da eb tvoyu mat' kakoy pidoras delal etu ukassu
2025-11-08 10:53:02 +03:00
Egor 0746b2a5a7 Merge pull request #1778 from Fr1ngg/main
w
2025-11-08 10:52:15 +03:00
Egor e8a72860dc Merge pull request #1777 from Fr1ngg/bedolaga/fix-webhook-ip-verification-for
Handle Cloudflare forwarded IPs for YooKassa webhooks
2025-11-08 10:51:50 +03:00
Egor abbfe4a7d3 Handle Cloudflare forwarded IPs for YooKassa webhooks 2025-11-08 10:50:56 +03:00
763 changed files with 235636 additions and 82954 deletions
+4
View File
@@ -16,6 +16,10 @@ __pycache__/
.pytest_cache/
.coverage
htmlcov/
.venv/
tests/
.mypy_cache/
.ruff_cache/
# Environment files
.env
+564 -21
View File
@@ -3,26 +3,132 @@
# ===============================================
# ===== TELEGRAM BOT =====
# Токен бота от @BotFather
# ВАЖНО: Также используется для авторизации виджета личного кабинета (Cabinet WebApp)
# через Telegram.WebApp.initData
BOT_TOKEN=
ADMIN_IDS=
# Ссылка на поддержку: Telegram username (например, @support) или полный URL
SUPPORT_USERNAME=@support
# Имя пользователя бота (опционально, автоопределяется)
# BOT_USERNAME=
# ===== СЕТЬ И ПРОКСИ =====
# 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
# Режим системы поддержки: tickets (тикеты), contact (контакт), both (оба)
SUPPORT_SYSTEM_MODE=both
# SLA для тикетов поддержки
SUPPORT_TICKET_SLA_ENABLED=false
SUPPORT_TICKET_SLA_MINUTES=60
SUPPORT_TICKET_SLA_CHECK_INTERVAL_SECONDS=300
SUPPORT_TICKET_SLA_REMINDER_COOLDOWN_MINUTES=30
# ===== ЛИЧНЫЙ КАБИНЕТ (CABINET) =====
# Включить личный кабинет пользователя (веб-интерфейс для управления подпиской)
CABINET_ENABLED=false
# URL кабинета для ссылок в email (например: https://cabinet.example.com)
CABINET_URL=
# Секретный ключ для JWT токенов (если не указан, используется BOT_TOKEN)
CABINET_JWT_SECRET=
# Время жизни access token в минутах (по умолчанию 15)
CABINET_ACCESS_TOKEN_EXPIRE_MINUTES=15
# Время жизни refresh token в днях (по умолчанию 7)
CABINET_REFRESH_TOKEN_EXPIRE_DAYS=7
# Разрешенные origins для CORS (через запятую, например: https://cabinet.example.com)
CABINET_ALLOWED_ORIGINS=
# Включить верификацию email (требует настройки SMTP)
CABINET_EMAIL_VERIFICATION_ENABLED=false
# Включить регистрацию/вход по email (если false - только Telegram)
CABINET_EMAIL_AUTH_ENABLED=true
# ===== ТЕСТОВЫЙ EMAIL ДЛЯ РАЗРАБОТКИ =====
# Тестовый email для проверки регистрации без SMTP
# При использовании этого email верификация пропускается
TEST_EMAIL=
TEST_EMAIL_PASSWORD=
# Время жизни токена верификации email в часах
CABINET_EMAIL_VERIFICATION_EXPIRE_HOURS=24
# Время жизни токена сброса пароля в часах
CABINET_PASSWORD_RESET_EXPIRE_HOURS=1
# Время жизни кода подтверждения смены email в минутах
CABINET_EMAIL_CHANGE_CODE_EXPIRE_MINUTES=15
# ===== SMTP НАСТРОЙКИ (для email в личном кабинете) =====
# SMTP сервер (например: smtp.gmail.com, smtp.yandex.ru)
SMTP_HOST=
SMTP_PORT=587
SMTP_USER=
SMTP_PASSWORD=
# Email отправителя (если не указан, используется SMTP_USER)
SMTP_FROM_EMAIL=
SMTP_FROM_NAME=VPN Service
# Использовать TLS шифрование
SMTP_USE_TLS=true
# Уведомления администраторов
ADMIN_NOTIFICATIONS_ENABLED=true
ADMIN_NOTIFICATIONS_CHAT_ID=-1001234567890 # Замени на ID твоего канала (-100) - ПРЕФИКС ЗАКРЫТОГО КАНАЛА! ВСТАВИТЬ СВОЙ ID СРАЗУ ПОСЛЕ (-100) БЕЗ ПРОБЕЛОВ!
ADMIN_NOTIFICATIONS_TOPIC_ID=123 # Опционально: ID топика
ADMIN_NOTIFICATIONS_TICKET_TOPIC_ID=126 # Опционально: ID топика для тикетов
ADMIN_NOTIFICATIONS_NALOG_TOPIC_ID=133 # Опционально: ID топика для уведомлений о чеках NaloGO
# Автоматические отчеты
ADMIN_REPORTS_ENABLED=false
ADMIN_REPORTS_CHAT_ID= # Опционально: чат для отчетов (по умолчанию ADMIN_NOTIFICATIONS_CHAT_ID)
ADMIN_REPORTS_TOPIC_ID= # ID топика для отчетов
ADMIN_REPORTS_SEND_TIME=10:00 # Время отправки (по МСК) ежедневного отчета
# Обязательная подписка на канал
CHANNEL_SUB_ID= # Опционально ID твоего канала (-100)
# ===== МОНИТОРИНГ ТРАФИКА =====
# Логика: при запуске бота создаётся snapshot трафика всех пользователей.
# Через указанный интервал проверяется дельта (разница) трафика.
# Если дельта превышает порог — отправляется уведомление админам.
# Быстрая проверка (дельта трафика за интервал)
TRAFFIC_FAST_CHECK_ENABLED=false # Включить быструю проверку
TRAFFIC_FAST_CHECK_INTERVAL_MINUTES=10 # Интервал проверки в минутах
TRAFFIC_FAST_CHECK_THRESHOLD_GB=5.0 # Порог дельты в ГБ (сколько потрачено за интервал)
# Суточная проверка (трафик за 24 часа через bandwidth API)
TRAFFIC_DAILY_CHECK_ENABLED=false # Включить суточную проверку
TRAFFIC_DAILY_CHECK_TIME=00:00 # Время суточной проверки (HH:MM по UTC)
TRAFFIC_DAILY_THRESHOLD_GB=50.0 # Порог суточного трафика в ГБ
# Куда отправлять уведомления
SUSPICIOUS_NOTIFICATIONS_TOPIC_ID=14 # ID топика для уведомлений о подозрительной активности
# Фильтрация по серверам (UUID нод через запятую)
TRAFFIC_MONITORED_NODES= # Только эти ноды (пусто = все)
TRAFFIC_IGNORED_NODES= # Исключить эти ноды
# Исключить пользователей (UUID через запятую)
TRAFFIC_EXCLUDED_USER_UUIDS= # Служебные/тунельные пользователи
# Производительность
TRAFFIC_CHECK_BATCH_SIZE=1000 # Размер батча для получения пользователей
TRAFFIC_CHECK_CONCURRENCY=10 # Параллельных запросов к API
TRAFFIC_NOTIFICATION_COOLDOWN_MINUTES=60 # Кулдаун уведомлений на пользователя (минуты)
TRAFFIC_SNAPSHOT_TTL_HOURS=24 # TTL snapshot трафика в Redis (часы, сохраняется при рестарте)
# Черный список
BLACKLIST_CHECK_ENABLED=false # Включить проверку пользователей по черному списку
BLACKLIST_GITHUB_URL=https://raw.githubusercontent.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/refs/heads/main/blacklist.txt # URL к файлу черного списка на GitHub
BLACKLIST_UPDATE_INTERVAL_HOURS=24 # Интервал обновления черного списка с GitHub (в часах)
BLACKLIST_IGNORE_ADMINS=true # Игнорировать администраторов (из ADMIN_IDS) при проверке черного списка
SUBSCRIPTION_RENEWAL_BALANCE_THRESHOLD_KOPEKS=20000 # Порог баланса (в копейках) для фильтра «готовы к продлению»
# Channel subscription settings (channels are managed via admin panel)
CHANNEL_IS_REQUIRED_SUB=false # Обязательна ли подписка на канал
CHANNEL_LINK= # Опционально ссылка на канал
CHANNEL_DISABLE_TRIAL_ON_UNSUBSCRIBE=true # Отключать триальные подписки при отписке от канала
CHANNEL_REQUIRED_FOR_ALL=false # Требовать подписку на канал для ВСЕХ пользователей (платных и триальных)
# ===== DATABASE CONFIGURATION =====
# Режим базы данных: "auto", "postgresql", "sqlite"
@@ -44,13 +150,16 @@ LOCALES_PATH=./locales
# Redis
REDIS_URL=redis://redis:6379/0
# Время жизни корзины пользователя в Redis (секунды, по умолчанию 1 час)
CART_TTL_SECONDS=3600
# ===== REMNAWAVE API =====
REMNAWAVE_API_URL=https://panel.example.com
REMNAWAVE_API_KEY=your_api_key_here
# Тип авторизации: "api_key", "basic_auth"
# Тип авторизации: "api_key", "basic_auth", "caddy"
REMNAWAVE_AUTH_TYPE=api_key
REMNAWAVE_CADDY_TOKEN=
# Для панелей с Basic Auth (опционально)
REMNAWAVE_USERNAME=
@@ -80,11 +189,94 @@ REMNAWAVE_USER_USERNAME_TEMPLATE="user_{telegram_id}"
# disable - только деактивировать пользователя
REMNAWAVE_USER_DELETE_MODE=delete
# Автоматическая синхронизация пользователей с панелью Remnawave
REMNAWAVE_AUTO_SYNC_ENABLED=false
# Времена синхронизации (через запятую, формат HH:MM по МСК)
REMNAWAVE_AUTO_SYNC_TIMES=03:00
# ===== REMNAWAVE WEBHOOKS (входящие события из панели) =====
# Включить приём вебхуков от панели Remnawave (real-time события)
REMNAWAVE_WEBHOOK_ENABLED=false
# Путь для приёма вебхуков (должен совпадать с настройкой в панели)
REMNAWAVE_WEBHOOK_PATH=/remnawave-webhook
# Общий секрет для подписи HMAC-SHA256 (минимум 32 символа)
# Сгенерируйте: openssl rand -hex 32
# ВАЖНО: этот же секрет указывается в панели Remnawave при создании вебхука
REMNAWAVE_WEBHOOK_SECRET=
# Уведомления администраторам о потере/восстановлении связи с нодами
# false = не отправлять события node.connection_lost / node.connection_restored
REMNAWAVE_WEBHOOK_NOTIFY_NODE_CONNECTION_STATUS=true
# ===== УВЕДОМЛЕНИЯ ОТ ВЕБХУКОВ (что получают пользователи) =====
# Глобальный переключатель уведомлений пользователям от вебхуков
WEBHOOK_NOTIFY_USER_ENABLED=true
# Отключение/активация подписки администратором
WEBHOOK_NOTIFY_SUB_STATUS=true
# Истечение подписки
WEBHOOK_NOTIFY_SUB_EXPIRED=true
# Предупреждения о скором истечении (72ч, 48ч, 24ч)
WEBHOOK_NOTIFY_SUB_EXPIRING=true
# Достижение лимита трафика
WEBHOOK_NOTIFY_SUB_LIMITED=true
# Сброс счётчика трафика
WEBHOOK_NOTIFY_TRAFFIC_RESET=true
# Удаление пользователя из панели
WEBHOOK_NOTIFY_SUB_DELETED=true
# Обновление ключей подписки (revoke)
WEBHOOK_NOTIFY_SUB_REVOKED=true
# Первое подключение к VPN
WEBHOOK_NOTIFY_FIRST_CONNECTED=true
# Напоминание о неподключении
WEBHOOK_NOTIFY_NOT_CONNECTED=true
# Предупреждение о приближении к лимиту трафика
WEBHOOK_NOTIFY_BANDWIDTH_THRESHOLD=true
# Подключение и отключение устройств
WEBHOOK_NOTIFY_DEVICES=true
# Теги пользователей в Remnawave (A-Z, 0-9, _, макс. 16 символов)
# Тег для пробных пользователей (опционально)
# TRIAL_USER_TAG=TRIAL
# Тег для платных пользователей (опционально)
# PAID_SUBSCRIPTION_USER_TAG=PAID
# ========= ПОДПИСКИ =========
# ===== РЕЖИМ ПРОДАЖ =====
# Режим продаж подписок (можно переключить в кабинете: Настройки → Подписки):
# "classic" - классический режим:
# - Пользователь выбирает период, серверы, трафик, устройства отдельно
# - Цены периодов берутся из PERIOD_PRICES ниже
# - Подходит для гибкой настройки под каждого пользователя
# "tariffs" - режим тарифов:
# - Пользователь выбирает готовый тариф (Premium, Basic и т.д.)
# - Тарифы создаются в кабинете: Админ → Тарифы
# - Каждый тариф имеет свои серверы, трафик, устройства и цены за периоды
# - Подходит для продажи готовых пакетов услуг
SALES_MODE=tariffs
# Управление сменой тарифа (для SALES_MODE=tariffs)
# UPGRADE / DOWNGRADE:
# true / true = все направления разрешены
# true / false = только повышение (на более дорогой тариф)
# false / true = только понижение (на более дешёвый тариф)
# false / false = смена тарифа полностью отключена
TARIFF_SWITCH_UPGRADE_ENABLED=true
TARIFF_SWITCH_DOWNGRADE_ENABLED=true
# Сброс привязанных устройств при продлении подписки (однократно при каждом продлении)
RESET_DEVICES_ON_RENEWAL=false
# ===== ТРИАЛ ПОДПИСКА =====
TRIAL_DURATION_DAYS=3
TRIAL_TRAFFIC_LIMIT_GB=10
TRIAL_DEVICE_LIMIT=1
# ID тарифа для триала в режиме тарифов (0 = использовать стандартные настройки триала)
# Если указан ID тарифа, параметры триала берутся из тарифа (traffic_limit_gb, device_limit, allowed_squads)
# Длительность триала всё равно берётся из TRIAL_DURATION_DAYS
TRIAL_TARIFF_ID=0
# Платный триал: если TRIAL_ACTIVATION_PRICE > 0, триал становится платным
# Цена в копейках (1000 = 10 рублей). Пользователь может оплатить триал любым методом оплаты.
# TRIAL_PAYMENT_ENABLED опционален (для обратной совместимости)
TRIAL_PAYMENT_ENABLED=false
TRIAL_ACTIVATION_PRICE=0
@@ -92,7 +284,7 @@ TRIAL_ACTIVATION_PRICE=0
# Сколько устройств доступно по дефолту при покупке платной подписки
DEFAULT_DEVICE_LIMIT=3
# Максимум устройств достопных к покупке (0 = Нет лимита)
# Максимум устройств доступных к покупке (0 = Нет лимита)
MAX_DEVICES_LIMIT=15
# Дефолт параметры для подписок выданных через админку
@@ -116,15 +308,36 @@ TRAFFIC_SELECTION_MODE=selectable
# 0 = безлимит
FIXED_TRAFFIC_LIMIT_GB=100
# ===== ДОКУПКА ТРАФИКА =====
# Включить/выключить функцию докупки трафика к существующей подписке
TRAFFIC_TOPUP_ENABLED=true
# Показывать кнопку "Докупить трафик" в меню
BUY_TRAFFIC_BUTTON_VISIBLE=true
# Пакеты для докупки трафика (формат: "гб:цена_в_копейках:enabled")
# Пустая строка = использовать TRAFFIC_PACKAGES_CONFIG
# Пример: "10:5000:true,25:10000:true,50:15000:true,100:25000:true"
TRAFFIC_TOPUP_PACKAGES_CONFIG=
# ===== СБРОС ТРАФИКА =====
# Режим расчета цены сброса трафика:
# "period" - фиксированная цена = стоимость периода 30 дней (старое поведение, может быть абьюзом!)
# "traffic" - цена = стоимость текущего пакета трафика подписки
# "traffic_with_purchased" - цена = стоимость базового + докупленного трафика (рекомендуется)
TRAFFIC_RESET_PRICE_MODE=traffic_with_purchased
# Базовая цена сброса в копейках (0 = использовать PERIOD_PRICES[30])
# Используется как минимальная цена или фиксированная в режиме "period"
TRAFFIC_RESET_BASE_PRICE=0
# ===== ПЕРИОДЫ ПОДПИСКИ =====
# Доступные периоды подписки (через запятую)
# Возможные значения: 14,30,60,90,180,360
AVAILABLE_SUBSCRIPTION_PERIODS=30,90,180
AVAILABLE_RENEWAL_PERIODS=30,90,180
# ===== НАСТРОЙКИ ПРОСТОЙ ПОКУПКИ =====
# Включить упрощённую покупку из меню
SIMPLE_SUBSCRIPTION_ENABLED=false
# ===== ПРОСТАЯ ПОКУПКА ПОДПИСКИ =====
SIMPLE_SUBSCRIPTION_ENABLED=true
# Стандартный период (должен совпадать с одним из AVAILABLE_SUBSCRIPTION_PERIODS)
SIMPLE_SUBSCRIPTION_PERIOD_DAYS=30
# Сколько устройств выдаётся в рамках простой подписки
@@ -152,6 +365,8 @@ BASE_PROMO_GROUP_PERIOD_DISCOUNTS=60:10,90:20,180:40,360:70
# Выводимые пакеты трафика и их цены в копейках
TRAFFIC_PACKAGES_CONFIG="5:2000:false,10:3500:false,25:7000:false,50:11000:true,100:15000:true,250:17000:false,500:19000:false,1000:19500:true,0:0:true"
# Цена за безлимитный трафик (в копейках)
PRICE_TRAFFIC_UNLIMITED=20000
# Цена за дополнительное устройство (DEFAULT_DEVICE_LIMIT идет бесплатно!)
PRICE_PER_DEVICE=10000
@@ -160,19 +375,63 @@ DEVICES_SELECTION_ENABLED=true
# Единое количество устройств для режима без выбора (0 — не назначать устройства)
DEVICES_SELECTION_DISABLED_AMOUNT=0
# ===== МОДЕМ =====
# Включить функционал подключения модема
MODEM_ENABLED=false
# Цена модема в копейках за месяц (добавляется к ежемесячному платежу)
MODEM_PRICE_PER_MONTH=10000
# Скидки на модем за длительный срок: "месяцев:процент,месяцев:процент"
# Пример: 3 мес = 15%, 6 мес = 20%, 12 мес = 25%
MODEM_PERIOD_DISCOUNTS=3:15,6:20,12:25
# Отключение превью ссылок в сообщениях бота
DISABLE_WEB_PAGE_PREVIEW=false
# ===== РЕФЕРАЛЬНАЯ СИСТЕМА =====
REFERRAL_PROGRAM_ENABLED=true
REFERRAL_MINIMUM_TOPUP_KOPEKS=10000
REFERRAL_FIRST_TOPUP_BONUS_KOPEKS=10000
REFERRAL_INVITER_BONUS_KOPEKS=10000
REFERRAL_COMMISSION_PERCENT=25
# Макс. кол-во платежей реферала, с которых начисляется комиссия (0 = без лимита)
REFERRAL_MAX_COMMISSION_PAYMENTS=0
# Показывать раздел партнёрки в кабинете
REFERRAL_PARTNER_SECTION_VISIBLE=true
# Уведомления
REFERRAL_NOTIFICATIONS_ENABLED=true
REFERRAL_NOTIFICATION_RETRY_ATTEMPTS=3
# ===== ВЫВОД РЕФЕРАЛЬНОГО БАЛАНСА =====
# Включить функцию вывода реферального баланса
REFERRAL_WITHDRAWAL_ENABLED=false
# Минимальная сумма вывода в копейках (по умолчанию 50000 = 500₽)
REFERRAL_WITHDRAWAL_MIN_AMOUNT_KOPEKS=50000
# Интервал между запросами на вывод (дни)
REFERRAL_WITHDRAWAL_COOLDOWN_DAYS=30
# Текст-подсказка для поля реквизитов при выводе (пустая строка = стандартный текст)
REFERRAL_WITHDRAWAL_REQUISITES_TEXT=
# Выводить только реферальный баланс (true) или весь баланс (false)
REFERRAL_WITHDRAWAL_ONLY_REFERRAL_BALANCE=true
# ID топика для уведомлений о заявках на вывод (0 = основной чат)
REFERRAL_WITHDRAWAL_NOTIFICATIONS_TOPIC_ID=0
# Тестовый режим (позволяет админам тестировать функционал)
REFERRAL_WITHDRAWAL_TEST_MODE=false
# Настройки анализа на подозрительную активность
# Минимальная сумма депозита от реферала для анализа (в копейках)
REFERRAL_WITHDRAWAL_SUSPICIOUS_MIN_DEPOSIT_KOPEKS=100000
# Максимум пополнений от одного реферала в месяц
REFERRAL_WITHDRAWAL_SUSPICIOUS_MAX_DEPOSITS_PER_MONTH=10
# Коэффициент подозрительности (пополнено в X раз больше, чем потрачено)
REFERRAL_WITHDRAWAL_SUSPICIOUS_NO_PURCHASES_RATIO=3
# ===== АВТОПРОДЛЕНИЕ =====
# Глобально включить/выключить функцию автопродления (false = функция скрыта)
ENABLE_AUTOPAY=false
# Дни до окончания подписки, когда отправлять предупреждение (через запятую)
AUTOPAY_WARNING_DAYS=3,1
# Включить автопродление для новых пользователей по умолчанию
DEFAULT_AUTOPAY_ENABLED=true
DEFAULT_AUTOPAY_DAYS_BEFORE=3
MIN_BALANCE_FOR_AUTOPAY_KOPEKS=10000
@@ -212,6 +471,12 @@ YOOKASSA_VAT_CODE=1
# 4 - НДС 20%
# 5 - НДС 10/110
# 6 - НДС 20/120
# 7 - НДС 5%
# 8 - НДС 7%
# 9 - НДС 5/105
# 10 - НДС 7/107
# 11 - НДС 22%
# 12 - НДС 22/122
YOOKASSA_PAYMENT_MODE=full_payment
# Способы расчета:
@@ -243,22 +508,38 @@ YOOKASSA_PAYMENT_SUBJECT=service
YOOKASSA_WEBHOOK_PATH=/yookassa-webhook
YOOKASSA_WEBHOOK_HOST=0.0.0.0
YOOKASSA_WEBHOOK_PORT=8082
# Доверенные сети для webhook (IP-адреса YooKassa, через запятую)
# YOOKASSA_TRUSTED_PROXY_NETWORKS=185.71.76.0/24,185.71.77.0/24
# Лимиты сумм пополнения через YooKassa (в копейках)
YOOKASSA_MIN_AMOUNT_KOPEKS=5000
YOOKASSA_MAX_AMOUNT_KOPEKS=1000000
# Быстрый выбор суммы пополнения через YooKassa
YOOKASSA_QUICK_AMOUNT_SELECTION_ENABLED=true
# Рекуррентные платежи YooKassa (автосохранение карты для автоплатежей)
YOOKASSA_RECURRENT_ENABLED=false
# true = карта сохраняется обязательно, false = пользователь решает (чекбокс на стороне YooKassa)
YOOKASSA_RECURRENT_REQUIRED=true
# Отключить отображение кнопок выбора суммы пополнения (оставить только ввод вручную)
DISABLE_TOPUP_BUTTONS=false
# Отключить пополнение баланса через поддержку
SUPPORT_TOPUP_ENABLED=true
# Автоматическая проверка зависших пополнений и повторные обращения к провайдерам
PAYMENT_VERIFICATION_AUTO_CHECK_ENABLED=false
# Интервал (в минутах) между автоматическими проверками пополнений
PAYMENT_VERIFICATION_AUTO_CHECK_INTERVAL_MINUTES=10
# ===== НАЛОГОВАЯ СЛУЖБА (NaloGO) =====
# Автоматическая отправка чеков в налоговую при пополнении баланса
NALOGO_ENABLED=false
NALOGO_INN= # ИНН самозанятого
NALOGO_PASSWORD= # Пароль от личного кабинета налоговой
NALOGO_DEVICE_ID= # Опционально: ID устройства для авторизации
NALOGO_STORAGE_PATH=./nalogo_tokens.json # Путь к файлу с токенами
NALOGO_QUEUE_CHECK_INTERVAL=300 # Интервал проверки очереди чеков (секунды)
NALOGO_QUEUE_RECEIPT_DELAY=3 # Задержка между отправкой чеков (секунды)
NALOGO_QUEUE_MAX_ATTEMPTS=10 # Максимум попыток отправки одного чека
# NALOGO_PROXY_URL=socks5://127.0.0.1:1080 # SOCKS прокси для nalog.ru (если не задан — используется PROXY_URL)
# ===== НАСТРОЙКИ ОПИСАНИЙ ПЛАТЕЖЕЙ =====
# Эти настройки позволяют изменить описания платежей,
# чтобы избежать блокировок платежных систем
@@ -306,13 +587,21 @@ MULENPAY_SHOP_ID=<ID магазина>
# необязательно, есть дефолтные значения
MULENPAY_BASE_URL=https://mulenpay.ru/api
MULENPAY_WEBHOOK_PATH=/mulenpay-webhook
# Название кнопки в интерфейсе
MULENPAY_DISPLAY_NAME=Mulen Pay
MULENPAY_DESCRIPTION="Пополнение баланса"
# Запрещённые ключевые слова в display_name (КАЗИНО, СТАВКИ и т.п. — блокируются Mulenpay)
# DISPLAY_NAME_BANNED_KEYWORDS=КАЗИНО,СТАВКИ,CASINO,BET,1XBET
MULENPAY_LANGUAGE=ru
MULENPAY_VAT_CODE=0
MULENPAY_PAYMENT_SUBJECT=4
MULENPAY_PAYMENT_MODE=4
MULENPAY_MIN_AMOUNT_KOPEKS=10000
MULENPAY_MAX_AMOUNT_KOPEKS=10000000
# Ожидаемый origin для iframe (опционально, для безопасности)
# MULENPAY_IFRAME_EXPECTED_ORIGIN=https://mulenpay.ru
# URL для редиректа после оплаты (по умолчанию WEBHOOK_URL)
# MULENPAY_WEBSITE_URL=https://your-cabinet-url.com
# PAYPALYCH / PAL24
PAL24_ENABLED=false
@@ -321,7 +610,6 @@ PAL24_SHOP_ID=
PAL24_SIGNATURE_TOKEN=
PAL24_BASE_URL=https://pal24.pro/api/v1/
PAL24_WEBHOOK_PATH=/pal24-webhook
PAL24_WEBHOOK_PORT=8084
PAL24_PAYMENT_DESCRIPTION="Пополнение баланса"
PAL24_MIN_AMOUNT_KOPEKS=10000
PAL24_MAX_AMOUNT_KOPEKS=100000000
@@ -336,25 +624,207 @@ PLATEGA_ENABLED=false
PLATEGA_MERCHANT_ID=
PLATEGA_SECRET=
PLATEGA_BASE_URL=https://app.platega.io
# Название кнопки в интерфейсе
PLATEGA_DISPLAY_NAME=Platega
PLATEGA_RETURN_URL=
PLATEGA_FAILED_URL=
PLATEGA_CURRENCY=RUB
# Список ID активных методов из кабинета Platega (через запятую)
PLATEGA_ACTIVE_METHODS=2,10,11,12,13
PLATEGA_MIN_AMOUNT_KOPEKS=10000
PLATEGA_ACTIVE_METHODS=2,11,12,13
PLATEGA_MIN_AMOUNT_KOPEKS=100
PLATEGA_MAX_AMOUNT_KOPEKS=100000000
PLATEGA_WEBHOOK_PATH=/platega-webhook
PLATEGA_WEBHOOK_HOST=0.0.0.0
PLATEGA_WEBHOOK_PORT=8086
# ===== FREEKASSA =====
FREEKASSA_ENABLED=false
FREEKASSA_SHOP_ID=
FREEKASSA_API_KEY=
# Секретное слово 1 (для формы оплаты)
FREEKASSA_SECRET_WORD_1=
# Секретное слово 2 (для webhook)
FREEKASSA_SECRET_WORD_2=
FREEKASSA_DISPLAY_NAME=Freekassa
FREEKASSA_CURRENCY=RUB
FREEKASSA_MIN_AMOUNT_KOPEKS=10000
FREEKASSA_MAX_AMOUNT_KOPEKS=100000000
FREEKASSA_PAYMENT_TIMEOUT_SECONDS=3600
FREEKASSA_WEBHOOK_PATH=/freekassa-webhook
FREEKASSA_WEBHOOK_HOST=0.0.0.0
FREEKASSA_WEBHOOK_PORT=8088
# Способ оплаты: пусто = форма выбора, 42 = обычный СБП, 44 = NSPK СБП
FREEKASSA_PAYMENT_SYSTEM_ID=
# Использовать API для создания заказов (обязательно для NSPK СБП)
FREEKASSA_USE_API=false
# Раздельные методы оплаты (отображаются как отдельные кнопки)
# СБП (QR код) — i=44
FREEKASSA_SBP_ENABLED=false
FREEKASSA_SBP_DISPLAY_NAME=СБП (QR код)
# Карты РФ — i=36
FREEKASSA_CARD_ENABLED=false
FREEKASSA_CARD_DISPLAY_NAME=Карта РФ
# ===== KASSA AI (api.fk.life) =====
# Отдельная платёжная система, работает параллельно с Freekassa
KASSA_AI_ENABLED=false
KASSA_AI_SHOP_ID=
KASSA_AI_API_KEY=
# Секретное слово 2 (для webhook)
KASSA_AI_SECRET_WORD_2=
KASSA_AI_DISPLAY_NAME=KassaAI
KASSA_AI_CURRENCY=RUB
KASSA_AI_MIN_AMOUNT_KOPEKS=10000
KASSA_AI_MAX_AMOUNT_KOPEKS=100000000
KASSA_AI_WEBHOOK_PATH=/kassa-ai-webhook
KASSA_AI_WEBHOOK_HOST=0.0.0.0
KASSA_AI_WEBHOOK_PORT=8089
# Способ оплаты: 44 = СБП (QR), 36 = Карты РФ, 43 = SberPay
KASSA_AI_PAYMENT_SYSTEM_ID=44
# ===== RIOPAY (api.riopay.online) =====
RIOPAY_ENABLED=false
RIOPAY_API_TOKEN=
# Ключ для HMAC-SHA512 верификации вебхуков (если не указан, используется RIOPAY_API_TOKEN)
RIOPAY_WEBHOOK_SECRET=
RIOPAY_DISPLAY_NAME=RioPay
RIOPAY_CURRENCY=RUB
RIOPAY_MIN_AMOUNT_KOPEKS=10000
RIOPAY_MAX_AMOUNT_KOPEKS=100000000
RIOPAY_WEBHOOK_PATH=/riopay-webhook
# URL для редиректа после оплаты (опционально)
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
WATA_ACCESS_TOKEN=
WATA_TERMINAL_PUBLIC_ID=
WATA_PAYMENT_DESCRIPTION=Пополнение баланса
# Тип платежа: card, sbp, all
WATA_PAYMENT_TYPE=all
WATA_SUCCESS_REDIRECT_URL=
WATA_FAIL_REDIRECT_URL=
WATA_LINK_TTL_MINUTES=60
WATA_MIN_AMOUNT_KOPEKS=10000
WATA_MAX_AMOUNT_KOPEKS=10000000
WATA_REQUEST_TIMEOUT=30
WATA_WEBHOOK_PATH=/wata-webhook
WATA_WEBHOOK_HOST=0.0.0.0
WATA_WEBHOOK_PORT=8087
# Кэширование публичного ключа WATA (секунды)
WATA_PUBLIC_KEY_CACHE_SECONDS=3600
# URL для получения публичного ключа (опционально)
# WATA_PUBLIC_KEY_URL=
# ===== CLOUDPAYMENTS =====
CLOUDPAYMENTS_ENABLED=false
CLOUDPAYMENTS_PUBLIC_ID=
CLOUDPAYMENTS_API_SECRET=
# URL API CloudPayments
CLOUDPAYMENTS_API_URL=https://api.cloudpayments.ru
# URL виджета оплаты
CLOUDPAYMENTS_WIDGET_URL=https://widget.cloudpayments.ru/show
CLOUDPAYMENTS_DESCRIPTION=Пополнение баланса
CLOUDPAYMENTS_CURRENCY=RUB
CLOUDPAYMENTS_MIN_AMOUNT_KOPEKS=10000
CLOUDPAYMENTS_MAX_AMOUNT_KOPEKS=10000000
CLOUDPAYMENTS_WEBHOOK_PATH=/cloudpayments-webhook
CLOUDPAYMENTS_WEBHOOK_HOST=0.0.0.0
CLOUDPAYMENTS_WEBHOOK_PORT=8089
# URL для возврата после оплаты (опционально)
# CLOUDPAYMENTS_RETURN_URL=
# Скин виджета: mini, classic, modern
CLOUDPAYMENTS_SKIN=mini
CLOUDPAYMENTS_REQUIRE_EMAIL=false
CLOUDPAYMENTS_TEST_MODE=false
# ===== ИНТЕРФЕЙС И UX =====
# Включить логотип для всех сообщений (true - с изображением, false - только текст)
ENABLE_LOGO_MODE=true
LOGO_FILE=vpn_logo.png
# Режим главного меню (default - классический режим работы бота, text - режим работы с активным ЛК MiniApp, отключает покупку/управление подпиской в меню, заменяет все кнопками открытия в MiniApp ЛК)
# Режим главного меню:
# default - классический режим работы бота (все кнопки внутри Telegram)
# cabinet - режим Cabinet с активным ЛК MiniApp, кнопки ведут на конкретные
# разделы кабинета (/balance, /subscription, /referral и т.д.)
# Требует MINIAPP_CUSTOM_URL
# Алиасы для обратной совместимости: text, text_only, minimal
MAIN_MENU_MODE=default
# Стиль кнопок в режиме Cabinet (Bot API 9.4):
# primary - синий
# success - зелёный
# danger - красный
# (пустое) - цвета по умолчанию для каждой секции
CABINET_BUTTON_STYLE=
# Включить управление меню через API (позволяет динамически менять структуру кнопок)
MENU_LAYOUT_ENABLED=false
# Скрыть блок с ссылкой подключения в разделе с информацией о подписке
HIDE_SUBSCRIPTION_LINK=false
@@ -365,11 +835,13 @@ HIDE_SUBSCRIPTION_LINK=false
# miniapp_custom - открывает заданную ссылку в мини-приложении (режим 3)
# link - Открывает ссылку напрямую в браузере (режим 4)
# happ_cryptolink - Вывод cryptoLink ссылки на подписку Happ (режим 5)
CONNECT_BUTTON_MODE=guide
CONNECT_BUTTON_MODE=miniapp_subscription
# URL для режима miniapp_custom (обязателен при CONNECT_BUTTON_MODE=miniapp_custom)
MINIAPP_CUSTOM_URL=
MINIAPP_STATIC_PATH=miniapp
# URL для редиректа на страницу покупки в мини-приложении (опционально)
# MINIAPP_PURCHASE_URL=
MINIAPP_SERVICE_NAME_EN=Bedolaga VPN
MINIAPP_SERVICE_NAME_RU=Bedolaga VPN
MINIAPP_SERVICE_DESCRIPTION_EN=Secure & Fast Connection
@@ -381,6 +853,8 @@ HAPP_DOWNLOAD_LINK_IOS=
HAPP_DOWNLOAD_LINK_ANDROID=
HAPP_DOWNLOAD_LINK_MACOS=
HAPP_DOWNLOAD_LINK_WINDOWS=
# Универсальная ссылка для ПК (если MACOS и WINDOWS не заданы отдельно)
HAPP_DOWNLOAD_LINK_PC=
# Кнопка (Подключится) с редиректом (тк ссылки с happ:// тг не поддерживает) - Без установленной ссылки на редирект кнопки (подключится) не будет! Пример: https://sub.domain.sub/redirect-page/?redirect_to=
HAPP_CRYPTOLINK_REDIRECT_TEMPLATE=
@@ -428,18 +902,33 @@ MAINTENANCE_MESSAGE=Ведутся технические работы. Серв
# ===== ЛОКАЛИЗАЦИЯ =====
# Укажите язык из AVAILABLE_LANGUAGES. При некорректном значении используется ru.
DEFAULT_LANGUAGE=ru
AVAILABLE_LANGUAGES=ru,en
AVAILABLE_LANGUAGES=ru,en,ua,zh,fa
# Включить выбор языка при старте и отображение кнопки в меню
LANGUAGE_SELECTION_ENABLED=true
# Округление цен при отображении (≤50 коп вниз, >50 коп вверх)
# true: 14.78₽ → 15₽, 14.12₽ → 14₽
# false: показывать точные суммы с копейками
PRICE_ROUNDING_ENABLED=true
# Часовой пояс
TZ=Europe/Moscow # или UTC, America/New_York и т.д.
# ===== ДОПОЛНИТЕЛЬНЫЕ НАСТРОЙКИ =====
# Конфигурация приложений для гайда подключения
APP_CONFIG_PATH=app-config.json
ENABLE_DEEP_LINKS=true
APP_CONFIG_CACHE_TTL=3600
# ===== BAN SYSTEM INTEGRATION (BedolagaBan) =====
# Интеграция с системой мониторинга банов BedolagaBan
# Включить интеграцию с Ban системой
BAN_SYSTEM_ENABLED=false
# URL API сервера Ban системы (например: http://ban-server:8000)
BAN_SYSTEM_API_URL=
# API токен для авторизации в Ban системе
BAN_SYSTEM_API_TOKEN=
# Таймаут запросов к API (секунды)
BAN_SYSTEM_REQUEST_TIMEOUT=30
# ===== СИСТЕМА БЕКАПОВ =====
BACKUP_AUTO_ENABLED=true
BACKUP_INTERVAL_HOURS=24
@@ -456,6 +945,8 @@ BACKUP_SEND_ENABLED=true
BACKUP_SEND_CHAT_ID=-100123456789 # Замени на ID твоего канала (-100) - ПРЕФИКС ЗАКРЫТОГО КАНАЛА!
# ВСТАВИТЬ СВОЙ ID СРАЗУ ПОСЛЕ (-100) БЕЗ ПРОБЕЛОВ!
BACKUP_SEND_TOPIC_ID=123 # Опционально: ID топика
# Пароль для архива бекапа (опционально). Если задан - бекап отправляется в зашифрованном ZIP с AES
BACKUP_ARCHIVE_PASSWORD=
# ===== ПРОВЕРКА ОБНОВЛЕНИЙ БОТА =====
VERSION_CHECK_ENABLED=true
@@ -465,25 +956,77 @@ VERSION_CHECK_INTERVAL_HOURS=1
# ===== ЛОГИРОВАНИЕ =====
LOG_LEVEL=INFO
LOG_FILE=logs/bot.log
# ANSI-цвета в консоли (true — цветной вывод с Rich, false — plain-text)
LOG_COLORS=true
# === Ротация логов ===
# Включить новую систему ротации (по умолчанию старое поведение)
LOG_ROTATION_ENABLED=false
# Время ротации (HH:MM)
LOG_ROTATION_TIME=00:00
# Хранить архивы N дней
LOG_ROTATION_KEEP_DAYS=7
# Сжимать архивы gzip
LOG_ROTATION_COMPRESS=true
# Отправлять архивы в Telegram-канал
LOG_ROTATION_SEND_TO_TELEGRAM=false
# Канал для логов (если не задан, используется BACKUP_SEND_CHAT_ID)
LOG_ROTATION_CHAT_ID=
# Топик в канале (если не задан, используется BACKUP_SEND_TOPIC_ID)
LOG_ROTATION_TOPIC_ID=
# Пути к лог-файлам (при LOG_ROTATION_ENABLED=true)
LOG_DIR=logs
LOG_INFO_FILE=info.log
LOG_WARNING_FILE=warning.log
LOG_ERROR_FILE=error.log
LOG_PAYMENTS_FILE=payments.log
# ===== РАЗРАБОТКА =====
DEBUG=false
WEBHOOK_URL=
WEBHOOK_PATH=/webhook
WEBHOOK_SECRET_TOKEN=
# IP адрес сервера для setWebhook — Telegram будет использовать его напрямую без DNS резолва домена
# Необходимо в регионах где Telegram не может резолвить домены (РФ и др.)
# WEBHOOK_IP=
WEBHOOK_DROP_PENDING_UPDATES=true
WEBHOOK_MAX_QUEUE_SIZE=1024
WEBHOOK_WORKERS=4
WEBHOOK_ENQUEUE_TIMEOUT=0.1
WEBHOOK_WORKER_SHUTDOWN_TIMEOUT=30.0
BOT_RUN_MODE=polling # polling, webhook или both
BOT_RUN_MODE=polling # polling или webhook
# ===== КОНКУРСНАЯ СИСТЕМА =====
CONTESTS_ENABLED=false
CONTESTS_BUTTON_VISIBLE=false
# Реферальные конкурсы (турниры среди рефералов)
REFERRAL_CONTESTS_ENABLED=false
# ===== АВТОПОКУПКА ПОСЛЕ ПОПОЛНЕНИЯ =====
# Автоматическая покупка из сохранённой корзины после пополнения баланса
AUTO_PURCHASE_AFTER_TOPUP_ENABLED=false
# ===== КНОПКА АКТИВАЦИИ =====
ACTIVATE_BUTTON_VISIBLE=false
# ACTIVATE_BUTTON_TEXT=активировать
# ===== ЕДИНЫЙ ВЕБ-СЕРВЕР =====
WEB_API_ENABLED=false
WEB_API_HOST=0.0.0.0
WEB_API_PORT=8080
# Количество воркеров (для продакшена рекомендуется 2-4)
WEB_API_WORKERS=1
WEB_API_ALLOWED_ORIGINS=*
WEB_API_DOCS_ENABLED=false
# Название и версия API (для документации)
WEB_API_TITLE=Remnawave Bot Admin API
WEB_API_VERSION=1.0.0
# Токен по умолчанию для начальной настройки
WEB_API_DEFAULT_TOKEN=
WEB_API_DEFAULT_TOKEN_NAME=Bootstrap Token
# Алгоритм хеширования токенов
WEB_API_TOKEN_HASH_ALGORITHM=sha256
# Логирование запросов
WEB_API_REQUEST_LOGGING=true
MINIAPP_STATIC_PATH=miniapp
Binary file not shown.

After

Width:  |  Height:  |  Size: 850 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 822 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

+13 -11
View File
@@ -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="v2.6.1-$(git rev-parse --short HEAD)"
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="v2.6.1-dev-$(git rev-parse --short HEAD)"
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="v2.6.1-pr-$(git rev-parse --short HEAD)"
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 "==========================="
+11 -8
View File
@@ -14,7 +14,7 @@ on:
env:
REGISTRY: ghcr.io
IMAGE_NAME: fr1ngg/remnawave-bedolaga-telegram-bot
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-push:
@@ -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="v2.6.1-$(git rev-parse --short HEAD)"
VERSION="v${BASE_VERSION}-${SHORT_SHA}"
echo "🚀 Building main version: $VERSION"
elif [[ $GITHUB_REF == refs/heads/dev ]]; then
VERSION="v2.6.1-dev-$(git rev-parse --short HEAD)"
VERSION="v${BASE_VERSION}-dev-${SHORT_SHA}"
echo "🧪 Building dev version: $VERSION"
else
VERSION="v2.6.1-pr-$(git rev-parse --short HEAD)"
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"
+27
View File
@@ -0,0 +1,27 @@
name: Lint
on:
push:
branches: ['**']
pull_request:
branches: ['**']
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v5
- uses: actions/setup-python@v5
with:
python-version: '3.13'
- run: uv sync --group dev
- name: Check formatting
run: uv run ruff format --check .
- name: Check linting
run: uv run ruff check .
+24
View File
@@ -0,0 +1,24 @@
name: Release Please
on:
push:
branches:
- main
permissions:
contents: write
pull-requests: write
jobs:
release-please:
runs-on: ubuntu-latest
outputs:
release_created: ${{ steps.release.outputs.release_created }}
tag_name: ${{ steps.release.outputs.tag_name }}
version: ${{ steps.release.outputs.version }}
steps:
- uses: googleapis/release-please-action@v4
id: release
with:
config-file: release-please-config.json
manifest-file: .release-please-manifest.json
+168
View File
@@ -0,0 +1,168 @@
name: Release
on:
push:
tags:
- 'v*'
permissions:
contents: write
jobs:
lint:
uses: ./.github/workflows/lint.yml
release:
needs: lint
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get previous tag
id: prev_tag
run: |
PREV_TAG=$(git describe --tags --abbrev=0 ${{ github.ref_name }}^ 2>/dev/null || echo "")
echo "tag=$PREV_TAG" >> $GITHUB_OUTPUT
- name: Generate changelog
id: changelog
run: |
TAG="${{ github.ref_name }}"
PREV_TAG="${{ steps.prev_tag.outputs.tag }}"
if [ -z "$PREV_TAG" ]; then
RANGE="$TAG"
else
RANGE="${PREV_TAG}..${TAG}"
fi
# Collect commits by category
FEATURES=$(git log $RANGE --pretty=format:"%s|%an|%h" --no-merges | grep -iE "^feat" || true)
FIXES=$(git log $RANGE --pretty=format:"%s|%an|%h" --no-merges | grep -iE "^fix" || true)
PERF=$(git log $RANGE --pretty=format:"%s|%an|%h" --no-merges | grep -iE "^perf|^refactor" || true)
DOCS=$(git log $RANGE --pretty=format:"%s|%an|%h" --no-merges | grep -iE "^docs|^style" || true)
CHORE=$(git log $RANGE --pretty=format:"%s|%an|%h" --no-merges | grep -iE "^chore|^ci|^build|^test" || true)
OTHER=$(git log $RANGE --pretty=format:"%s|%an|%h" --no-merges | grep -ivE "^(feat|fix|perf|refactor|docs|style|chore|ci|build|test)" || true)
# Collect unique contributors
CONTRIBUTORS=$(git log $RANGE --pretty=format:"%an" --no-merges | sort -u)
# Stats
TOTAL_COMMITS=$(git log $RANGE --oneline --no-merges | wc -l | tr -d ' ')
FILES_CHANGED=$(git diff --stat $RANGE 2>/dev/null | tail -1 || echo "N/A")
# Format function
format_section() {
local commits="$1"
if [ -n "$commits" ]; then
echo "$commits" | while IFS='|' read -r msg author hash; do
# Clean conventional commit prefix
clean_msg=$(echo "$msg" | sed -E 's/^(feat|fix|perf|refactor|docs|style|chore|ci|build|test)(\([^)]*\))?:\s*//')
echo "- ${clean_msg} (\`${hash}\`) — @${author}"
done
fi
}
# Build changelog
{
echo "changelog<<CHANGELOG_EOF"
if [ -n "$FEATURES" ]; then
echo "### New Features"
echo ""
format_section "$FEATURES"
echo ""
fi
if [ -n "$FIXES" ]; then
echo "### Bug Fixes"
echo ""
format_section "$FIXES"
echo ""
fi
if [ -n "$PERF" ]; then
echo "### Performance & Refactoring"
echo ""
format_section "$PERF"
echo ""
fi
if [ -n "$DOCS" ]; then
echo "### Documentation & Style"
echo ""
format_section "$DOCS"
echo ""
fi
if [ -n "$CHORE" ]; then
echo "### Maintenance"
echo ""
format_section "$CHORE"
echo ""
fi
if [ -n "$OTHER" ]; then
echo "### Other Changes"
echo ""
format_section "$OTHER"
echo ""
fi
echo "---"
echo ""
echo "### Contributors"
echo ""
if [ -n "$CONTRIBUTORS" ]; then
echo "$CONTRIBUTORS" | while read -r name; do
echo "- @${name}"
done
fi
echo ""
echo "### Stats"
echo ""
echo "- **Commits:** ${TOTAL_COMMITS}"
echo "- **Changes:** ${FILES_CHANGED}"
if [ -n "$PREV_TAG" ]; then
echo "- **Full diff:** [\`${PREV_TAG}...${TAG}\`](https://github.com/${{ github.repository }}/compare/${PREV_TAG}...${TAG})"
fi
echo "CHANGELOG_EOF"
} >> $GITHUB_OUTPUT
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
name: ${{ github.ref_name }}
body: |
## What's Changed
${{ steps.changelog.outputs.changelog }}
---
### Docker
```bash
# Docker Hub
docker pull fr1ngg/remnawave-bedolaga-telegram-bot:${{ github.ref_name }}
# GitHub Container Registry
docker pull ghcr.io/${{ github.repository }}:${{ github.ref_name }}
```
### Update
```bash
# Docker Compose
docker compose pull && docker compose up -d
# Or with Make
make reload
```
draft: false
prerelease: ${{ contains(github.ref_name, 'beta') || contains(github.ref_name, 'alpha') || contains(github.ref_name, 'rc') || contains(github.ref_name, 'dev') }}
generate_release_notes: false
+86 -22
View File
@@ -1,37 +1,101 @@
# Игнорируем все файлы и папки по умолчанию
*
docker-compose.override.yml
# Исключения: разрешаем только нужные файлы
# ========== WHITELIST: разрешённые файлы ==========
# Конфигурация проекта
!.dockerignore
!.env.example
!install_bot.sh
!.gitignore
!.python-version
!Dockerfile
!app-config.json
!main.py
!docker-compose.yml
!docker-compose.local.yml
!Makefile
!pyproject.toml
!uv.lock
!requirements.txt
!docs/
!docs/**
!alembic.ini
!release-please-config.json
!.release-please-manifest.json
# Документация
!README.md
!LICENSE
!CONTRIBUTING.md
!SECURITY.md
# Скрипты
!install_bot.sh
!main.py
# Статические файлы
!vpn_logo.png
# ========== WHITELIST: разрешённые папки ==========
# Разрешаем папку app/ и все её содержимое рекурсивно
!app/
!app/**
!tests/
!tests/**
!migrations/
!migrations/**
!docs/
!docs/**
!assets/
!assets/**
!locales/
!locales/**
!.github/
!.github/**
# Дополнительно разрешаем README и лицензию (опционально)
!README.md
!LICENSE
# ========== BLACKLIST: игнорируемые внутри папок ==========
# Разрешаем .gitignore чтобы он попал в репозиторий
!.gitignore
# Python
__pycache__/
**/__pycache__/
*.py[cod]
*$py.class
*.so
# Внутри разрешенных папок игнорируем служебные файлы
app/__pycache__/
app/**/__pycache__/
app/**/*.pyc
app/**/*.pyo
app/**/*.pyd
*.pyc
*.pyo
*.pyd
# Virtual environments
.venv/
venv/
ENV/
# IDE
.idea/
.vscode/
*.swp
*.swo
*~
# Build/dist
build/
dist/
*.egg-info/
.eggs/
# Testing/coverage
.coverage
htmlcov/
.pytest_cache/
.mypy_cache/
.ruff_cache/
# Local overrides (не коммитить!)
docker-compose.override.yml
.env
.env.local
.env.*.local
# Runtime data
logs/
data/
*.log
*.db
*.sqlite3
# OS files
.DS_Store
Thumbs.db
+1
View File
@@ -0,0 +1 @@
3.13
+3
View File
@@ -0,0 +1,3 @@
{
".": "3.54.0"
}
+2173
View File
File diff suppressed because it is too large Load Diff
+19 -32
View File
@@ -197,28 +197,17 @@ async def create_subscription(
### Документация кода
```python
async def calculate_subscription_price(
period_days: int,
traffic_gb: int,
devices_count: int,
servers_count: int
) -> int:
"""
Рассчитывает стоимость подписки.
Args:
period_days: Период подписки в днях
traffic_gb: Лимит трафика в ГБ (0 = безлимит)
devices_count: Количество устройств
servers_count: Количество серверов
Returns:
Стоимость в копейках
Raises:
ValueError: Если переданы некорректные параметры
"""
# implementation
from app.services.pricing_engine import PricingEngine
pricing = PricingEngine.calculate_renewal_price(
subscription=subscription,
period_days=30,
user=user,
)
# pricing.final_total — стоимость в копейках
# pricing.original_total — цена до скидок
# pricing.promo_group_discount — скидка промогруппы
# pricing.promo_offer_discount — скидка промо-оффера
```
### Обработка ошибок
@@ -341,20 +330,18 @@ python main.py
### Тестирование компонентов
```python
# tests/test_subscription_service.py
# tests/services/test_pricing_engine.py
import pytest
from app.services.subscription_service import SubscriptionService
from app.services.pricing_engine import PricingEngine
@pytest.mark.asyncio
async def test_calculate_price():
price = await SubscriptionService.calculate_subscription_price(
def test_calculate_renewal_price():
pricing = PricingEngine.calculate_renewal_price(
subscription=mock_subscription,
period_days=30,
traffic_gb=100,
devices_count=3,
servers_count=1
user=mock_user,
)
assert price > 0
assert isinstance(price, int)
assert pricing.final_total > 0
assert isinstance(pricing.final_total, int)
```
### Integration тесты
+17 -17
View File
@@ -4,27 +4,27 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
&& rm -rf /var/lib/apt/lists/*
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY --from=ghcr.io/astral-sh/uv:0.10.8 /uv /uvx /bin/
COPY requirements.txt .
ENV UV_COMPILE_BYTECODE=1 \
UV_LINK_MODE=copy \
UV_PYTHON_DOWNLOADS=never
RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir -r requirements.txt
WORKDIR /app
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
--mount=type=bind,source=uv.lock,target=uv.lock \
uv sync --frozen --no-dev
FROM python:3.13-slim
ARG VERSION="v2.6.1"
ARG VERSION="v3.54.0" # x-release-please-version
ARG BUILD_DATE
ARG VCS_REF
RUN apt-get update && apt-get install -y --no-install-recommends \
wget \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get clean
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY --from=builder /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH"
RUN groupadd -g 1000 app && \
useradd -u 1000 -g 1000 -m -s /bin/bash app
@@ -33,8 +33,8 @@ WORKDIR /app
COPY --chown=app:app . .
RUN mkdir -p logs data && \
chown -R app:app /app logs data
RUN mkdir -p logs data uploads/images uploads/videos uploads/thumbnails locales && \
chown -R app:app logs data uploads locales
USER app
@@ -56,7 +56,7 @@ LABEL org.opencontainers.image.title="Bedolaga RemnaWave Bot" \
org.opencontainers.image.url="https://github.com/fr1ngg/remnawave-bedolaga-telegram-bot" \
org.opencontainers.image.vendor="fr1ngg"
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')" || exit 1
CMD ["python", "main.py"]
+25
View File
@@ -1,3 +1,28 @@
"Commons Clause" License Condition v1.0
The Software is provided to you by the Licensor under the License,
as defined below, subject to the following condition.
Without limiting other conditions in the License, the grant of rights
under the License will not include, and the License does not grant to
you, the right to Sell the Software.
For purposes of the foregoing, "Sell" means practicing any or all of
the rights granted to you under the License to provide to third parties,
for a fee or other consideration (including without limitation fees for
hosting or consulting/support services related to the Software), a
product or service whose value derives, entirely or substantially, from
the functionality of the Software.
Any license notice or attribution required by the License must also
include this Commons Clause License Condition notice.
Software: remnawave-bedolaga-telegram-bot
License: MIT
Licensor: Fr1ngg
---
MIT License
Copyright (c) 2025 Fr1ngg
+31 -5
View File
@@ -25,15 +25,41 @@ reload-follow: ## Перезапустить контейнеры с логам
.PHONY: test
test: ## Запустить тесты
@echo "🧪 Запускаем тесты..."
pytest -v
uv run pytest -v
.PHONY: lint
lint: ## Проверить код (ruff check)
uv run ruff check .
.PHONY: format
format: ## Форматировать код (ruff format)
uv run ruff format .
.PHONY: fix
fix: ## Исправить код (ruff check --fix + format)
uv run ruff check . --fix
uv run ruff format .
.PHONY: migrate
migrate: ## Применить миграции (alembic upgrade head)
uv run alembic upgrade head
.PHONY: migration
migration: ## Создать миграцию (usage: make migration m="description")
uv run alembic revision --autogenerate -m "$(m)"
.PHONY: migrate-stamp
migrate-stamp: ## Пометить БД как актуальную (для существующих БД)
uv run alembic stamp head
.PHONY: migrate-history
migrate-history: ## Показать историю миграций
uv run alembic history --verbose
.PHONY: help
help: ## Показать список доступных команд
@echo ""
@echo "📘 Команды Makefile:"
@echo ""
@grep -E '^[a-zA-Z0-9_-]+:.*?##' $(MAKEFILE_LIST) | \
sed -E 's/:.*?## /| /' | \
awk -F'|' '{printf " \033[36m%-16s\033[0m %s\n", $$1, $$2}'
@awk -F':.*## ' '/^[a-zA-Z0-9_-]+:.*## / {printf " \033[36m%-16s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@echo ""
+300 -1335
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -2,7 +2,7 @@
script_location = migrations/alembic
prepend_sys_path = .
version_path_separator = os
sqlalchemy.url = postgresql+asyncpg://vpn_user:your_password@localhost:5432/vpn_bot
sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]
-658
View File
@@ -1,658 +0,0 @@
{
"config": {
"additionalLocales": [
"ru",
"zh",
"fa"
],
"branding": {
"name": "Subscription",
"logoUrl": "https://raw.githubusercontent.com/Fr1ngg/remnawave-bedolaga-telegram-bot/bf0c1ce711a26fa2f24559e7e4443820e68d758b/assets/bedolaga_app3.svg",
"supportUrl": "https://t.me"
}
},
"platforms": {
"ios": [
{
"id": "happ",
"name": "Happ",
"isFeatured": true,
"urlScheme": "happ://add/",
"installationStep": {
"buttons": [
{
"buttonLink": "https://apps.apple.com/us/app/happ-proxy-utility/id6504287215",
"buttonText": {
"en": "Open in App Store [EU]",
"fa": "باز کردن در App Store [EU]",
"ru": "Открыть в App Store [EU]",
"zh": "在 App Store 中打开 [EU]"
}
},
{
"buttonLink": "https://apps.apple.com/ru/app/happ-proxy-utility-plus/id6746188973",
"buttonText": {
"en": "Open in App Store [RU]",
"fa": "باز کردن در App Store [RU]",
"ru": "Открыть в App Store [RU]",
"zh": "在 App Store 中打开 [RU]"
}
}
],
"description": {
"en": "Open the page in App Store and install the app. Launch it, in the VPN configuration permission window click Allow and enter your passcode.",
"fa": "صفحه را در App Store باز کنید و برنامه را نصب کنید. آن را اجرا کنید، در پنجره مجوز پیکربندی VPN روی Allow کلیک کنید و رمز عبور خود را وارد کنید.",
"ru": "Откройте страницу в App Store и установите приложение. Запустите его, в окне разрешения VPN-конфигурации нажмите Allow и введите свой пароль.",
"zh": "在 App Store 中打开页面并安装应用。启动应用后,在 VPN 配置权限窗口中点击\"允许\"并输入您的密码。"
}
},
"addSubscriptionStep": {
"description": {
"en": "Click the button below — the app will open and the subscription will be added automatically",
"fa": "برای افزودن خودکار اشتراک روی دکمه زیر کلیک کنید - برنامه باز خواهد شد",
"ru": "Нажмите кнопку ниже — приложение откроется, и подписка добавится автоматически.",
"zh": "点击下方按钮 — 应用将打开并自动添加订阅"
}
},
"connectAndUseStep": {
"description": {
"en": "In the main section, click the large power button in the center to connect to VPN. Don't forget to select a server from the server list. If needed, choose another server from the server list.",
"fa": "در بخش اصلی، دکمه بزرگ روشن/خاموش در مرکز را برای اتصال به VPN کلیک کنید. فراموش نکنید که یک سرور را از لیست سرورها انتخاب کنید. در صورت نیاز، سرور دیگری را از لیست سرورها انتخاب کنید.",
"ru": "В главном разделе нажмите большую кнопку включения в центре для подключения к VPN. Не забудьте выбрать сервер в списке серверов. При необходимости выберите другой сервер из списка серверов.",
"zh": "在主界面中,点击中央的大电源按钮连接到 VPN。别忘了从服务器列表中选择一个服务器。如有需要,可从服务器列表中选择其他服务器。"
}
}
},
{
"id": "streisand",
"name": "Streisand",
"isFeatured": false,
"urlScheme": "streisand://import/",
"installationStep": {
"buttons": [
{
"buttonLink": "https://apps.apple.com/ru/app/streisand/id6450534064",
"buttonText": {
"en": "Open in App Store",
"fa": "باز کردن در App Store",
"ru": "Открыть в App Store",
"zh": "在 App Store 中打开"
}
}
],
"description": {
"en": "Open the page in App Store and install the app. Launch it, in the VPN configuration permission window click Allow and enter your passcode.",
"fa": "صفحه را در App Store باز کنید و برنامه را نصب کنید. آن را اجرا کنید، در پنجره مجوز پیکربندی VPN روی Allow کلیک کنید و رمز عبور خود را وارد کنید.",
"ru": "Откройте страницу в App Store и установите приложение. Запустите его, в окне разрешения VPN-конфигурации нажмите Allow и введите свой пароль.",
"zh": "在 App Store 中打开页面并安装应用。启动应用后,在 VPN 配置权限窗口中点击\"允许\"并输入您的密码。"
}
},
"addSubscriptionStep": {
"description": {
"en": "Click the button below — the app will open and the subscription will be added automatically",
"fa": "برای افزودن خودکار اشتراک روی دکمه زیر کلیک کنید - برنامه باز خواهد شد",
"ru": "Нажмите кнопку ниже — приложение откроется, и подписка добавится автоматически.",
"zh": "点击下方按钮 — 应用将打开并自动添加订阅"
}
},
"connectAndUseStep": {
"description": {
"en": "In the main section, click the large power button in the center to connect to VPN. Don't forget to select a server from the server list. If needed, choose another server from the server list.",
"fa": "در بخش اصلی، دکمه بزرگ روشن/خاموش در مرکز را برای اتصال به VPN کلیک کنید. فراموش نکنید که یک سرور را از لیست سرورها انتخاب کنید. در صورت نیاز، سرور دیگری را از لیست سرورها انتخاب کنید.",
"ru": "В главном разделе нажмите большую кнопку включения в центре для подключения к VPN. Не забудьте выбрать сервер в списке серверов. При необходимости выберите другой сервер из списка серверов.",
"zh": "在主界面中,点击中央的大电源按钮连接到 VPN。别忘了从服务器列表中选择一个服务器。如有需要,可从服务器列表中选择其他服务器。"
}
}
},
{
"id": "shadowrocket",
"name": "Shadowrocket",
"isFeatured": false,
"urlScheme": "sub://",
"isNeedBase64Encoding": true,
"installationStep": {
"buttons": [
{
"buttonLink": "https://apps.apple.com/ru/app/shadowrocket/id932747118",
"buttonText": {
"en": "Open in App Store",
"fa": "باز کردن در App Store",
"ru": "Открыть в App Store",
"zh": "在 App Store 中打开"
}
}
],
"description": {
"en": "Open the page in App Store and install the app. Launch it, in the VPN configuration permission window click Allow and enter your passcode.",
"fa": "صفحه را در App Store باز کنید و برنامه را نصب کنید. آن را اجرا کنید، در پنجره مجوز پیکربندی VPN روی Allow کلیک کنید و رمز عبور خود را وارد کنید.",
"ru": "Откройте страницу в App Store и установите приложение. Запустите его, в окне разрешения VPN-конфигурации нажмите Allow и введите свой пароль.",
"zh": "在 App Store 中打开页面并安装应用。启动应用后,在 VPN 配置权限窗口中点击\"允许\"并输入您的密码。"
}
},
"addSubscriptionStep": {
"description": {
"en": "Click the button below — the app will open and the subscription will be added automatically",
"fa": "برای افزودن خودکار اشتراک روی دکمه زیر کلیک کنید - برنامه باز خواهد شد",
"ru": "Нажмите кнопку ниже — приложение откроется, и подписка добавится автоматически.",
"zh": "点击下方按钮 — 应用将打开并自动添加订阅"
}
},
"connectAndUseStep": {
"description": {
"en": "In the main section, click the large power button in the center to connect to VPN. Don't forget to select a server from the server list. If needed, choose another server from the server list.",
"fa": "در بخش اصلی، دکمه بزرگ روشن/خاموش در مرکز را برای اتصال به VPN کلیک کنید. فراموش نکنید که یک سرور را از لیست سرورها انتخاب کنید. در صورت نیاز، سرور دیگری را از لیست سرورها انتخاب کنید.",
"ru": "В главном разделе нажмите большую кнопку включения в центре для подключения к VPN. Не забудьте выбрать сервер в списке серверов. При необходимости выберите другой сервер из списка серверов.",
"zh": "在主界面中,点击中央的大电源按钮连接到 VPN。别忘了从服务器列表中选择一个服务器。如有需要,可从服务器列表中选择其他服务器。"
}
}
}
],
"android": [
{
"id": "happ",
"name": "Happ",
"isFeatured": true,
"urlScheme": "happ://add/",
"installationStep": {
"buttons": [
{
"buttonLink": "https://play.google.com/store/apps/details?id=com.happproxy",
"buttonText": {
"en": "Open in Google Play",
"fa": "باز کردن در Google Play",
"ru": "Открыть в Google Play",
"zh": "在 Google Play 中打开"
}
},
{
"buttonLink": "https://github.com/Happ-proxy/happ-android/releases/latest/download/Happ.apk",
"buttonText": {
"en": "Download APK",
"fa": "دانلود APK",
"ru": "Скачать APK",
"zh": "下载 APK"
}
}
],
"description": {
"en": "Open the page in Google Play and install the app. Or install the app directly from the APK file if Google Play is not working.",
"fa": "صفحه را در Google Play باز کنید و برنامه را نصب کنید. یا برنامه را مستقیماً از فایل APK نصب کنید، اگر Google Play کار نمی کند.",
"ru": "Откройте страницу в Google Play и установите приложение. Или установите приложение из APK файла напрямую, если Google Play не работает.",
"zh": "在 Google Play 中打开页面并安装应用。如果 Google Play 无法使用,也可以直接从 APK 文件安装应用。"
}
},
"addSubscriptionStep": {
"description": {
"en": "Click the button below to add subscription",
"fa": "برای افزودن اشتراک روی دکمه زیر کلیک کنید",
"ru": "Нажмите кнопку ниже, чтобы добавить подписку",
"zh": "点击下方按钮添加订阅"
}
},
"connectAndUseStep": {
"description": {
"en": "Open the app and connect to the server",
"fa": "برنامه را باز کنید و به سرور متصل شوید",
"ru": "Откройте приложение и подключитесь к серверу",
"zh": "打开应用并连接到服务器"
}
}
},
{
"id": "clash-meta",
"name": "Clash Meta",
"isFeatured": false,
"urlScheme": "clash://install-config?url=",
"installationStep": {
"buttons": [
{
"buttonLink": "https://github.com/MetaCubeX/ClashMetaForAndroid/releases/download/v2.11.7/cmfa-2.11.7-meta-universal-release.apk",
"buttonText": {
"en": "Download APK",
"fa": "دانلود APK",
"ru": "Скачать APK",
"zh": "下载 APK"
}
},
{
"buttonLink": "https://f-droid.org/packages/com.github.metacubex.clash.meta/",
"buttonText": {
"en": "Open in F-Droid",
"fa": "در F-Droid باز کنید",
"ru": "Открыть в F-Droid",
"zh": "在 F-Droid 中打开"
}
}
],
"description": {
"en": "Download and install Clash Meta APK",
"fa": "دانلود و نصب Clash Meta APK",
"ru": "Скачайте и установите Clash Meta APK",
"zh": "下载并安装 Clash Meta APK"
}
},
"addSubscriptionStep": {
"description": {
"en": "Tap the button to import configuration",
"fa": "برای وارد کردن پیکربندی روی دکمه ضربه بزنید",
"ru": "Нажмите кнопку, чтобы импортировать конфигурацию",
"zh": "点击按钮导入配置"
}
},
"connectAndUseStep": {
"description": {
"en": "Open Clash Meta and tap on Connect",
"fa": "Clash Meta را باز کنید و روی اتصال ضربه بزنید",
"ru": "Откройте Clash Meta и нажмите Подключиться",
"zh": "打开 Clash Meta 并点击连接"
}
}
}
],
"macos": [
{
"id": "clash-verge",
"name": "Clash Verge",
"isFeatured": true,
"urlScheme": "clash://install-config?url=",
"installationStep": {
"buttons": [
{
"buttonLink": "https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v2.2.2/Clash.Verge_2.2.2_x64-setup.exe",
"buttonText": {
"en": "Windows",
"fa": "ویندوز",
"ru": "Windows",
"zh": "Windows"
}
},
{
"buttonLink": "https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v2.2.2/Clash.Verge_2.2.2_x64.dmg",
"buttonText": {
"en": "macOS (Intel)",
"fa": "مک (اینتل)",
"ru": "macOS (Intel)",
"zh": "macOS (Intel)"
}
},
{
"buttonLink": "https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v2.2.2/Clash.Verge_2.2.2_aarch64.dmg",
"buttonText": {
"en": "macOS (Apple Silicon)",
"fa": "مک (Apple Silicon)",
"ru": "macOS (Apple Silicon)",
"zh": "macOS (Apple Silicon)"
}
},
{
"buttonLink": "https://github.com/clash-verge-rev/clash-verge-rev/releases",
"buttonText": {
"en": "Linux",
"fa": "لینوکس",
"ru": "Linux",
"zh": "Linux"
}
}
],
"description": {
"en": "Choose the version for your device, click the button below and install the app.",
"fa": "نسخه مناسب برای دستگاه خود را انتخاب کنید، دکمه زیر را فشار دهید و برنامه را نصب کنید",
"ru": "Выберите подходящую версию для вашего устройства, нажмите на кнопку ниже и установите приложение.",
"zh": "选择适合您设备的版本,点击下方按钮并安装应用。"
}
},
"additionalBeforeAddSubscriptionStep": {
"buttons": [],
"description": {
"en": "After launching the app, you can change the language in settings. In the left panel, find the gear icon, then navigate to Verge 设置 and select 语言设置.",
"fa": "پس از راه‌اندازی برنامه، می‌توانید زبان را در تنظیمات تغییر دهید. در پنل سمت چپ، نماد چرخ دنده را پیدا کنید، سپس به Verge 设置 بروید و 语言设置 را انتخاب کنید.",
"ru": "После запуска приложения вы можете сменить язык в настройках. В левой панели найдите иконку шестеренки, далее ориентируйтесь на Verge 设置 и выберите пункт 语言设置.",
"zh": "启动应用后,您可以在设置中更改语言。在左侧面板找到齿轮图标,然后导航到 Verge 设置并选择语言设置。"
},
"title": {
"en": "Change language",
"fa": "تغییر زبان",
"ru": "Смена языка",
"zh": "更改语言"
}
},
"addSubscriptionStep": {
"description": {
"en": "Click the button below to add subscription",
"fa": "برای افزودن اشتراک روی دکمه زیر کلیک کنید",
"ru": "Нажмите кнопку ниже, чтобы добавить подписку",
"zh": "点击下方按钮添加订阅"
}
},
"additionalAfterAddSubscriptionStep": {
"buttons": [],
"title": {
"en": "If the subscription is not added",
"fa": "اگر اشتراک در برنامه نصب نشده است",
"ru": "Если подписка не добавилась",
"zh": "如果订阅未添加"
},
"description": {
"en": "If nothing happens after clicking the button, add the subscription manually. Click the Get Link button in the top right corner of this page, copy the link. In Clash Verge, go to the Profiles section and paste the link in the text field, then click the Import button.",
"fa": "اگر پس از کلیک روی دکمه اتفاقی نیفتاد، اشتراک را به صورت دستی اضافه کنید. در گوشه بالا سمت راست این صفحه روی دکمه دریافت لینک کلیک کنید، لینک را کپی کنید. در Clash Verge به بخش پروفایل‌ها بروید و لینک را در فیلد متنی وارد کنید، سپس روی دکمه وارد کردن کلیک کنید.",
"ru": "Если после нажатия на кнопку ничего не произошло, добавьте подписку вручную. Нажмите на этой страницу кнопку Получить ссылку в правом верхнем углу, скопируйте ссылку. В Clash Verge перейдите в раздел Профили и вставьте ссылку в текстовое поле, затем нажмите на кнопку Импорт.",
"zh": "如果点击按钮后没有反应,请手动添加订阅。点击此页面右上角的获取链接按钮,复制链接。在 Clash Verge 中,转到配置文件部分,将链接粘贴到文本字段中,然后点击导入按钮。"
}
},
"connectAndUseStep": {
"description": {
"en": "You can select a server in the Proxy section, and enable VPN in the Settings section. Set the TUN Mode switch to ON.",
"fa": "می‌توانید در بخش پروکسی سرور را انتخاب کنید و در بخش تنظیمات VPN را فعال کنید. کلید TUN Mode را در حالت روشن قرار دهید.",
"ru": "Выбрать сервер можно в разделе Прокси, включить VPN можно в разделе Настройки. Установите переключатель TUN Mode в положение ВКЛ.",
"zh": "您可以在代理部分选择服务器,在设置部分启用 VPN。将 TUN 模式开关设置为开启。"
}
}
},
{
"id": "hiddify",
"name": "Hiddify",
"isFeatured": false,
"urlScheme": "hiddify://import/",
"installationStep": {
"buttons": [
{
"buttonLink": "https://github.com/hiddify/hiddify-app/releases/download/v2.5.7/Hiddify-Windows-Setup-x64.exe",
"buttonText": {
"en": "Windows",
"fa": "ویندوز",
"ru": "Windows",
"zh": "Windows"
}
},
{
"buttonLink": "https://github.com/hiddify/hiddify-app/releases/download/v2.5.7/Hiddify-MacOS.dmg",
"buttonText": {
"en": "macOS",
"fa": "مک",
"ru": "macOS",
"zh": "macOS"
}
},
{
"buttonLink": "https://github.com/hiddify/hiddify-app/releases/download/v2.5.7/Hiddify-Linux-x64.AppImage",
"buttonText": {
"en": "Linux",
"fa": "لینوکس",
"ru": "Linux",
"zh": "Linux"
}
}
],
"description": {
"en": "In the main section, click the large power button in the center to connect to VPN. If needed, select a different server in the Proxy section",
"fa": "در بخش اصلی، دکمه بزرگ روشن/خاموش در مرکز را برای اتصال به VPN کلیک کنید. در صورت نیاز، سرور دیگری را در بخش پروکسی انتخاب کنید",
"ru": "В главном разделе нажмите большую кнопку включения в центре для подключения к VPN. При необходимости выберите другой сервер в разделе Прокси.",
"zh": "在主界面中,点击中央的大电源按钮连接 VPN。如有需要,可在代理部分选择不同的服务器"
}
},
"addSubscriptionStep": {
"description": {
"en": "Click the button below to add subscription",
"fa": "برای افزودن اشتراک روی دکمه زیر کلیک کنید",
"ru": "Нажмите кнопку ниже, чтобы добавить подписку",
"zh": "点击下方按钮添加订阅"
}
},
"connectAndUseStep": {
"description": {
"en": "In the main section, click the large power button in the center to connect to VPN. Don't forget to select a server from the server list. If needed, select a different server from the server list.",
"fa": "در بخش اصلی، دکمه بزرگ روشن/خاموش در مرکز را برای اتصال به VPN کلیک کنید. فراموش نکنید که یک سرور را از لیست سرورها انتخاب کنید. در صورت نیاز، سرور دیگری را از لیست سرورها انتخاب کنید.",
"ru": "В главном разделе нажмите большую кнопку включения в центре для подключения к VPN. Не забудьте выбрать сервер в списке серверов. При необходимости выберите другой сервер из списка серверов.",
"zh": "在主界面中,点击中央的大电源按钮连接到 VPN。别忘了从服务器列表中选择一个服务器。如有需要,可从服务器列表中选择其他服务器。"
}
}
}
],
"windows": [
{
"id": "clash-verge",
"name": "Clash Verge",
"isFeatured": true,
"urlScheme": "clash://install-config?url=",
"installationStep": {
"buttons": [
{
"buttonLink": "https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v2.2.2/Clash.Verge_2.2.2_x64-setup.exe",
"buttonText": {
"en": "Windows",
"fa": "ویندوز",
"ru": "Windows",
"zh": "Windows"
}
},
{
"buttonLink": "https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v2.2.2/Clash.Verge_2.2.2_x64.dmg",
"buttonText": {
"en": "macOS (Intel)",
"fa": "مک (اینتل)",
"ru": "macOS (Intel)",
"zh": "macOS (Intel)"
}
},
{
"buttonLink": "https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v2.2.2/Clash.Verge_2.2.2_aarch64.dmg",
"buttonText": {
"en": "macOS (Apple Silicon)",
"fa": "مک (Apple Silicon)",
"ru": "macOS (Apple Silicon)",
"zh": "macOS (Apple Silicon)"
}
},
{
"buttonLink": "https://github.com/clash-verge-rev/clash-verge-rev/releases",
"buttonText": {
"en": "Linux",
"fa": "لینوکس",
"ru": "Linux",
"zh": "Linux"
}
}
],
"description": {
"en": "Choose the version for your device, click the button below and install the app.",
"fa": "نسخه مناسب برای دستگاه خود را انتخاب کنید، دکمه زیر را فشار دهید و برنامه را نصب کنید",
"ru": "Выберите подходящую версию для вашего устройства, нажмите на кнопку ниже и установите приложение.",
"zh": "选择适合您设备的版本,点击下方按钮并安装应用。"
}
},
"additionalBeforeAddSubscriptionStep": {
"buttons": [],
"description": {
"en": "After launching the app, you can change the language in settings. In the left panel, find the gear icon, then navigate to Verge 设置 and select 语言设置.",
"fa": "پس از راه‌اندازی برنامه، می‌توانید زبان را در تنظیمات تغییر دهید. در پنل سمت چپ، نماد چرخ دنده را پیدا کنید، سپس به Verge 设置 بروید و 语言设置 را انتخاب کنید.",
"ru": "После запуска приложения вы можете сменить язык в настройках. В левой панели найдите иконку шестеренки, далее ориентируйтесь на Verge 设置 и выберите пункт 语言设置.",
"zh": "启动应用后,您可以在设置中更改语言。在左侧面板找到齿轮图标,然后导航到 Verge 设置并选择语言设置。"
},
"title": {
"en": "Change language",
"fa": "تغییر زبان",
"ru": "Смена языка",
"zh": "更改语言"
}
},
"addSubscriptionStep": {
"description": {
"en": "Click the button below to add subscription",
"fa": "برای افزودن اشتراک روی دکمه زیر کلیک کنید",
"ru": "Нажмите кнопку ниже, чтобы добавить подписку",
"zh": "点击下方按钮添加订阅"
}
},
"additionalAfterAddSubscriptionStep": {
"buttons": [],
"title": {
"en": "If the subscription is not added",
"fa": "اگر اشتراک در برنامه نصب نشده است",
"ru": "Если подписка не добавилась",
"zh": "如果订阅未添加"
},
"description": {
"en": "If nothing happens after clicking the button, add the subscription manually. Click the Get Link button in the top right corner of this page, copy the link. In Clash Verge, go to the Profiles section and paste the link in the text field, then click the Import button.",
"fa": "اگر پس از کلیک روی دکمه اتفاقی نیفتاد، اشتراک را به صورت دستی اضافه کنید. در گوشه بالا سمت راست این صفحه روی دکمه دریافت لینک کلیک کنید، لینک را کپی کنید. در Clash Verge به بخش پروفایل‌ها بروید و لینک را در فیلد متنی وارد کنید، سپس روی دکمه وارد کردن کلیک کنید.",
"ru": "Если после нажатия на кнопку ничего не произошло, добавьте подписку вручную. Нажмите на этой страницу кнопку Получить ссылку в правом верхнем углу, скопируйте ссылку. В Clash Verge перейдите в раздел Профили и вставьте ссылку в текстовое поле, затем нажмите на кнопку Импорт.",
"zh": "如果点击按钮后没有反应,请手动添加订阅。点击此页面右上角的获取链接按钮,复制链接。在 Clash Verge 中,转到配置文件部分,将链接粘贴到文本字段中,然后点击导入按钮。"
}
},
"connectAndUseStep": {
"description": {
"en": "You can select a server in the Proxy section, and enable VPN in the Settings section. Set the TUN Mode switch to ON.",
"fa": "می‌توانید در بخش پروکسی سرور را انتخاب کنید و در بخش تنظیمات VPN را فعال کنید. کلید TUN Mode را در حالت روشن قرار دهید.",
"ru": "Выبрать сервер можно в разделе Прокси, включить VPN можно в разделе Настройки. Установите переключатель TUN Mode в положение ВКЛ.",
"zh": "您可以在代理部分选择服务器,在设置部分启用 VPN。将 TUN 模式开关设置为开启。"
}
}
},
{
"id": "hiddify",
"name": "Hiddify",
"isFeatured": false,
"urlScheme": "hiddify://import/",
"installationStep": {
"buttons": [
{
"buttonLink": "https://github.com/hiddify/hiddify-app/releases/download/v2.5.7/Hiddify-Windows-Setup-x64.exe",
"buttonText": {
"en": "Windows",
"fa": "ویندوز",
"ru": "Windows",
"zh": "Windows"
}
},
{
"buttonLink": "https://github.com/hiddify/hiddify-app/releases/download/v2.5.7/Hiddify-MacOS.dmg",
"buttonText": {
"en": "macOS",
"fa": "مک",
"ru": "macOS",
"zh": "macOS"
}
},
{
"buttonLink": "https://github.com/hiddify/hiddify-app/releases/download/v2.5.7/Hiddify-Linux-x64.AppImage",
"buttonText": {
"en": "Linux",
"fa": "لینوکس",
"ru": "Linux",
"zh": "Linux"
}
}
],
"description": {
"en": "In the main section, click the large power button in the center to connect to VPN. If needed, select a different server in the Proxy section",
"fa": "در بخش اصلی، دکمه بزرگ روشن/خاموش در مرکز را برای اتصال به VPN کلیک کنید. در صورت نیاز، سرور دیگری را در بخش پروکسی انتخاب کنید",
"ru": "В главном разделе нажмите большую кнопку включения в центре для подключения к VPN. При необходимости выберите другой сервер в разделе Прокси.",
"zh": "在主界面中,点击中央的大电源按钮连接 VPN。如有需要,可在代理部分选择不同的服务器"
}
},
"addSubscriptionStep": {
"description": {
"en": "Click the button below to add subscription",
"fa": "برای افزودن اشتراک روی دکمه زیر کلیک کنید",
"ru": "Нажмите кнопку ниже, чтобы добавить подписку",
"zh": "点击下方按钮添加订阅"
}
},
"connectAndUseStep": {
"description": {
"en": "In the main section, click the large power button in the center to connect to VPN. Don't forget to select a server from the server list. If needed, select a different server from the server list.",
"fa": "در بخش اصلی، دکمه بزرگ روشن/خاموش در مرکز را برای اتصال به VPN کلیک کنید. فراموش نکنید که یک سرور را از لیست سرورها انتخاب کنید. در صورت نیاز، سرور دیگری را از لیست سرورها انتخاب کنید.",
"ru": "В главном разделе нажмите большую кнопку включения в центре для подключения к VPN. Не забудьте выбрать сервер в списке серверов. При необходимости выберите другой сервер из списка серверов.",
"zh": "在主界面中,点击中央的大电源按钮连接到 VPN。别忘了从服务器列表中选择一个服务器。如有需要,可从服务器列表中选择其他服务器。"
}
}
}
],
"linux": [],
"androidTV": [
{
"id": "new-app-androidtv-1760203310792",
"name": "Happ",
"isFeatured": true,
"urlScheme": "happ://add/",
"installationStep": {
"buttons": [
{
"buttonLink": "https://play.google.com/store/apps/details?id=com.vpn4tv.hiddify",
"buttonText": {
"en": "Google Play",
"ru": "Button TextGoogle Play",
"zh": "Button Text",
"fa": "Button Text"
}
}
],
"description": {
"en": "Open the page in Google Play and install the app. Or install the app directly from the APK file if Google Play is not working.",
"ru": "Откройте страницу в Google Play и установите приложение",
"zh": "-",
"fa": "-"
}
},
"addSubscriptionStep": {
"description": {
"en": "Click the button below to add subscription",
"ru": "Нажмите кнопку выше — (Скопировать ссылку подписки) ты скопируешь свою подписку, далее на телевизоре открой VPN4TV, следуя инструкция передай telegram боту ссылку, которую ты скопировал",
"zh": "-",
"fa": "-"
}
},
"connectAndUseStep": {
"description": {
"en": "Open the app and connect to the server",
"ru": "Приложение автоматически обновится и загрузит нужные конфиги на твой телевизор, подключай VPN",
"zh": "-",
"fa": "-"
}
}
}
],
"appleTV": [
{
"id": "new-app-appletv-1760203488851",
"name": "Happ",
"isFeatured": true,
"urlScheme": "happ://add/",
"installationStep": {
"buttons": [
{
"buttonLink": "https://play.google.com/store/apps/details?id=com.vpn4tv.hiddify",
"buttonText": {
"en": "Google Play",
"ru": "Google Play",
"zh": "Button Text",
"fa": "Button Text"
}
}
],
"description": {
"en": "Open the page in Google Play and install the app. Or install the app directly from the APK file if Google Play is not working.",
"ru": "Откройте страницу в Google Play и установите приложение",
"zh": "-",
"fa": "-"
}
},
"addSubscriptionStep": {
"description": {
"en": "Click the button below to add subscription",
"ru": "Нажмите кнопку выше — (Скопировать ссылку подписки) ты скопируешь свою подписку, далее на телевизоре открой VPN4TV, следуя инструкция передай telegram боту ссылку, которую ты скопировал",
"zh": "-",
"fa": "-"
}
},
"connectAndUseStep": {
"description": {
"en": "Open the app and connect to the server",
"ru": "Приложение автоматически обновится и загрузит нужные конфиги на твой телевизор, подключай VPN",
"zh": "-",
"fa": "-"
}
}
}
]
}
}
+205 -101
View File
@@ -1,141 +1,174 @@
import logging
from aiogram import Bot, Dispatcher, types
from aiogram.fsm.storage.redis import RedisStorage
from aiogram.fsm.storage.memory import MemoryStorage
import redis.asyncio as redis
import structlog
from aiogram import Bot, Dispatcher, types
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.fsm.storage.redis import RedisStorage
from app.config import settings
from app.middlewares.global_error import GlobalErrorMiddleware
from app.middlewares.auth import AuthMiddleware
from app.middlewares.logging import LoggingMiddleware
from app.middlewares.throttling import ThrottlingMiddleware
from app.middlewares.subscription_checker import SubscriptionStatusMiddleware
from app.middlewares.maintenance import MaintenanceMiddleware
from app.middlewares.display_name_restriction import DisplayNameRestrictionMiddleware
from app.services.maintenance_service import maintenance_service
from app.utils.cache import cache
from app.handlers import (
start,
menu,
subscription,
balance,
common,
contests as user_contests,
menu,
polls as user_polls,
promocode,
referral,
support,
server_status,
common,
simple_subscription,
start,
subscription,
support,
tickets,
)
from app.handlers import polls as user_polls
from app.handlers import simple_subscription
from app.handlers.admin import (
backup as admin_backup,
blacklist as admin_blacklist,
blocked_users as admin_blocked_users,
bot_configuration as admin_bot_configuration,
bulk_ban as admin_bulk_ban,
campaigns as admin_campaigns,
contests as admin_contests,
daily_contests as admin_daily_contests,
faq as admin_faq,
main as admin_main,
users as admin_users,
subscriptions as admin_subscriptions,
promocodes as admin_promocodes,
maintenance as admin_maintenance,
messages as admin_messages,
monitoring as admin_monitoring,
referrals as admin_referrals,
rules as admin_rules,
remnawave as admin_remnawave,
statistics as admin_statistics,
payments as admin_payments,
polls as admin_polls,
servers as admin_servers,
maintenance as admin_maintenance,
promo_groups as admin_promo_groups,
campaigns as admin_campaigns,
promo_offers as admin_promo_offers,
user_messages as admin_user_messages,
updates as admin_updates,
backup as admin_backup,
system_logs as admin_system_logs,
welcome_text as admin_welcome_text,
tickets as admin_tickets,
reports as admin_reports,
bot_configuration as admin_bot_configuration,
pricing as admin_pricing,
privacy_policy as admin_privacy_policy,
promo_groups as admin_promo_groups,
promo_offers as admin_promo_offers,
promocodes as admin_promocodes,
public_offer as admin_public_offer,
faq as admin_faq,
payments as admin_payments,
referrals as admin_referrals,
remnawave as admin_remnawave,
reports as admin_reports,
required_channels as admin_required_channels,
rules as admin_rules,
servers as admin_servers,
statistics as admin_statistics,
subscriptions as admin_subscriptions,
system_logs as admin_system_logs,
tariffs as admin_tariffs,
tickets as admin_tickets,
trials as admin_trials,
updates as admin_updates,
user_messages as admin_user_messages,
users as admin_users,
welcome_text as admin_welcome_text,
)
from app.handlers.channel_member import register_handlers as register_channel_member_handlers
from app.handlers.gift_activation import register_handlers as register_gift_activation_handlers
from app.handlers.stars_payments import register_stars_handlers
from app.middlewares.auth import AuthMiddleware
from app.middlewares.blacklist import BlacklistMiddleware
from app.middlewares.button_stats import ButtonStatsMiddleware
from app.middlewares.chat_type_filter import ChatTypeFilterMiddleware
from app.middlewares.context_binding import ContextVarsMiddleware
from app.middlewares.display_name_restriction import DisplayNameRestrictionMiddleware
from app.middlewares.global_error import GlobalErrorMiddleware
from app.middlewares.logging import LoggingMiddleware
from app.middlewares.maintenance import MaintenanceMiddleware
from app.middlewares.subscription_checker import SubscriptionStatusMiddleware
from app.middlewares.throttling import ThrottlingMiddleware
from app.services.maintenance_service import maintenance_service
from app.utils.cache import cache
from app.utils.message_patch import patch_message_methods
patch_message_methods()
logger = logging.getLogger(__name__)
logger = structlog.get_logger(__name__)
async def debug_callback_handler(callback: types.CallbackQuery):
logger.info(f"🔍 DEBUG CALLBACK:")
logger.info(f" - Data: {callback.data}")
logger.info(f" - User: {callback.from_user.id}")
logger.info(f" - Username: {callback.from_user.username}")
logger.info('🔍 DEBUG CALLBACK:')
logger.info('Data', callback_data=callback.data)
logger.info('User', from_user_id=callback.from_user.id)
logger.info('Username', username=callback.from_user.username)
async def setup_bot() -> tuple[Bot, Dispatcher]:
try:
await cache.connect()
logger.info("Кеш инициализирован")
logger.info('Кеш инициализирован')
except Exception as e:
logger.warning(f"Кеш не инициализирован: {e}")
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
logger.warning('Кеш не инициализирован', error=e)
from app.bot_factory import create_bot
bot = create_bot()
proxy_url = settings.get_proxy_url()
nalogo_proxy_url = settings.get_nalogo_proxy_url()
if proxy_url or nalogo_proxy_url:
from app.utils.proxy import mask_proxy_url
if proxy_url:
logger.info('Proxy configured', proxy_url=mask_proxy_url(proxy_url))
if nalogo_proxy_url:
source = 'NALOGO_PROXY_URL' if settings.NALOGO_PROXY_URL else 'PROXY_URL (fallback)'
logger.info('Nalogo proxy configured', proxy_url=mask_proxy_url(nalogo_proxy_url), source=source)
bot = Bot(
token=settings.BOT_TOKEN,
default=DefaultBotProperties(parse_mode=ParseMode.HTML)
)
maintenance_service.set_bot(bot)
logger.info("Бот установлен в maintenance_service")
logger.info('Бот установлен в maintenance_service')
try:
redis_client = redis.from_url(settings.REDIS_URL)
await redis_client.ping()
storage = RedisStorage(redis_client)
logger.info("Подключено к Redis для FSM storage")
logger.info('Подключено к Redis для FSM storage')
except Exception as e:
logger.warning(f"Не удалось подключиться к Redis: {e}")
logger.info("Используется MemoryStorage для FSM")
logger.warning('Не удалось подключиться к Redis', error=e)
logger.info('Используется MemoryStorage для FSM')
storage = MemoryStorage()
dp = Dispatcher(storage=storage)
dp.message.middleware(ContextVarsMiddleware())
dp.callback_query.middleware(ContextVarsMiddleware())
dp.pre_checkout_query.middleware(ContextVarsMiddleware())
chat_type_filter = ChatTypeFilterMiddleware()
dp.message.middleware(chat_type_filter)
dp.callback_query.middleware(chat_type_filter)
dp.message.middleware(LoggingMiddleware())
dp.callback_query.middleware(LoggingMiddleware())
dp.message.middleware(GlobalErrorMiddleware())
dp.callback_query.middleware(GlobalErrorMiddleware())
dp.pre_checkout_query.middleware(GlobalErrorMiddleware())
dp.message.middleware(LoggingMiddleware())
dp.callback_query.middleware(LoggingMiddleware())
dp.message.middleware(MaintenanceMiddleware())
dp.callback_query.middleware(MaintenanceMiddleware())
display_name_middleware = DisplayNameRestrictionMiddleware()
dp.message.middleware(display_name_middleware)
dp.callback_query.middleware(display_name_middleware)
dp.pre_checkout_query.middleware(display_name_middleware)
dp.message.middleware(ThrottlingMiddleware())
dp.callback_query.middleware(ThrottlingMiddleware())
blacklist_middleware = BlacklistMiddleware()
dp.message.middleware(blacklist_middleware)
dp.callback_query.middleware(blacklist_middleware)
dp.pre_checkout_query.middleware(blacklist_middleware)
throttling_middleware = ThrottlingMiddleware()
dp.message.middleware(throttling_middleware)
dp.callback_query.middleware(throttling_middleware)
if settings.CHANNEL_IS_REQUIRED_SUB:
from app.middlewares.channel_checker import ChannelCheckerMiddleware
# Middleware для автоматического логирования кликов по кнопкам
if settings.MENU_LAYOUT_ENABLED:
button_stats_middleware = ButtonStatsMiddleware()
dp.callback_query.middleware(button_stats_middleware)
logger.info('📊 ButtonStatsMiddleware активирован')
channel_checker_middleware = ChannelCheckerMiddleware()
dp.message.middleware(channel_checker_middleware)
dp.callback_query.middleware(channel_checker_middleware)
logger.info("🔒 Обязательная подписка включена - ChannelCheckerMiddleware активирован")
else:
logger.info("🔓 Обязательная подписка отключена - ChannelCheckerMiddleware не зарегистрирован")
from app.middlewares.channel_checker import ChannelCheckerMiddleware
channel_checker = ChannelCheckerMiddleware()
dp.message.middleware(channel_checker)
dp.callback_query.middleware(channel_checker)
dp.message.middleware(AuthMiddleware())
dp.callback_query.middleware(AuthMiddleware())
dp.pre_checkout_query.middleware(AuthMiddleware())
display_name_restriction = DisplayNameRestrictionMiddleware()
dp.message.middleware(display_name_restriction)
dp.callback_query.middleware(display_name_restriction)
dp.message.middleware(SubscriptionStatusMiddleware())
dp.callback_query.middleware(SubscriptionStatusMiddleware())
dp.pre_checkout_query.middleware(SubscriptionStatusMiddleware())
start.register_handlers(dp)
menu.register_handlers(dp)
subscription.register_handlers(dp)
@@ -148,7 +181,7 @@ async def setup_bot() -> tuple[Bot, Dispatcher]:
admin_main.register_handlers(dp)
admin_users.register_handlers(dp)
admin_subscriptions.register_handlers(dp)
admin_servers.register_handlers(dp)
admin_servers.register_handlers(dp)
admin_promocodes.register_handlers(dp)
admin_messages.register_handlers(dp)
admin_monitoring.register_handlers(dp)
@@ -159,6 +192,8 @@ async def setup_bot() -> tuple[Bot, Dispatcher]:
admin_polls.register_handlers(dp)
admin_promo_groups.register_handlers(dp)
admin_campaigns.register_handlers(dp)
admin_contests.register_handlers(dp)
admin_daily_contests.register_handlers(dp)
admin_promo_offers.register_handlers(dp)
admin_maintenance.register_handlers(dp)
admin_user_messages.register_handlers(dp)
@@ -174,38 +209,107 @@ async def setup_bot() -> tuple[Bot, Dispatcher]:
admin_public_offer.register_handlers(dp)
admin_faq.register_handlers(dp)
admin_payments.register_handlers(dp)
admin_trials.register_handlers(dp)
admin_tariffs.register_handlers(dp)
admin_bulk_ban.register_bulk_ban_handlers(dp)
admin_blacklist.register_blacklist_handlers(dp)
admin_blocked_users.register_handlers(dp)
admin_required_channels.register_handlers(dp)
register_channel_member_handlers(dp)
register_gift_activation_handlers(dp)
common.register_handlers(dp)
register_stars_handlers(dp)
user_contests.register_handlers(dp)
user_polls.register_handlers(dp)
simple_subscription.register_simple_subscription_handlers(dp)
logger.info("⭐ Зарегистрированы обработчики Telegram Stars платежей")
logger.info("⚡ Зарегистрированы обработчики простой покупки")
logger.info("⚡ Зарегистрированы обработчики простой подписки")
logger.info('⭐ Зарегистрированы обработчики Telegram Stars платежей')
logger.info('⚡ Зарегистрированы обработчики простой покупки')
logger.info('⚡ Зарегистрированы обработчики простой подписки')
if settings.is_maintenance_monitoring_enabled():
try:
await maintenance_service.start_monitoring()
logger.info("Мониторинг техработ запущен")
logger.info('Мониторинг техработ запущен')
except Exception as e:
logger.error(f"Ошибка запуска мониторинга техработ: {e}")
logger.error('Ошибка запуска мониторинга техработ', error=e)
else:
logger.info("Мониторинг техработ отключен настройками")
logger.info("🛡️ GlobalErrorMiddleware активирован - бот защищен от устаревших callback queries")
logger.info("Бот успешно настроен")
logger.info('Мониторинг техработ отключен настройками')
logger.info('🛡️ GlobalErrorMiddleware активирован - бот защищен от устаревших callback queries')
# Validate CONNECT_BUTTON_MODE dependencies
if not settings.get_happ_cryptolink_redirect_template():
if settings.CONNECT_BUTTON_MODE == 'happ_cryptolink':
logger.warning(
'⚠️ CONNECT_BUTTON_MODE=happ_cryptolink, но HAPP_CRYPTOLINK_REDIRECT_TEMPLATE не задан! '
'Кнопка "Подключиться" не будет отображаться.'
)
elif settings.CONNECT_BUTTON_MODE == 'guide':
logger.warning(
'⚠️ CONNECT_BUTTON_MODE=guide, но HAPP_CRYPTOLINK_REDIRECT_TEMPLATE не задан! '
'Кнопка "Подключиться" в гайдах не будет работать — Telegram не поддерживает '
'кастомные схемы (happ://, v2ray://) в inline-кнопках без HTTPS-редиректа.'
)
if settings.CONNECT_BUTTON_MODE == 'miniapp_custom' and not settings.MINIAPP_CUSTOM_URL:
logger.warning(
'⚠️ CONNECT_BUTTON_MODE=miniapp_custom, но MINIAPP_CUSTOM_URL не задан! '
'Кнопка "Подключиться" не будет работать.'
)
if settings.is_cabinet_mode() and not settings.MINIAPP_CUSTOM_URL:
logger.warning(
'⚠️ MAIN_MENU_MODE=cabinet, но MINIAPP_CUSTOM_URL не задан! '
'Кнопки кабинета не смогут открывать разделы MiniApp. '
'Установите MINIAPP_CUSTOM_URL.'
)
elif settings.is_cabinet_mode():
logger.info('🏠 Режим Cabinet активен, базовый URL', MINIAPP_CUSTOM_URL=settings.MINIAPP_CUSTOM_URL)
# Load per-section button styles cache and menu layout cache
if settings.is_cabinet_mode():
try:
from app.utils.button_styles_cache import load_button_styles_cache
await load_button_styles_cache()
except Exception as e:
logger.warning('Failed to load button styles cache', error=e)
try:
from app.utils.menu_layout_cache import load_menu_layout_cache
await load_menu_layout_cache()
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:
await maintenance_service.stop_monitoring()
logger.info("Мониторинг техработ остановлен")
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(f"Ошибка остановки мониторинга: {e}")
logger.error('Ошибка остановки RemnaWave retry queue', error=e)
try:
await maintenance_service.stop_monitoring()
logger.info('Мониторинг техработ остановлен')
except Exception as e:
logger.error('Ошибка остановки мониторинга', error=e)
try:
await cache.close()
logger.info("Соединения с кешем закрыты")
logger.info('Соединения с кешем закрыты')
except Exception as e:
logger.error(f"Ошибка закрытия кеша: {e}")
logger.error('Ошибка закрытия кеша', error=e)
+28
View File
@@ -0,0 +1,28 @@
"""Factory for creating Bot instances with proxy and custom API server support."""
from aiogram import Bot
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from app.config import settings
def create_bot(token: str | None = None, **kwargs) -> Bot:
"""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 or telegram_api_url:
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.client.telegram import TelegramAPIServer
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)
+10
View File
@@ -0,0 +1,10 @@
"""
Cabinet module - Personal Account for VPN Bot users.
This module provides:
- JWT-based authentication (Telegram + Email)
- Subscription management
- Balance & payments
- Referral program
- Support tickets
"""
+25
View File
@@ -0,0 +1,25 @@
"""Cabinet authentication module."""
from .jwt_handler import (
create_access_token,
create_auto_login_token,
create_refresh_token,
decode_token,
get_token_payload,
)
from .password_utils import hash_password, verify_password
from .telegram_auth import validate_telegram_init_data, validate_telegram_login_widget, validate_telegram_oidc_token
__all__ = [
'create_access_token',
'create_auto_login_token',
'create_refresh_token',
'decode_token',
'get_token_payload',
'hash_password',
'validate_telegram_init_data',
'validate_telegram_login_widget',
'validate_telegram_oidc_token',
'verify_password',
]
+84
View File
@@ -0,0 +1,84 @@
"""Email verification token generation and validation."""
import secrets
from datetime import UTC, datetime, timedelta
from app.config import settings
def generate_email_change_code() -> str:
"""
Generate a 6-digit verification code for email change.
Returns:
6-digit numeric string
"""
return str(secrets.randbelow(900000) + 100000)
def get_email_change_expires_at() -> datetime:
"""
Get the expiration datetime for an email change code.
Returns:
Datetime when the email change code expires
"""
minutes = settings.get_cabinet_email_change_code_expire_minutes()
return datetime.now(UTC) + timedelta(minutes=minutes)
def generate_verification_token() -> str:
"""
Generate a secure random verification token.
Returns:
32-character hex token string
"""
return secrets.token_hex(32)
def generate_password_reset_token() -> str:
"""
Generate a secure random password reset token.
Returns:
32-character hex token string
"""
return secrets.token_hex(32)
def get_verification_expires_at() -> datetime:
"""
Get the expiration datetime for a verification token.
Returns:
Datetime when the verification token expires
"""
hours = settings.get_cabinet_email_verification_expire_hours()
return datetime.now(UTC) + timedelta(hours=hours)
def get_password_reset_expires_at() -> datetime:
"""
Get the expiration datetime for a password reset token.
Returns:
Datetime when the password reset token expires
"""
hours = settings.get_cabinet_password_reset_expire_hours()
return datetime.now(UTC) + timedelta(hours=hours)
def is_token_expired(expires_at: datetime | None) -> bool:
"""
Check if a token has expired.
Args:
expires_at: Token expiration datetime
Returns:
True if expired or no expiration set, False otherwise
"""
if expires_at is None:
return True
return datetime.now(UTC) > expires_at
+141
View File
@@ -0,0 +1,141 @@
"""JWT token handling for cabinet authentication."""
from datetime import UTC, datetime, timedelta
from typing import Any
import jwt
from app.config import settings
JWT_ALGORITHM = 'HS256'
def create_access_token(
user_id: int,
telegram_id: int | None = None,
*,
permissions: list[str] | None = None,
roles: list[str] | None = None,
role_level: int = 0,
) -> str:
"""
Create a short-lived access token.
Args:
user_id: Database user ID
telegram_id: Telegram user ID (optional for email-only users)
permissions: RBAC permission strings to embed in token
roles: Role names to embed in token
role_level: Maximum role level (0 = no special level)
Returns:
Encoded JWT access token
"""
expire_minutes = settings.get_cabinet_access_token_expire_minutes()
expires = datetime.now(UTC) + timedelta(minutes=expire_minutes)
payload = {
'sub': str(user_id),
'type': 'access',
'exp': expires,
'iat': datetime.now(UTC),
}
# Добавляем telegram_id только если он есть
if telegram_id is not None:
payload['telegram_id'] = telegram_id
# RBAC data — only include when provided to keep token compact
if permissions is not None:
payload['permissions'] = permissions
if roles is not None:
payload['roles'] = roles
if role_level > 0:
payload['role_level'] = role_level
secret = settings.get_cabinet_jwt_secret()
return jwt.encode(payload, secret, algorithm=JWT_ALGORITHM)
def create_refresh_token(user_id: int) -> str:
"""
Create a long-lived refresh token.
Args:
user_id: Database user ID
Returns:
Encoded JWT refresh token
"""
expire_days = settings.get_cabinet_refresh_token_expire_days()
expires = datetime.now(UTC) + timedelta(days=expire_days)
payload = {
'sub': str(user_id),
'type': 'refresh',
'exp': expires,
'iat': datetime.now(UTC),
}
secret = settings.get_cabinet_jwt_secret()
return jwt.encode(payload, secret, algorithm=JWT_ALGORITHM)
def decode_token(token: str) -> dict[str, Any] | None:
"""
Decode and validate a JWT token.
Args:
token: JWT token string
Returns:
Decoded payload dict or None if invalid/expired
"""
try:
secret = settings.get_cabinet_jwt_secret()
return jwt.decode(token, secret, algorithms=[JWT_ALGORITHM])
except jwt.ExpiredSignatureError:
return None
except jwt.InvalidTokenError:
return None
def get_token_payload(token: str, expected_type: str = 'access') -> dict[str, Any] | None:
"""
Decode token and verify its type.
Args:
token: JWT token string
expected_type: Expected token type ("access" or "refresh")
Returns:
Decoded payload dict or None if invalid/expired/wrong type
"""
payload = decode_token(token)
if not payload:
return None
if payload.get('type') != expected_type:
return None
return payload
def create_auto_login_token(user_id: int, ttl_hours: int = 72) -> str:
"""Short-lived JWT for auto-login from guest purchase success page."""
expires = datetime.now(UTC) + timedelta(hours=ttl_hours)
payload = {
'sub': str(user_id),
'type': 'auto_login',
'exp': expires,
'iat': datetime.now(UTC),
}
return jwt.encode(payload, settings.get_cabinet_jwt_secret(), algorithm=JWT_ALGORITHM)
def get_refresh_token_expires_at() -> datetime:
"""Get the expiration datetime for a new refresh token."""
expire_days = settings.get_cabinet_refresh_token_expire_days()
return datetime.now(UTC) + timedelta(days=expire_days)
+154
View File
@@ -0,0 +1,154 @@
"""Temporary merge token management for account linking.
Stores short-lived tokens in Redis so the user can confirm merging
two cabinet accounts (primary absorbs secondary) via a separate
confirmation endpoint.
"""
import secrets
from datetime import UTC, datetime
from typing import Any
import structlog
from app.utils.cache import cache, cache_key
logger = structlog.get_logger(__name__)
MERGE_TOKEN_TTL_SECONDS = 1800 # 30 minutes
MERGE_TOKEN_PREFIX = 'account_merge'
async def create_merge_token(
primary_user_id: int,
secondary_user_id: int,
provider: str,
provider_id: str,
) -> str:
"""Generate a merge token and store its payload in Redis.
The token is a one-time confirmation handle: whoever presents it
within ``MERGE_TOKEN_TTL_SECONDS`` can execute the account merge.
Returns the raw token string (URL-safe base64, 32 bytes of entropy).
Raises ``RuntimeError`` if Redis write fails.
"""
token = secrets.token_urlsafe(32)
value: dict[str, Any] = {
'primary_user_id': primary_user_id,
'secondary_user_id': secondary_user_id,
'provider': provider,
'provider_id': provider_id,
'created_at': datetime.now(UTC).isoformat(),
}
key = cache_key(MERGE_TOKEN_PREFIX, token)
stored = await cache.set(key, value, expire=MERGE_TOKEN_TTL_SECONDS)
if not stored:
logger.error(
'Failed to store merge token in Redis',
primary_user_id=primary_user_id,
secondary_user_id=secondary_user_id,
provider=provider,
)
raise RuntimeError('Failed to store merge token')
logger.info(
'Merge token created',
primary_user_id=primary_user_id,
secondary_user_id=secondary_user_id,
provider=provider,
provider_id=provider_id,
)
return token
async def get_merge_token_data(token: str) -> dict[str, Any] | None:
"""Read merge token payload *without* consuming it.
Intended for preview / confirmation screens where the user sees
what will happen before they press "Confirm".
Returns ``None`` when the token is expired, missing, or malformed.
"""
key = cache_key(MERGE_TOKEN_PREFIX, token)
data: Any = await cache.get(key)
if data is None or not isinstance(data, dict):
return None
return data
async def consume_merge_token(token: str) -> dict[str, Any] | None:
"""Atomically read and delete a merge token (GETDEL).
This prevents double-merge race conditions: only the first caller
that reaches Redis will get the payload; every subsequent attempt
receives ``None``.
Returns the stored dict or ``None`` if already consumed / expired.
"""
key = cache_key(MERGE_TOKEN_PREFIX, token)
data: Any = await cache.getdel(key)
if data is None or not isinstance(data, dict):
return None
logger.info(
'Merge token consumed',
primary_user_id=data.get('primary_user_id'),
secondary_user_id=data.get('secondary_user_id'),
provider=data.get('provider'),
)
return data
_MAX_MERGE_RESTORE_ATTEMPTS = 3
async def restore_merge_token(token: str, data: dict[str, Any]) -> bool:
"""Re-store a consumed merge token so the user can retry after a DB failure.
Uses the remaining TTL based on the original ``created_at``.
Uses SETNX to avoid overwriting a fresh token.
Caps restore attempts to prevent infinite retry cycles.
Returns ``True`` if restored, ``False`` if exhausted or Redis write failed.
"""
restore_count = data.get('_restore_count', 0) + 1
if restore_count > _MAX_MERGE_RESTORE_ATTEMPTS:
logger.warning(
'Merge token exhausted restore attempts',
primary_user_id=data.get('primary_user_id'),
secondary_user_id=data.get('secondary_user_id'),
restore_count=restore_count,
)
return False
# Shallow copy to avoid mutating the caller's dict
data = {**data, '_restore_count': restore_count}
created_at_str: str = data.get('created_at', '')
try:
created_at = datetime.fromisoformat(created_at_str)
if created_at.tzinfo is None:
created_at = created_at.replace(tzinfo=UTC)
elapsed = (datetime.now(UTC) - created_at).total_seconds()
remaining_ttl = max(1, min(int(MERGE_TOKEN_TTL_SECONDS - elapsed), MERGE_TOKEN_TTL_SECONDS))
except (ValueError, TypeError):
remaining_ttl = 60 # brief retry window — fail closed
key = cache_key(MERGE_TOKEN_PREFIX, token)
stored = await cache.setnx(key, data, expire=remaining_ttl)
if stored:
logger.info(
'Merge token restored after failed merge',
primary_user_id=data.get('primary_user_id'),
secondary_user_id=data.get('secondary_user_id'),
remaining_ttl=remaining_ttl,
restore_count=restore_count,
)
else:
logger.error(
'Failed to restore merge token to Redis (key may already exist)',
primary_user_id=data.get('primary_user_id'),
secondary_user_id=data.get('secondary_user_id'),
)
return bool(stored)
+513
View File
@@ -0,0 +1,513 @@
"""OAuth 2.0 provider implementations for cabinet authentication."""
import base64
import hashlib
import secrets
from abc import ABC, abstractmethod
from typing import Any, TypedDict
import httpx
import structlog
from pydantic import BaseModel
from app.config import settings
from app.utils.cache import cache, cache_key
logger = structlog.get_logger(__name__)
STATE_TTL_SECONDS = 600 # 10 minutes
# --- Typed dicts for provider API responses ---
class OAuthProviderConfig(TypedDict):
client_id: str
client_secret: str
enabled: bool
display_name: str
class OAuthTokenResponse(TypedDict, total=False):
access_token: str
token_type: str
expires_in: int
refresh_token: str
scope: str
# Provider-specific extra fields (optional)
email: str
user_id: int
class GoogleUserInfoResponse(TypedDict, total=False):
sub: str
email: str
email_verified: bool
given_name: str
family_name: str
picture: str
name: str
class YandexUserInfoResponse(TypedDict, total=False):
id: str
login: str
default_email: str
emails: list[str]
first_name: str
last_name: str
default_avatar_id: str
class DiscordUserInfoResponse(TypedDict, total=False):
id: str
username: str
global_name: str
email: str
verified: bool
avatar: str
class VKIDUserData(TypedDict, total=False):
"""VK ID /oauth2/user_info response user object."""
user_id: str
first_name: str
last_name: str
phone: str
avatar: str
email: str
class VKIDUserInfoResponse(TypedDict, total=False):
user: VKIDUserData
# --- Models ---
class OAuthUserInfo(BaseModel):
"""Normalized user info from OAuth provider."""
provider: str
provider_id: str
email: str | None = None
email_verified: bool = False
first_name: str | None = None
last_name: str | None = None
username: str | None = None
avatar_url: str | None = None
# --- CSRF state management (Redis) ---
async def generate_oauth_state(provider: str, extra_data: dict[str, str] | None = None) -> str:
"""Generate a CSRF state token for OAuth flow.
Stores provider name and optional extra data (e.g., PKCE code_verifier) in Redis with TTL.
Keys prefixed with '_' are ephemeral and NOT stored in Redis (e.g., _code_challenge).
CacheService handles JSON serialization internally.
"""
state = secrets.token_urlsafe(32)
value: dict[str, Any] = {'provider': provider}
if extra_data:
# Filter out ephemeral keys (prefixed with '_') — they're only needed for the URL
value.update({k: v for k, v in extra_data.items() if not k.startswith('_')})
stored = await cache.set(cache_key('oauth_state', state), value, expire=STATE_TTL_SECONDS)
if not stored:
logger.error('Failed to store OAuth state in Redis')
raise RuntimeError('Failed to store OAuth state')
return state
async def validate_oauth_state(state: str, provider: str | None = None) -> dict[str, Any] | None:
"""Validate and consume a CSRF state token from Redis.
Uses atomic GETDEL to prevent TOCTOU race conditions.
Returns the stored data dict (with 'provider' key + any extra data) or None if invalid.
Args:
state: The state token to validate.
provider: If provided, verifies it matches the stored provider.
If None, skips provider check (used for server-complete flow).
"""
key = cache_key('oauth_state', state)
data: Any = await cache.getdel(key)
if data is None:
return None
if not isinstance(data, dict):
return None
if provider is not None and data.get('provider') != provider:
return None
return data
# --- Provider implementations ---
class OAuthProvider(ABC):
"""Base class for OAuth 2.0 providers."""
name: str
display_name: str
def __init__(self, client_id: str, client_secret: str, redirect_uri: str) -> None:
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
def prepare_auth_state(self) -> dict[str, str]:
"""Return extra data to store with OAuth state (e.g., PKCE code_verifier).
Override in providers that need PKCE or other state-stored data.
The returned dict is stored in Redis alongside the state token
and passed back via validate_oauth_state().
"""
return {}
@abstractmethod
def get_authorization_url(self, state: str, **kwargs: Any) -> str:
"""Build the authorization URL for the provider.
kwargs may contain extra data from prepare_auth_state() (e.g., code_challenge).
"""
@abstractmethod
async def exchange_code(self, code: str, **kwargs: Any) -> OAuthTokenResponse:
"""Exchange authorization code for tokens.
kwargs may contain provider-specific params (e.g., device_id, code_verifier for VK).
"""
@abstractmethod
async def get_user_info(self, token_data: OAuthTokenResponse) -> OAuthUserInfo:
"""Fetch user info from the provider."""
class GoogleProvider(OAuthProvider):
name = 'google'
display_name = 'Google'
AUTHORIZE_URL = 'https://accounts.google.com/o/oauth2/v2/auth'
TOKEN_URL = 'https://oauth2.googleapis.com/token'
USERINFO_URL = 'https://www.googleapis.com/oauth2/v3/userinfo'
def get_authorization_url(self, state: str, **kwargs: Any) -> str:
params: dict[str, str] = {
'client_id': self.client_id,
'redirect_uri': self.redirect_uri,
'response_type': 'code',
'scope': 'openid email profile',
'state': state,
'access_type': 'offline',
'prompt': 'select_account',
}
request = httpx.Request('GET', self.AUTHORIZE_URL, params=params)
return str(request.url)
async def exchange_code(self, code: str, **kwargs: Any) -> OAuthTokenResponse:
async with httpx.AsyncClient(timeout=30) as client:
response = await client.post(
self.TOKEN_URL,
json={
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
'grant_type': 'authorization_code',
'redirect_uri': self.redirect_uri,
},
)
response.raise_for_status()
data: OAuthTokenResponse = response.json()
return data
async def get_user_info(self, token_data: OAuthTokenResponse) -> OAuthUserInfo:
access_token = token_data['access_token']
async with httpx.AsyncClient(timeout=30) as client:
response = await client.get(
self.USERINFO_URL,
headers={'Authorization': f'Bearer {access_token}'},
)
response.raise_for_status()
data: GoogleUserInfoResponse = response.json()
return OAuthUserInfo(
provider='google',
provider_id=str(data['sub']),
email=data.get('email'),
email_verified=data.get('email_verified', False),
first_name=data.get('given_name'),
last_name=data.get('family_name'),
avatar_url=data.get('picture'),
)
class YandexProvider(OAuthProvider):
name = 'yandex'
display_name = 'Yandex'
AUTHORIZE_URL = 'https://oauth.yandex.com/authorize'
TOKEN_URL = 'https://oauth.yandex.com/token'
USERINFO_URL = 'https://login.yandex.ru/info'
def get_authorization_url(self, state: str, **kwargs: Any) -> str:
params: dict[str, str] = {
'client_id': self.client_id,
'redirect_uri': self.redirect_uri,
'response_type': 'code',
'scope': 'login:info login:email',
'state': state,
'force_confirm': 'yes',
}
request = httpx.Request('GET', self.AUTHORIZE_URL, params=params)
return str(request.url)
async def exchange_code(self, code: str, **kwargs: Any) -> OAuthTokenResponse:
async with httpx.AsyncClient(timeout=30) as client:
response = await client.post(
self.TOKEN_URL,
data={
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
'grant_type': 'authorization_code',
},
)
response.raise_for_status()
data: OAuthTokenResponse = response.json()
return data
async def get_user_info(self, token_data: OAuthTokenResponse) -> OAuthUserInfo:
access_token = token_data['access_token']
async with httpx.AsyncClient(timeout=30) as client:
response = await client.get(
self.USERINFO_URL,
params={'format': 'json'},
headers={'Authorization': f'OAuth {access_token}'},
)
response.raise_for_status()
data: YandexUserInfoResponse = response.json()
default_email = data.get('default_email')
emails = data.get('emails', [])
email = default_email or (emails[0] if emails else None)
return OAuthUserInfo(
provider='yandex',
provider_id=str(data['id']),
email=email,
email_verified=bool(email),
first_name=data.get('first_name'),
last_name=data.get('last_name'),
username=data.get('login'),
avatar_url=(
f'https://avatars.yandex.net/get-yapic/{data["default_avatar_id"]}/islands-200'
if data.get('default_avatar_id')
else None
),
)
class DiscordProvider(OAuthProvider):
name = 'discord'
display_name = 'Discord'
AUTHORIZE_URL = 'https://discord.com/api/oauth2/authorize'
TOKEN_URL = 'https://discord.com/api/oauth2/token'
USERINFO_URL = 'https://discord.com/api/v10/users/@me'
def get_authorization_url(self, state: str, **kwargs: Any) -> str:
params: dict[str, str] = {
'client_id': self.client_id,
'redirect_uri': self.redirect_uri,
'response_type': 'code',
'scope': 'identify email',
'state': state,
'prompt': 'consent',
}
request = httpx.Request('GET', self.AUTHORIZE_URL, params=params)
return str(request.url)
async def exchange_code(self, code: str, **kwargs: Any) -> OAuthTokenResponse:
async with httpx.AsyncClient(timeout=30) as client:
response = await client.post(
self.TOKEN_URL,
data={
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
'grant_type': 'authorization_code',
'redirect_uri': self.redirect_uri,
},
)
response.raise_for_status()
data: OAuthTokenResponse = response.json()
return data
async def get_user_info(self, token_data: OAuthTokenResponse) -> OAuthUserInfo:
access_token = token_data['access_token']
async with httpx.AsyncClient(timeout=30) as client:
response = await client.get(
self.USERINFO_URL,
headers={'Authorization': f'Bearer {access_token}'},
)
response.raise_for_status()
data: DiscordUserInfoResponse = response.json()
avatar_url: str | None = None
if data.get('avatar'):
avatar_url = f'https://cdn.discordapp.com/avatars/{data["id"]}/{data["avatar"]}.png'
return OAuthUserInfo(
provider='discord',
provider_id=str(data['id']),
email=data.get('email'),
email_verified=data.get('verified', False),
first_name=data.get('global_name') or data.get('username'),
username=data.get('username'),
avatar_url=avatar_url,
)
class VKProvider(OAuthProvider):
"""VK ID OAuth 2.1 provider (id.vk.ru).
Uses OAuth 2.1 with mandatory PKCE (S256).
Old oauth.vk.com endpoints deprecated since September 30, 2025.
"""
name = 'vk'
display_name = 'VK'
AUTHORIZE_URL = 'https://id.vk.ru/authorize'
TOKEN_URL = 'https://id.vk.ru/oauth2/auth'
USERINFO_URL = 'https://id.vk.ru/oauth2/user_info'
@staticmethod
def _generate_pkce() -> tuple[str, str]:
"""Generate PKCE code_verifier and code_challenge (S256)."""
code_verifier = secrets.token_urlsafe(64)
digest = hashlib.sha256(code_verifier.encode('ascii')).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
return code_verifier, code_challenge
def prepare_auth_state(self) -> dict[str, str]:
"""Generate PKCE pair. code_verifier stored in Redis, code_challenge only goes to URL."""
code_verifier, code_challenge = self._generate_pkce()
# code_challenge is ephemeral — only needed for the authorization URL,
# not stored in Redis (code_verifier is the secret used during token exchange)
return {
'code_verifier': code_verifier,
'_code_challenge': code_challenge,
}
def get_authorization_url(self, state: str, **kwargs: Any) -> str:
code_challenge: str = kwargs.get('_code_challenge', '')
params: dict[str, str] = {
'client_id': self.client_id,
'redirect_uri': self.redirect_uri,
'response_type': 'code',
'scope': 'vkid.personal_info email',
'state': state,
'code_challenge': code_challenge,
'code_challenge_method': 'S256',
}
request = httpx.Request('GET', self.AUTHORIZE_URL, params=params)
return str(request.url)
async def exchange_code(self, code: str, **kwargs: Any) -> OAuthTokenResponse:
device_id: str = kwargs.get('device_id', '')
code_verifier: str = kwargs.get('code_verifier', '')
state: str = kwargs.get('state', '')
if not device_id:
raise ValueError('device_id is required for VK ID token exchange')
if not code_verifier:
raise ValueError('code_verifier is required for VK ID token exchange')
async with httpx.AsyncClient(timeout=30) as client:
response = await client.post(
self.TOKEN_URL,
data={
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': self.redirect_uri,
'client_id': self.client_id,
'device_id': device_id,
'code_verifier': code_verifier,
'state': state,
},
)
response.raise_for_status()
data: OAuthTokenResponse = response.json()
return data
async def get_user_info(self, token_data: OAuthTokenResponse) -> OAuthUserInfo:
access_token = token_data['access_token']
async with httpx.AsyncClient(timeout=30) as client:
response = await client.post(
self.USERINFO_URL,
data={
'access_token': access_token,
'client_id': self.client_id,
},
)
response.raise_for_status()
data: VKIDUserInfoResponse = response.json()
user_data = data.get('user')
if not user_data:
raise ValueError('VK ID response missing user data')
user_id = user_data.get('user_id')
if not user_id:
raise ValueError('VK ID response missing user_id')
# VK ID returns email only if 'email' scope was granted and user has a verified email
email: str | None = user_data.get('email') or None
return OAuthUserInfo(
provider='vk',
provider_id=str(user_id),
email=email,
email_verified=bool(email),
first_name=user_data.get('first_name'),
last_name=user_data.get('last_name'),
avatar_url=user_data.get('avatar'),
)
# --- Provider factory ---
_PROVIDERS: dict[str, type[OAuthProvider]] = {
'google': GoogleProvider,
'yandex': YandexProvider,
'discord': DiscordProvider,
'vk': VKProvider,
}
def get_provider(name: str) -> OAuthProvider | None:
"""Get an OAuth provider instance if enabled.
Returns None if the provider is not enabled or not found.
"""
providers_config: dict[str, OAuthProviderConfig] = settings.get_oauth_providers_config()
config = providers_config.get(name)
if not config or not config['enabled']:
return None
provider_class = _PROVIDERS.get(name)
if not provider_class:
return None
redirect_uri = f'{settings.CABINET_URL}/auth/oauth/callback'
return provider_class(
client_id=config['client_id'],
client_secret=config['client_secret'],
redirect_uri=redirect_uri,
)
+41
View File
@@ -0,0 +1,41 @@
"""Password hashing utilities using bcrypt."""
import bcrypt
BCRYPT_ROUNDS = 12
def hash_password(password: str) -> str:
"""
Hash a password using bcrypt.
Args:
password: Plain text password
Returns:
Hashed password string
"""
password_bytes = password.encode('utf-8')
salt = bcrypt.gensalt(rounds=BCRYPT_ROUNDS)
hashed = bcrypt.hashpw(password_bytes, salt)
return hashed.decode('utf-8')
def verify_password(password: str, password_hash: str) -> bool:
"""
Verify a password against its hash.
Args:
password: Plain text password to verify
password_hash: Previously hashed password
Returns:
True if password matches, False otherwise
"""
try:
password_bytes = password.encode('utf-8')
hash_bytes = password_hash.encode('utf-8')
return bcrypt.checkpw(password_bytes, hash_bytes)
except (ValueError, TypeError):
return False
+274
View File
@@ -0,0 +1,274 @@
"""Telegram authentication validation for cabinet."""
import asyncio
import hashlib
import hmac
import json
from datetime import UTC, datetime, timedelta
from typing import Any
from urllib.parse import parse_qsl
import httpx
import jwt as pyjwt
import structlog
from app.config import settings
logger = structlog.get_logger(__name__)
# Maximum allowed clock skew (seconds) for auth_date — tolerates minor drift between Telegram servers and ours.
_MAX_CLOCK_SKEW_SECONDS = 300
def validate_telegram_login_widget(data: dict[str, Any], max_age_seconds: int = 86400) -> bool:
"""
Validate Telegram Login Widget data.
https://core.telegram.org/widgets/login#checking-authorization
Args:
data: Dictionary with Telegram login data (id, first_name, auth_date, hash, etc.)
max_age_seconds: Maximum allowed age of auth_date (default 24 hours)
Returns:
True if data is valid, False otherwise
"""
auth_data = data.copy()
check_hash = auth_data.pop('hash', None)
if not check_hash:
return False
# Check auth_date is present and within valid range
auth_date = auth_data.get('auth_date')
if not auth_date:
return False
try:
auth_time = datetime.fromtimestamp(int(auth_date), tz=UTC)
age = (datetime.now(UTC) - auth_time).total_seconds()
if age > max_age_seconds or age < -_MAX_CLOCK_SKEW_SECONDS:
logger.warning(
'Telegram widget auth rejected: too old',
age_hours=round(age / 3600, 1),
max_age_hours=round(max_age_seconds / 3600, 1),
)
return False
if age > 86400:
logger.info(
'Telegram widget auth accepted with stale auth_date',
age_hours=round(age / 3600, 1),
)
except (ValueError, TypeError, OSError):
return False
# Build data-check-string (sorted key=value pairs, newline-separated)
data_check_arr = [f'{k}={v}' for k, v in sorted(auth_data.items()) if v is not None]
data_check_string = '\n'.join(data_check_arr)
# Create secret key from bot token using SHA256
bot_token = settings.BOT_TOKEN
secret_key = hashlib.sha256(bot_token.encode()).digest()
# Calculate expected hash
calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(calculated_hash, check_hash)
def validate_telegram_init_data(init_data: str, max_age_seconds: int = 86400) -> dict[str, Any] | None:
"""
Validate Telegram WebApp initData.
https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app
Args:
init_data: Raw initData string from Telegram WebApp
max_age_seconds: Maximum allowed age of auth_date (default 24 hours)
Returns:
Parsed user data dict if valid, None otherwise
"""
try:
# Parse the init_data string
parsed = dict(parse_qsl(init_data, keep_blank_values=True))
received_hash = parsed.pop('hash', None)
if not received_hash:
return None
# Check auth_date is present and within valid range
auth_date = parsed.get('auth_date')
if not auth_date:
return None
try:
auth_time = datetime.fromtimestamp(int(auth_date), tz=UTC)
age = (datetime.now(UTC) - auth_time).total_seconds()
if age > max_age_seconds or age < -_MAX_CLOCK_SKEW_SECONDS:
logger.warning(
'Telegram initData rejected: too old',
age_hours=round(age / 3600, 1),
max_age_hours=round(max_age_seconds / 3600, 1),
)
return None
if age > 86400:
logger.info(
'Telegram initData accepted with stale auth_date (Telegram caching bug)',
age_hours=round(age / 3600, 1),
)
except (ValueError, TypeError, OSError):
return None
# Build data-check-string
data_check_arr = [f'{k}={v}' for k, v in sorted(parsed.items())]
data_check_string = '\n'.join(data_check_arr)
# Create secret key: HMAC_SHA256(bot_token, "WebAppData")
bot_token = settings.BOT_TOKEN
secret_key = hmac.new(b'WebAppData', bot_token.encode(), hashlib.sha256).digest()
# Calculate expected hash
calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(calculated_hash, received_hash):
return None
# Parse user data from the validated data
user_data_str = parsed.get('user')
if user_data_str:
user_data = json.loads(user_data_str)
return user_data
return parsed
except (ValueError, TypeError, json.JSONDecodeError):
return None
def extract_telegram_user_from_init_data(init_data: str) -> dict[str, Any] | None:
"""
Extract and validate user info from Telegram WebApp initData.
Args:
init_data: Raw initData string from Telegram WebApp
Returns:
User data dict with id, first_name, last_name, username, etc. or None if invalid
"""
return validate_telegram_init_data(init_data)
# JWKS cache (module-level, refreshed periodically)
_jwks_cache: dict[str, Any] = {}
_jwks_cache_expiry: datetime | None = None
_JWKS_CACHE_TTL_SECONDS = 3600 # 1 hour
_JWKS_URL = 'https://oauth.telegram.org/.well-known/jwks.json'
_OIDC_ISSUER = 'https://oauth.telegram.org'
_jwks_lock = asyncio.Lock()
_jwks_last_force_refresh: datetime | None = None
_JWKS_FORCE_REFRESH_COOLDOWN_SECONDS = 30
def _build_public_keys(jwks_data: dict[str, Any]) -> dict[str, Any]:
"""Build public key mapping from JWKS data."""
public_keys: dict[str, Any] = {}
for key_data in jwks_data.get('keys', []):
kid = key_data.get('kid')
if kid:
public_keys[kid] = pyjwt.algorithms.RSAAlgorithm.from_jwk(key_data)
return public_keys
async def _get_jwks(force: bool = False) -> dict[str, Any]:
"""Fetch and cache Telegram OIDC JWKS keys."""
global _jwks_cache, _jwks_cache_expiry
now = datetime.now(UTC)
if not force and _jwks_cache and _jwks_cache_expiry and now < _jwks_cache_expiry:
return _jwks_cache
async with _jwks_lock:
# Double-check after acquiring lock
now = datetime.now(UTC)
if not force and _jwks_cache and _jwks_cache_expiry and now < _jwks_cache_expiry:
return _jwks_cache
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()
_jwks_cache_expiry = now + timedelta(seconds=_JWKS_CACHE_TTL_SECONDS)
return _jwks_cache
async def _force_refresh_jwks(kid: str) -> dict[str, Any] | None:
"""Force JWKS refresh with cooldown protection. Returns refreshed JWKS or None if on cooldown."""
global _jwks_cache_expiry, _jwks_last_force_refresh
async with _jwks_lock:
now = datetime.now(UTC)
if (
_jwks_last_force_refresh
and (now - _jwks_last_force_refresh).total_seconds() < _JWKS_FORCE_REFRESH_COOLDOWN_SECONDS
):
logger.warning('Telegram OIDC: JWKS force refresh on cooldown', kid=kid)
return None
_jwks_last_force_refresh = now
_jwks_cache_expiry = None
return await _get_jwks(force=True)
async def validate_telegram_oidc_token(id_token: str, client_id: str) -> dict[str, Any] | None:
"""
Validate a Telegram OIDC id_token using JWKS.
Args:
id_token: JWT id_token from Telegram OIDC flow
client_id: Expected audience (bot's numeric ID as string)
Returns:
Decoded claims dict if valid, None otherwise.
Claims include: sub, id, name, preferred_username, picture, iss, aud, exp, iat
"""
try:
# Build public keys from JWKS
jwks_data = await _get_jwks()
public_keys = _build_public_keys(jwks_data)
# Decode header to get kid
unverified_header = pyjwt.get_unverified_header(id_token)
kid = unverified_header.get('kid')
# If kid not found, force JWKS refresh (key rotation) with cooldown
if kid and kid not in public_keys:
refreshed = await _force_refresh_jwks(kid)
if refreshed:
public_keys = _build_public_keys(refreshed)
if not kid or kid not in public_keys:
logger.warning('Telegram OIDC: unknown kid in id_token', kid=kid)
return None
claims = pyjwt.decode(
id_token,
key=public_keys[kid],
algorithms=['RS256'],
audience=client_id,
issuer=_OIDC_ISSUER,
options={'require': ['exp', 'iat', 'iss', 'aud', 'sub']},
)
return claims
except pyjwt.ExpiredSignatureError:
logger.warning('Telegram OIDC: id_token expired')
return None
except pyjwt.InvalidTokenError as e:
logger.warning('Telegram OIDC: invalid id_token', error=str(e))
return None
except httpx.HTTPError as e:
logger.error('Telegram OIDC: failed to fetch JWKS', error=str(e))
return None
+378
View File
@@ -0,0 +1,378 @@
"""FastAPI dependencies for cabinet module."""
from datetime import UTC, datetime
import structlog
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.user import get_user_by_id
from app.database.database import AsyncSessionLocal
from app.database.models import User
from app.services.blacklist_service import blacklist_service
from app.services.maintenance_service import maintenance_service
from .auth.jwt_handler import get_token_payload
from .auth.telegram_auth import validate_telegram_init_data
from .ip_utils import get_client_ip
logger = structlog.get_logger(__name__)
security = HTTPBearer(auto_error=False)
async def get_cabinet_db() -> AsyncSession:
"""Get database session for cabinet operations."""
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
async def get_current_cabinet_user(
request: Request,
credentials: HTTPAuthorizationCredentials | None = Depends(security),
db: AsyncSession = Depends(get_cabinet_db),
) -> User:
"""
Get current authenticated cabinet user from JWT token.
Args:
request: FastAPI request object (for reading X-Telegram-Init-Data header)
credentials: HTTP Bearer credentials
db: Database session
Returns:
Authenticated User object
Raises:
HTTPException: If token is invalid, expired, or user not found
"""
# Check maintenance mode first (except for admins - checked later)
if maintenance_service.is_maintenance_active():
# We need to check token first to see if user is admin
pass # Will check after getting user
if not credentials:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Authentication required',
headers={'WWW-Authenticate': 'Bearer'},
)
token = credentials.credentials
payload = get_token_payload(token, expected_type='access')
if not payload:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid or expired token',
headers={'WWW-Authenticate': 'Bearer'},
)
try:
user_id = int(payload.get('sub'))
except (TypeError, ValueError):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid token payload',
headers={'WWW-Authenticate': 'Bearer'},
)
user = await get_user_by_id(db, user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='User not found',
)
if user.status != 'active':
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='User account is not active',
)
# Defense in depth: cross-validate Telegram identity.
# The frontend sends X-Telegram-Init-Data on every request.
# If the header is present and cryptographically valid, verify that
# the Telegram user ID matches the JWT user's telegram_id.
# This prevents cross-account token reuse when Telegram WebView
# shares localStorage across accounts on the same device.
init_data_raw = request.headers.get('X-Telegram-Init-Data')
if init_data_raw and user.telegram_id is not None:
# Use generous max_age: Telegram Desktop caches initData
tg_user = validate_telegram_init_data(init_data_raw, max_age_seconds=86400 * 30)
if tg_user is None:
logger.warning(
'Telegram initData validation failed but header was present',
jwt_user_id=user.id,
)
elif tg_user.get('id') != user.telegram_id:
logger.warning(
'Telegram identity mismatch: JWT belongs to different user than current Telegram account',
jwt_user_id=user.id,
jwt_telegram_id=user.telegram_id,
init_data_telegram_id=tg_user.get('id'),
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Session belongs to a different Telegram account. Please restart the app.',
headers={'WWW-Authenticate': 'Bearer'},
)
# Check blacklist
if user.telegram_id is not None:
is_blacklisted, reason = await blacklist_service.is_user_blacklisted(user.telegram_id, user.username)
if is_blacklisted:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={
'code': 'blacklisted',
'message': reason or 'Доступ запрещен',
},
)
# Check maintenance mode (allow admins to pass)
if maintenance_service.is_maintenance_active():
# Проверяем админа по telegram_id ИЛИ email
is_admin = settings.is_admin(telegram_id=user.telegram_id, email=user.email if user.email_verified else None)
if not is_admin:
status_info = maintenance_service.get_status_info()
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail={
'code': 'maintenance',
'message': maintenance_service.get_maintenance_message() or 'Service is under maintenance',
'reason': status_info.get('reason'),
},
)
# Check required channel subscription - Telegram users only
if settings.CHANNEL_IS_REQUIRED_SUB:
# Skip for email-only users (no telegram_id)
if user.telegram_id is not None:
# Skip admin check
is_admin = settings.is_admin(
telegram_id=user.telegram_id, email=user.email if user.email_verified else None
)
if not is_admin:
from app.services.channel_subscription_service import channel_subscription_service
channels_with_status = await channel_subscription_service.get_channels_with_status(user.telegram_id)
is_subscribed = (
all(ch['is_subscribed'] for ch in channels_with_status) if channels_with_status else True
)
if not is_subscribed:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={
'code': 'channel_subscription_required',
'message': 'Please subscribe to the required channels to continue',
'channels': channels_with_status,
},
)
# Throttled update of cabinet_last_login (at most every 5 minutes)
now = datetime.now(UTC)
if not user.cabinet_last_login or (now - user.cabinet_last_login).total_seconds() > 300:
try:
user.cabinet_last_login = now
await db.commit()
except Exception:
pass
return user
async def get_optional_cabinet_user(
request: Request,
credentials: HTTPAuthorizationCredentials | None = Depends(security),
db: AsyncSession = Depends(get_cabinet_db),
) -> User | None:
"""
Optionally get current authenticated cabinet user.
Returns None if no valid token is provided instead of raising an exception.
"""
if not credentials:
return None
token = credentials.credentials
payload = get_token_payload(token, expected_type='access')
if not payload:
return None
try:
user_id = int(payload.get('sub'))
except (TypeError, ValueError):
return None
user = await get_user_by_id(db, user_id)
if not user or user.status != 'active':
return None
# Cross-validate Telegram identity (same as get_current_cabinet_user)
init_data_raw = request.headers.get('X-Telegram-Init-Data')
if init_data_raw and user.telegram_id is not None:
tg_user = validate_telegram_init_data(init_data_raw, max_age_seconds=86400 * 30)
if tg_user and tg_user.get('id') != user.telegram_id:
logger.warning(
'Telegram identity mismatch in optional auth',
jwt_user_id=user.id,
jwt_telegram_id=user.telegram_id,
init_data_telegram_id=tg_user.get('id'),
)
return None
return user
async def get_current_admin_user(
request: Request,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> User:
"""
Get current authenticated admin user.
Checks if the user is admin by legacy config (ADMIN_IDS / ADMIN_EMAILS)
**or** by RBAC role assignment (any role with level > 0).
Args:
request: FastAPI request object
user: Authenticated User object
db: Database session
Returns:
Authenticated admin User object
Raises:
HTTPException: If user is not an admin by either mechanism
"""
# Legacy check: config-based admin list
is_legacy_admin = settings.is_admin(
telegram_id=user.telegram_id,
email=user.email if user.email_verified else None,
)
if is_legacy_admin:
return user
# RBAC check: user has any active role with level > 0
from app.database.crud.rbac import UserRoleCRUD
_permissions, _role_names, max_level = await UserRoleCRUD.get_user_permissions(db, user.id)
if max_level > 0:
return user
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Admin access required',
)
def require_permission(*permissions: str):
"""
FastAPI dependency factory for RBAC permission checks.
Usage::
@router.get("/users", dependencies=[Depends(require_permission("users:read"))])
async def list_users(...): ...
# Or inject the user:
@router.get("/users")
async def list_users(user: User = Depends(require_permission("users:read"))): ...
"""
if not permissions:
raise ValueError('require_permission() requires at least one permission argument')
async def dependency(
request: Request,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> User:
from app.services.permission_service import PermissionService
try:
client_ip = get_client_ip(request)
except HTTPException:
logger.warning('Unable to determine client IP in require_permission')
client_ip = 'unknown'
user_agent = request.headers.get('user-agent', '')
# Extract resource_type from the first permission (section before ':')
resource_type = None
if permissions:
first_perm = permissions[0]
if ':' in first_perm:
resource_type = first_perm.split(':', maxsplit=1)[0]
for perm in permissions:
allowed, reason = await PermissionService.check_permission(
db,
user,
perm,
ip_address=client_ip,
)
if not allowed:
await PermissionService.log_action(
db,
user_id=user.id,
action=perm,
resource_type=resource_type,
status='denied',
ip_address=client_ip,
user_agent=user_agent,
request_method=request.method,
request_path=str(request.url.path),
details={'reason': reason},
)
await db.commit()
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f'Permission denied: {reason}',
)
# Capture request details
details: dict = {
'method': request.method,
'path': str(request.url.path),
}
query_params = dict(request.query_params)
if query_params:
details['query_params'] = query_params
if request.method in ('POST', 'PUT', 'PATCH', 'DELETE'):
try:
body = await request.body()
if body:
import json
details['request_body'] = json.loads(body)
except Exception:
pass
# Log successful access with all requested permissions
await PermissionService.log_action(
db,
user_id=user.id,
action=','.join(permissions),
resource_type=resource_type,
status='success',
ip_address=client_ip,
user_agent=user_agent,
request_method=request.method,
request_path=str(request.url.path),
details=details,
)
await db.commit()
return user
return dependency
+60
View File
@@ -0,0 +1,60 @@
"""Shared IP extraction utilities for cabinet module."""
from ipaddress import ip_address, ip_network
from fastapi import HTTPException, Request, status
from app.config import settings
def _is_trusted_proxy(peer_ip: str, trusted: set[str]) -> bool:
"""Check if peer IP matches any trusted proxy entry (IP or CIDR)."""
if not trusted:
return False
try:
addr = ip_address(peer_ip)
except ValueError:
return False
for entry in trusted:
try:
if '/' in entry:
if addr in ip_network(entry, strict=False):
return True
elif addr == ip_address(entry):
return True
except ValueError:
continue
return False
def get_client_ip(request: Request) -> str:
"""Extract real client IP, trusting proxy headers only from known proxies.
Raises HTTPException 400 if the peer IP cannot be determined
(request.client is None — e.g., test harness or broken transport).
"""
if not request.client:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Unable to determine client IP',
)
peer_ip = request.client.host
trusted_proxies = settings.get_cabinet_trusted_proxies()
if trusted_proxies and _is_trusted_proxy(peer_ip, trusted_proxies):
forwarded = request.headers.get('X-Forwarded-For', '').split(',')[0].strip()
if forwarded:
try:
ip_address(forwarded)
return forwarded
except ValueError:
pass # invalid IP in header — fall through to peer_ip
real_ip = request.headers.get('X-Real-IP', '').strip()
if real_ip:
try:
ip_address(real_ip)
return real_ip
except ValueError:
pass
return peer_ip
+165
View File
@@ -0,0 +1,165 @@
"""Cabinet API routes."""
from fastapi import APIRouter
from .account_linking import merge_router as merge_router, router as account_linking_router
from .admin_apps import router as admin_apps_router
from .admin_audit_log import router as admin_audit_log_router
from .admin_ban_system import router as admin_ban_system_router
from .admin_broadcasts import router as admin_broadcasts_router
from .admin_bulk_actions import router as admin_bulk_actions_router
from .admin_button_styles import router as admin_button_styles_router
from .admin_campaigns import router as admin_campaigns_router
from .admin_channels import router as admin_channels_router
from .admin_email_templates import router as admin_email_templates_router
from .admin_info_pages import router as admin_info_pages_router
from .admin_landings import router as admin_landings_router
from .admin_menu_layout import router as admin_menu_layout_router
from .admin_news import router as admin_news_router
from .admin_news_categories import router as admin_news_categories_router
from .admin_news_media import router as admin_news_media_router
from .admin_news_tags import router as admin_news_tags_router
from .admin_partners import router as admin_partners_router
from .admin_payment_methods import router as admin_payment_methods_router
from .admin_payments import router as admin_payments_router
from .admin_pinned_messages import router as admin_pinned_messages_router
from .admin_policies import router as admin_policies_router
from .admin_promo_offers import router as admin_promo_offers_router
from .admin_promocodes import promo_groups_router as admin_promo_groups_router, router as admin_promocodes_router
from .admin_referral_network import router as admin_referral_network_router
from .admin_remnawave import router as admin_remnawave_router
from .admin_roles import router as admin_roles_router
from .admin_sales_stats import router as admin_sales_stats_router
from .admin_servers import router as admin_servers_router
from .admin_settings import router as admin_settings_router
from .admin_stats import router as admin_stats_router
from .admin_tariffs import router as admin_tariffs_router
from .admin_tickets import router as admin_tickets_router
from .admin_traffic import router as admin_traffic_router
from .admin_updates import router as admin_updates_router
from .admin_users import router as admin_users_router
from .admin_wheel import router as admin_wheel_router
from .admin_withdrawals import router as admin_withdrawals_router
from .auth import router as auth_router
from .balance import router as balance_router
from .branding import router as branding_router
from .contests import router as contests_router
from .gift import router as gift_router
from .info import router as info_router
from .info_pages import router as info_pages_router
from .landing import router as landing_router
from .media import router as media_router
from .news import router as news_router
from .notifications import router as notifications_router
from .oauth import router as oauth_router
from .partner_application import router as partner_application_router
from .polls import router as polls_router
from .promo import router as promo_router
from .promocode import router as promocode_router
from .referral import router as referral_router
from .subscription import router as subscription_router
from .subscription_modules.multi_tariff import router as multi_tariff_subscription_router
from .ticket_notifications import (
admin_router as admin_ticket_notifications_router,
router as ticket_notifications_router,
)
from .tickets import router as tickets_router
from .websocket import router as websocket_router
from .wheel import router as wheel_router
from .withdrawal import router as withdrawal_router
# Conditional imports
try:
from .apple_iap import router as apple_iap_router
except ImportError:
apple_iap_router = None
# Main cabinet router
router = APIRouter(prefix='/cabinet', tags=['Cabinet'], redirect_slashes=False)
# Include all sub-routers
router.include_router(auth_router)
router.include_router(oauth_router)
router.include_router(account_linking_router)
router.include_router(merge_router)
router.include_router(subscription_router)
router.include_router(multi_tariff_subscription_router)
router.include_router(balance_router)
router.include_router(referral_router)
# Apple IAP routes
if apple_iap_router is not None:
router.include_router(apple_iap_router)
router.include_router(partner_application_router)
router.include_router(withdrawal_router)
# Notifications router MUST be before tickets router to avoid route conflict
router.include_router(ticket_notifications_router)
router.include_router(tickets_router)
router.include_router(promocode_router)
router.include_router(contests_router)
router.include_router(polls_router)
router.include_router(promo_router)
router.include_router(notifications_router)
router.include_router(info_router)
router.include_router(branding_router)
router.include_router(landing_router)
router.include_router(media_router)
router.include_router(news_router)
router.include_router(info_pages_router)
# Wheel routes
router.include_router(wheel_router)
# Gift routes
router.include_router(gift_router)
# Admin routes (notifications router MUST be before tickets router to avoid route conflict)
router.include_router(admin_ticket_notifications_router)
router.include_router(admin_tickets_router)
router.include_router(admin_settings_router)
router.include_router(admin_wheel_router)
router.include_router(admin_tariffs_router)
router.include_router(admin_servers_router)
router.include_router(admin_stats_router)
router.include_router(admin_referral_network_router)
router.include_router(admin_sales_stats_router)
router.include_router(admin_ban_system_router)
router.include_router(admin_broadcasts_router)
router.include_router(admin_promocodes_router)
router.include_router(admin_promo_groups_router)
router.include_router(admin_campaigns_router)
router.include_router(admin_partners_router)
router.include_router(admin_withdrawals_router)
router.include_router(admin_users_router)
router.include_router(admin_bulk_actions_router)
router.include_router(admin_payment_methods_router)
router.include_router(admin_landings_router)
router.include_router(admin_payments_router)
router.include_router(admin_promo_offers_router)
router.include_router(admin_remnawave_router)
router.include_router(admin_email_templates_router)
router.include_router(admin_updates_router)
router.include_router(admin_traffic_router)
router.include_router(admin_pinned_messages_router)
router.include_router(admin_button_styles_router)
router.include_router(admin_menu_layout_router)
router.include_router(admin_channels_router)
router.include_router(admin_apps_router)
router.include_router(admin_roles_router)
router.include_router(admin_policies_router)
router.include_router(admin_audit_log_router)
# Categories/tags/media routers MUST be before the main news router
# to avoid /admin/news/{article_id} catching /admin/news/categories etc.
router.include_router(admin_news_categories_router)
router.include_router(admin_news_tags_router)
router.include_router(admin_news_media_router)
router.include_router(admin_news_router)
router.include_router(admin_info_pages_router)
# WebSocket route
router.include_router(websocket_router)
__all__ = ['router']
+930
View File
@@ -0,0 +1,930 @@
"""Account linking and merge routes for cabinet.
Router 1 (`router`): JWT-protected endpoints for linking/unlinking OAuth providers.
Exception: `link/server-complete` uses state-token auth instead of JWT (for Mini App external browser flow).
Router 2 (`merge_router`): Public endpoints for merge preview and execution.
"""
import hashlib
from datetime import UTC, datetime
from typing import Literal, NotRequired, TypedDict
import structlog
from fastapi import APIRouter, Depends, HTTPException, Path, Request, status
from pydantic import BaseModel, Field, model_validator
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.system_setting import get_setting_value
from app.database.crud.user import (
OAUTH_PROVIDER_COLUMNS,
clear_user_oauth_provider_id,
get_user_by_id,
get_user_by_oauth_provider,
get_user_by_telegram_id,
set_user_oauth_provider_id,
)
from app.database.models import User
from app.services.account_merge_service import compute_auth_methods, execute_merge, get_merge_preview
from app.utils.cache import RateLimitCache, TokenReplayCache
from ..auth.merge_service import (
MERGE_TOKEN_TTL_SECONDS,
consume_merge_token,
create_merge_token,
get_merge_token_data,
restore_merge_token,
)
from ..auth.oauth_providers import (
generate_oauth_state,
get_provider,
validate_oauth_state,
)
from ..auth.telegram_auth import (
validate_telegram_init_data,
validate_telegram_login_widget,
validate_telegram_oidc_token,
)
from ..dependencies import get_cabinet_db, get_current_cabinet_user
from ..ip_utils import get_client_ip
from ..schemas.auth import UserResponse
from .auth import _create_auth_response, _store_refresh_token, _user_to_response
logger = structlog.get_logger(__name__)
OAuthProviderName = Literal['google', 'yandex', 'discord', 'vk']
# Ensure OAuthProviderName Literal stays in sync with OAUTH_PROVIDER_COLUMNS
_EXPECTED_PROVIDERS = {'google', 'yandex', 'discord', 'vk'}
if set(OAUTH_PROVIDER_COLUMNS.keys()) != _EXPECTED_PROVIDERS:
raise RuntimeError(
f'OAuthProviderName Literal is out of sync with OAUTH_PROVIDER_COLUMNS: '
f'{set(OAUTH_PROVIDER_COLUMNS.keys())} != {_EXPECTED_PROVIDERS}'
)
class OAuthStateData(TypedDict):
"""Typed dict for Redis-stored OAuth state data."""
provider: str # Always present
linking: NotRequired[str] # 'true' if account linking flow
user_id: NotRequired[str] # ID of user who initiated linking
code_verifier: NotRequired[str] # PKCE code verifier (VK)
def _get_active_providers() -> list[str]:
"""Вернуть список активных провайдеров аутентификации (только включённые)."""
providers: list[str] = ['telegram']
if settings.is_cabinet_email_auth_enabled():
providers.append('email')
providers.extend(settings.get_enabled_oauth_provider_names())
return providers
# ---------------------------------------------------------------------------
# Schemas
# ---------------------------------------------------------------------------
class LinkedProvider(BaseModel):
provider: str
linked: bool
identifier: str | None = None
class LinkedProvidersResponse(BaseModel):
providers: list[LinkedProvider]
class LinkInitResponse(BaseModel):
authorize_url: str
state: str
class LinkCallbackRequest(BaseModel):
code: str = Field(..., min_length=1, max_length=2048, description='Authorization code from provider')
state: str = Field(..., min_length=1, max_length=128, description='CSRF state token')
device_id: str | None = Field(None, max_length=256, description='Device ID from VK ID callback')
class LinkCallbackResponse(BaseModel):
success: bool
message: str | None = None
merge_required: bool = False
merge_token: str | None = None
class UnlinkResponse(BaseModel):
success: bool
class LinkTelegramRequest(BaseModel):
"""Request for linking Telegram account. Supply EITHER init_data, id_token, OR widget fields."""
# Mini App: Telegram WebApp initData
init_data: str | None = Field(None, max_length=4096, description='Telegram WebApp initData string')
# OIDC: id_token from Telegram Login popup
id_token: str | None = Field(None, max_length=4096, description='Telegram OIDC id_token (JWT)')
# Login Widget fields
id: int | None = Field(None, description='Telegram user ID from Login Widget')
first_name: str | None = Field(None, max_length=256, description="User's first name")
last_name: str | None = Field(None, max_length=256, description="User's last name")
username: str | None = Field(None, max_length=256, description="User's username")
photo_url: str | None = Field(None, max_length=2048, description="User's photo URL")
auth_date: int | None = Field(None, description='Unix timestamp of authentication')
hash: str | None = Field(None, min_length=64, max_length=64, description='Authentication hash (SHA-256 hex)')
@model_validator(mode='after')
def check_exclusive(self) -> 'LinkTelegramRequest':
has_init = self.init_data is not None
has_oidc = self.id_token is not None
has_widget = self.id is not None or self.hash is not None or self.auth_date is not None
modes = sum([has_init, has_oidc, has_widget])
if modes > 1:
raise ValueError('Provide exactly one of: init_data, id_token, or Login Widget fields')
if modes == 0:
raise ValueError('Provide one of: init_data, id_token, or Login Widget fields (id, auth_date, hash)')
if has_widget and not (self.id is not None and self.auth_date is not None and self.hash is not None):
raise ValueError('Login Widget mode requires id, auth_date, and hash fields')
return self
class MergePreviewSubscription(BaseModel):
status: str
is_trial: bool
end_date: datetime | None = None
traffic_limit_gb: float
traffic_used_gb: float
device_limit: int
tariff_name: str | None = None
autopay_enabled: bool
class MergePreviewUser(BaseModel):
id: int
username: str | None = None
first_name: str | None = None
email: str | None = None
auth_methods: list[str]
balance_kopeks: int = 0
subscription: MergePreviewSubscription | None = None
created_at: datetime | None = None
class MergePreviewResponse(BaseModel):
primary: MergePreviewUser
secondary: MergePreviewUser
expires_in_seconds: int
class MergeRequest(BaseModel):
keep_subscription_from: int = Field(..., description='User ID whose subscription to keep')
class MergeResponse(BaseModel):
success: bool
access_token: str | None = None
refresh_token: str | None = None
user: UserResponse | None = None
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _get_provider_identifier(user: User, provider: str) -> str | None:
"""Return the identifier (provider_id or email) for a given provider, or None."""
match provider:
case 'telegram':
return str(user.telegram_id) if user.telegram_id else None
case 'email':
return user.email if user.email and user.password_hash else None
case _:
column = OAUTH_PROVIDER_COLUMNS.get(provider)
if not column:
return None
value = getattr(user, column, None)
return str(value) if value else None
def _count_auth_methods(user: User) -> int:
"""Count how many auth methods the user has linked."""
return len(compute_auth_methods(user))
async def _exchange_and_link_oauth(
*,
db: AsyncSession,
user: User,
provider: str,
code: str,
state: str,
state_data: OAuthStateData,
device_id: str | None,
log_context: str,
) -> LinkCallbackResponse:
"""Shared OAuth linking logic: exchange code, fetch user info, link or merge.
Used by both link_provider_callback (JWT-authed) and link_server_complete (state-authed).
"""
oauth_provider = get_provider(provider)
if not oauth_provider:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Requested OAuth provider is not available',
)
# Exchange code for tokens
exchange_kwargs: dict[str, str] = {'state': state}
code_verifier = state_data.get('code_verifier')
if code_verifier:
exchange_kwargs['code_verifier'] = code_verifier
if device_id:
exchange_kwargs['device_id'] = device_id
try:
token_data = await oauth_provider.exchange_code(code, **exchange_kwargs)
except Exception as exc:
logger.error('OAuth code exchange failed', context=log_context, provider=provider, exc_info=True)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Failed to exchange authorization code',
) from exc
# Fetch user info from provider
try:
user_info = await oauth_provider.get_user_info(token_data)
except Exception as exc:
logger.error('OAuth user info fetch failed', context=log_context, provider=provider, exc_info=True)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Failed to fetch user information from provider',
) from exc
# Check if provider_id is already linked to THIS user
column = OAUTH_PROVIDER_COLUMNS[provider]
current_value = getattr(user, column, None)
if current_value and str(current_value) == user_info.provider_id:
return LinkCallbackResponse(success=True, message='already_linked')
# Check if provider_id is linked to ANOTHER user
existing_user = await get_user_by_oauth_provider(db, provider, user_info.provider_id)
if existing_user and existing_user.id != user.id:
logger.info(
'Account linking conflict: provider already linked to another user',
context=log_context,
provider=provider,
provider_id=user_info.provider_id,
current_user_id=user.id,
existing_user_id=existing_user.id,
)
merge_token = await create_merge_token(
primary_user_id=user.id,
secondary_user_id=existing_user.id,
provider=provider,
provider_id=user_info.provider_id,
)
return LinkCallbackResponse(
success=False,
merge_required=True,
merge_token=merge_token,
)
# Link the provider to current user
await set_user_oauth_provider_id(db, user, provider, user_info.provider_id)
try:
await db.commit()
except IntegrityError as exc:
await db.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='This provider account was just linked to another user',
) from exc
logger.info(
'OAuth provider linked to account',
context=log_context,
provider=provider,
provider_id=user_info.provider_id,
user_id=user.id,
)
return LinkCallbackResponse(success=True, message='linked')
# ---------------------------------------------------------------------------
# Router 1: Account linking (JWT required)
# ---------------------------------------------------------------------------
router = APIRouter(prefix='/auth/account', tags=['Cabinet Account Linking'])
@router.get('/linked-providers', response_model=LinkedProvidersResponse)
async def get_linked_providers(
user: User = Depends(get_current_cabinet_user),
) -> LinkedProvidersResponse:
"""Return all auth methods with their link status for the current user."""
providers: list[LinkedProvider] = []
for provider in _get_active_providers():
identifier = _get_provider_identifier(user, provider)
providers.append(
LinkedProvider(
provider=provider,
linked=identifier is not None,
identifier=identifier,
)
)
return LinkedProvidersResponse(providers=providers)
@router.get('/link/{provider}/init', response_model=LinkInitResponse)
async def link_provider_init(
provider: OAuthProviderName,
user: User = Depends(get_current_cabinet_user),
) -> LinkInitResponse:
"""Start OAuth flow for linking a new provider to the current account."""
# Check if already linked
column = OAUTH_PROVIDER_COLUMNS[provider]
if getattr(user, column, None):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Provider is already linked to your account',
)
oauth_provider = get_provider(provider)
if not oauth_provider:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Requested OAuth provider is not available',
)
# Generate PKCE data for VK (and potentially future providers)
auth_extra = oauth_provider.prepare_auth_state()
extra_data: dict[str, str] = {
'linking': 'true',
'user_id': str(user.id),
}
if auth_extra:
extra_data.update(auth_extra)
state = await generate_oauth_state(provider, extra_data=extra_data)
# Only pass URL-safe params (prefixed with _) to authorize URL; exclude secrets like code_verifier
url_params = {k: v for k, v in auth_extra.items() if k.startswith('_')} if auth_extra else {}
authorize_url = oauth_provider.get_authorization_url(state, **url_params)
return LinkInitResponse(authorize_url=authorize_url, state=state)
@router.post('/link/{provider}/callback', response_model=LinkCallbackResponse)
async def link_provider_callback(
provider: OAuthProviderName,
request: LinkCallbackRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> LinkCallbackResponse:
"""Handle OAuth callback for linking a provider to the current account."""
# 1. Validate CSRF state
state_data = await validate_oauth_state(request.state, provider)
if not state_data:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid or expired OAuth state',
)
# 1b. Validate that this state was created for account linking (not login)
if state_data.get('linking') != 'true' or not state_data.get('user_id'):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='OAuth state was not initiated for account linking',
)
# 1c. Validate that the user who initiated the link flow is the same user completing it
state_user_id = state_data['user_id']
if str(user.id) != state_user_id:
logger.warning(
'OAuth state user_id mismatch in link callback',
state_user_id=state_user_id,
current_user_id=user.id,
provider=provider,
)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='OAuth state was initiated by a different user',
)
# 2-7. Exchange code, fetch user info, link or merge
return await _exchange_and_link_oauth(
db=db,
user=user,
provider=provider,
code=request.code,
state=request.state,
state_data=state_data,
device_id=request.device_id,
log_context='link-callback',
)
@router.post('/unlink/{provider}', response_model=UnlinkResponse)
async def unlink_provider(
provider: OAuthProviderName,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> UnlinkResponse:
"""Unlink an OAuth provider from the current account."""
column = OAUTH_PROVIDER_COLUMNS[provider]
if not getattr(user, column, None):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Provider is not linked to your account',
)
# Ensure at least one auth method remains
if _count_auth_methods(user) <= 1:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Cannot unlink last authentication method',
)
await clear_user_oauth_provider_id(db, user, provider)
await db.commit()
return UnlinkResponse(success=True)
@router.post('/link/telegram', response_model=LinkCallbackResponse)
async def link_telegram(
request: LinkTelegramRequest,
raw_request: Request,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> LinkCallbackResponse:
"""Link Telegram account via WebApp initData, OIDC id_token, or Login Widget."""
# Rate limit
client_ip = get_client_ip(raw_request)
if await RateLimitCache.is_ip_rate_limited(client_ip, 'link_telegram', limit=10, window=60, fail_closed=True):
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail='Too many requests',
headers={'Retry-After': '60'},
)
# 1. Already has Telegram linked?
if user.telegram_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Telegram is already linked to your account',
)
# 2. Validate and extract telegram_id
telegram_id: int | None = None
telegram_username: str | None = None
telegram_first_name: str | None = None
telegram_last_name: str | None = None
if request.init_data:
# Mini App flow: validate initData
# Generous max_age: Telegram Desktop/iOS cache initData with stale auth_date
user_data = validate_telegram_init_data(request.init_data, max_age_seconds=86400 * 30)
if not user_data or not user_data.get('id'):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid or expired Telegram initData',
)
telegram_id = int(user_data['id'])
telegram_username = user_data.get('username')
telegram_first_name = user_data.get('first_name')
telegram_last_name = user_data.get('last_name')
elif request.id_token:
# OIDC flow: validate id_token via JWKS
oidc_enabled_val = await get_setting_value(db, 'TELEGRAM_OIDC_ENABLED')
oidc_client_id_val = await get_setting_value(db, 'TELEGRAM_OIDC_CLIENT_ID')
oidc_client_id = oidc_client_id_val or settings.TELEGRAM_OIDC_CLIENT_ID
oidc_enabled = (
oidc_enabled_val.lower() == 'true' if oidc_enabled_val is not None else settings.TELEGRAM_OIDC_ENABLED
) and bool(oidc_client_id)
if not oidc_enabled:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Telegram OIDC is not configured',
)
claims = await validate_telegram_oidc_token(request.id_token, oidc_client_id)
if not claims:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid or expired Telegram OIDC token',
)
# Replay detection
token_hash = hashlib.sha256(request.id_token.encode()).hexdigest()
token_ttl = max(int(claims.get('exp', 0) - datetime.now(UTC).timestamp()), 60)
if await TokenReplayCache.is_token_replayed(token_hash, ttl=min(token_ttl, 600)):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid or expired Telegram OIDC token',
)
try:
telegram_id = int(claims.get('id', claims.get('sub', 0)))
except (ValueError, TypeError) as exc:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid user ID in OIDC claims',
) from exc
if not telegram_id:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Missing user ID in OIDC claims',
)
telegram_username = claims.get('preferred_username')
telegram_first_name = claims.get('name', claims.get('given_name', ''))
telegram_last_name = claims.get('family_name')
elif request.id is not None and request.hash is not None and request.auth_date is not None:
# Login Widget flow: validate widget hash
widget_data = {
'id': request.id,
'auth_date': request.auth_date,
'hash': request.hash,
}
if request.first_name is not None:
widget_data['first_name'] = request.first_name
if request.last_name is not None:
widget_data['last_name'] = request.last_name
if request.username is not None:
widget_data['username'] = request.username
if request.photo_url is not None:
widget_data['photo_url'] = request.photo_url
# Generous max_age: Telegram caches auth data with stale auth_date
if not validate_telegram_login_widget(widget_data, max_age_seconds=86400 * 30):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid or expired Telegram Login Widget data',
)
telegram_id = request.id
telegram_username = request.username
telegram_first_name = request.first_name
telegram_last_name = request.last_name
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Provide init_data (Mini App), id_token (OIDC), or Login Widget fields (id, auth_date, hash)',
)
# 3. Check if telegram_id is linked to ANOTHER user
existing_user = await get_user_by_telegram_id(db, telegram_id)
if existing_user and existing_user.id != user.id:
logger.info(
'Telegram linking conflict: telegram_id already linked to another user',
telegram_id=telegram_id,
current_user_id=user.id,
existing_user_id=existing_user.id,
)
merge_token = await create_merge_token(
primary_user_id=user.id,
secondary_user_id=existing_user.id,
provider='telegram',
provider_id=str(telegram_id),
)
return LinkCallbackResponse(
success=False,
merge_required=True,
merge_token=merge_token,
)
# 4. Link Telegram to current user
user.telegram_id = telegram_id
if telegram_username and not user.username:
user.username = telegram_username
if telegram_first_name and not user.first_name:
user.first_name = telegram_first_name
if telegram_last_name and not user.last_name:
user.last_name = telegram_last_name
user.updated_at = datetime.now(UTC)
try:
await db.commit()
except IntegrityError as exc:
await db.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='This Telegram account was just linked to another user',
) from exc
logger.info(
'Telegram linked to account',
telegram_id=telegram_id,
user_id=user.id,
)
# 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')
# ---------------------------------------------------------------------------
# Server-side OAuth linking callback (NO JWT required — auth via state token)
# Used by Telegram Mini App where OAuth must open in external browser.
# ---------------------------------------------------------------------------
class ServerCompleteRequest(BaseModel):
code: str = Field(..., min_length=1, max_length=2048, description='Authorization code from provider')
state: str = Field(..., min_length=1, max_length=128, description='CSRF state token')
provider: OAuthProviderName | None = Field(None, description='OAuth provider name (resolved from state if omitted)')
device_id: str | None = Field(None, max_length=256, description='Device ID from VK ID callback')
class ServerCompleteResponse(LinkCallbackResponse):
provider: str
@router.post('/link/server-complete', response_model=ServerCompleteResponse)
async def link_server_complete(
request: ServerCompleteRequest,
raw_request: Request,
db: AsyncSession = Depends(get_cabinet_db),
) -> ServerCompleteResponse:
"""Complete OAuth account linking without JWT.
Authenticates via the one-time state token stored in Redis during link_provider_init.
Used when OAuth opens in an external browser (e.g., from Telegram Mini App).
Provider is resolved from the state token if not explicitly provided.
"""
# Rate limit by IP (unauthenticated endpoint)
client_ip = get_client_ip(raw_request)
if await RateLimitCache.is_ip_rate_limited(client_ip, 'server_complete', limit=10, window=60, fail_closed=True):
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
# 1. Validate and consume state from Redis (one-time use).
# Provider may be None — validate_oauth_state will skip provider check,
# and we'll resolve it from state_data['provider'].
state_data = await validate_oauth_state(request.state, request.provider)
if not state_data:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid or expired OAuth state',
)
# Resolve provider from state data (canonical source)
state_provider: str = state_data.get('provider', '')
if not state_provider or state_provider not in OAUTH_PROVIDER_COLUMNS:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Could not determine OAuth provider',
)
# If request explicitly provides a provider, ensure it matches the state
if request.provider and request.provider != state_provider:
logger.warning(
'Provider mismatch in server-complete',
request_provider=request.provider,
state_provider=state_provider,
)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Provider does not match OAuth state',
)
provider_name: str = state_provider
# 2. Must be a linking state (not login)
if state_data.get('linking') != 'true' or not state_data.get('user_id'):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='OAuth state was not initiated for account linking',
)
# 3. Parse and validate user_id from state
try:
user_id = int(state_data['user_id'])
except (ValueError, TypeError) as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid user_id in OAuth state',
) from exc
# 4. Load user from DB
user = await get_user_by_id(db, user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='User not found',
)
# 5-9. Exchange code, fetch user info, link or merge
result = await _exchange_and_link_oauth(
db=db,
user=user,
provider=provider_name,
code=request.code,
state=request.state,
state_data=state_data,
device_id=request.device_id,
log_context='server-complete',
)
return ServerCompleteResponse(
success=result.success,
message=result.message,
merge_required=result.merge_required,
merge_token=result.merge_token,
provider=provider_name,
)
# ---------------------------------------------------------------------------
# Router 2: Merge (NO JWT required)
# ---------------------------------------------------------------------------
merge_router = APIRouter(prefix='/auth/merge', tags=['Cabinet Account Merge'])
@merge_router.get('/{merge_token}', response_model=MergePreviewResponse)
async def get_merge_preview_endpoint(
raw_request: Request,
merge_token: str = Path(..., min_length=32, max_length=64),
db: AsyncSession = Depends(get_cabinet_db),
) -> MergePreviewResponse:
"""Preview the result of merging two accounts before confirming."""
# Rate limit by IP (unauthenticated endpoint)
client_ip = get_client_ip(raw_request)
if await RateLimitCache.is_ip_rate_limited(client_ip, 'merge_preview', limit=15, window=60, fail_closed=True):
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
token_data = await get_merge_token_data(merge_token)
if not token_data:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Merge token is invalid or expired',
)
primary_user_id: int = token_data['primary_user_id']
secondary_user_id: int = token_data['secondary_user_id']
try:
preview = await get_merge_preview(db, primary_user_id, secondary_user_id)
except ValueError as exc:
logger.error('Merge preview failed', error=str(exc))
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='One or both users not found',
) from exc
# Calculate remaining TTL
created_at_str: str = token_data.get('created_at', '')
try:
created_at = datetime.fromisoformat(created_at_str)
if created_at.tzinfo is None:
created_at = created_at.replace(tzinfo=UTC)
elapsed = (datetime.now(UTC) - created_at).total_seconds()
expires_in_seconds = max(0, int(MERGE_TOKEN_TTL_SECONDS - elapsed))
except (ValueError, TypeError):
expires_in_seconds = 0
return MergePreviewResponse(
primary=MergePreviewUser(**preview['primary']),
secondary=MergePreviewUser(**preview['secondary']),
expires_in_seconds=expires_in_seconds,
)
@merge_router.post('/{merge_token}', response_model=MergeResponse)
async def execute_merge_endpoint(
request: MergeRequest,
raw_request: Request,
merge_token: str = Path(..., min_length=32, max_length=64),
db: AsyncSession = Depends(get_cabinet_db),
) -> MergeResponse:
"""Execute account merge. Consumes the merge token (one-time use)."""
# Rate limit by IP (unauthenticated endpoint)
client_ip = get_client_ip(raw_request)
if await RateLimitCache.is_ip_rate_limited(client_ip, 'merge_execute', limit=5, window=60, fail_closed=True):
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
# 1. Consume token atomically first (GETDEL — one-time use, no TOCTOU)
consumed = await consume_merge_token(merge_token)
if not consumed:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Merge token is invalid, expired, or already consumed',
)
primary_user_id: int = consumed['primary_user_id']
secondary_user_id: int = consumed['secondary_user_id']
provider: str = consumed.get('provider', '')
provider_id: str = consumed.get('provider_id', '')
# 2. Validate keep_subscription_from — restore token if invalid
if request.keep_subscription_from not in (primary_user_id, secondary_user_id):
await restore_merge_token(merge_token, consumed)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='keep_subscription_from must be one of the two user IDs being merged',
)
# Convert user_id to 'primary'/'secondary' string for execute_merge()
keep_from: Literal['primary', 'secondary'] = (
'primary' if request.keep_subscription_from == primary_user_id else 'secondary'
)
# 3. Execute merge
try:
merged_user = await execute_merge(
db=db,
primary_user_id=primary_user_id,
secondary_user_id=secondary_user_id,
keep_subscription_from=keep_from,
provider=provider,
provider_id=provider_id,
)
await db.commit()
except ValueError as exc:
await db.rollback()
await restore_merge_token(merge_token, consumed)
logger.error('Merge execution failed (ValueError)', error=str(exc))
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Account merge cannot be completed. The accounts may have already been merged or deleted.',
) from exc
except Exception as exc:
await db.rollback()
await restore_merge_token(merge_token, consumed)
logger.exception('Merge execution failed')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Account merge failed due to an internal error',
) from exc
# 4. Re-fetch merged user with full relationships for auth response
merged_user = await get_user_by_id(db, primary_user_id)
if not merged_user:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load merged user',
)
# 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)
await _store_refresh_token(db, merged_user.id, auth_response.refresh_token, device_info='merge')
except Exception as exc:
logger.exception('Failed to create auth tokens after merge')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Merge succeeded but failed to create new session',
) from exc
logger.info(
'Account merge completed successfully',
primary_user_id=primary_user_id,
secondary_user_id=secondary_user_id,
provider=provider,
)
return MergeResponse(
success=True,
access_token=auth_response.access_token,
refresh_token=auth_response.refresh_token,
user=_user_to_response(merged_user),
)
+163
View File
@@ -0,0 +1,163 @@
"""Admin routes for managing RemnaWave app configuration."""
import re
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import User
from app.services.remnawave_service import RemnaWaveService
from app.services.system_settings_service import bot_configuration_service
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/apps', tags=['Cabinet Admin Apps'])
# ============ Schemas ============
class RemnaWaveConfigStatus(BaseModel):
"""Status of RemnaWave config integration."""
enabled: bool
config_uuid: str | None = None
class UpdateRemnaWaveUuidRequest(BaseModel):
"""Request to update RemnaWave config UUID."""
uuid: str | None = None
# ============ Helpers ============
_UUID_PATTERN = re.compile(r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')
def _get_remnawave_config_uuid() -> str | None:
"""Get RemnaWave config UUID from system settings or env."""
try:
return bot_configuration_service.get_current_value('CABINET_REMNA_SUB_CONFIG')
except Exception:
return settings.CABINET_REMNA_SUB_CONFIG
# ============ Routes ============
@router.get('/remnawave/status', response_model=RemnaWaveConfigStatus)
async def get_remnawave_config_status(
admin: User = Depends(require_permission('apps:read')),
):
"""Get RemnaWave config integration status."""
config_uuid = _get_remnawave_config_uuid()
return RemnaWaveConfigStatus(
enabled=bool(config_uuid),
config_uuid=config_uuid,
)
@router.put('/remnawave/uuid', response_model=RemnaWaveConfigStatus)
async def set_remnawave_config_uuid(
request: UpdateRemnaWaveUuidRequest,
admin: User = Depends(require_permission('apps:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Set RemnaWave subscription config UUID."""
uuid_value = request.uuid.strip() if request.uuid else None
if uuid_value and not _UUID_PATTERN.match(uuid_value):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid UUID format',
)
try:
await bot_configuration_service.set_value(db, 'CABINET_REMNA_SUB_CONFIG', uuid_value)
await db.commit()
from app.handlers.subscription.common import invalidate_app_config_cache
invalidate_app_config_cache()
logger.info('Admin updated CABINET_REMNA_SUB_CONFIG', admin_id=admin.id, uuid_value=uuid_value)
except Exception as e:
logger.error('Error saving RemnaWave config UUID', error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to save configuration',
)
return RemnaWaveConfigStatus(
enabled=bool(uuid_value),
config_uuid=uuid_value,
)
@router.get('/remnawave/config')
async def get_remnawave_subscription_config(
admin: User = Depends(require_permission('apps:read')),
):
"""Fetch subscription page config from RemnaWave panel."""
config_uuid = _get_remnawave_config_uuid()
if not config_uuid:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='RemnaWave subscription config is not configured',
)
try:
service = RemnaWaveService()
async with service.get_api_client() as api:
config = await api.get_subscription_page_config(config_uuid)
if not config:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Subscription config not found',
)
return {
'uuid': config.uuid,
'name': config.name,
'view_position': config.view_position,
'config': config.config,
}
except HTTPException:
raise
except Exception as e:
logger.error('Error fetching RemnaWave config', error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to fetch config from RemnaWave',
)
@router.get('/remnawave/configs')
async def list_remnawave_subscription_configs(
admin: User = Depends(require_permission('apps:read')),
):
"""List available subscription page configs from RemnaWave panel."""
try:
service = RemnaWaveService()
async with service.get_api_client() as api:
configs = await api.get_subscription_page_configs()
return [
{
'uuid': c.uuid,
'name': c.name,
'view_position': c.view_position,
}
for c in configs
]
except Exception as e:
logger.error('Error listing RemnaWave configs', error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to fetch configs from RemnaWave',
)
+208
View File
@@ -0,0 +1,208 @@
"""Admin audit log routes — view and export admin action history."""
from __future__ import annotations
import csv
import io
from datetime import UTC, datetime
from typing import Any
import structlog
from fastapi import APIRouter, Depends, Query
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.rbac import AuditLogCRUD
from app.database.models import User
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/rbac/audit-log', tags=['Admin RBAC Audit Log'])
# ============ Schemas ============
class AuditLogEntry(BaseModel):
"""Single audit log entry."""
id: int
user_id: int
action: str
resource_type: str | None = None
resource_id: str | None = None
details: dict[str, Any] | None = None
ip_address: str | None = None
user_agent: str | None = None
status: str
request_method: str | None = None
request_path: str | None = None
created_at: datetime | None = None
user_first_name: str | None = None
user_email: str | None = None
class AuditLogListResponse(BaseModel):
"""Paginated audit log list."""
items: list[AuditLogEntry]
total: int
limit: int
offset: int
# ============ CSV Export ============
_CSV_COLUMNS = [
'id',
'user_id',
'action',
'resource_type',
'resource_id',
'status',
'ip_address',
'request_method',
'request_path',
'created_at',
'user_agent',
'details',
]
def _sanitize_csv_cell(value: str) -> str:
"""Prevent CSV formula injection by prefixing dangerous leading characters."""
if value and value[0] in ('=', '+', '-', '@', '\t', '\r'):
return f"'{value}"
return value
def _logs_to_csv(logs) -> str:
"""Serialize audit log entries to CSV string."""
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(_CSV_COLUMNS)
for log in logs:
writer.writerow(
[
log.id,
log.user_id,
log.action,
log.resource_type or '',
log.resource_id or '',
log.status,
log.ip_address or '',
log.request_method or '',
_sanitize_csv_cell(log.request_path or ''),
log.created_at.isoformat() if log.created_at else '',
_sanitize_csv_cell((log.user_agent or '')[:200]),
_sanitize_csv_cell(str(log.details) if log.details else ''),
]
)
return output.getvalue()
# ============ Routes ============
@router.get('', response_model=AuditLogListResponse)
async def list_audit_logs(
admin: User = Depends(require_permission('audit_log:read')),
db: AsyncSession = Depends(get_cabinet_db),
user_id: int | None = Query(default=None),
action: str | None = Query(default=None),
resource_type: str | None = Query(default=None),
status: str | None = Query(default=None),
date_from: datetime | None = Query(default=None),
date_to: datetime | None = Query(default=None),
limit: int = Query(default=50, ge=1, le=500),
offset: int = Query(default=0, ge=0),
):
"""List audit log entries with optional filters and pagination."""
logs, total = await AuditLogCRUD.get_logs(
db,
user_id=user_id,
action=action,
resource_type=resource_type,
status=status,
date_from=date_from,
date_to=date_to,
limit=limit,
offset=offset,
load_user=True,
)
items = [
AuditLogEntry(
id=log.id,
user_id=log.user_id,
action=log.action,
resource_type=log.resource_type,
resource_id=log.resource_id,
details=log.details,
ip_address=log.ip_address,
user_agent=log.user_agent,
status=log.status,
request_method=log.request_method,
request_path=log.request_path,
created_at=log.created_at,
user_first_name=log.user.first_name if log.user else None,
user_email=log.user.email if log.user else None,
)
for log in logs
]
return AuditLogListResponse(
items=items,
total=total,
limit=limit,
offset=offset,
)
@router.get('/export')
async def export_audit_logs(
admin: User = Depends(require_permission('audit_log:export')),
db: AsyncSession = Depends(get_cabinet_db),
user_id: int | None = Query(default=None),
action: str | None = Query(default=None),
resource_type: str | None = Query(default=None),
status: str | None = Query(default=None),
date_from: datetime | None = Query(default=None),
date_to: datetime | None = Query(default=None),
limit: int = Query(default=10000, ge=1, le=50000),
):
"""Export audit logs as CSV file."""
logs, _total = await AuditLogCRUD.get_logs(
db,
user_id=user_id,
action=action,
resource_type=resource_type,
status=status,
date_from=date_from,
date_to=date_to,
limit=limit,
offset=0,
)
csv_content = _logs_to_csv(logs)
timestamp = datetime.now(UTC).strftime('%Y%m%d_%H%M%S')
filename = f'audit_log_{timestamp}.csv'
logger.info(
'Admin exported audit logs',
admin_id=admin.id,
rows=len(logs),
filename=filename,
)
return StreamingResponse(
iter([csv_content]),
media_type='text/csv',
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
)
File diff suppressed because it is too large Load Diff
+750
View File
@@ -0,0 +1,750 @@
"""Admin routes for broadcasts in cabinet."""
from datetime import UTC, datetime
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import distinct, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import BroadcastHistory, Subscription, SubscriptionStatus, Tariff, User
from app.handlers.admin.messages import get_target_users_count
from app.keyboards.admin import BROADCAST_BUTTONS, DEFAULT_BROADCAST_BUTTONS
from app.services.broadcast_service import (
BroadcastConfig,
BroadcastMediaConfig,
EmailBroadcastConfig,
broadcast_service,
email_broadcast_service,
)
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.broadcasts import (
BroadcastButton,
BroadcastButtonsResponse,
BroadcastCreateRequest,
BroadcastFilter,
BroadcastFiltersResponse,
BroadcastListResponse,
BroadcastPreviewRequest,
BroadcastPreviewResponse,
BroadcastResponse,
BroadcastTariffsResponse,
CombinedBroadcastCreateRequest,
EmailFilterItem,
EmailFiltersResponse,
EmailPreviewRequest,
EmailPreviewResponse,
TariffFilter,
TariffForBroadcast,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/broadcasts', tags=['Cabinet Admin Broadcasts'])
# ============ Filter Labels ============
FILTER_LABELS = {
'all': 'Все пользователи',
'active': 'Активные подписки',
'trial': 'Триальные',
'no': 'Без подписки',
'expiring': 'Истекают (3 дня)',
'expired': 'Истекшие',
'zero': 'Нулевой трафик',
'active_zero': 'Активные с нулевым трафиком',
'trial_zero': 'Триальные с нулевым трафиком',
}
FILTER_GROUPS = {
'all': 'basic',
'active': 'subscription',
'trial': 'subscription',
'no': 'subscription',
'expiring': 'subscription',
'expired': 'subscription',
'zero': 'traffic',
'active_zero': 'traffic',
'trial_zero': 'traffic',
}
CUSTOM_FILTER_LABELS = {
'custom_today': 'Регистрация сегодня',
'custom_week': 'Регистрация за неделю',
'custom_month': 'Регистрация за месяц',
'custom_active_today': 'Активны сегодня',
'custom_inactive_week': 'Неактивны 7+ дней',
'custom_inactive_month': 'Неактивны 30+ дней',
'custom_referrals': 'Пришли по рефералу',
'custom_direct': 'Прямая регистрация',
}
CUSTOM_FILTER_GROUPS = {
'custom_today': 'registration',
'custom_week': 'registration',
'custom_month': 'registration',
'custom_active_today': 'activity',
'custom_inactive_week': 'activity',
'custom_inactive_month': 'activity',
'custom_referrals': 'source',
'custom_direct': 'source',
}
# ============ Email Filter Labels ============
EMAIL_FILTER_LABELS = {
'all_email': 'Все с email',
'email_only': 'Только email-регистрация',
'telegram_with_email': 'Telegram с email',
'active_email': 'С активной подпиской',
'expired_email': 'С истекшей подпиской',
}
EMAIL_FILTER_GROUPS = {
'all_email': 'basic',
'email_only': 'auth_type',
'telegram_with_email': 'auth_type',
'active_email': 'subscription',
'expired_email': 'subscription',
}
# ============ Helper Functions ============
def _serialize_broadcast(broadcast: BroadcastHistory) -> BroadcastResponse:
"""Serialize broadcast to response model."""
blocked = broadcast.blocked_count or 0
progress = 0.0
if broadcast.total_count > 0:
progress = round((broadcast.sent_count + broadcast.failed_count + blocked) / broadcast.total_count * 100, 1)
return BroadcastResponse(
id=broadcast.id,
target_type=broadcast.target_type,
message_text=broadcast.message_text,
has_media=broadcast.has_media,
media_type=broadcast.media_type,
media_file_id=broadcast.media_file_id,
media_caption=broadcast.media_caption,
total_count=broadcast.total_count,
sent_count=broadcast.sent_count,
failed_count=broadcast.failed_count,
blocked_count=blocked,
status=broadcast.status,
admin_id=broadcast.admin_id,
admin_name=broadcast.admin_name,
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),
)
async def _get_email_filter_count(db: AsyncSession, target: str) -> int:
"""Get count of email users matching the filter."""
base_conditions = [
User.email.isnot(None),
User.email_verified == True,
User.status == 'active',
]
if target == 'all_email':
query = select(func.count(User.id)).where(*base_conditions)
elif target == 'email_only':
query = select(func.count(User.id)).where(
*base_conditions,
User.auth_type == 'email',
)
elif target == 'telegram_with_email':
query = select(func.count(User.id)).where(
*base_conditions,
User.auth_type == 'telegram',
User.telegram_id.isnot(None),
)
elif target == 'active_email':
query = (
select(func.count(distinct(User.id)))
.join(Subscription, User.id == Subscription.user_id)
.where(
*base_conditions,
Subscription.status == SubscriptionStatus.ACTIVE.value,
)
)
elif target == 'expired_email':
query = (
select(func.count(distinct(User.id)))
.join(Subscription, User.id == Subscription.user_id)
.where(
*base_conditions,
Subscription.status.in_(
[
SubscriptionStatus.EXPIRED.value,
SubscriptionStatus.DISABLED.value,
]
),
)
)
else:
return 0
result = await db.execute(query)
return result.scalar() or 0
def _validate_email_target(target: str) -> bool:
"""Validate email target filter."""
return target in EMAIL_FILTER_LABELS
async def _get_tariff_user_counts(db: AsyncSession) -> dict:
"""Get count of active users per tariff."""
result = await db.execute(
select(Subscription.tariff_id, func.count(func.distinct(Subscription.user_id)).label('count'))
.join(User, User.id == Subscription.user_id)
.where(
User.status == 'active',
Subscription.status == SubscriptionStatus.ACTIVE.value,
)
.group_by(Subscription.tariff_id)
)
return {row.tariff_id: row.count for row in result.all()}
def _validate_target(target: str, tariff_ids: set) -> bool:
"""Validate target value."""
if target in FILTER_LABELS:
return True
if target in CUSTOM_FILTER_LABELS:
return True
if target.startswith('tariff_'):
try:
tariff_id = int(target.split('_')[1])
return tariff_id in tariff_ids
except (ValueError, IndexError):
return False
return False
def _validate_buttons(buttons: list[str]) -> bool:
"""Validate button keys."""
return all(button in BROADCAST_BUTTONS for button in buttons)
# ============ Endpoints ============
@router.get('/filters', response_model=BroadcastFiltersResponse)
async def get_filters(
admin: User = Depends(require_permission('broadcasts:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> BroadcastFiltersResponse:
"""Get all available filters with user counts."""
# Basic filters
filters = []
for key, label in FILTER_LABELS.items():
try:
count = await get_target_users_count(db, key)
except Exception as e:
logger.warning('Failed to get count for filter', key=key, error=e)
count = 0
filters.append(
BroadcastFilter(
key=key,
label=label,
count=count,
group=FILTER_GROUPS.get(key),
)
)
# Custom filters
custom_filters = []
for key, label in CUSTOM_FILTER_LABELS.items():
try:
count = await get_target_users_count(db, key)
except Exception as e:
logger.warning('Failed to get count for custom filter', key=key, error=e)
count = 0
custom_filters.append(
BroadcastFilter(
key=key,
label=label,
count=count,
group=CUSTOM_FILTER_GROUPS.get(key),
)
)
# Tariff filters
tariff_counts = await _get_tariff_user_counts(db)
result = await db.execute(select(Tariff).where(Tariff.is_active == True).order_by(Tariff.name))
tariffs = result.scalars().all()
tariff_filters = []
for tariff in tariffs:
tariff_filters.append(
TariffFilter(
key=f'tariff_{tariff.id}',
label=tariff.name,
tariff_id=tariff.id,
count=tariff_counts.get(tariff.id, 0),
)
)
return BroadcastFiltersResponse(
filters=filters,
tariff_filters=tariff_filters,
custom_filters=custom_filters,
)
@router.get('/tariffs', response_model=BroadcastTariffsResponse)
async def get_tariffs(
admin: User = Depends(require_permission('broadcasts:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> BroadcastTariffsResponse:
"""Get tariffs for broadcast filtering."""
tariff_counts = await _get_tariff_user_counts(db)
result = await db.execute(select(Tariff).where(Tariff.is_active == True).order_by(Tariff.name))
tariffs = result.scalars().all()
return BroadcastTariffsResponse(
tariffs=[
TariffForBroadcast(
id=t.id,
name=t.name,
filter_key=f'tariff_{t.id}',
active_users_count=tariff_counts.get(t.id, 0),
)
for t in tariffs
]
)
@router.get('/buttons', response_model=BroadcastButtonsResponse)
async def get_buttons(
admin: User = Depends(require_permission('broadcasts:read')),
) -> BroadcastButtonsResponse:
"""Get available buttons for broadcasts."""
default_buttons = set(DEFAULT_BROADCAST_BUTTONS)
buttons = []
for key, config in BROADCAST_BUTTONS.items():
buttons.append(
BroadcastButton(
key=key,
label=config.get('default_text', key),
default=key in default_buttons,
)
)
return BroadcastButtonsResponse(buttons=buttons)
@router.post('/preview', response_model=BroadcastPreviewResponse)
async def preview_broadcast(
request: BroadcastPreviewRequest,
admin: User = Depends(require_permission('broadcasts:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> BroadcastPreviewResponse:
"""Preview broadcast recipients count."""
# Get tariff IDs for validation
result = await db.execute(select(Tariff.id))
tariff_ids = {row[0] for row in result.all()}
if not _validate_target(request.target, tariff_ids):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid target: {request.target}',
)
try:
count = await get_target_users_count(db, request.target)
except Exception as e:
logger.error('Failed to get count for target', target=request.target, error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to count recipients',
)
return BroadcastPreviewResponse(target=request.target, count=count)
@router.post('', response_model=BroadcastResponse, status_code=status.HTTP_201_CREATED)
async def create_broadcast(
request: BroadcastCreateRequest,
admin: User = Depends(require_permission('broadcasts:create')),
db: AsyncSession = Depends(get_cabinet_db),
) -> BroadcastResponse:
"""Create and start a broadcast."""
# Validate target
result = await db.execute(select(Tariff.id))
tariff_ids = {row[0] for row in result.all()}
if not _validate_target(request.target, tariff_ids):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid target: {request.target}',
)
# Validate buttons
if not _validate_buttons(request.selected_buttons):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid button key',
)
message_text = request.message_text.strip()
if not message_text:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Message text must not be empty',
)
media_payload = request.media
# Validate caption length for media messages (Telegram limit: 1024 chars)
if media_payload and len(message_text) > 1024:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Текст слишком длинный для сообщения с медиа. Максимум 1024 символов, сейчас {len(message_text)}. Сократите текст или уберите медиафайл.',
)
# Create broadcast record
broadcast = BroadcastHistory(
target_type=request.target,
message_text=message_text,
has_media=media_payload is not None,
media_type=media_payload.type if media_payload else None,
media_file_id=media_payload.file_id if media_payload else None,
media_caption=media_payload.caption if media_payload else None,
total_count=0,
sent_count=0,
failed_count=0,
status='queued',
admin_id=admin.id,
admin_name=admin.username or f'Admin #{admin.id}',
category=request.category,
)
db.add(broadcast)
await db.commit()
await db.refresh(broadcast)
# Prepare media config
media_config = None
if media_payload:
media_config = BroadcastMediaConfig(
type=media_payload.type,
file_id=media_payload.file_id,
caption=media_payload.caption or message_text,
)
# Create broadcast config
config = BroadcastConfig(
target=request.target,
message_text=message_text,
selected_buttons=request.selected_buttons,
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
await broadcast_service.start_broadcast(broadcast.id, config)
await db.refresh(broadcast)
logger.info(
'Admin created broadcast for target', admin_id=admin.id, broadcast_id=broadcast.id, target=request.target
)
return _serialize_broadcast(broadcast)
@router.get('', response_model=BroadcastListResponse)
async def list_broadcasts(
admin: User = Depends(require_permission('broadcasts:read')),
db: AsyncSession = Depends(get_cabinet_db),
limit: int = Query(20, ge=1, le=100),
offset: int = Query(0, ge=0),
) -> BroadcastListResponse:
"""Get list of broadcasts with pagination."""
total = await db.scalar(select(func.count(BroadcastHistory.id))) or 0
result = await db.execute(
select(BroadcastHistory).order_by(BroadcastHistory.created_at.desc()).offset(offset).limit(limit)
)
broadcasts = result.scalars().all()
return BroadcastListResponse(
items=[_serialize_broadcast(b) for b in broadcasts],
total=int(total),
limit=limit,
offset=offset,
)
# ============ Email Broadcast Endpoints ============
@router.get('/email-filters', response_model=EmailFiltersResponse)
async def get_email_filters(
admin: User = Depends(require_permission('broadcasts:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> EmailFiltersResponse:
"""Get all available email filters with user counts."""
filters = []
total_with_email = 0
for key, label in EMAIL_FILTER_LABELS.items():
try:
count = await _get_email_filter_count(db, key)
except Exception as e:
logger.warning('Failed to get count for email filter', key=key, error=e)
count = 0
filters.append(
EmailFilterItem(
key=key,
label=label,
count=count,
group=EMAIL_FILTER_GROUPS.get(key),
)
)
# Track total with email (all_email filter)
if key == 'all_email':
total_with_email = count
return EmailFiltersResponse(
filters=filters,
total_with_email=total_with_email,
)
@router.post('/email-preview', response_model=EmailPreviewResponse)
async def preview_email_broadcast(
request: EmailPreviewRequest,
admin: User = Depends(require_permission('broadcasts:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> EmailPreviewResponse:
"""Preview email broadcast recipients count."""
if not _validate_email_target(request.target):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid email target: {request.target}',
)
try:
count = await _get_email_filter_count(db, request.target)
except Exception as e:
logger.error('Failed to get email count for target', target=request.target, error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to count email recipients',
)
return EmailPreviewResponse(target=request.target, count=count)
@router.post('/send', response_model=BroadcastResponse, status_code=status.HTTP_201_CREATED)
async def create_combined_broadcast(
request: CombinedBroadcastCreateRequest,
admin: User = Depends(require_permission('broadcasts:send')),
db: AsyncSession = Depends(get_cabinet_db),
) -> BroadcastResponse:
"""Create and start a combined broadcast (telegram/email/both)."""
# Get tariff IDs for target validation
result = await db.execute(select(Tariff.id))
tariff_ids = {row[0] for row in result.all()}
admin_name = admin.username or f'Admin #{admin.id}'
# Validate based on channel
if request.channel in ('telegram', 'both'):
# Validate telegram target
if not _validate_target(request.target, tariff_ids):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid target: {request.target}',
)
# Validate telegram message
if not request.message_text or not request.message_text.strip():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Message text is required for Telegram broadcast',
)
# Validate buttons
if not _validate_buttons(request.selected_buttons):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid button key',
)
if request.channel in ('email', 'both'):
# For email channel, target must be email filter or we use telegram target for 'both'
if request.channel == 'email' and not _validate_email_target(request.target):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid email target: {request.target}',
)
# Validate email fields
if not request.email_subject or not request.email_subject.strip():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Email subject is required for email broadcast',
)
if not request.email_html_content or not request.email_html_content.strip():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Email HTML content is required for email broadcast',
)
media_payload = request.media
# Create broadcast record
broadcast = BroadcastHistory(
target_type=request.target,
message_text=request.message_text.strip() if request.message_text else None,
has_media=media_payload is not None,
media_type=media_payload.type if media_payload else None,
media_file_id=media_payload.file_id if media_payload else None,
media_caption=media_payload.caption if media_payload else None,
total_count=0,
sent_count=0,
failed_count=0,
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,
)
db.add(broadcast)
await db.commit()
await db.refresh(broadcast)
# Start broadcasts based on channel
if request.channel in ('telegram', 'both'):
# Prepare media config
media_config = None
if media_payload:
media_config = BroadcastMediaConfig(
type=media_payload.type,
file_id=media_payload.file_id,
caption=media_payload.caption or request.message_text,
)
# Create telegram broadcast config
telegram_config = BroadcastConfig(
target=request.target,
message_text=request.message_text.strip(),
selected_buttons=request.selected_buttons,
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)
if request.channel in ('email', 'both'):
# For 'both' channel, we use 'all_email' as default email target
# since telegram target won't match email filters
email_target = request.target if request.channel == 'email' else 'all_email'
# Create email broadcast config
email_config = EmailBroadcastConfig(
target=email_target,
email_subject=request.email_subject.strip(),
email_html_content=request.email_html_content.strip(),
initiator_name=admin_name,
)
await email_broadcast_service.start_broadcast(broadcast.id, email_config)
await db.refresh(broadcast)
logger.info(
'Admin created broadcast for target',
admin_id=admin.id,
channel=request.channel,
broadcast_id=broadcast.id,
target=request.target,
)
return _serialize_broadcast(broadcast)
@router.get('/{broadcast_id}', response_model=BroadcastResponse)
async def get_broadcast(
broadcast_id: int,
admin: User = Depends(require_permission('broadcasts:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> BroadcastResponse:
"""Get broadcast details."""
broadcast = await db.get(BroadcastHistory, broadcast_id)
if not broadcast:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Broadcast not found',
)
return _serialize_broadcast(broadcast)
@router.post('/{broadcast_id}/stop', response_model=BroadcastResponse)
async def stop_broadcast(
broadcast_id: int,
admin: User = Depends(require_permission('broadcasts:send')),
db: AsyncSession = Depends(get_cabinet_db),
) -> BroadcastResponse:
"""Stop a running broadcast (telegram or email)."""
broadcast = await db.get(BroadcastHistory, broadcast_id)
if not broadcast:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Broadcast not found',
)
if broadcast.status not in {'queued', 'in_progress', 'cancelling'}:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Broadcast is not running',
)
# Try to stop both telegram and email broadcasts (one or both may be running)
channel = getattr(broadcast, 'channel', 'telegram') or 'telegram'
is_running = False
if channel in ('telegram', 'both'):
is_running = await broadcast_service.request_stop(broadcast_id) or is_running
if channel in ('email', 'both'):
is_running = await email_broadcast_service.request_stop(broadcast_id) or is_running
if is_running:
broadcast.status = 'cancelling'
else:
broadcast.status = 'cancelled'
broadcast.completed_at = datetime.now(UTC)
await db.commit()
await db.refresh(broadcast)
logger.info('Admin stopped broadcast', admin_id=admin.id, broadcast_id=broadcast_id)
return _serialize_broadcast(broadcast)
File diff suppressed because it is too large Load Diff
+255
View File
@@ -0,0 +1,255 @@
"""Admin routes for per-section cabinet button style configuration."""
import json
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import User
from app.utils.button_styles_cache import (
ALLOWED_STYLE_VALUES,
BOT_LOCALES,
BUTTON_STYLES_KEY,
DEFAULT_BUTTON_STYLES,
SECTIONS,
load_button_styles_cache,
)
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/button-styles', tags=['Admin Button Styles'])
# ---- Schemas ---------------------------------------------------------------
class ButtonSectionConfig(BaseModel):
"""Configuration for a single button section."""
style: str = 'primary'
icon_custom_emoji_id: str = ''
enabled: bool = True
labels: dict[str, str] = {}
class ButtonStylesResponse(BaseModel):
"""Full button styles configuration (all 7 sections)."""
home: ButtonSectionConfig = ButtonSectionConfig()
subscription: ButtonSectionConfig = ButtonSectionConfig()
balance: ButtonSectionConfig = ButtonSectionConfig()
referral: ButtonSectionConfig = ButtonSectionConfig()
support: ButtonSectionConfig = ButtonSectionConfig()
info: ButtonSectionConfig = ButtonSectionConfig()
admin: ButtonSectionConfig = ButtonSectionConfig()
MAX_LABEL_LENGTH = 100
class ButtonSectionUpdate(BaseModel):
"""Partial update for a single section (None = keep current)."""
style: str | None = None
icon_custom_emoji_id: str | None = None
enabled: bool | None = None
labels: dict[str, str] | None = None
class ButtonStylesUpdate(BaseModel):
"""Partial update — only include sections you want to change."""
home: ButtonSectionUpdate | None = None
subscription: ButtonSectionUpdate | None = None
balance: ButtonSectionUpdate | None = None
referral: ButtonSectionUpdate | None = None
support: ButtonSectionUpdate | None = None
info: ButtonSectionUpdate | None = None
admin: ButtonSectionUpdate | None = None
# ---- Helpers ---------------------------------------------------------------
async def _get_setting_value(db: AsyncSession, key: str) -> str | None:
from sqlalchemy import select
from app.database.models import SystemSetting
result = await db.execute(select(SystemSetting).where(SystemSetting.key == key))
setting = result.scalar_one_or_none()
return setting.value if setting else None
async def _set_setting_value(db: AsyncSession, key: str, value: str) -> None:
from sqlalchemy import select
from app.database.models import SystemSetting
result = await db.execute(select(SystemSetting).where(SystemSetting.key == key))
setting = result.scalar_one_or_none()
if setting:
setting.value = value
else:
setting = SystemSetting(key=key, value=value)
db.add(setting)
await db.commit()
def _build_response(styles: dict[str, dict]) -> ButtonStylesResponse:
return ButtonStylesResponse(
**{section: ButtonSectionConfig(**cfg) for section, cfg in styles.items() if section in SECTIONS},
)
# ---- Routes ----------------------------------------------------------------
@router.get('', response_model=ButtonStylesResponse)
async def get_button_styles(
_admin: User = Depends(require_permission('settings:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Return current per-section button styles. Admin only."""
raw = await _get_setting_value(db, BUTTON_STYLES_KEY)
merged = {section: {**cfg, 'labels': dict(cfg.get('labels', {}))} for section, cfg in DEFAULT_BUTTON_STYLES.items()}
if raw:
try:
db_data = json.loads(raw)
for section, overrides in db_data.items():
if section in merged and isinstance(overrides, dict):
if overrides.get('style') in ALLOWED_STYLE_VALUES:
merged[section]['style'] = overrides['style']
if isinstance(overrides.get('icon_custom_emoji_id'), str):
merged[section]['icon_custom_emoji_id'] = overrides['icon_custom_emoji_id']
if isinstance(overrides.get('enabled'), bool):
merged[section]['enabled'] = overrides['enabled']
if isinstance(overrides.get('labels'), dict):
merged[section]['labels'] = {
k: v
for k, v in overrides['labels'].items()
if isinstance(k, str) and isinstance(v, str) and k in BOT_LOCALES
}
except (json.JSONDecodeError, TypeError):
pass
return _build_response(merged)
@router.patch('', response_model=ButtonStylesResponse)
async def update_button_styles(
payload: ButtonStylesUpdate,
admin: User = Depends(require_permission('settings:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Partially update per-section button styles. Admin only."""
# Load current state
raw = await _get_setting_value(db, BUTTON_STYLES_KEY)
current: dict[str, dict] = {
section: {**cfg, 'labels': dict(cfg.get('labels', {}))} for section, cfg in DEFAULT_BUTTON_STYLES.items()
}
if raw:
try:
db_data = json.loads(raw)
for section, overrides in db_data.items():
if section in current and isinstance(overrides, dict):
if overrides.get('style') in ALLOWED_STYLE_VALUES:
current[section]['style'] = overrides['style']
if isinstance(overrides.get('icon_custom_emoji_id'), str):
current[section]['icon_custom_emoji_id'] = overrides['icon_custom_emoji_id']
if isinstance(overrides.get('enabled'), bool):
current[section]['enabled'] = overrides['enabled']
if isinstance(overrides.get('labels'), dict):
current[section]['labels'] = {
k: v
for k, v in overrides['labels'].items()
if isinstance(k, str) and isinstance(v, str) and k in BOT_LOCALES
}
except (json.JSONDecodeError, TypeError):
pass
# Apply updates
update_data = payload.model_dump(exclude_none=True)
changed_sections: list[str] = []
for section, updates in update_data.items():
if section not in current or not isinstance(updates, dict):
continue
if 'style' in updates:
style_val = updates['style']
if style_val not in ALLOWED_STYLE_VALUES:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid style "{style_val}" for section "{section}". '
f'Allowed: {", ".join(sorted(ALLOWED_STYLE_VALUES))}',
)
current[section]['style'] = style_val
if 'icon_custom_emoji_id' in updates:
emoji_val = (updates['icon_custom_emoji_id'] or '').strip()
current[section]['icon_custom_emoji_id'] = emoji_val
if 'enabled' in updates:
current[section]['enabled'] = updates['enabled']
if 'labels' in updates:
raw_labels = updates['labels'] or {}
sanitized: dict[str, str] = {}
for locale_key, label_val in raw_labels.items():
if locale_key not in BOT_LOCALES:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid locale "{locale_key}" for section "{section}". '
f'Allowed: {", ".join(BOT_LOCALES)}',
)
if not isinstance(label_val, str):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Label value for locale "{locale_key}" must be a string.',
)
stripped = label_val.strip()
if len(stripped) > MAX_LABEL_LENGTH:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Label for locale "{locale_key}" exceeds {MAX_LABEL_LENGTH} characters.',
)
# Empty string = remove custom label (use default)
if stripped:
sanitized[locale_key] = stripped
current[section]['labels'] = sanitized
changed_sections.append(section)
# Persist
await _set_setting_value(db, BUTTON_STYLES_KEY, json.dumps(current))
# Refresh in-process cache
await load_button_styles_cache()
logger.info(
'Admin updated button styles for sections', telegram_id=admin.telegram_id, changed_sections=changed_sections
)
return _build_response(current)
@router.post('/reset', response_model=ButtonStylesResponse)
async def reset_button_styles(
admin: User = Depends(require_permission('settings:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Reset all button styles to defaults. Admin only."""
await _set_setting_value(db, BUTTON_STYLES_KEY, json.dumps(DEFAULT_BUTTON_STYLES))
await load_button_styles_cache()
logger.info('Admin reset button styles to defaults', telegram_id=admin.telegram_id)
return _build_response(DEFAULT_BUTTON_STYLES)
+622
View File
@@ -0,0 +1,622 @@
"""Admin routes for managing advertising campaigns in cabinet."""
from datetime import UTC, datetime
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.cabinet.utils.links import get_campaign_deep_link, get_campaign_web_link
from app.database.crud.campaign import (
create_campaign,
delete_campaign,
get_campaign_by_id,
get_campaign_by_start_parameter,
get_campaign_statistics,
get_campaigns_count,
get_campaigns_list,
get_campaigns_overview,
update_campaign,
)
from app.database.crud.server_squad import get_all_server_squads
from app.database.crud.tariff import get_all_tariffs
from app.database.models import (
AdvertisingCampaign,
AdvertisingCampaignRegistration,
PartnerStatus,
Subscription,
Tariff,
User,
)
from app.services.partner_stats_service import PartnerStatsService
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.campaigns import (
AdminCampaignChartDataResponse,
AvailablePartnerItem,
CampaignCreateRequest,
CampaignDetailResponse,
CampaignListItem,
CampaignListResponse,
CampaignRegistrationItem,
CampaignRegistrationsResponse,
CampaignsOverviewResponse,
CampaignStatisticsResponse,
CampaignToggleResponse,
CampaignUpdateRequest,
ServerSquadInfo,
TariffInfo,
)
from ..schemas.tariffs import TariffListItem
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/campaigns', tags=['Cabinet Admin Campaigns'])
def _safe_div(value: float | None, divisor: int = 100) -> float:
"""Safely divide kopeks to rubles, handling None values."""
return (value or 0) / divisor
def _get_partner_name(campaign: AdvertisingCampaign) -> str | None:
"""Get partner display name from campaign."""
if not campaign.partner_user_id or not campaign.partner:
return None
partner = campaign.partner
return partner.first_name or partner.username or f'#{partner.id}'
@router.get('/overview', response_model=CampaignsOverviewResponse)
async def get_overview(
admin: User = Depends(require_permission('campaigns:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get campaigns overview statistics."""
try:
overview = await get_campaigns_overview(db)
# Count tariff bonuses
tariff_result = await db.execute(
select(func.count(AdvertisingCampaignRegistration.id)).where(
AdvertisingCampaignRegistration.bonus_type == 'tariff'
)
)
tariff_count = tariff_result.scalar() or 0
return CampaignsOverviewResponse(
total=overview['total'],
active=overview['active'],
inactive=overview['inactive'],
total_registrations=overview['registrations'],
total_balance_issued_kopeks=overview['balance_total'],
total_balance_issued_rubles=_safe_div(overview['balance_total']),
total_subscription_issued=overview['subscription_total'],
total_tariff_issued=tariff_count,
)
except HTTPException:
raise
except Exception as e:
logger.error('Failed to get campaigns overview', error=str(e), exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load campaigns overview',
)
@router.get('/available-servers', response_model=list[ServerSquadInfo])
async def get_available_servers(
admin: User = Depends(require_permission('campaigns:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of available server squads for campaign subscription bonus."""
servers, _ = await get_all_server_squads(db, available_only=False)
return [
ServerSquadInfo(
id=server.id,
squad_uuid=server.squad_uuid,
display_name=server.display_name,
country_code=server.country_code,
)
for server in servers
]
@router.get('/available-tariffs', response_model=list[TariffListItem])
async def get_available_tariffs(
admin: User = Depends(require_permission('campaigns:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of available tariffs for campaign tariff bonus."""
tariffs = await get_all_tariffs(db, include_inactive=False)
return [
TariffListItem(
id=tariff.id,
name=tariff.name,
description=tariff.description,
is_active=tariff.is_active,
is_trial_available=tariff.is_trial_available,
is_daily=tariff.is_daily,
daily_price_kopeks=tariff.daily_price_kopeks or 0,
allow_traffic_topup=tariff.allow_traffic_topup,
traffic_limit_gb=tariff.traffic_limit_gb,
device_limit=tariff.device_limit,
tier_level=tariff.tier_level,
display_order=tariff.display_order,
servers_count=len(tariff.allowed_squads or []),
subscriptions_count=0,
created_at=tariff.created_at,
)
for tariff in tariffs
]
@router.get('/available-partners', response_model=list[AvailablePartnerItem])
async def get_available_partners(
admin: User = Depends(require_permission('campaigns:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of approved partners for campaign partner selector."""
result = await db.execute(
select(User).where(User.partner_status == PartnerStatus.APPROVED.value).order_by(User.first_name, User.username)
)
partners = result.scalars().all()
return [
AvailablePartnerItem(
user_id=p.id,
username=p.username,
first_name=p.first_name,
)
for p in partners
]
@router.get('', response_model=CampaignListResponse)
async def list_campaigns(
include_inactive: bool = True,
offset: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=100),
admin: User = Depends(require_permission('campaigns:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of all campaigns."""
campaigns = await get_campaigns_list(db, offset=offset, limit=limit, include_inactive=include_inactive)
total = await get_campaigns_count(db, is_active=True if not include_inactive else None)
items = []
for campaign in campaigns:
# Get quick stats
stats = await get_campaign_statistics(db, campaign.id)
items.append(
CampaignListItem(
id=campaign.id,
name=campaign.name,
start_parameter=campaign.start_parameter,
bonus_type=campaign.bonus_type,
is_active=campaign.is_active,
registrations_count=stats['registrations'],
total_revenue_kopeks=stats['total_revenue_kopeks'],
conversion_rate=stats['conversion_rate'],
partner_user_id=campaign.partner_user_id,
partner_name=_get_partner_name(campaign),
created_at=campaign.created_at,
)
)
return CampaignListResponse(campaigns=items, total=total)
@router.get('/{campaign_id}', response_model=CampaignDetailResponse)
async def get_campaign(
campaign_id: int,
admin: User = Depends(require_permission('campaigns:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get detailed campaign info."""
campaign = await get_campaign_by_id(db, campaign_id)
if not campaign:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Campaign not found',
)
tariff_info = None
if campaign.tariff:
tariff_info = TariffInfo(
id=campaign.tariff.id,
name=campaign.tariff.name,
)
return CampaignDetailResponse(
id=campaign.id,
name=campaign.name,
start_parameter=campaign.start_parameter,
bonus_type=campaign.bonus_type,
is_active=campaign.is_active,
balance_bonus_kopeks=campaign.balance_bonus_kopeks or 0,
balance_bonus_rubles=_safe_div(campaign.balance_bonus_kopeks),
subscription_duration_days=campaign.subscription_duration_days,
subscription_traffic_gb=campaign.subscription_traffic_gb,
subscription_device_limit=campaign.subscription_device_limit,
subscription_squads=campaign.subscription_squads or [],
tariff_id=campaign.tariff_id,
tariff_duration_days=campaign.tariff_duration_days,
tariff=tariff_info,
partner_user_id=campaign.partner_user_id,
partner_name=_get_partner_name(campaign),
created_by=campaign.created_by,
created_at=campaign.created_at,
updated_at=campaign.updated_at,
deep_link=get_campaign_deep_link(campaign.start_parameter),
web_link=get_campaign_web_link(campaign.start_parameter),
)
@router.get('/{campaign_id}/chart-data', response_model=AdminCampaignChartDataResponse)
async def get_campaign_chart_data(
campaign_id: int,
admin: User = Depends(require_permission('campaigns:stats')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get chart data for admin campaign analytics."""
try:
campaign = await get_campaign_by_id(db, campaign_id)
if not campaign:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Campaign not found',
)
data = await PartnerStatsService.get_admin_campaign_chart_data(db, campaign_id)
return AdminCampaignChartDataResponse(**data)
except HTTPException:
raise
except Exception as e:
logger.error('Failed to get campaign chart data', error=str(e), campaign_id=campaign_id, exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load campaign chart data',
)
@router.get('/{campaign_id}/stats', response_model=CampaignStatisticsResponse)
async def get_campaign_stats(
campaign_id: int,
admin: User = Depends(require_permission('campaigns:stats')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get detailed campaign statistics."""
try:
campaign = await get_campaign_by_id(db, campaign_id)
if not campaign:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Campaign not found',
)
stats = await get_campaign_statistics(db, campaign_id)
return CampaignStatisticsResponse(
id=campaign.id,
name=campaign.name,
start_parameter=campaign.start_parameter,
bonus_type=campaign.bonus_type,
is_active=campaign.is_active,
registrations=stats['registrations'],
balance_issued_kopeks=stats['balance_issued'],
balance_issued_rubles=_safe_div(stats['balance_issued']),
subscription_issued=stats['subscription_issued'],
last_registration=stats['last_registration'],
total_revenue_kopeks=stats['total_revenue_kopeks'],
total_revenue_rubles=_safe_div(stats['total_revenue_kopeks']),
avg_revenue_per_user_kopeks=stats['avg_revenue_per_user_kopeks'],
avg_revenue_per_user_rubles=_safe_div(stats['avg_revenue_per_user_kopeks']),
avg_first_payment_kopeks=stats['avg_first_payment_kopeks'],
avg_first_payment_rubles=_safe_div(stats['avg_first_payment_kopeks']),
trial_users_count=stats['trial_users_count'],
active_trials_count=stats['active_trials_count'],
conversion_count=stats['conversion_count'],
paid_users_count=stats['paid_users_count'],
conversion_rate=stats['conversion_rate'],
trial_conversion_rate=stats['trial_conversion_rate'],
deep_link=get_campaign_deep_link(campaign.start_parameter),
web_link=get_campaign_web_link(campaign.start_parameter),
)
except HTTPException:
raise
except Exception as e:
logger.error('Failed to get campaign stats', error=str(e), campaign_id=campaign_id, exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load campaign statistics',
)
@router.get('/{campaign_id}/registrations', response_model=CampaignRegistrationsResponse)
async def get_campaign_registrations(
campaign_id: int,
page: int = Query(1, ge=1),
per_page: int = Query(50, ge=1, le=100),
admin: User = Depends(require_permission('campaigns:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of users registered through campaign."""
campaign = await get_campaign_by_id(db, campaign_id)
if not campaign:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Campaign not found',
)
offset = (page - 1) * per_page
# Get registrations with user info
result = await db.execute(
select(AdvertisingCampaignRegistration, User)
.join(User, AdvertisingCampaignRegistration.user_id == User.id)
.where(AdvertisingCampaignRegistration.campaign_id == campaign_id)
.order_by(AdvertisingCampaignRegistration.created_at.desc())
.offset(offset)
.limit(per_page)
)
rows = result.all()
# Count total
count_result = await db.execute(
select(func.count(AdvertisingCampaignRegistration.id)).where(
AdvertisingCampaignRegistration.campaign_id == campaign_id
)
)
total = count_result.scalar() or 0
# Batch query: find which users have active subscriptions (avoids N+1)
user_ids = [user.id for _reg, user in rows]
active_sub_user_ids: set[int] = set()
if user_ids:
sub_result = await db.execute(
select(Subscription.user_id)
.where(
Subscription.user_id.in_(user_ids),
Subscription.status == 'active',
)
.distinct()
)
active_sub_user_ids = set(sub_result.scalars().all())
items = []
for reg, user in rows:
items.append(
CampaignRegistrationItem(
id=reg.id,
user_id=user.id,
telegram_id=user.telegram_id,
username=user.username,
first_name=user.first_name,
bonus_type=reg.bonus_type,
balance_bonus_kopeks=reg.balance_bonus_kopeks or 0,
subscription_duration_days=reg.subscription_duration_days,
tariff_id=reg.tariff_id,
tariff_duration_days=reg.tariff_duration_days,
created_at=reg.created_at,
user_balance_kopeks=user.balance_kopeks or 0,
has_subscription=user.id in active_sub_user_ids,
has_paid=user.has_had_paid_subscription or False,
)
)
return CampaignRegistrationsResponse(
registrations=items,
total=total,
page=page,
per_page=per_page,
)
@router.post('', response_model=CampaignDetailResponse)
async def create_new_campaign(
request: CampaignCreateRequest,
admin: User = Depends(require_permission('campaigns:create')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Create a new advertising campaign."""
# Check if start_parameter is unique
existing = await get_campaign_by_start_parameter(db, request.start_parameter)
if existing:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Campaign with start parameter '{request.start_parameter}' already exists",
)
# Validate tariff exists if tariff bonus type
if request.bonus_type == 'tariff':
if not request.tariff_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Tariff ID is required for tariff bonus type',
)
tariff_result = await db.execute(select(Tariff).where(Tariff.id == request.tariff_id))
tariff = tariff_result.scalar_one_or_none()
if not tariff:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Tariff not found',
)
# Validate partner exists and is approved
if request.partner_user_id is not None:
partner_user = await db.get(User, request.partner_user_id)
if not partner_user or partner_user.partner_status != PartnerStatus.APPROVED.value:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Partner not found or not approved',
)
campaign = await create_campaign(
db,
name=request.name,
start_parameter=request.start_parameter,
bonus_type=request.bonus_type,
created_by=admin.id,
balance_bonus_kopeks=request.balance_bonus_kopeks,
subscription_duration_days=request.subscription_duration_days,
subscription_traffic_gb=request.subscription_traffic_gb,
subscription_device_limit=request.subscription_device_limit,
subscription_squads=request.subscription_squads,
tariff_id=request.tariff_id,
tariff_duration_days=request.tariff_duration_days,
is_active=request.is_active,
partner_user_id=request.partner_user_id,
)
logger.info('Admin created campaign', admin_id=admin.id, campaign_id=campaign.id, campaign_name=campaign.name)
return await get_campaign(campaign.id, admin, db)
@router.put('/{campaign_id}', response_model=CampaignDetailResponse)
async def update_existing_campaign(
campaign_id: int,
request: CampaignUpdateRequest,
admin: User = Depends(require_permission('campaigns:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update an existing campaign."""
campaign = await get_campaign_by_id(db, campaign_id)
if not campaign:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Campaign not found',
)
# Check if start_parameter is unique (if changing)
if request.start_parameter and request.start_parameter != campaign.start_parameter:
existing = await get_campaign_by_start_parameter(db, request.start_parameter)
if existing:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Campaign with start parameter '{request.start_parameter}' already exists",
)
# Validate tariff if changing to tariff bonus type
if request.bonus_type == 'tariff' or (campaign.bonus_type == 'tariff' and request.tariff_id):
tariff_id = request.tariff_id or campaign.tariff_id
if tariff_id:
tariff_result = await db.execute(select(Tariff).where(Tariff.id == tariff_id))
tariff = tariff_result.scalar_one_or_none()
if not tariff:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Tariff not found',
)
# Build updates using model_fields_set to distinguish "not sent" from "sent as None"
updates = {}
if 'name' in request.model_fields_set:
updates['name'] = request.name
if 'start_parameter' in request.model_fields_set:
updates['start_parameter'] = request.start_parameter
if 'bonus_type' in request.model_fields_set:
updates['bonus_type'] = request.bonus_type
if 'is_active' in request.model_fields_set:
updates['is_active'] = request.is_active
if 'balance_bonus_kopeks' in request.model_fields_set:
updates['balance_bonus_kopeks'] = request.balance_bonus_kopeks
if 'subscription_duration_days' in request.model_fields_set:
updates['subscription_duration_days'] = request.subscription_duration_days
if 'subscription_traffic_gb' in request.model_fields_set:
updates['subscription_traffic_gb'] = request.subscription_traffic_gb
if 'subscription_device_limit' in request.model_fields_set:
updates['subscription_device_limit'] = request.subscription_device_limit
if 'subscription_squads' in request.model_fields_set:
updates['subscription_squads'] = request.subscription_squads
if 'tariff_id' in request.model_fields_set:
updates['tariff_id'] = request.tariff_id
if 'tariff_duration_days' in request.model_fields_set:
updates['tariff_duration_days'] = request.tariff_duration_days
# Handle partner_user_id separately (allows explicit None to unassign)
partner_changed = False
if 'partner_user_id' in request.model_fields_set:
new_partner_id = request.partner_user_id
if new_partner_id is not None:
partner_user = await db.get(User, new_partner_id)
if not partner_user or partner_user.partner_status != PartnerStatus.APPROVED.value:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Partner not found or not approved',
)
campaign.partner_user_id = new_partner_id
campaign.updated_at = datetime.now(UTC)
partner_changed = True
if updates:
await update_campaign(db, campaign, **updates)
elif partner_changed:
await db.commit()
await db.refresh(campaign)
logger.info('Admin updated campaign', admin_id=admin.id, campaign_id=campaign_id)
return await get_campaign(campaign_id, admin, db)
@router.delete('/{campaign_id}')
async def delete_existing_campaign(
campaign_id: int,
admin: User = Depends(require_permission('campaigns:delete')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Delete a campaign."""
campaign = await get_campaign_by_id(db, campaign_id)
if not campaign:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Campaign not found',
)
# Check if campaign has registrations (COUNT query instead of loading all)
reg_count_result = await db.execute(
select(func.count(AdvertisingCampaignRegistration.id)).where(
AdvertisingCampaignRegistration.campaign_id == campaign_id
)
)
reg_count = reg_count_result.scalar() or 0
if reg_count > 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Cannot delete campaign with {reg_count} registrations. Deactivate it instead.',
)
await delete_campaign(db, campaign)
logger.info('Admin deleted campaign', admin_id=admin.id, campaign_id=campaign_id, campaign_name=campaign.name)
return {'message': 'Campaign deleted successfully'}
@router.post('/{campaign_id}/toggle', response_model=CampaignToggleResponse)
async def toggle_campaign(
campaign_id: int,
admin: User = Depends(require_permission('campaigns:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Toggle campaign active status."""
campaign = await get_campaign_by_id(db, campaign_id)
if not campaign:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Campaign not found',
)
new_status = not campaign.is_active
await update_campaign(db, campaign, is_active=new_status)
status_text = 'activated' if new_status else 'deactivated'
logger.info('Admin campaign', admin_id=admin.id, status_text=status_text, campaign_id=campaign_id)
return CampaignToggleResponse(
id=campaign_id,
is_active=new_status,
message=f'Campaign {status_text}',
)
+98
View File
@@ -0,0 +1,98 @@
"""Admin API for managing required channels."""
import structlog
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.required_channel import (
add_channel,
delete_channel,
get_all_channels,
toggle_channel,
update_channel,
)
from app.database.models import User
from app.services.channel_subscription_service import channel_subscription_service
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.channel import (
ChannelCreateRequest,
ChannelListResponse,
ChannelResponse,
ChannelUpdateRequest,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/channel-subscriptions', tags=['Cabinet Admin Channels'])
@router.get('', response_model=ChannelListResponse)
async def list_channels(
db: AsyncSession = Depends(get_cabinet_db),
_admin: User = Depends(require_permission('channels:read')),
) -> ChannelListResponse:
channels = await get_all_channels(db)
return ChannelListResponse(
items=[ChannelResponse.model_validate(ch) for ch in channels],
total=len(channels),
)
@router.post('', response_model=ChannelResponse, status_code=201)
async def create_channel(
data: ChannelCreateRequest,
db: AsyncSession = Depends(get_cabinet_db),
_admin: User = Depends(require_permission('channels:edit')),
) -> ChannelResponse:
ch = await add_channel(
db,
channel_id=data.channel_id,
channel_link=data.channel_link,
title=data.title,
disable_trial_on_leave=data.disable_trial_on_leave,
disable_paid_on_leave=data.disable_paid_on_leave,
)
await channel_subscription_service.invalidate_channels_cache()
return ChannelResponse.model_validate(ch)
@router.patch('/{channel_db_id}', response_model=ChannelResponse)
async def update_channel_endpoint(
channel_db_id: int,
data: ChannelUpdateRequest,
db: AsyncSession = Depends(get_cabinet_db),
_admin: User = Depends(require_permission('channels:edit')),
) -> ChannelResponse:
update_data = data.model_dump(exclude_unset=True)
ch = await update_channel(db, channel_db_id, **update_data)
if not ch:
raise HTTPException(status_code=404, detail='Channel not found')
await channel_subscription_service.invalidate_channels_cache()
return ChannelResponse.model_validate(ch)
@router.post('/{channel_db_id}/toggle', response_model=ChannelResponse)
async def toggle_channel_endpoint(
channel_db_id: int,
db: AsyncSession = Depends(get_cabinet_db),
_admin: User = Depends(require_permission('channels:edit')),
) -> ChannelResponse:
ch = await toggle_channel(db, channel_db_id)
if not ch:
raise HTTPException(status_code=404, detail='Channel not found')
await channel_subscription_service.invalidate_channels_cache()
return ChannelResponse.model_validate(ch)
@router.delete('/{channel_db_id}', status_code=204)
async def delete_channel_endpoint(
channel_db_id: int,
db: AsyncSession = Depends(get_cabinet_db),
_admin: User = Depends(require_permission('channels:edit')),
) -> None:
ok = await delete_channel(db, channel_db_id)
if not ok:
raise HTTPException(status_code=404, detail='Channel not found')
await channel_subscription_service.invalidate_channels_cache()
+791
View File
@@ -0,0 +1,791 @@
"""Admin routes for managing email notification templates."""
import asyncio
from typing import Any
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import User
from ..dependencies import get_cabinet_db, require_permission
from ..services.email_template_overrides import (
delete_template_override,
get_all_overrides,
get_overrides_for_type,
save_template_override,
)
from ..services.email_templates import EmailNotificationTemplates
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/email-templates', tags=['Admin Email Templates'])
# ============ Template type metadata ============
TEMPLATE_TYPES = [
{
'type': 'balance_topup',
'label': {'ru': 'Пополнение баланса', 'en': 'Balance Top-up', 'zh': '余额充值', 'ua': 'Поповнення балансу'},
'description': {
'ru': 'Уведомление о пополнении баланса',
'en': 'Balance top-up notification',
'zh': '余额充值通知',
'ua': 'Сповіщення про поповнення балансу',
},
'context_vars': ['formatted_amount', 'formatted_balance', 'amount_rubles', 'new_balance_rubles'],
},
{
'type': 'balance_change',
'label': {'ru': 'Изменение баланса', 'en': 'Balance Change', 'zh': '余额变动', 'ua': 'Зміна балансу'},
'description': {
'ru': 'Уведомление об изменении баланса',
'en': 'Balance change notification',
'zh': '余额变动通知',
'ua': 'Сповіщення про зміну балансу',
},
'context_vars': ['formatted_amount', 'formatted_balance', 'amount_rubles', 'new_balance_rubles'],
},
{
'type': 'subscription_expiring',
'label': {
'ru': 'Подписка истекает',
'en': 'Subscription Expiring',
'zh': '订阅即将到期',
'ua': 'Підписка закінчується',
},
'description': {
'ru': 'Предупреждение об истечении подписки',
'en': 'Subscription expiring warning',
'zh': '订阅即将到期警告',
'ua': 'Попередження про закінчення підписки',
},
'context_vars': ['days_left', 'expires_at'],
},
{
'type': 'subscription_expired',
'label': {
'ru': 'Подписка истекла',
'en': 'Subscription Expired',
'zh': '订阅已到期',
'ua': 'Підписка закінчилась',
},
'description': {
'ru': 'Уведомление об истечении подписки',
'en': 'Subscription expired notification',
'zh': '订阅已到期通知',
'ua': 'Сповіщення про закінчення підписки',
},
'context_vars': [],
},
{
'type': 'subscription_renewed',
'label': {
'ru': 'Подписка продлена',
'en': 'Subscription Renewed',
'zh': '订阅已续期',
'ua': 'Підписка продовжена',
},
'description': {
'ru': 'Уведомление о продлении подписки',
'en': 'Subscription renewed notification',
'zh': '订阅已续期通知',
'ua': 'Сповіщення про продовження підписки',
},
'context_vars': ['new_expires_at', 'tariff_name', 'traffic_limit_gb', 'device_limit'],
},
{
'type': 'subscription_activated',
'label': {
'ru': 'Подписка активирована',
'en': 'Subscription Activated',
'zh': '订阅已激活',
'ua': 'Підписка активована',
},
'description': {
'ru': 'Уведомление об активации подписки',
'en': 'Subscription activated notification',
'zh': '订阅已激活通知',
'ua': 'Сповіщення про активацію підписки',
},
'context_vars': ['expires_at', 'tariff_name', 'traffic_limit_gb', 'device_limit'],
},
{
'type': 'autopay_success',
'label': {
'ru': 'Автоплатёж успешен',
'en': 'Autopay Success',
'zh': '自动续费成功',
'ua': 'Автоплатіж успішний',
},
'description': {
'ru': 'Уведомление об успешном автоплатеже',
'en': 'Autopay success notification',
'zh': '自动续费成功通知',
'ua': 'Сповіщення про успішний автоплатіж',
},
'context_vars': ['formatted_amount', 'amount_rubles', 'new_expires_at'],
},
{
'type': 'autopay_failed',
'label': {
'ru': 'Автоплатёж не удался',
'en': 'Autopay Failed',
'zh': '自动续费失败',
'ua': 'Автоплатіж не вдався',
},
'description': {
'ru': 'Уведомление о неудачном автоплатеже',
'en': 'Autopay failed notification',
'zh': '自动续费失败通知',
'ua': 'Сповіщення про невдалий автоплатіж',
},
'context_vars': ['reason'],
},
{
'type': 'autopay_insufficient_funds',
'label': {
'ru': 'Недостаточно средств (автоплатёж)',
'en': 'Insufficient Funds (Autopay)',
'zh': '余额不足(自动续费)',
'ua': 'Недостатньо коштів (автоплатіж)',
},
'description': {
'ru': 'Уведомление о нехватке средств для автоплатежа',
'en': 'Insufficient funds for autopay notification',
'zh': '自动续费余额不足通知',
'ua': 'Сповіщення про нестачу коштів для автоплатежу',
},
'context_vars': ['required_amount', 'current_balance'],
},
{
'type': 'daily_debit',
'label': {'ru': 'Суточное списание', 'en': 'Daily Debit', 'zh': '每日扣费', 'ua': 'Добове списання'},
'description': {
'ru': 'Уведомление о суточном списании',
'en': 'Daily debit notification',
'zh': '每日扣费通知',
'ua': 'Сповіщення про добове списання',
},
'context_vars': ['formatted_amount', 'formatted_balance', 'amount_rubles', 'new_balance_rubles'],
},
{
'type': 'daily_insufficient_funds',
'label': {
'ru': 'Недостаточно средств (суточное)',
'en': 'Insufficient Funds (Daily)',
'zh': '余额不足(每日)',
'ua': 'Недостатньо коштів (добове)',
},
'description': {
'ru': 'Уведомление о нехватке средств для суточного списания',
'en': 'Insufficient funds for daily debit',
'zh': '每日扣费余额不足通知',
'ua': 'Сповіщення про нестачу коштів для добового списання',
},
'context_vars': ['required_amount', 'current_balance'],
},
{
'type': 'ban_notification',
'label': {'ru': 'Блокировка аккаунта', 'en': 'Account Banned', 'zh': '账户被封禁', 'ua': 'Блокування акаунту'},
'description': {
'ru': 'Уведомление о блокировке аккаунта',
'en': 'Account banned notification',
'zh': '账户被封禁通知',
'ua': 'Сповіщення про блокування акаунту',
},
'context_vars': ['reason'],
},
{
'type': 'unban_notification',
'label': {
'ru': 'Разблокировка аккаунта',
'en': 'Account Unbanned',
'zh': '账户已解封',
'ua': 'Розблокування акаунту',
},
'description': {
'ru': 'Уведомление о разблокировке аккаунта',
'en': 'Account unbanned notification',
'zh': '账户已解封通知',
'ua': 'Сповіщення про розблокування акаунту',
},
'context_vars': [],
},
{
'type': 'warning_notification',
'label': {'ru': 'Предупреждение', 'en': 'Warning', 'zh': '警告', 'ua': 'Попередження'},
'description': {
'ru': 'Предупреждение пользователю',
'en': 'Warning notification',
'zh': '警告通知',
'ua': 'Попередження користувачу',
},
'context_vars': ['message'],
},
{
'type': 'referral_bonus',
'label': {'ru': 'Реферальный бонус', 'en': 'Referral Bonus', 'zh': '推荐奖励', 'ua': 'Реферальний бонус'},
'description': {
'ru': 'Уведомление о начислении реферального бонуса',
'en': 'Referral bonus notification',
'zh': '推荐奖励通知',
'ua': 'Сповіщення про нарахування реферального бонусу',
},
'context_vars': ['formatted_bonus', 'bonus_rubles', 'referral_name'],
},
{
'type': 'referral_registered',
'label': {'ru': 'Новый реферал', 'en': 'New Referral', 'zh': '新推荐用户', 'ua': 'Новий реферал'},
'description': {
'ru': 'Уведомление о регистрации реферала',
'en': 'New referral registered notification',
'zh': '新推荐用户注册通知',
'ua': 'Сповіщення про реєстрацію реферала',
},
'context_vars': ['referral_name'],
},
{
'type': 'traffic_reset',
'label': {'ru': 'Сброс трафика', 'en': 'Traffic Reset', 'zh': '流量重置', 'ua': 'Скидання трафіку'},
'description': {
'ru': 'Уведомление о сбросе трафика',
'en': 'Traffic reset notification',
'zh': '流量重置通知',
'ua': 'Сповіщення про скидання трафіку',
},
'context_vars': ['reset_gb', 'current_limit_gb'],
},
{
'type': 'payment_received',
'label': {'ru': 'Платёж получен', 'en': 'Payment Received', 'zh': '收到付款', 'ua': 'Платіж отримано'},
'description': {
'ru': 'Уведомление о получении платежа',
'en': 'Payment received notification',
'zh': '收到付款通知',
'ua': 'Сповіщення про отримання платежу',
},
'context_vars': ['formatted_amount', 'payment_method'],
},
{
'type': 'email_verification',
'label': {
'ru': 'Подтверждение email',
'en': 'Email Verification',
'zh': '邮箱验证',
'ua': 'Підтвердження email',
},
'description': {
'ru': 'Письмо для подтверждения email адреса при регистрации',
'en': 'Email address verification letter sent during registration',
'zh': '注册时发送的邮箱验证邮件',
'ua': 'Лист для підтвердження email адреси при реєстрації',
},
'context_vars': ['username', 'verification_url', 'expire_hours'],
},
{
'type': 'password_reset',
'label': {'ru': 'Сброс пароля', 'en': 'Password Reset', 'zh': '重置密码', 'ua': 'Скидання пароля'},
'description': {
'ru': 'Письмо для сброса пароля',
'en': 'Password reset email',
'zh': '密码重置邮件',
'ua': 'Лист для скидання пароля',
},
'context_vars': ['username', 'reset_url', 'expire_hours'],
},
{
'type': 'guest_subscription_delivered',
'label': {
'ru': 'Быстрая покупка: подписка доставлена',
'en': 'Quick Purchase: Subscription Delivered',
'zh': '快捷购买:订阅已交付',
'ua': 'Швидка покупка: підписка доставлена',
},
'description': {
'ru': 'Письмо покупателю после успешной оплаты через лендинг',
'en': 'Email to buyer after successful landing page payment',
'zh': '通过落地页成功付款后发送给买家的邮件',
'ua': 'Лист покупцю після успішної оплати через лендінг',
},
'context_vars': ['tariff_name', 'period_days', 'cabinet_url', 'cabinet_email', 'cabinet_password'],
},
{
'type': 'guest_activation_required',
'label': {
'ru': 'Быстрая покупка: требуется активация',
'en': 'Quick Purchase: Activation Required',
'zh': '快捷购买:需要激活',
'ua': 'Швидка покупка: потрібна активація',
},
'description': {
'ru': 'Письмо когда у покупателя уже есть активная подписка',
'en': 'Email when buyer already has an active subscription',
'zh': '买家已有活跃订阅时发送的邮件',
'ua': 'Лист коли у покупця вже є активна підписка',
},
'context_vars': ['tariff_name', 'period_days', 'success_page_url', 'gift_message', 'is_gift'],
},
{
'type': 'guest_gift_received',
'label': {
'ru': 'Быстрая покупка: подарок получен',
'en': 'Quick Purchase: Gift Received',
'zh': '快捷购买:收到礼物',
'ua': 'Швидка покупка: подарунок отримано',
},
'description': {
'ru': 'Письмо получателю подарочной подписки',
'en': 'Email to gift subscription recipient',
'zh': '发送给礼物订阅接收者的邮件',
'ua': 'Лист отримувачу подарункової підписки',
},
'context_vars': [
'tariff_name',
'period_days',
'cabinet_url',
'gift_message',
'cabinet_email',
'cabinet_password',
],
},
{
'type': 'guest_cabinet_credentials',
'label': {
'ru': 'Быстрая покупка: данные для входа',
'en': 'Quick Purchase: Login Credentials',
'zh': '快捷购买:登录凭据',
'ua': 'Швидка покупка: дані для входу',
},
'description': {
'ru': 'Письмо с логином и паролем для личного кабинета',
'en': 'Email with login credentials for the cabinet',
'zh': '包含个人中心登录信息的邮件',
'ua': 'Лист з логіном та паролем для особистого кабінету',
},
'context_vars': ['tariff_name', 'period_days', 'cabinet_url', 'cabinet_email', 'cabinet_password'],
},
]
SAMPLE_CONTEXTS: dict[str, dict[str, Any]] = {
'balance_topup': {
'formatted_amount': '500.00 ₽',
'formatted_balance': '1500.00 ₽',
'amount_rubles': 500,
'new_balance_rubles': 1500,
},
'balance_change': {
'formatted_amount': '-200.00 ₽',
'formatted_balance': '1300.00 ₽',
'amount_rubles': -200,
'new_balance_rubles': 1300,
},
'subscription_expiring': {'days_left': 3, 'expires_at': '2025-01-30'},
'subscription_expired': {},
'subscription_renewed': {
'new_expires_at': '2025-02-28',
'tariff_name': 'Premium',
'traffic_limit_gb': 100,
'device_limit': 3,
},
'subscription_activated': {
'expires_at': '2025-02-28',
'tariff_name': 'Premium',
'traffic_limit_gb': 100,
'device_limit': 3,
},
'autopay_success': {'formatted_amount': '300.00 ₽', 'amount_rubles': 300, 'new_expires_at': '2025-02-28'},
'autopay_failed': {'reason': 'Card declined'},
'autopay_insufficient_funds': {'required_amount': '300.00 ₽', 'current_balance': '50.00 ₽'},
'daily_debit': {
'formatted_amount': '10.00 ₽',
'formatted_balance': '490.00 ₽',
'amount_rubles': 10,
'new_balance_rubles': 490,
},
'daily_insufficient_funds': {'required_amount': '10.00 ₽', 'current_balance': '5.00 ₽'},
'ban_notification': {'reason': 'Violation of terms of service'},
'unban_notification': {},
'warning_notification': {'message': 'Please review our terms of service'},
'referral_bonus': {'formatted_bonus': '100.00 ₽', 'bonus_rubles': 100, 'referral_name': 'John'},
'referral_registered': {'referral_name': 'John'},
'traffic_reset': {'reset_gb': 50, 'current_limit_gb': 100},
'payment_received': {'formatted_amount': '500.00 ₽', 'amount_rubles': 500, 'payment_method': 'YooKassa'},
'email_verification': {
'username': 'John',
'verification_url': 'https://example.com/verify?token=abc123',
'expire_hours': 24,
},
'password_reset': {'username': 'John', 'reset_url': 'https://example.com/reset?token=abc123', 'expire_hours': 1},
'guest_subscription_delivered': {
'tariff_name': 'Premium',
'period_days': 30,
'cabinet_url': 'https://example.com/cabinet',
'cabinet_email': 'user@example.com',
'cabinet_password': 'SecurePass123',
},
'guest_activation_required': {
'tariff_name': 'Premium',
'period_days': 30,
'success_page_url': 'https://example.com/cabinet/buy/success/abc123',
'is_gift': True,
'gift_message': 'Happy birthday!',
},
'guest_gift_received': {
'tariff_name': 'Premium',
'period_days': 30,
'cabinet_url': 'https://example.com/cabinet',
'gift_message': 'Happy birthday!',
'cabinet_email': 'recipient@example.com',
'cabinet_password': 'SecurePass123',
},
'guest_cabinet_credentials': {
'tariff_name': 'Premium',
'period_days': 30,
'cabinet_url': 'https://example.com/cabinet',
'cabinet_email': 'user@example.com',
'cabinet_password': 'SecurePass123',
},
}
AVAILABLE_LANGUAGES = ['ru', 'en', 'zh', 'ua', 'fa']
# ============ Schemas ============
class EmailTemplateUpdate(BaseModel):
"""Request to update an email template."""
subject: str = Field(..., min_length=1, max_length=500)
body_html: str = Field(..., min_length=1)
class EmailTemplatePreviewRequest(BaseModel):
"""Request to preview an email template."""
language: str = Field(default='ru')
subject: str = Field(default='')
body_html: str = Field(default='')
class EmailTemplateSendTestRequest(BaseModel):
"""Request to send a test email."""
language: str = Field(default='ru')
email: str = Field(default='')
# ============ Endpoints ============
@router.get('', summary='List all email template types')
async def list_template_types(
_admin: User = Depends(require_permission('email_templates:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> dict[str, Any]:
"""List all available email template types with override status."""
overrides = await get_all_overrides(db)
# Build a map of overrides by type
override_map: dict[str, dict[str, bool]] = {}
for o in overrides:
ntype = o['notification_type']
if ntype not in override_map:
override_map[ntype] = {}
override_map[ntype][o['language']] = o['is_active']
result = []
for tpl_type in TEMPLATE_TYPES:
type_key = tpl_type['type']
languages = {}
for lang in AVAILABLE_LANGUAGES:
languages[lang] = {
'has_custom': lang in override_map.get(type_key, {}),
}
result.append(
{
**tpl_type,
'languages': languages,
}
)
return {'items': result, 'available_languages': AVAILABLE_LANGUAGES}
@router.get('/{notification_type}', summary='Get templates for a notification type')
async def get_templates_for_type(
notification_type: str,
_admin: User = Depends(require_permission('email_templates:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> dict[str, Any]:
"""Get all language templates for a specific notification type."""
# Validate type
valid_types = [t['type'] for t in TEMPLATE_TYPES]
if notification_type not in valid_types:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f'Unknown template type: {notification_type}',
)
# Get overrides from DB
overrides = await get_overrides_for_type(notification_type, db)
override_map = {o['language']: o for o in overrides}
# Get defaults from hardcoded templates
templates_instance = EmailNotificationTemplates()
sample_context = SAMPLE_CONTEXTS.get(notification_type, {})
# Get type metadata
type_meta = next(t for t in TEMPLATE_TYPES if t['type'] == notification_type)
# Build combined result per language
languages = {}
for lang in AVAILABLE_LANGUAGES:
# Get default template
try:
from app.services.notification_delivery_service import NotificationType
ntype_enum = NotificationType(notification_type)
default_template = templates_instance.get_template(ntype_enum, lang, sample_context)
except Exception:
default_template = None
default_subject = ''
default_body_html = ''
if default_template:
default_subject = default_template.get('subject', '')
default_body_html = default_template.get('body_html', '')
# Check for override
override = override_map.get(lang)
if override:
languages[lang] = {
'subject': override['subject'],
'body_html': override['body_html'],
'is_default': False,
'default_subject': default_subject,
'default_body_html': default_body_html,
}
else:
languages[lang] = {
'subject': default_subject,
'body_html': default_body_html,
'is_default': True,
'default_subject': default_subject,
'default_body_html': default_body_html,
}
return {
'notification_type': notification_type,
'label': type_meta['label'],
'description': type_meta['description'],
'context_vars': type_meta['context_vars'],
'languages': languages,
}
@router.put('/{notification_type}/{language}', summary='Save custom template')
async def update_template(
notification_type: str,
language: str,
data: EmailTemplateUpdate,
admin: User = Depends(require_permission('email_templates:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> dict[str, Any]:
"""Save a custom email template override."""
valid_types = [t['type'] for t in TEMPLATE_TYPES]
if notification_type not in valid_types:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f'Unknown template type: {notification_type}',
)
if language not in AVAILABLE_LANGUAGES:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid language: {language}. Available: {AVAILABLE_LANGUAGES}',
)
result = await save_template_override(
notification_type=notification_type,
language=language,
subject=data.subject,
body_html=data.body_html,
db=db,
)
logger.info(
'Админ обновил email шаблон /', admin_id=admin.id, notification_type=notification_type, language=language
)
return {'status': 'ok', 'template': result}
@router.delete('/{notification_type}/{language}', summary='Reset template to default')
async def reset_template(
notification_type: str,
language: str,
admin: User = Depends(require_permission('email_templates:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> dict[str, Any]:
"""Delete custom template override, reverting to default."""
valid_types = [t['type'] for t in TEMPLATE_TYPES]
if notification_type not in valid_types:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f'Unknown template type: {notification_type}',
)
deleted = await delete_template_override(notification_type, language, db)
if deleted:
logger.info(
'Админ сбросил email шаблон / к дефолту',
admin_id=admin.id,
notification_type=notification_type,
language=language,
)
return {'status': 'ok', 'was_custom': deleted}
@router.post('/{notification_type}/preview', summary='Preview rendered template')
async def preview_template(
notification_type: str,
data: EmailTemplatePreviewRequest,
_admin: User = Depends(require_permission('email_templates:read')),
) -> dict[str, Any]:
"""Preview a rendered email template with sample data."""
valid_types = [t['type'] for t in TEMPLATE_TYPES]
if notification_type not in valid_types:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f'Unknown template type: {notification_type}',
)
templates_instance = EmailNotificationTemplates()
language = data.language if data.language in AVAILABLE_LANGUAGES else 'ru'
if data.body_html:
# Preview custom content — auto-detects styled vs simple HTML
rendered_html = templates_instance._wrap_override_template(data.body_html, language)
subject = data.subject or notification_type
else:
# Preview default template
sample_context = SAMPLE_CONTEXTS.get(notification_type, {})
try:
from app.services.notification_delivery_service import NotificationType
ntype_enum = NotificationType(notification_type)
default_template = templates_instance.get_template(ntype_enum, language, sample_context)
except Exception:
default_template = None
if default_template:
rendered_html = default_template['body_html']
subject = default_template['subject']
else:
rendered_html = '<p>Template not found</p>'
subject = 'N/A'
return {
'subject': subject,
'body_html': rendered_html,
}
@router.post('/{notification_type}/test', summary='Send test email')
async def send_test_email(
notification_type: str,
data: EmailTemplateSendTestRequest,
admin: User = Depends(require_permission('email_templates:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> dict[str, Any]:
"""Send a test email to the admin's email address."""
from app.cabinet.services.email_service import email_service
if not email_service.is_configured():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='SMTP is not configured',
)
to_email = data.email or admin.email
if not to_email:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='No email address provided and admin has no email',
)
valid_types = [t['type'] for t in TEMPLATE_TYPES]
if notification_type not in valid_types:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f'Unknown template type: {notification_type}',
)
language = data.language if data.language in AVAILABLE_LANGUAGES else 'ru'
sample_context = SAMPLE_CONTEXTS.get(notification_type, {})
templates_instance = EmailNotificationTemplates()
# Check for DB override (get_rendered_override substitutes sample context vars)
from ..services.email_template_overrides import get_rendered_override
rendered = await get_rendered_override(notification_type, language, sample_context, db)
if rendered:
subject, body_html = rendered
else:
try:
from app.services.notification_delivery_service import NotificationType
ntype_enum = NotificationType(notification_type)
default_template = templates_instance.get_template(ntype_enum, language, sample_context)
except Exception:
default_template = None
if default_template:
subject = default_template['subject']
body_html = default_template['body_html']
else:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Template not found',
)
subject = f'[TEST] {subject}'
try:
success = await asyncio.to_thread(
email_service.send_email,
to_email=to_email,
subject=subject,
body_html=body_html,
)
except Exception as e:
logger.error('Ошибка отправки тестового email', e=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f'Failed to send test email: {e!s}',
)
if not success:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to send test email',
)
logger.info(
'Админ отправил тестовый email / на',
admin_id=admin.id,
notification_type=notification_type,
language=language,
to_email=to_email,
)
return {'status': 'ok', 'sent_to': to_email}
+219
View File
@@ -0,0 +1,219 @@
"""Admin routes for managing info pages in cabinet."""
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.info_pages import (
clear_replaces_tab,
create_info_page,
delete_info_page,
get_all_info_pages,
get_info_page_by_id,
reorder_info_pages,
update_info_page,
)
from app.database.models import User
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.info_pages import (
InfoPageCreateRequest,
InfoPageListItem,
InfoPageResponse,
InfoPageUpdateRequest,
ReorderRequest,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/info-pages', tags=['Cabinet Admin Info Pages'])
@router.get('', response_model=list[InfoPageListItem])
async def list_all_info_pages(
page_type: str | None = Query(None, pattern=r'^(page|faq)$'),
admin: User = Depends(require_permission('info_pages:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> list[InfoPageListItem]:
"""Get all info pages (admin view, includes inactive)."""
try:
pages = await get_all_info_pages(db, include_inactive=True, page_type=page_type)
return [InfoPageListItem.model_validate(p) for p in pages]
except HTTPException:
raise
except Exception:
logger.exception('Failed to list info pages')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load info pages',
)
@router.get('/{page_id}', response_model=InfoPageResponse)
async def get_info_page_detail(
page_id: int,
admin: User = Depends(require_permission('info_pages:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> InfoPageResponse:
"""Get a single info page by ID (admin view)."""
page = await get_info_page_by_id(db, page_id)
if not page:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Info page not found',
)
return InfoPageResponse.model_validate(page)
@router.post('', response_model=InfoPageResponse, status_code=status.HTTP_201_CREATED)
async def create_page(
request: InfoPageCreateRequest,
admin: User = Depends(require_permission('info_pages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> InfoPageResponse:
"""Create a new info page."""
try:
if request.replaces_tab:
await clear_replaces_tab(db, request.replaces_tab)
page = await create_info_page(
db,
slug=request.slug,
title=request.title,
content=request.content,
page_type=request.page_type,
is_active=request.is_active,
sort_order=request.sort_order,
icon=request.icon,
replaces_tab=request.replaces_tab,
)
except IntegrityError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='An info page with this slug already exists',
)
except Exception:
logger.exception('Failed to create info page')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to create info page',
)
return InfoPageResponse.model_validate(page)
@router.put('/{page_id}', response_model=InfoPageResponse)
async def update_page(
page_id: int,
request: InfoPageUpdateRequest,
admin: User = Depends(require_permission('info_pages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> InfoPageResponse:
"""Update an existing info page."""
existing = await get_info_page_by_id(db, page_id)
if not existing:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Info page not found',
)
try:
update_data = request.model_dump(exclude_unset=True)
replaces_tab = update_data.get('replaces_tab')
if replaces_tab is not None:
await clear_replaces_tab(db, replaces_tab, exclude_page_id=page_id)
page = await update_info_page(db, page_id, **update_data)
except IntegrityError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='An info page with this slug already exists',
)
except Exception:
logger.exception('Failed to update info page', page_id=page_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to update info page',
)
if not page:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Info page not found after update',
)
return InfoPageResponse.model_validate(page)
@router.delete('/{page_id}', status_code=status.HTTP_204_NO_CONTENT)
async def remove_page(
page_id: int,
admin: User = Depends(require_permission('info_pages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> None:
"""Delete an info page."""
existing = await get_info_page_by_id(db, page_id)
if not existing:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Info page not found',
)
try:
await delete_info_page(db, page_id)
except Exception:
logger.exception('Failed to delete info page', page_id=page_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to delete info page',
)
@router.post('/reorder', status_code=status.HTTP_204_NO_CONTENT)
async def reorder_pages(
request: ReorderRequest,
admin: User = Depends(require_permission('info_pages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> None:
"""Bulk update sort_order for info pages."""
try:
await reorder_info_pages(db, request.items)
except Exception:
logger.exception('Failed to reorder info pages')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to reorder info pages',
)
@router.post('/{page_id}/toggle-active', response_model=InfoPageResponse)
async def toggle_active(
page_id: int,
admin: User = Depends(require_permission('info_pages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> InfoPageResponse:
"""Toggle the active status of an info page."""
existing = await get_info_page_by_id(db, page_id)
if not existing:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Info page not found',
)
try:
page = await update_info_page(db, page_id, is_active=not existing.is_active)
except Exception:
logger.exception('Failed to toggle info page active status', page_id=page_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to toggle active status',
)
if not page:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Info page not found after toggle',
)
return InfoPageResponse.model_validate(page)
File diff suppressed because it is too large Load Diff
+398
View File
@@ -0,0 +1,398 @@
"""Admin routes for cabinet menu layout configuration (rows + custom URL buttons).
Serves a MERGED view combining ``CABINET_MENU_LAYOUT`` (row arrangement, custom buttons)
and ``CABINET_BUTTON_STYLES`` (per-section style/emoji/enabled/labels) to the frontend.
On save, splits the payload back into two SystemSetting keys.
"""
import json
import re
from typing import Literal
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import User
from app.utils.button_styles_cache import (
ALLOWED_STYLE_VALUES,
BOT_LOCALES,
BUTTON_STYLES_KEY,
DEFAULT_BUTTON_STYLES,
get_cached_button_styles,
load_button_styles_cache,
)
from app.utils.menu_layout_cache import (
BUILTIN_SECTIONS,
DEFAULT_MENU_LAYOUT,
MENU_LAYOUT_KEY,
VALID_CUSTOM_BUTTON_STYLES,
get_cached_menu_layout,
load_menu_layout_cache,
)
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/menu-layout', tags=['Admin Menu Layout'])
# ---- Constants ---------------------------------------------------------------
MAX_ROWS = 20
MAX_BUTTONS_PER_ROW = 8 # Telegram inline keyboard limit
MAX_LABEL_LENGTH = 100
URL_PATTERN = re.compile(r'^(https?://|tg://)')
# ---- Schemas -----------------------------------------------------------------
class ButtonConfig(BaseModel):
"""Configuration for a single button (built-in or custom URL)."""
id: str = Field(max_length=100)
type: Literal['builtin', 'custom']
style: str = Field(default='primary', max_length=20)
icon_custom_emoji_id: str = Field(default='', max_length=100)
enabled: bool = True
labels: dict[str, str] = Field(default_factory=dict, max_length=10)
url: str | None = Field(default=None, max_length=2048)
open_in: Literal['external', 'webapp'] = 'external'
class RowConfig(BaseModel):
"""Configuration for a single row of buttons."""
id: str = Field(max_length=100)
max_per_row: int = Field(default=2, ge=1, le=3)
buttons: list[ButtonConfig] = Field(default_factory=list, max_length=MAX_BUTTONS_PER_ROW)
class MenuConfigResponse(BaseModel):
"""Full merged menu configuration returned to the frontend."""
rows: list[RowConfig]
class MenuConfigUpdateRequest(BaseModel):
"""Full menu configuration submitted by the frontend."""
rows: list[RowConfig] = Field(max_length=MAX_ROWS)
# ---- Helpers -----------------------------------------------------------------
async def _get_setting_value(db: AsyncSession, key: str) -> str | None:
from sqlalchemy import select
from app.database.models import SystemSetting
result = await db.execute(select(SystemSetting).where(SystemSetting.key == key))
setting = result.scalar_one_or_none()
return setting.value if setting else None
async def _upsert_setting(db: AsyncSession, key: str, value: str) -> None:
"""Insert or update a SystemSetting without committing."""
from sqlalchemy import select
from app.database.models import SystemSetting
result = await db.execute(select(SystemSetting).where(SystemSetting.key == key))
setting = result.scalar_one_or_none()
if setting:
setting.value = value
else:
setting = SystemSetting(key=key, value=value)
db.add(setting)
def _build_merged_response(
layout: dict[str, object],
button_styles: dict[str, dict],
) -> MenuConfigResponse:
"""Merge layout rows with button_styles into a unified response.
Built-in buttons get style/emoji/enabled/labels from ``button_styles``.
Custom URL buttons get all config from layout's ``custom_buttons``.
"""
custom_buttons: dict[str, dict] = layout.get('custom_buttons', {})
# Collect row entries sorted numerically (row_1, row_2, ..., row_10, ...)
row_keys = sorted(
(k for k in layout if k.startswith('row_')),
key=lambda k: int(k.split('_', 1)[1]) if k.split('_', 1)[1].isdigit() else 0,
)
rows: list[RowConfig] = []
for row_key in row_keys:
row_data = layout[row_key]
if not isinstance(row_data, dict):
continue
raw_buttons: list[str] = row_data.get('buttons', [])
max_per_row: int = row_data.get('max_per_row', 2)
row_id: str = row_data.get('id', row_key)
merged_buttons: list[ButtonConfig] = []
for btn_id in raw_buttons:
if btn_id in BUILTIN_SECTIONS:
# Built-in: pull style data from button_styles cache
style_cfg = button_styles.get(btn_id, {})
merged_buttons.append(
ButtonConfig(
id=btn_id,
type='builtin',
style=style_cfg.get('style', 'primary'),
icon_custom_emoji_id=style_cfg.get('icon_custom_emoji_id', ''),
enabled=style_cfg.get('enabled', True),
labels=style_cfg.get('labels', {}),
),
)
elif btn_id.startswith('custom_') and btn_id in custom_buttons:
# Custom URL button: pull config from layout's custom_buttons
cb = custom_buttons[btn_id]
merged_buttons.append(
ButtonConfig(
id=btn_id,
type='custom',
style=cb.get('style', 'primary'),
icon_custom_emoji_id=cb.get('icon_custom_emoji_id', ''),
enabled=cb.get('enabled', True),
labels=cb.get('labels', {}),
url=cb.get('url'),
open_in=cb.get('open_in', 'external'),
),
)
rows.append(
RowConfig(
id=row_id,
max_per_row=max_per_row,
buttons=merged_buttons,
),
)
return MenuConfigResponse(rows=rows)
def _split_update(
rows: list[RowConfig],
) -> tuple[dict[str, object], dict[str, dict]]:
"""Split a flat list of RowConfig back into layout_data and button_styles_updates.
Returns:
(layout_data, button_styles_updates)
- layout_data: rows + custom_buttons for ``CABINET_MENU_LAYOUT``
- button_styles_updates: ``{section: {style, icon_custom_emoji_id, enabled, labels}}``
for built-in sections only
"""
layout_data: dict[str, object] = {}
custom_buttons: dict[str, dict] = {}
button_styles_updates: dict[str, dict] = {}
for idx, row in enumerate(rows, start=1):
row_key = f'row_{idx}'
button_ids: list[str] = []
for btn in row.buttons:
button_ids.append(btn.id)
if btn.type == 'builtin' and btn.id in BUILTIN_SECTIONS:
button_styles_updates[btn.id] = {
'style': btn.style,
'icon_custom_emoji_id': btn.icon_custom_emoji_id,
'enabled': btn.enabled,
'labels': btn.labels,
}
elif btn.type == 'custom' and btn.id.startswith('custom_'):
custom_buttons[btn.id] = {
'id': btn.id,
'url': btn.url or '',
'style': btn.style,
'icon_custom_emoji_id': btn.icon_custom_emoji_id,
'enabled': btn.enabled,
'labels': btn.labels,
'open_in': btn.open_in,
}
layout_data[row_key] = {
'id': row.id or row_key,
'buttons': button_ids,
'max_per_row': row.max_per_row,
}
layout_data['custom_buttons'] = custom_buttons
return layout_data, button_styles_updates
def _validate_update_payload(rows: list[RowConfig]) -> None:
"""Validate the full update payload. Raises HTTPException on failure."""
if len(rows) > MAX_ROWS:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Too many rows: {len(rows)}. Maximum allowed: {MAX_ROWS}.',
)
# Check for duplicate button IDs across all rows
seen_ids: set[str] = set()
for row in rows:
for btn in row.buttons:
if btn.id in seen_ids:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Duplicate button ID: "{btn.id}". Each button can only appear once.',
)
seen_ids.add(btn.id)
for row in rows:
if len(row.buttons) > MAX_BUTTONS_PER_ROW:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Row "{row.id}" has {len(row.buttons)} buttons. Maximum per row: {MAX_BUTTONS_PER_ROW}.',
)
for btn in row.buttons:
# Validate button type consistency
if btn.type == 'builtin' and btn.id not in BUILTIN_SECTIONS:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Unknown built-in section: "{btn.id}".',
)
if btn.type == 'custom' and not btn.id.startswith('custom_'):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Custom button id must start with "custom_": "{btn.id}".',
)
# Validate URL for custom buttons
if btn.type == 'custom':
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://, https://, or tg://.',
)
if btn.open_in == 'webapp' and not btn.url.startswith('https://'):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Custom button "{btn.id}" with webapp mode requires an https:// URL.',
)
# Validate style
all_allowed = ALLOWED_STYLE_VALUES | VALID_CUSTOM_BUTTON_STYLES
if btn.style not in all_allowed:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid style "{btn.style}" for button "{btn.id}". '
f'Allowed: {", ".join(sorted(all_allowed))}.',
)
# Validate labels
for locale_key, label_val in btn.labels.items():
if locale_key not in BOT_LOCALES:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid locale "{locale_key}" for button "{btn.id}". '
f'Allowed: {", ".join(BOT_LOCALES)}.',
)
if not isinstance(label_val, str):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Label value for locale "{locale_key}" must be a string.',
)
if len(label_val.strip()) > MAX_LABEL_LENGTH:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Label for locale "{locale_key}" on button "{btn.id}" '
f'exceeds {MAX_LABEL_LENGTH} characters.',
)
# ---- Routes ------------------------------------------------------------------
@router.get('', response_model=MenuConfigResponse)
async def get_menu_layout(
_admin: User = Depends(require_permission('settings:read')),
):
"""Return merged menu layout config (rows + button styles). Admin only."""
layout = get_cached_menu_layout()
button_styles = get_cached_button_styles()
return _build_merged_response(layout, button_styles)
@router.put('', response_model=MenuConfigResponse)
async def update_menu_layout(
payload: MenuConfigUpdateRequest,
admin: User = Depends(require_permission('settings:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Save full menu layout config. Splits into layout + button styles. Admin only."""
_validate_update_payload(payload.rows)
layout_data, button_styles_updates = _split_update(payload.rows)
# Save layout to CABINET_MENU_LAYOUT (without committing)
await _upsert_setting(db, MENU_LAYOUT_KEY, json.dumps(layout_data))
# Merge button styles updates with existing styles (don't overwrite sections not in request)
if button_styles_updates:
raw = await _get_setting_value(db, BUTTON_STYLES_KEY)
current_styles: dict[str, dict] = {}
if raw:
try:
current_styles = json.loads(raw)
except (json.JSONDecodeError, TypeError):
current_styles = {}
for section, updates in button_styles_updates.items():
current_styles[section] = updates
await _upsert_setting(db, BUTTON_STYLES_KEY, json.dumps(current_styles))
# Single atomic commit for both settings
await db.commit()
# Refresh caches after commit
await load_button_styles_cache()
await load_menu_layout_cache()
logger.info(
'Admin updated menu layout',
telegram_id=admin.telegram_id,
rows_count=len(payload.rows),
custom_buttons_count=len(layout_data.get('custom_buttons', {})),
)
# Return merged response from fresh caches
layout = get_cached_menu_layout()
button_styles = get_cached_button_styles()
return _build_merged_response(layout, button_styles)
@router.post('/reset', response_model=MenuConfigResponse)
async def reset_menu_layout(
admin: User = Depends(require_permission('settings:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Reset menu layout AND button styles to defaults. Admin only."""
await _upsert_setting(db, MENU_LAYOUT_KEY, json.dumps(DEFAULT_MENU_LAYOUT))
await _upsert_setting(db, BUTTON_STYLES_KEY, json.dumps(DEFAULT_BUTTON_STYLES))
# Single atomic commit for both settings
await db.commit()
# Refresh caches after commit
await load_button_styles_cache()
await load_menu_layout_cache()
logger.info('Admin reset menu layout and button styles to defaults', telegram_id=admin.telegram_id)
layout = get_cached_menu_layout()
button_styles = get_cached_button_styles()
return _build_merged_response(layout, button_styles)
+343
View File
@@ -0,0 +1,343 @@
"""Admin routes for managing news articles in cabinet."""
from datetime import UTC, datetime
from typing import Any
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.news import (
create_news_article,
delete_news_article,
get_all_news,
get_all_news_count,
get_news_article_by_id,
unfeature_all_news,
update_news_article,
)
from app.database.crud.news_categories import get_category_by_id
from app.database.crud.news_tags import get_tag_by_id
from app.database.models import NewsArticle, User
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.news import (
NewsArticleListItem,
NewsArticleResponse,
NewsCreateRequest,
NewsListResponse,
NewsToggleResponse,
NewsUpdateRequest,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/news', tags=['Cabinet Admin News'])
def _article_to_detail(article: NewsArticle) -> dict[str, Any]:
"""Convert NewsArticle ORM instance to full detail dict.
Expects the ``author`` relationship to be eagerly loaded.
"""
author_name: str | None = None
if article.author:
author_name = article.author.first_name or article.author.username or f'#{article.author.id}'
return {
'id': article.id,
'title': article.title,
'slug': article.slug,
'content': article.content,
'excerpt': article.excerpt,
'category': article.category,
'category_color': article.category_color,
'tag': article.tag,
'category_id': article.category_id,
'tag_id': article.tag_id,
'featured_image_url': article.featured_image_url,
'is_published': article.is_published,
'is_featured': article.is_featured,
'published_at': article.published_at,
'read_time_minutes': article.read_time_minutes,
'views_count': article.views_count,
'author_name': author_name,
'created_at': article.created_at,
'updated_at': article.updated_at,
}
@router.get('', response_model=NewsListResponse)
async def list_all_news(
admin: User = Depends(require_permission('news:read')),
db: AsyncSession = Depends(get_cabinet_db),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
) -> NewsListResponse:
"""Get all news articles (admin view, includes unpublished)."""
try:
articles = await get_all_news(db, limit=limit, offset=offset)
total = await get_all_news_count(db)
items = [NewsArticleListItem.model_validate(a) for a in articles]
return NewsListResponse(items=items, total=total)
except HTTPException:
raise
except Exception:
logger.exception('Failed to list all news')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load news articles',
)
@router.get('/{article_id}', response_model=NewsArticleResponse)
async def get_article_detail(
article_id: int,
admin: User = Depends(require_permission('news:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> NewsArticleResponse:
"""Get a single news article by ID (admin view)."""
article = await get_news_article_by_id(db, article_id)
if not article:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Article not found',
)
return NewsArticleResponse(**_article_to_detail(article))
@router.post('', response_model=NewsArticleResponse, status_code=status.HTTP_201_CREATED)
async def create_article(
request: NewsCreateRequest,
admin: User = Depends(require_permission('news:create')),
db: AsyncSession = Depends(get_cabinet_db),
) -> NewsArticleResponse:
"""Create a new news article."""
try:
# Resolve category from FK -- sync legacy string fields from the managed entity
category_name = request.category
category_color = request.category_color
if request.category_id is not None:
cat = await get_category_by_id(db, request.category_id)
if not cat:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f'Category with id={request.category_id} not found',
)
category_name = cat.name
category_color = cat.color
# Resolve tag from FK -- sync legacy string field from the managed entity
tag_name = request.tag
if request.tag_id is not None:
tag_obj = await get_tag_by_id(db, request.tag_id)
if not tag_obj:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f'Tag with id={request.tag_id} not found',
)
tag_name = tag_obj.name
if request.is_featured:
await unfeature_all_news(db)
article = await create_news_article(
db,
title=request.title,
slug=request.slug,
content=request.content,
excerpt=request.excerpt,
category=category_name,
category_color=category_color,
tag=tag_name,
category_id=request.category_id,
tag_id=request.tag_id,
featured_image_url=request.featured_image_url,
is_published=request.is_published,
is_featured=request.is_featured,
read_time_minutes=request.read_time_minutes,
created_by=admin.id,
)
except IntegrityError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='An article with this slug already exists',
)
except Exception:
logger.exception('Failed to create news article')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to create article',
)
# Reload with author relationship
article = await get_news_article_by_id(db, article.id)
if not article:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to reload article after creation',
)
return NewsArticleResponse(**_article_to_detail(article))
@router.put('/{article_id}', response_model=NewsArticleResponse)
async def update_article(
article_id: int,
request: NewsUpdateRequest,
admin: User = Depends(require_permission('news:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> NewsArticleResponse:
"""Update an existing news article."""
article = await get_news_article_by_id(db, article_id)
if not article:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Article not found',
)
try:
update_data = request.model_dump(exclude_unset=True)
# Resolve category from FK -- sync legacy string fields from the managed entity
if 'category_id' in update_data and update_data['category_id'] is not None:
cat = await get_category_by_id(db, update_data['category_id'])
if not cat:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f'Category with id={update_data["category_id"]} not found',
)
update_data['category'] = cat.name
update_data['category_color'] = cat.color
# Resolve tag from FK -- sync legacy string field from the managed entity
if 'tag_id' in update_data and update_data['tag_id'] is not None:
tag_obj = await get_tag_by_id(db, update_data['tag_id'])
if not tag_obj:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f'Tag with id={update_data["tag_id"]} not found',
)
update_data['tag'] = tag_obj.name
if update_data.get('is_featured'):
await unfeature_all_news(db)
article = await update_news_article(db, article, **update_data)
except IntegrityError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='An article with this slug already exists',
)
except Exception:
logger.exception('Failed to update news article', article_id=article_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to update article',
)
# Reload with author relationship (update used bulk UPDATE, author not populated)
article = await get_news_article_by_id(db, article.id)
if not article:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to reload article after update',
)
return NewsArticleResponse(**_article_to_detail(article))
@router.delete('/{article_id}', status_code=status.HTTP_204_NO_CONTENT)
async def remove_article(
article_id: int,
admin: User = Depends(require_permission('news:delete')),
db: AsyncSession = Depends(get_cabinet_db),
) -> None:
"""Delete a news article."""
article = await get_news_article_by_id(db, article_id)
if not article:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Article not found',
)
try:
await delete_news_article(db, article)
except Exception:
logger.exception('Failed to delete news article', article_id=article_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to delete article',
)
@router.post('/{article_id}/publish', response_model=NewsToggleResponse)
async def toggle_publish(
article_id: int,
admin: User = Depends(require_permission('news:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> NewsToggleResponse:
"""Toggle the published status of a news article."""
article = await get_news_article_by_id(db, article_id)
if not article:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Article not found',
)
new_published = not article.is_published
update_kwargs: dict[str, Any] = {'is_published': new_published}
# Auto-set published_at on first publish
if new_published and article.published_at is None:
update_kwargs['published_at'] = datetime.now(UTC)
try:
article = await update_news_article(db, article, **update_kwargs)
return NewsToggleResponse(
id=article.id,
is_published=article.is_published,
is_featured=article.is_featured,
published_at=article.published_at,
)
except Exception:
logger.exception('Failed to toggle publish', article_id=article_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to toggle publish status',
)
@router.post('/{article_id}/feature', response_model=NewsToggleResponse)
async def toggle_featured(
article_id: int,
admin: User = Depends(require_permission('news:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> NewsToggleResponse:
"""Toggle the featured status of a news article."""
article = await get_news_article_by_id(db, article_id)
if not article:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Article not found',
)
try:
new_featured = not article.is_featured
# Only one article can be featured at a time — unfeature all others first
if new_featured:
await unfeature_all_news(db)
article = await update_news_article(db, article, is_featured=new_featured)
return NewsToggleResponse(
id=article.id,
is_published=article.is_published,
is_featured=article.is_featured,
published_at=article.published_at,
)
except Exception:
logger.exception('Failed to toggle featured', article_id=article_id)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to toggle featured status',
)
@@ -0,0 +1,90 @@
"""Admin routes for managing news categories."""
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.news_categories import (
create_category,
delete_category,
get_all_categories,
get_category_by_id,
update_category,
)
from app.database.models import User
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.news_categories import NewsCategoryCreate, NewsCategoryResponse, NewsCategoryUpdate
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/news/categories', tags=['Cabinet Admin News Categories'])
@router.get('', response_model=list[NewsCategoryResponse])
async def list_categories(
admin: User = Depends(require_permission('news:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> list[NewsCategoryResponse]:
"""Get all news categories."""
categories = await get_all_categories(db)
return [NewsCategoryResponse.model_validate(c) for c in categories]
@router.post('', response_model=NewsCategoryResponse, status_code=status.HTTP_201_CREATED)
async def create_new_category(
request: NewsCategoryCreate,
admin: User = Depends(require_permission('news:create')),
db: AsyncSession = Depends(get_cabinet_db),
) -> NewsCategoryResponse:
"""Create a new news category."""
try:
category = await create_category(db, name=request.name, color=request.color)
except IntegrityError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='Category already exists',
)
return NewsCategoryResponse.model_validate(category)
@router.put('/{category_id}', response_model=NewsCategoryResponse)
async def update_existing_category(
category_id: int,
request: NewsCategoryUpdate,
admin: User = Depends(require_permission('news:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> NewsCategoryResponse:
"""Update an existing news category."""
category = await get_category_by_id(db, category_id)
if not category:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Category not found',
)
try:
category = await update_category(db, category, **request.model_dump(exclude_unset=True))
except IntegrityError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='Category name already exists',
)
return NewsCategoryResponse.model_validate(category)
@router.delete('/{category_id}', status_code=status.HTTP_204_NO_CONTENT)
async def remove_category(
category_id: int,
admin: User = Depends(require_permission('news:delete')),
db: AsyncSession = Depends(get_cabinet_db),
) -> None:
"""Delete a news category. Articles using it will have category_id set to NULL."""
category = await get_category_by_id(db, category_id)
if not category:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Category not found',
)
await delete_category(db, category)
+157
View File
@@ -0,0 +1,157 @@
"""Admin routes for managing news article media (images/videos)."""
import asyncio
import re
import structlog
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile, status
from PIL import Image as PILImage
from app.config import settings
from app.database.models import User
from app.services.news_media_service import (
SavedMedia,
delete_media_file,
detect_file_type,
ensure_upload_dirs,
save_image,
save_video,
)
from ..dependencies import require_permission
from ..schemas.news_media import NewsMediaUploadResponse
logger = structlog.get_logger(__name__)
_BYTES_PER_MB = 1024 * 1024
# Only allow UUID-hex filenames with expected extensions (path traversal defense-in-depth).
# thumb_ prefix is NOT allowed — thumbnails are cleaned up automatically when the main file is deleted.
_SAFE_FILENAME_RE = re.compile(r'^[0-9a-f]{32}\.(jpg|mp4|webm)$')
router = APIRouter(prefix='/admin/news/media', tags=['Cabinet Admin News Media'])
_ALLOWED_SCHEMES = frozenset({'http', 'https'})
def _build_media_url(request: Request, relative_path: str) -> str:
"""Build a full URL for a media file, respecting reverse proxy headers."""
proto = request.headers.get('X-Forwarded-Proto', request.url.scheme).split(',')[0].strip()
if proto not in _ALLOWED_SCHEMES:
proto = 'https'
host = request.headers.get('X-Forwarded-Host', request.headers.get('Host', request.url.netloc))
host = host.split(',')[0].strip()
return f'{proto}://{host}/uploads/{relative_path}'
def _build_response(request: Request, saved: SavedMedia) -> NewsMediaUploadResponse:
"""Convert SavedMedia to API response with full URLs."""
thumbnail_url = _build_media_url(request, saved.thumbnail_path) if saved.thumbnail_path else None
return NewsMediaUploadResponse(
url=_build_media_url(request, saved.relative_path),
thumbnail_url=thumbnail_url,
media_type=saved.media_type,
filename=saved.filename,
size_bytes=saved.size_bytes,
width=saved.width,
height=saved.height,
)
@router.post('/upload', response_model=NewsMediaUploadResponse, status_code=status.HTTP_201_CREATED)
async def upload_media(
request: Request,
file: UploadFile = File(...),
admin: User = Depends(require_permission('news:edit')),
) -> NewsMediaUploadResponse:
"""Upload an image or video for a news article."""
# Read with a hard budget to prevent memory exhaustion from huge uploads.
# Read slightly over the max allowed size so we can detect oversized files.
absolute_max_bytes = settings.MEDIA_MAX_VIDEO_SIZE_MB * _BYTES_PER_MB + 1
data = await file.read(absolute_max_bytes)
await file.close()
if not data:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Empty file',
)
if len(data) >= absolute_max_bytes:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail=f'File too large. Absolute maximum: {settings.MEDIA_MAX_VIDEO_SIZE_MB} MB',
)
# Detect type from magic bytes
try:
media_type, _ext = detect_file_type(data)
except ValueError:
raise HTTPException(
status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
detail='Unsupported file type. Allowed: JPEG, PNG, WebP, MP4, WebM',
) from None
# Enforce per-type size limits
max_size_mb = settings.MEDIA_MAX_IMAGE_SIZE_MB if media_type == 'image' else settings.MEDIA_MAX_VIDEO_SIZE_MB
if len(data) > max_size_mb * _BYTES_PER_MB:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
detail=f'File too large. Maximum size for {media_type}: {max_size_mb} MB',
)
upload_path = settings.get_media_upload_path()
await asyncio.to_thread(ensure_upload_dirs, upload_path)
try:
if media_type == 'image':
saved = await save_image(
data,
upload_path,
max_dim=settings.MEDIA_IMAGE_MAX_DIMENSION,
quality=settings.MEDIA_JPEG_QUALITY,
)
else:
saved = await save_video(data, upload_path)
except (ValueError, OSError, PILImage.DecompressionBombError) as exc:
logger.warning('Failed to save uploaded media', media_type=media_type, error=str(exc))
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail='Failed to process uploaded file',
) from None
logger.info(
'Media uploaded',
filename=saved.filename,
media_type=saved.media_type,
size_bytes=saved.size_bytes,
admin_id=admin.id,
)
return _build_response(request, saved)
@router.delete('/{filename}', status_code=status.HTTP_204_NO_CONTENT)
async def delete_media(
filename: str,
admin: User = Depends(require_permission('news:delete')),
) -> None:
"""Delete a previously uploaded media file."""
if not _SAFE_FILENAME_RE.match(filename):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid filename',
)
upload_path = settings.get_media_upload_path()
deleted = await asyncio.to_thread(delete_media_file, filename, upload_path)
if not deleted:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='File not found',
)
logger.info('Media deleted', filename=filename, admin_id=admin.id)
+90
View File
@@ -0,0 +1,90 @@
"""Admin routes for managing news tags."""
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.news_tags import (
create_tag,
delete_tag,
get_all_tags,
get_tag_by_id,
update_tag,
)
from app.database.models import User
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.news_tags import NewsTagCreate, NewsTagResponse, NewsTagUpdate
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/news/tags', tags=['Cabinet Admin News Tags'])
@router.get('', response_model=list[NewsTagResponse])
async def list_tags(
admin: User = Depends(require_permission('news:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> list[NewsTagResponse]:
"""Get all news tags."""
tags = await get_all_tags(db)
return [NewsTagResponse.model_validate(t) for t in tags]
@router.post('', response_model=NewsTagResponse, status_code=status.HTTP_201_CREATED)
async def create_new_tag(
request: NewsTagCreate,
admin: User = Depends(require_permission('news:create')),
db: AsyncSession = Depends(get_cabinet_db),
) -> NewsTagResponse:
"""Create a new news tag."""
try:
tag = await create_tag(db, name=request.name, color=request.color)
except IntegrityError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='Tag already exists',
)
return NewsTagResponse.model_validate(tag)
@router.put('/{tag_id}', response_model=NewsTagResponse)
async def update_existing_tag(
tag_id: int,
request: NewsTagUpdate,
admin: User = Depends(require_permission('news:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> NewsTagResponse:
"""Update an existing news tag."""
tag = await get_tag_by_id(db, tag_id)
if not tag:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Tag not found',
)
try:
tag = await update_tag(db, tag, **request.model_dump(exclude_unset=True))
except IntegrityError:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='Tag name already exists',
)
return NewsTagResponse.model_validate(tag)
@router.delete('/{tag_id}', status_code=status.HTTP_204_NO_CONTENT)
async def remove_tag(
tag_id: int,
admin: User = Depends(require_permission('news:delete')),
db: AsyncSession = Depends(get_cabinet_db),
) -> None:
"""Delete a news tag. Articles using it will have tag_id set to NULL."""
tag = await get_tag_by_id(db, tag_id)
if not tag:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Tag not found',
)
await delete_tag(db, tag)
+606
View File
@@ -0,0 +1,606 @@
"""Admin routes for managing partners in cabinet."""
from datetime import UTC, datetime
from typing import Literal
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field
from sqlalchemy import desc, func, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import (
AdvertisingCampaign,
PartnerApplication,
PartnerStatus,
ReferralEarning,
User,
)
from app.services.partner_application_service import partner_application_service
from app.services.partner_stats_service import PartnerStatsService
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.partners import (
AdminApproveRequest,
AdminPartnerApplicationItem,
AdminPartnerApplicationsResponse,
AdminPartnerDetailResponse,
AdminPartnerItem,
AdminPartnerListResponse,
AdminRejectRequest,
AdminUpdateCommissionRequest,
CampaignSummary,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/partners', tags=['Cabinet Admin Partners'])
# ==================== Settings ====================
class PartnerSettingsResponse(BaseModel):
withdrawal_enabled: bool
withdrawal_min_amount_kopeks: int
withdrawal_cooldown_days: int
withdrawal_requisites_text: str
partner_section_visible: bool
referral_program_enabled: bool
class PartnerSettingsUpdateRequest(BaseModel):
withdrawal_enabled: bool | None = None
withdrawal_min_amount_kopeks: int | None = Field(None, ge=0, le=100_000_000)
withdrawal_cooldown_days: int | None = Field(None, ge=0, le=365)
withdrawal_requisites_text: str | None = Field(None, max_length=2000)
partner_section_visible: bool | None = None
referral_program_enabled: bool | None = None
def _build_partner_settings_response() -> PartnerSettingsResponse:
return PartnerSettingsResponse(
withdrawal_enabled=settings.REFERRAL_WITHDRAWAL_ENABLED,
withdrawal_min_amount_kopeks=settings.REFERRAL_WITHDRAWAL_MIN_AMOUNT_KOPEKS,
withdrawal_cooldown_days=settings.REFERRAL_WITHDRAWAL_COOLDOWN_DAYS,
withdrawal_requisites_text=settings.REFERRAL_WITHDRAWAL_REQUISITES_TEXT,
partner_section_visible=settings.REFERRAL_PARTNER_SECTION_VISIBLE,
referral_program_enabled=settings.REFERRAL_PROGRAM_ENABLED,
)
@router.get('/settings', response_model=PartnerSettingsResponse)
async def get_partner_settings(
admin: User = Depends(require_permission('partners:settings')),
):
"""Get partner system settings."""
return _build_partner_settings_response()
@router.patch('/settings', response_model=PartnerSettingsResponse)
async def update_partner_settings(
request: PartnerSettingsUpdateRequest,
admin: User = Depends(require_permission('partners:settings')),
):
"""Update partner system settings."""
import asyncio
from pathlib import Path
# Update in-memory settings
if request.withdrawal_enabled is not None:
settings.REFERRAL_WITHDRAWAL_ENABLED = request.withdrawal_enabled
if request.withdrawal_min_amount_kopeks is not None:
settings.REFERRAL_WITHDRAWAL_MIN_AMOUNT_KOPEKS = request.withdrawal_min_amount_kopeks
if request.withdrawal_cooldown_days is not None:
settings.REFERRAL_WITHDRAWAL_COOLDOWN_DAYS = request.withdrawal_cooldown_days
if request.withdrawal_requisites_text is not None:
settings.REFERRAL_WITHDRAWAL_REQUISITES_TEXT = request.withdrawal_requisites_text
if request.partner_section_visible is not None:
settings.REFERRAL_PARTNER_SECTION_VISIBLE = request.partner_section_visible
if request.referral_program_enabled is not None:
settings.REFERRAL_PROGRAM_ENABLED = request.referral_program_enabled
# Persist to .env file
try:
env_file = Path('.env')
if await asyncio.to_thread(env_file.exists):
lines = (await asyncio.to_thread(env_file.read_text)).splitlines()
updates: dict[str, str] = {}
if request.withdrawal_enabled is not None:
updates['REFERRAL_WITHDRAWAL_ENABLED'] = str(request.withdrawal_enabled).lower()
if request.withdrawal_min_amount_kopeks is not None:
updates['REFERRAL_WITHDRAWAL_MIN_AMOUNT_KOPEKS'] = str(request.withdrawal_min_amount_kopeks)
if request.withdrawal_cooldown_days is not None:
updates['REFERRAL_WITHDRAWAL_COOLDOWN_DAYS'] = str(request.withdrawal_cooldown_days)
if request.withdrawal_requisites_text is not None:
# Sanitize: replace newlines to prevent .env injection
sanitized = (
request.withdrawal_requisites_text.replace('\r\n', ' ').replace('\n', ' ').replace('\r', ' ')
)
updates['REFERRAL_WITHDRAWAL_REQUISITES_TEXT'] = sanitized
if request.partner_section_visible is not None:
updates['REFERRAL_PARTNER_SECTION_VISIBLE'] = str(request.partner_section_visible).lower()
if request.referral_program_enabled is not None:
updates['REFERRAL_PROGRAM_ENABLED'] = str(request.referral_program_enabled).lower()
new_lines = []
updated_keys: set[str] = set()
for line in lines:
updated = False
for key, value in updates.items():
if line.startswith(f'{key}='):
new_lines.append(f'{key}={value}')
updated_keys.add(key)
updated = True
break
if not updated:
new_lines.append(line)
for key, value in updates.items():
if key not in updated_keys:
new_lines.append(f'{key}={value}')
await asyncio.to_thread(env_file.write_text, '\n'.join(new_lines) + '\n')
logger.info('Updated partner settings in .env file', admin_id=admin.id)
except Exception as e:
logger.warning('Failed to update .env file', error=e)
return _build_partner_settings_response()
# ==================== Applications (static paths first) ====================
@router.get('/applications', response_model=AdminPartnerApplicationsResponse)
async def list_applications(
application_status: Literal['pending', 'approved', 'rejected', 'none'] | None = Query(None, alias='status'),
offset: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=100),
admin: User = Depends(require_permission('partners:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""List partner applications."""
applications, total = await partner_application_service.get_all_applications(
db, status=application_status, limit=limit, offset=offset
)
# Batch-fetch users to avoid N+1
user_ids = list({app.user_id for app in applications})
if user_ids:
users_result = await db.execute(select(User).where(User.id.in_(user_ids)))
users_map = {u.id: u for u in users_result.scalars().all()}
else:
users_map = {}
items = []
for app in applications:
user = users_map.get(app.user_id)
items.append(
AdminPartnerApplicationItem(
id=app.id,
user_id=app.user_id,
username=user.username if user else None,
first_name=user.first_name if user else None,
telegram_id=user.telegram_id if user else None,
company_name=app.company_name,
website_url=app.website_url,
telegram_channel=app.telegram_channel,
description=app.description,
expected_monthly_referrals=app.expected_monthly_referrals,
desired_commission_percent=app.desired_commission_percent,
status=app.status,
admin_comment=app.admin_comment,
approved_commission_percent=app.approved_commission_percent,
created_at=app.created_at,
processed_at=app.processed_at,
)
)
return AdminPartnerApplicationsResponse(items=items, total=total)
@router.post('/applications/{application_id}/approve')
async def approve_application(
application_id: int,
request: AdminApproveRequest,
admin: User = Depends(require_permission('partners:approve')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Approve a partner application."""
success, error = await partner_application_service.approve_application(
db,
application_id=application_id,
admin_id=admin.id,
commission_percent=request.commission_percent,
comment=request.comment,
)
if not success:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error,
)
# Notify user about approval
try:
from app.bot_factory import create_bot
from app.config import settings
from app.services.notification_delivery_service import notification_delivery_service
if settings.BOT_TOKEN:
application = await db.get(PartnerApplication, application_id)
user = await db.get(User, application.user_id) if application else None
if user:
comment_text = f'\n{request.comment}' if request.comment else ''
tg_message = (
f'✅ Ваша заявка на партнёрство одобрена!\nКомиссия: {request.commission_percent}%{comment_text}'
)
bot = create_bot()
try:
await notification_delivery_service.notify_partner_approved(
user=user,
commission_percent=request.commission_percent,
comment=request.comment,
bot=bot,
telegram_message=tg_message,
)
finally:
await bot.session.close()
except Exception as e:
logger.error('Failed to send partner approval notification', error=e)
return {'success': True}
@router.post('/applications/{application_id}/reject')
async def reject_application(
application_id: int,
request: AdminRejectRequest,
admin: User = Depends(require_permission('partners:approve')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Reject a partner application."""
success, error = await partner_application_service.reject_application(
db,
application_id=application_id,
admin_id=admin.id,
comment=request.comment,
)
if not success:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error,
)
# Notify user about rejection
try:
from app.bot_factory import create_bot
from app.config import settings
from app.services.notification_delivery_service import notification_delivery_service
if settings.BOT_TOKEN:
application = await db.get(PartnerApplication, application_id)
user = await db.get(User, application.user_id) if application else None
if user:
comment_text = f'\nПричина: {request.comment}' if request.comment else ''
tg_message = f'❌ Ваша заявка на партнёрство отклонена.{comment_text}'
bot = create_bot()
try:
await notification_delivery_service.notify_partner_rejected(
user=user,
comment=request.comment,
bot=bot,
telegram_message=tg_message,
)
finally:
await bot.session.close()
except Exception as e:
logger.error('Failed to send partner rejection notification', error=e)
return {'success': True}
# ==================== Stats (static paths) ====================
@router.get('/stats')
async def get_partner_stats(
admin: User = Depends(require_permission('partners:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get overall partner statistics."""
total_partners = await db.execute(
select(func.count()).select_from(User).where(User.partner_status == PartnerStatus.APPROVED.value)
)
pending_apps = await db.execute(
select(func.count())
.select_from(PartnerApplication)
.where(PartnerApplication.status == PartnerStatus.PENDING.value)
)
total_referrals = await db.execute(select(func.count()).select_from(User).where(User.referred_by_id.isnot(None)))
total_earnings = await db.execute(select(func.coalesce(func.sum(ReferralEarning.amount_kopeks), 0)))
return {
'total_partners': total_partners.scalar() or 0,
'pending_applications': pending_apps.scalar() or 0,
'total_referrals': total_referrals.scalar() or 0,
'total_earnings_kopeks': total_earnings.scalar() or 0,
}
# ==================== Partners list ====================
@router.get('', response_model=AdminPartnerListResponse)
async def list_partners(
offset: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=100),
admin: User = Depends(require_permission('partners:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""List approved partners."""
count_result = await db.execute(
select(func.count()).select_from(User).where(User.partner_status == PartnerStatus.APPROVED.value)
)
total = count_result.scalar() or 0
result = await db.execute(
select(User)
.where(User.partner_status == PartnerStatus.APPROVED.value)
.order_by(desc(User.created_at))
.offset(offset)
.limit(limit)
)
partners = result.scalars().all()
# Batch-fetch earnings and referral counts to avoid N+1
partner_ids = [u.id for u in partners]
earnings_map: dict[int, int] = {}
referral_count_map: dict[int, int] = {}
if partner_ids:
earnings_result = await db.execute(
select(ReferralEarning.user_id, func.coalesce(func.sum(ReferralEarning.amount_kopeks), 0))
.where(ReferralEarning.user_id.in_(partner_ids))
.group_by(ReferralEarning.user_id)
)
earnings_map = {row[0]: int(row[1]) for row in earnings_result.all()}
referral_result = await db.execute(
select(User.referred_by_id, func.count())
.where(User.referred_by_id.in_(partner_ids))
.group_by(User.referred_by_id)
)
referral_count_map = {row[0]: row[1] for row in referral_result.all()}
items = []
for user in partners:
items.append(
AdminPartnerItem(
user_id=user.id,
username=user.username,
first_name=user.first_name,
telegram_id=user.telegram_id,
commission_percent=user.referral_commission_percent,
total_referrals=referral_count_map.get(user.id, 0),
total_earnings_kopeks=earnings_map.get(user.id, 0),
balance_kopeks=user.balance_kopeks,
partner_status=user.partner_status,
created_at=user.created_at,
)
)
return AdminPartnerListResponse(items=items, total=total)
# ==================== Partner detail (parametric paths last) ====================
@router.get('/{user_id}', response_model=AdminPartnerDetailResponse)
async def get_partner_detail(
user_id: int,
admin: User = Depends(require_permission('partners:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get detailed partner info."""
user = await db.get(User, user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Пользователь не найден',
)
stats = await PartnerStatsService.get_referrer_detailed_stats(db, user_id)
# Get assigned campaigns with per-campaign stats
campaigns_result = await db.execute(
select(AdvertisingCampaign).where(AdvertisingCampaign.partner_user_id == user_id)
)
campaigns = campaigns_result.scalars().all()
campaign_ids = [c.id for c in campaigns]
per_campaign_stats = await PartnerStatsService.get_per_campaign_stats(db, user_id, campaign_ids)
campaign_list = [
CampaignSummary(
id=c.id,
name=c.name,
start_parameter=c.start_parameter,
is_active=c.is_active,
registrations_count=per_campaign_stats.get(c.id, {}).get('registrations_count', 0),
referrals_count=per_campaign_stats.get(c.id, {}).get('referrals_count', 0),
earnings_kopeks=per_campaign_stats.get(c.id, {}).get('earnings_kopeks', 0),
)
for c in campaigns
]
summary = stats['summary']
earnings = stats['earnings']
return AdminPartnerDetailResponse(
user_id=user.id,
username=user.username,
first_name=user.first_name,
telegram_id=user.telegram_id,
commission_percent=user.referral_commission_percent,
partner_status=user.partner_status,
balance_kopeks=user.balance_kopeks,
total_referrals=summary['total_referrals'],
paid_referrals=summary['paid_referrals'],
active_referrals=summary['active_referrals'],
earnings_all_time=earnings['all_time_kopeks'],
earnings_today=earnings['today_kopeks'],
earnings_week=earnings['week_kopeks'],
earnings_month=earnings['month_kopeks'],
conversion_to_paid=summary['conversion_to_paid_percent'],
campaigns=campaign_list,
created_at=user.created_at,
)
@router.patch('/{user_id}/commission')
async def update_commission(
user_id: int,
request: AdminUpdateCommissionRequest,
admin: User = Depends(require_permission('partners:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update partner commission percent."""
user = await db.get(User, user_id)
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Пользователь не найден',
)
if user.partner_status != PartnerStatus.APPROVED.value:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Пользователь не является партнёром',
)
old_commission = user.referral_commission_percent
user.referral_commission_percent = request.commission_percent
await db.commit()
logger.info(
'Комиссия партнёра обновлена',
user_id=user_id,
old_commission=old_commission,
new_commission=request.commission_percent,
admin_id=admin.id,
)
return {'success': True, 'commission_percent': request.commission_percent}
@router.post('/{user_id}/revoke')
async def revoke_partner(
user_id: int,
admin: User = Depends(require_permission('partners:revoke')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Revoke partner status."""
success, error = await partner_application_service.revoke_partner(db, user_id=user_id, admin_id=admin.id)
if not success:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error,
)
return {'success': True}
@router.post('/{user_id}/campaigns/{campaign_id}/assign')
async def assign_campaign(
user_id: int,
campaign_id: int,
admin: User = Depends(require_permission('partners:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Assign a campaign to a partner."""
campaign = await db.get(AdvertisingCampaign, campaign_id)
if not campaign:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Кампания не найдена',
)
user = await db.get(User, user_id)
if not user or user.partner_status != PartnerStatus.APPROVED.value:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Пользователь не является партнёром',
)
# Atomic check-and-set to prevent race conditions
result = await db.execute(
update(AdvertisingCampaign)
.where(
AdvertisingCampaign.id == campaign_id,
or_(
AdvertisingCampaign.partner_user_id.is_(None),
AdvertisingCampaign.partner_user_id == user_id,
),
)
.values(partner_user_id=user_id, updated_at=datetime.now(UTC))
)
if result.rowcount == 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Кампания уже привязана к другому партнёру',
)
await db.commit()
logger.info(
'Кампания привязана к партнёру',
campaign_id=campaign_id,
partner_user_id=user_id,
admin_id=admin.id,
)
return {'success': True}
@router.post('/{user_id}/campaigns/{campaign_id}/unassign')
async def unassign_campaign(
user_id: int,
campaign_id: int,
admin: User = Depends(require_permission('partners:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Unassign a campaign from a partner."""
# Atomic check-and-unset to prevent race conditions
result = await db.execute(
update(AdvertisingCampaign)
.where(
AdvertisingCampaign.id == campaign_id,
AdvertisingCampaign.partner_user_id == user_id,
)
.values(partner_user_id=None, updated_at=datetime.now(UTC))
)
if result.rowcount == 0:
campaign = await db.get(AdvertisingCampaign, campaign_id)
if not campaign:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Кампания не найдена',
)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Кампания не привязана к этому партнёру',
)
await db.commit()
logger.info(
'Кампания откреплена от партнёра',
campaign_id=campaign_id,
partner_user_id=user_id,
admin_id=admin.id,
)
return {'success': True}
+241
View File
@@ -0,0 +1,241 @@
"""Admin routes for payment method configuration in cabinet."""
from datetime import datetime
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field, field_validator
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import User
from app.services.payment_method_config_service import (
_get_method_defaults,
get_all_configs,
get_all_promo_groups,
get_config_by_method_id,
update_config,
update_sort_order,
)
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/payment-methods', tags=['Cabinet Admin Payment Methods'])
# ============ Schemas ============
class SubOptionInfo(BaseModel):
id: str
name: str
class PaymentMethodConfigResponse(BaseModel):
method_id: str
sort_order: int
is_enabled: bool
display_name: str | None = None
default_display_name: str
sub_options: dict | None = None
available_sub_options: list[SubOptionInfo] | None = None
min_amount_kopeks: int | None = None
max_amount_kopeks: int | None = None
default_min_amount_kopeks: int
default_max_amount_kopeks: int
user_type_filter: str
first_topup_filter: str
promo_group_filter_mode: str
allowed_promo_group_ids: list[int] = Field(default_factory=list)
is_provider_configured: bool
created_at: datetime | None = None
updated_at: datetime | None = None
class Config:
from_attributes = True
class PaymentMethodConfigUpdateRequest(BaseModel):
is_enabled: bool | None = None
display_name: str | None = Field(default=None, description='Null to reset to default')
sub_options: dict[str, bool] | None = None
min_amount_kopeks: int | None = Field(default=None, ge=0)
max_amount_kopeks: int | None = Field(default=None, ge=0)
user_type_filter: str | None = Field(default=None, pattern='^(all|telegram|email)$')
@field_validator('sub_options', mode='before')
@classmethod
def validate_sub_options(cls, v: dict[str, bool] | None) -> dict[str, bool] | None:
if not v:
return None
if len(v) > 20:
raise ValueError('sub_options cannot have more than 20 keys')
for key in v:
if not isinstance(key, str) or len(key) > 50:
raise ValueError('sub_options keys must be strings of at most 50 characters')
return v
first_topup_filter: str | None = Field(default=None, pattern='^(any|yes|no)$')
promo_group_filter_mode: str | None = Field(default=None, pattern='^(all|selected)$')
allowed_promo_group_ids: list[int] | None = None
# Allow explicitly resetting display_name to null
reset_display_name: bool = False
reset_min_amount: bool = False
reset_max_amount: bool = False
class SortOrderRequest(BaseModel):
method_ids: list[str]
class PromoGroupSimple(BaseModel):
id: int
name: str
class Config:
from_attributes = True
# ============ Helpers ============
def _enrich_config(config, defaults: dict) -> PaymentMethodConfigResponse:
"""Enrich a PaymentMethodConfig with env-var defaults."""
method_def = defaults.get(config.method_id, {})
available_sub_options = None
raw_options = method_def.get('available_sub_options')
if raw_options:
available_sub_options = [SubOptionInfo(**opt) for opt in raw_options]
return PaymentMethodConfigResponse(
method_id=config.method_id,
sort_order=config.sort_order,
is_enabled=config.is_enabled,
display_name=config.display_name,
default_display_name=method_def.get('default_display_name', config.method_id),
sub_options=config.sub_options,
available_sub_options=available_sub_options,
min_amount_kopeks=config.min_amount_kopeks,
max_amount_kopeks=config.max_amount_kopeks,
default_min_amount_kopeks=method_def.get('default_min', 1000),
default_max_amount_kopeks=method_def.get('default_max', 10000000),
user_type_filter=config.user_type_filter,
first_topup_filter=config.first_topup_filter,
promo_group_filter_mode=config.promo_group_filter_mode,
allowed_promo_group_ids=[pg.id for pg in config.allowed_promo_groups],
is_provider_configured=method_def.get('is_configured', False),
created_at=config.created_at,
updated_at=config.updated_at,
)
# ============ Routes ============
@router.get('', response_model=list[PaymentMethodConfigResponse])
async def list_payment_methods(
admin: User = Depends(require_permission('payment_methods:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""List all payment method configurations."""
configs = await get_all_configs(db)
defaults = _get_method_defaults()
return [_enrich_config(c, defaults) for c in configs]
@router.get('/promo-groups', response_model=list[PromoGroupSimple])
async def list_promo_groups(
admin: User = Depends(require_permission('payment_methods:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""List all promo groups for filter selector."""
groups = await get_all_promo_groups(db)
return [PromoGroupSimple(id=g.id, name=g.name) for g in groups]
@router.get('/{method_id}', response_model=PaymentMethodConfigResponse)
async def get_payment_method(
method_id: str,
admin: User = Depends(require_permission('payment_methods:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get a single payment method configuration."""
config = await get_config_by_method_id(db, method_id)
if not config:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f'Payment method not found: {method_id}',
)
defaults = _get_method_defaults()
return _enrich_config(config, defaults)
@router.put('/order')
async def update_payment_methods_order(
request: SortOrderRequest,
admin: User = Depends(require_permission('payment_methods:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Batch update sort order for payment methods."""
await update_sort_order(db, request.method_ids)
logger.info('Admin updated payment methods order', admin_id=admin.id, method_ids=request.method_ids)
return {'success': True}
@router.put('/{method_id}', response_model=PaymentMethodConfigResponse)
async def update_payment_method(
method_id: str,
request: PaymentMethodConfigUpdateRequest,
admin: User = Depends(require_permission('payment_methods:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update a payment method configuration."""
# Build update data dict
data = {}
if request.is_enabled is not None:
data['is_enabled'] = request.is_enabled
if request.reset_display_name:
data['display_name'] = None
elif request.display_name is not None:
data['display_name'] = request.display_name.strip() or None
if request.sub_options is not None:
data['sub_options'] = request.sub_options
if request.reset_min_amount:
data['min_amount_kopeks'] = None
elif request.min_amount_kopeks is not None:
data['min_amount_kopeks'] = request.min_amount_kopeks
if request.reset_max_amount:
data['max_amount_kopeks'] = None
elif request.max_amount_kopeks is not None:
data['max_amount_kopeks'] = request.max_amount_kopeks
if request.user_type_filter is not None:
data['user_type_filter'] = request.user_type_filter
if request.first_topup_filter is not None:
data['first_topup_filter'] = request.first_topup_filter
if request.promo_group_filter_mode is not None:
data['promo_group_filter_mode'] = request.promo_group_filter_mode
promo_group_ids = request.allowed_promo_group_ids
config = await update_config(db, method_id, data, promo_group_ids)
if not config:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f'Payment method not found: {method_id}',
)
logger.info('Admin updated payment method config', admin_id=admin.id, method_id=method_id)
defaults = _get_method_defaults()
return _enrich_config(config, defaults)
+588
View File
@@ -0,0 +1,588 @@
"""Admin routes for payment verification in cabinet."""
import math
from datetime import UTC, datetime, timedelta
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.bot_factory import create_bot
from app.database.models import PaymentMethod, User
from app.services.payment_search_service import (
MAX_ALL_TIME_DAYS,
PeriodPreset,
SearchParams,
StatusFilter,
search_payments,
search_payments_stats,
)
from app.services.payment_service import PaymentService
from app.services.payment_verification_service import (
SUPPORTED_MANUAL_CHECK_METHODS,
PendingPayment,
get_payment_record,
list_recent_pending_payments,
method_display_name,
run_manual_check,
)
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/payments', tags=['Cabinet Admin Payments'])
# ============ Schemas ============
class PendingPaymentResponse(BaseModel):
"""Pending payment details."""
id: int
method: str
method_display: str
identifier: str
amount_kopeks: int
amount_rubles: float
status: str
status_emoji: str
status_text: str
is_paid: bool
is_checkable: bool
created_at: datetime
expires_at: datetime | None = None
payment_url: str | None = None
user_id: int | None = None
user_telegram_id: int | None = None
user_username: str | None = None
user_email: str | None = None
class Config:
from_attributes = True
class PendingPaymentListResponse(BaseModel):
"""Paginated list of pending payments."""
items: list[PendingPaymentResponse]
total: int
page: int
per_page: int
pages: int
class ManualCheckResponse(BaseModel):
"""Response after manual payment status check."""
success: bool
message: str
payment: PendingPaymentResponse | None = None
status_changed: bool = False
old_status: str | None = None
new_status: str | None = None
class PaymentsStatsResponse(BaseModel):
"""Statistics about pending payments."""
total_pending: int
by_method: dict
class SearchStatsResponse(BaseModel):
"""Statistics for payment search results."""
total: int
pending: int
paid: int
cancelled: int
by_method: dict
# ============ Helper functions ============
def _get_status_info(record: PendingPayment) -> tuple[str, str]:
"""Get status emoji and text for a pending payment."""
status_str = (record.status or '').lower()
if record.is_paid:
return '', 'Оплачено'
if record.method == PaymentMethod.PAL24:
mapping = {
'new': ('', 'Ожидает оплаты'),
'process': ('', 'Обрабатывается'),
'success': ('', 'Оплачено'),
'fail': ('', 'Ошибка'),
'canceled': ('', 'Отменено'),
}
return mapping.get(status_str, ('', 'Неизвестно'))
if record.method == PaymentMethod.MULENPAY:
mapping = {
'created': ('', 'Ожидает оплаты'),
'processing': ('', 'Обрабатывается'),
'hold': ('🔒', 'На удержании'),
'success': ('', 'Оплачено'),
'canceled': ('', 'Отменено'),
'error': ('', 'Ошибка'),
}
return mapping.get(status_str, ('', 'Неизвестно'))
if record.method == PaymentMethod.WATA:
mapping = {
'opened': ('', 'Ожидает оплаты'),
'pending': ('', 'Ожидает оплаты'),
'processing': ('', 'Обрабатывается'),
'paid': ('', 'Оплачено'),
'closed': ('', 'Оплачено'),
'declined': ('', 'Отклонено'),
'canceled': ('', 'Отменено'),
'expired': ('', 'Истёк'),
}
return mapping.get(status_str, ('', 'Неизвестно'))
if record.method == PaymentMethod.PLATEGA:
mapping = {
'pending': ('', 'Ожидает оплаты'),
'inprogress': ('', 'Обрабатывается'),
'confirmed': ('', 'Оплачено'),
'failed': ('', 'Ошибка'),
'canceled': ('', 'Отменено'),
'expired': ('', 'Истёк'),
}
return mapping.get(status_str, ('', 'Неизвестно'))
if record.method == PaymentMethod.HELEKET:
if status_str in {'pending', 'created', 'waiting', 'check', 'processing'}:
return '', 'Ожидает оплаты'
if status_str in {'paid', 'paid_over'}:
return '', 'Оплачено'
if status_str in {'cancel', 'canceled', 'fail', 'failed', 'expired'}:
return '', 'Отменено'
return '', 'Неизвестно'
if record.method == PaymentMethod.YOOKASSA:
mapping = {
'pending': ('', 'Ожидает оплаты'),
'waiting_for_capture': ('', 'Обрабатывается'),
'succeeded': ('', 'Оплачено'),
'canceled': ('', 'Отменено'),
}
return mapping.get(status_str, ('', 'Неизвестно'))
if record.method == PaymentMethod.CRYPTOBOT:
mapping = {
'active': ('', 'Ожидает оплаты'),
'paid': ('', 'Оплачено'),
'expired': ('', 'Истёк'),
}
return mapping.get(status_str, ('', 'Неизвестно'))
if record.method == PaymentMethod.CLOUDPAYMENTS:
mapping = {
'pending': ('', 'Ожидает оплаты'),
'authorized': ('', 'Авторизовано'),
'completed': ('', 'Оплачено'),
'failed': ('', 'Ошибка'),
}
return mapping.get(status_str, ('', 'Неизвестно'))
if record.method == PaymentMethod.FREEKASSA:
mapping = {
'pending': ('', 'Ожидает оплаты'),
'success': ('', 'Оплачено'),
'paid': ('', 'Оплачено'),
'canceled': ('', 'Отменено'),
'error': ('', 'Ошибка'),
}
return mapping.get(status_str, ('', 'Неизвестно'))
return '', 'Неизвестно'
def _is_checkable(record: PendingPayment) -> bool:
"""Check if payment can be manually checked."""
if record.method not in SUPPORTED_MANUAL_CHECK_METHODS:
return False
if not record.is_recent():
return False
status_str = (record.status or '').lower()
if record.method == PaymentMethod.PAL24:
return status_str in {'new', 'process'}
if record.method == PaymentMethod.MULENPAY:
return status_str in {'created', 'processing', 'hold'}
if record.method == PaymentMethod.WATA:
return status_str in {'opened', 'pending', 'processing', 'inprogress', 'in_progress'}
if record.method == PaymentMethod.PLATEGA:
return status_str in {'pending', 'inprogress', 'in_progress'}
if record.method == PaymentMethod.HELEKET:
return status_str not in {'paid', 'paid_over', 'cancel', 'canceled', 'fail', 'failed', 'expired'}
if record.method == PaymentMethod.YOOKASSA:
return status_str in {'pending', 'waiting_for_capture'}
if record.method == PaymentMethod.CRYPTOBOT:
return status_str == 'active'
if record.method == PaymentMethod.CLOUDPAYMENTS:
return status_str in {'pending', 'authorized'}
if record.method == PaymentMethod.FREEKASSA:
return status_str in {'pending', 'created', 'processing'}
return False
def _get_payment_url(record: PendingPayment) -> str | None:
"""Extract payment URL from record."""
payment = record.payment
payment_url = getattr(payment, 'payment_url', None)
if record.method == PaymentMethod.PAL24:
payment_url = getattr(payment, 'link_url', None) or getattr(payment, 'link_page_url', None) or payment_url
elif record.method == PaymentMethod.WATA:
payment_url = getattr(payment, 'url', None) or payment_url
elif record.method == PaymentMethod.YOOKASSA:
payment_url = getattr(payment, 'confirmation_url', None) or payment_url
elif record.method == PaymentMethod.CRYPTOBOT:
payment_url = (
getattr(payment, 'bot_invoice_url', None)
or getattr(payment, 'mini_app_invoice_url', None)
or getattr(payment, 'web_app_invoice_url', None)
or payment_url
)
elif record.method == PaymentMethod.PLATEGA:
payment_url = getattr(payment, 'redirect_url', None) or payment_url
elif record.method == PaymentMethod.CLOUDPAYMENTS or record.method == PaymentMethod.FREEKASSA:
payment_url = getattr(payment, 'payment_url', None) or payment_url
if payment_url and not payment_url.startswith(('https://', 'http://')):
return None
return payment_url
def _record_to_response(record: PendingPayment) -> PendingPaymentResponse:
"""Convert PendingPayment to API response."""
status_emoji, status_text = _get_status_info(record)
return PendingPaymentResponse(
id=record.local_id,
method=record.method.value,
method_display=method_display_name(record.method),
identifier=record.identifier,
amount_kopeks=record.amount_kopeks,
amount_rubles=record.amount_kopeks / 100,
status=record.status or '',
status_emoji=status_emoji,
status_text=status_text,
is_paid=record.is_paid,
is_checkable=_is_checkable(record),
created_at=record.created_at,
expires_at=record.expires_at,
payment_url=_get_payment_url(record),
user_id=record.user.id if record.user else None,
user_telegram_id=record.user.telegram_id if record.user else None,
user_username=record.user.username if record.user else None,
user_email=record.user.email if record.user else None,
)
# ============ Routes ============
@router.get('', response_model=PendingPaymentListResponse)
async def get_all_pending_payments(
page: int = Query(1, ge=1, description='Page number'),
per_page: int = Query(20, ge=1, le=100, description='Items per page'),
method_filter: str | None = Query(None, description='Filter by payment method'),
admin: User = Depends(require_permission('payments:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get all pending payments for admin verification."""
all_pending = await list_recent_pending_payments(db)
# Apply method filter if specified
if method_filter:
try:
filter_method = PaymentMethod(method_filter)
all_pending = [p for p in all_pending if p.method == filter_method]
except ValueError:
pass
total = len(all_pending)
pages = math.ceil(total / per_page) if total > 0 else 1
# Paginate
start_idx = (page - 1) * per_page
page_payments = all_pending[start_idx : start_idx + per_page]
items = [_record_to_response(p) for p in page_payments]
return PendingPaymentListResponse(
items=items,
total=total,
page=page,
per_page=per_page,
pages=pages,
)
@router.get('/stats', response_model=PaymentsStatsResponse)
async def get_payments_stats(
admin: User = Depends(require_permission('payments:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get statistics about pending payments."""
all_pending = await list_recent_pending_payments(db)
by_method = {}
for p in all_pending:
method_name = method_display_name(p.method)
if method_name not in by_method:
by_method[method_name] = 0
by_method[method_name] += 1
return PaymentsStatsResponse(
total_pending=len(all_pending),
by_method=by_method,
)
@router.get('/search', response_model=PendingPaymentListResponse)
async def search_payments_endpoint(
search: str | None = Query(
None, max_length=256, description='Search query (invoice, @username, telegram_id, email)'
),
status_filter: str = Query('all', description='Status filter: all, pending, paid, cancelled'),
method_filter: str | None = Query(None, description='Filter by payment method'),
period: str = Query('24h', description='Period preset: 24h, 7d, 30d, all'),
date_from: datetime | None = Query(None, description='Custom range start (ISO 8601)'),
date_to: datetime | None = Query(None, description='Custom range end (ISO 8601)'),
page: int = Query(1, ge=1, description='Page number'),
per_page: int = Query(20, ge=1, le=100, description='Items per page'),
admin: User = Depends(require_permission('payments:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Search payments across all providers with filters."""
try:
parsed_status = StatusFilter(status_filter)
except ValueError:
parsed_status = StatusFilter.ALL
try:
parsed_period = PeriodPreset(period)
except ValueError:
parsed_period = PeriodPreset.H24
parsed_method: PaymentMethod | None = None
if method_filter:
try:
parsed_method = PaymentMethod(method_filter)
except ValueError:
pass
# Ensure custom dates are timezone-aware
if date_from is not None and date_from.tzinfo is None:
date_from = date_from.replace(tzinfo=UTC)
if date_to is not None and date_to.tzinfo is None:
date_to = date_to.replace(tzinfo=UTC)
# Clamp custom dates to safety limit
min_allowed = datetime.now(UTC) - timedelta(days=MAX_ALL_TIME_DAYS)
if date_from is not None and date_from < min_allowed:
date_from = min_allowed
if date_from is not None and date_to is not None and date_from > date_to:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='date_from must be before date_to')
params = SearchParams(
search=search.strip() if search else None,
status_filter=parsed_status,
method_filter=parsed_method,
period=parsed_period,
date_from=date_from,
date_to=date_to,
page=page,
per_page=per_page,
)
page_items, total = await search_payments(db, params)
pages = math.ceil(total / per_page) if total > 0 else 1
items = [_record_to_response(p) for p in page_items]
return PendingPaymentListResponse(
items=items,
total=total,
page=page,
per_page=per_page,
pages=pages,
)
@router.get('/search/stats', response_model=SearchStatsResponse)
async def search_payments_stats_endpoint(
search: str | None = Query(
None, max_length=256, description='Search query (invoice, @username, telegram_id, email)'
),
status_filter: str = Query('all', description='Status filter: all, pending, paid, cancelled'),
method_filter: str | None = Query(None, description='Filter by payment method'),
period: str = Query('24h', description='Period preset: 24h, 7d, 30d, all'),
date_from: datetime | None = Query(None, description='Custom range start (ISO 8601)'),
date_to: datetime | None = Query(None, description='Custom range end (ISO 8601)'),
admin: User = Depends(require_permission('payments:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get aggregated statistics for payment search results."""
try:
parsed_status = StatusFilter(status_filter)
except ValueError:
parsed_status = StatusFilter.ALL
try:
parsed_period = PeriodPreset(period)
except ValueError:
parsed_period = PeriodPreset.H24
parsed_method: PaymentMethod | None = None
if method_filter:
try:
parsed_method = PaymentMethod(method_filter)
except ValueError:
pass
# Ensure custom dates are timezone-aware
if date_from is not None and date_from.tzinfo is None:
date_from = date_from.replace(tzinfo=UTC)
if date_to is not None and date_to.tzinfo is None:
date_to = date_to.replace(tzinfo=UTC)
# Clamp custom dates to safety limit
min_allowed = datetime.now(UTC) - timedelta(days=MAX_ALL_TIME_DAYS)
if date_from is not None and date_from < min_allowed:
date_from = min_allowed
if date_from is not None and date_to is not None and date_from > date_to:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='date_from must be before date_to')
params = SearchParams(
search=search.strip() if search else None,
status_filter=parsed_status,
method_filter=parsed_method,
period=parsed_period,
date_from=date_from,
date_to=date_to,
)
stats = await search_payments_stats(db, params)
return SearchStatsResponse(
total=stats.total,
pending=stats.pending,
paid=stats.paid,
cancelled=stats.cancelled,
by_method=stats.by_method or {},
)
@router.get('/{method}/{payment_id}', response_model=PendingPaymentResponse)
async def get_pending_payment_details(
method: str,
payment_id: int,
admin: User = Depends(require_permission('payments:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get details of a specific pending payment."""
try:
payment_method = PaymentMethod(method)
except ValueError:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid payment method',
)
record = await get_payment_record(db, payment_method, payment_id)
if not record:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Payment not found',
)
return _record_to_response(record)
@router.post('/{method}/{payment_id}/check', response_model=ManualCheckResponse)
async def check_payment_status(
method: str,
payment_id: int,
admin: User = Depends(require_permission('payments:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Manually check and update payment status."""
try:
payment_method = PaymentMethod(method)
except ValueError:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid payment method',
)
# Get current record
record = await get_payment_record(db, payment_method, payment_id)
if not record:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Payment not found',
)
# Check if manual check is available
if not _is_checkable(record):
return ManualCheckResponse(
success=False,
message='Ручная проверка недоступна для этого платежа',
payment=_record_to_response(record),
status_changed=False,
)
old_status = record.status
old_is_paid = record.is_paid
# Run manual check
bot = create_bot()
try:
payment_service = PaymentService(bot=bot)
updated = await run_manual_check(db, payment_method, payment_id, payment_service)
finally:
await bot.session.close()
if not updated:
return ManualCheckResponse(
success=False,
message='Не удалось проверить статус платежа',
payment=_record_to_response(record),
status_changed=False,
)
status_changed = updated.status != old_status or updated.is_paid != old_is_paid
if status_changed:
_, new_status_text = _get_status_info(updated)
message = f'Статус обновлён: {new_status_text}'
logger.info(
'Admin checked payment /',
admin_id=admin.id,
method=method,
payment_id=payment_id,
old_status=old_status,
status=updated.status,
)
else:
message = 'Статус не изменился'
return ManualCheckResponse(
success=True,
message=message,
payment=_record_to_response(updated),
status_changed=status_changed,
old_status=old_status,
new_status=updated.status,
)
+407
View File
@@ -0,0 +1,407 @@
"""Admin routes for pinned messages in cabinet."""
import time
from datetime import UTC, datetime
import structlog
from aiogram import Bot
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import func, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from app.bot_factory import create_bot
from app.database.models import PinnedMessage, User
from app.services.pinned_message_service import (
broadcast_pinned_message,
deactivate_active_pinned_message,
get_active_pinned_message,
set_active_pinned_message,
unpin_active_pinned_message,
)
from app.utils.validators import sanitize_html, validate_html_tags
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.pinned_messages import (
PinnedMessageBroadcastResponse,
PinnedMessageCreateRequest,
PinnedMessageListResponse,
PinnedMessageResponse,
PinnedMessageSettingsRequest,
PinnedMessageUnpinResponse,
PinnedMessageUpdateRequest,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/pinned-messages', tags=['Cabinet Admin Pinned Messages'])
# Broadcast cooldown: min 60 seconds between mass operations
_BROADCAST_COOLDOWN_SECONDS = 60
_last_broadcast_time: float = 0.0
def _check_broadcast_cooldown() -> None:
global _last_broadcast_time
now = time.monotonic()
elapsed = now - _last_broadcast_time
if _last_broadcast_time > 0 and elapsed < _BROADCAST_COOLDOWN_SECONDS:
remaining = int(_BROADCAST_COOLDOWN_SECONDS - elapsed)
raise HTTPException(
status.HTTP_429_TOO_MANY_REQUESTS,
f'Broadcast cooldown active. Try again in {remaining} seconds.',
)
_last_broadcast_time = now
def _serialize_pinned_message(msg: PinnedMessage) -> PinnedMessageResponse:
return PinnedMessageResponse(
id=msg.id,
content=msg.content,
media_type=msg.media_type,
media_file_id=msg.media_file_id,
send_before_menu=msg.send_before_menu,
send_on_every_start=msg.send_on_every_start,
is_active=msg.is_active,
created_by=msg.created_by,
created_at=msg.created_at,
updated_at=msg.updated_at,
)
_cached_bot: Bot | None = None
def _get_bot() -> Bot:
global _cached_bot
if _cached_bot is None:
_cached_bot = create_bot()
return _cached_bot
# ============ List / Get Endpoints ============
@router.get('', response_model=PinnedMessageListResponse)
async def list_pinned_messages(
admin: User = Depends(require_permission('pinned_messages:read')),
db: AsyncSession = Depends(get_cabinet_db),
limit: int = Query(20, ge=1, le=100),
offset: int = Query(0, ge=0),
active_only: bool = Query(False),
) -> PinnedMessageListResponse:
"""Get list of pinned messages with pagination."""
query = select(PinnedMessage).order_by(PinnedMessage.created_at.desc())
count_query = select(func.count(PinnedMessage.id))
if active_only:
query = query.where(PinnedMessage.is_active.is_(True))
count_query = count_query.where(PinnedMessage.is_active.is_(True))
total = await db.scalar(count_query) or 0
result = await db.execute(query.offset(offset).limit(limit))
items = result.scalars().all()
return PinnedMessageListResponse(
items=[_serialize_pinned_message(msg) for msg in items],
total=int(total),
limit=limit,
offset=offset,
)
@router.get('/active', response_model=PinnedMessageResponse | None)
async def get_active_message(
admin: User = Depends(require_permission('pinned_messages:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PinnedMessageResponse | None:
"""Get current active pinned message."""
msg = await get_active_pinned_message(db)
if not msg:
return None
return _serialize_pinned_message(msg)
@router.get('/{message_id}', response_model=PinnedMessageResponse)
async def get_pinned_message(
message_id: int,
admin: User = Depends(require_permission('pinned_messages:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PinnedMessageResponse:
"""Get pinned message by ID."""
result = await db.execute(select(PinnedMessage).where(PinnedMessage.id == message_id))
msg = result.scalar_one_or_none()
if not msg:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Pinned message not found')
return _serialize_pinned_message(msg)
# ============ Create / Update Endpoints ============
@router.post('', response_model=PinnedMessageBroadcastResponse, status_code=status.HTTP_201_CREATED)
async def create_pinned_message(
payload: PinnedMessageCreateRequest,
admin: User = Depends(require_permission('pinned_messages:create')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PinnedMessageBroadcastResponse:
"""
Create a new pinned message.
Automatically deactivates previous active message.
If broadcast=true, sends to all active users immediately.
"""
# Проверяем cooldown ДО мутации в БД
if payload.broadcast:
_check_broadcast_cooldown()
content = payload.content.strip()
if not content and not payload.media:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Either content or media must be provided')
media_type = payload.media.type if payload.media else None
media_file_id = payload.media.file_id if payload.media else None
try:
msg = await set_active_pinned_message(
db=db,
content=content,
created_by=admin.id,
media_type=media_type,
media_file_id=media_file_id,
send_before_menu=payload.send_before_menu,
send_on_every_start=payload.send_on_every_start,
)
except ValueError as e:
raise HTTPException(status.HTTP_400_BAD_REQUEST, str(e))
sent_count = 0
failed_count = 0
if payload.broadcast:
sent_count, failed_count = await broadcast_pinned_message(_get_bot(), db, msg)
logger.info(
'Admin created pinned message # (broadcast=)', admin_id=admin.id, message_id=msg.id, broadcast=payload.broadcast
)
return PinnedMessageBroadcastResponse(
message=_serialize_pinned_message(msg),
sent_count=sent_count,
failed_count=failed_count,
)
@router.patch('/{message_id}', response_model=PinnedMessageResponse)
async def update_pinned_message(
message_id: int,
payload: PinnedMessageUpdateRequest,
admin: User = Depends(require_permission('pinned_messages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PinnedMessageResponse:
"""Update a pinned message content, media, or settings."""
result = await db.execute(select(PinnedMessage).where(PinnedMessage.id == message_id))
msg = result.scalar_one_or_none()
if not msg:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Pinned message not found')
if payload.content is not None:
sanitized = sanitize_html(payload.content)
is_valid, error = validate_html_tags(sanitized)
if not is_valid:
raise HTTPException(status.HTTP_400_BAD_REQUEST, error)
msg.content = sanitized
if payload.media is not None:
msg.media_type = payload.media.type
msg.media_file_id = payload.media.file_id
if payload.send_before_menu is not None:
msg.send_before_menu = payload.send_before_menu
if payload.send_on_every_start is not None:
msg.send_on_every_start = payload.send_on_every_start
msg.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(msg)
logger.info('Admin updated pinned message #', admin_id=admin.id, message_id=message_id)
return _serialize_pinned_message(msg)
@router.patch('/{message_id}/settings', response_model=PinnedMessageResponse)
async def update_pinned_message_settings(
message_id: int,
payload: PinnedMessageSettingsRequest,
admin: User = Depends(require_permission('pinned_messages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PinnedMessageResponse:
"""Update only pinned message display settings."""
result = await db.execute(select(PinnedMessage).where(PinnedMessage.id == message_id))
msg = result.scalar_one_or_none()
if not msg:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Pinned message not found')
if payload.send_before_menu is not None:
msg.send_before_menu = payload.send_before_menu
if payload.send_on_every_start is not None:
msg.send_on_every_start = payload.send_on_every_start
msg.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(msg)
return _serialize_pinned_message(msg)
# ============ Active Message Actions (before /{message_id} POST routes) ============
@router.post('/active/deactivate', response_model=PinnedMessageResponse | None)
async def deactivate_active_message(
admin: User = Depends(require_permission('pinned_messages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PinnedMessageResponse | None:
"""Deactivate the current active pinned message without unpinning from users."""
msg = await deactivate_active_pinned_message(db)
if not msg:
return None
logger.info('Admin deactivated pinned message #', admin_id=admin.id, message_id=msg.id)
return _serialize_pinned_message(msg)
@router.post('/active/unpin', response_model=PinnedMessageUnpinResponse)
async def unpin_active_message(
admin: User = Depends(require_permission('pinned_messages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PinnedMessageUnpinResponse:
"""Unpin messages from all users and deactivate the active pinned message."""
_check_broadcast_cooldown()
unpinned_count, failed_count, was_active = await unpin_active_pinned_message(_get_bot(), db)
if was_active:
logger.info(
'Admin unpinned active message: unpinned=, failed',
admin_id=admin.id,
unpinned_count=unpinned_count,
failed_count=failed_count,
)
return PinnedMessageUnpinResponse(
unpinned_count=unpinned_count,
failed_count=failed_count,
was_active=was_active,
)
# ============ Per-Message Actions ============
@router.post('/{message_id}/activate', response_model=PinnedMessageBroadcastResponse)
async def activate_pinned_message(
message_id: int,
broadcast: bool = Query(False),
admin: User = Depends(require_permission('pinned_messages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PinnedMessageBroadcastResponse:
"""
Activate a pinned message.
Deactivates the current active message and activates the specified one.
If broadcast=true, sends to all active users immediately.
"""
# Проверяем cooldown ДО мутации в БД
if broadcast:
_check_broadcast_cooldown()
result = await db.execute(select(PinnedMessage).where(PinnedMessage.id == message_id))
msg = result.scalar_one_or_none()
if not msg:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Pinned message not found')
await db.execute(
update(PinnedMessage)
.where(PinnedMessage.is_active.is_(True))
.values(is_active=False, updated_at=datetime.now(UTC))
)
msg.is_active = True
msg.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(msg)
sent_count = 0
failed_count = 0
if broadcast:
sent_count, failed_count = await broadcast_pinned_message(_get_bot(), db, msg)
logger.info(
'Admin activated pinned message # (broadcast=)', admin_id=admin.id, message_id=message_id, broadcast=broadcast
)
return PinnedMessageBroadcastResponse(
message=_serialize_pinned_message(msg),
sent_count=sent_count,
failed_count=failed_count,
)
@router.post('/{message_id}/broadcast', response_model=PinnedMessageBroadcastResponse)
async def broadcast_message(
message_id: int,
admin: User = Depends(require_permission('pinned_messages:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PinnedMessageBroadcastResponse:
"""Broadcast a pinned message to all active users."""
_check_broadcast_cooldown()
result = await db.execute(select(PinnedMessage).where(PinnedMessage.id == message_id))
msg = result.scalar_one_or_none()
if not msg:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Pinned message not found')
sent_count, failed_count = await broadcast_pinned_message(_get_bot(), db, msg)
logger.info(
'Admin broadcast pinned message #: sent=, failed',
admin_id=admin.id,
message_id=message_id,
sent_count=sent_count,
failed_count=failed_count,
)
return PinnedMessageBroadcastResponse(
message=_serialize_pinned_message(msg),
sent_count=sent_count,
failed_count=failed_count,
)
@router.delete('/{message_id}', status_code=status.HTTP_204_NO_CONTENT, response_model=None)
async def delete_pinned_message(
message_id: int,
admin: User = Depends(require_permission('pinned_messages:delete')),
db: AsyncSession = Depends(get_cabinet_db),
) -> None:
"""Delete a pinned message. Active messages must be deactivated first."""
result = await db.execute(select(PinnedMessage).where(PinnedMessage.id == message_id))
msg = result.scalar_one_or_none()
if not msg:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Pinned message not found')
if msg.is_active:
raise HTTPException(
status.HTTP_409_CONFLICT,
'Cannot delete active pinned message. Deactivate it first.',
)
await db.delete(msg)
await db.commit()
logger.info('Admin deleted pinned message #', admin_id=admin.id, message_id=message_id)
+227
View File
@@ -0,0 +1,227 @@
"""Admin RBAC access policies management routes."""
from __future__ import annotations
from datetime import datetime
from typing import Any
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.rbac import AccessPolicyCRUD, AdminRoleCRUD
from app.database.models import User
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/rbac/policies', tags=['Admin RBAC Policies'])
# ============ Schemas ============
class PolicyResponse(BaseModel):
"""Access policy response."""
id: int
name: str
description: str | None = None
role_id: int | None = None
role_name: str | None = None
priority: int
effect: str
conditions: dict[str, Any] = Field(default_factory=dict)
resource: str
actions: list[str] = Field(default_factory=list)
is_active: bool
created_by: int | None = None
created_at: datetime | None = None
class PolicyCreateRequest(BaseModel):
"""Create a new access policy."""
name: str = Field(min_length=1, max_length=200)
description: str | None = None
role_id: int | None = None
priority: int = Field(default=0, ge=0, le=1000)
effect: str = Field(pattern=r'^(allow|deny)$')
conditions: dict[str, Any] = Field(default_factory=dict)
resource: str = Field(min_length=1, max_length=100)
actions: list[str] = Field(default_factory=list)
class PolicyUpdateRequest(BaseModel):
"""Update policy fields (all optional)."""
name: str | None = Field(default=None, min_length=1, max_length=200)
description: str | None = None
role_id: int | None = None
priority: int | None = Field(default=None, ge=0, le=1000)
effect: str | None = Field(default=None, pattern=r'^(allow|deny)$')
conditions: dict[str, Any] | None = None
resource: str | None = Field(default=None, min_length=1, max_length=100)
actions: list[str] | None = None
is_active: bool | None = None
# ============ Helper Functions ============
async def _policy_to_response(db: AsyncSession, policy) -> PolicyResponse:
"""Convert AccessPolicy model to PolicyResponse with role name."""
role_name = None
if policy.role_id is not None:
role = await AdminRoleCRUD.get_by_id(db, policy.role_id)
if role:
role_name = role.name
return PolicyResponse(
id=policy.id,
name=policy.name,
description=policy.description,
role_id=policy.role_id,
role_name=role_name,
priority=policy.priority,
effect=policy.effect,
conditions=policy.conditions or {},
resource=policy.resource,
actions=policy.actions or [],
is_active=policy.is_active,
created_by=policy.created_by,
created_at=policy.created_at,
)
# ============ Routes ============
@router.get('', response_model=list[PolicyResponse])
async def list_policies(
admin: User = Depends(require_permission('roles:read')),
db: AsyncSession = Depends(get_cabinet_db),
role_id: int | None = None,
):
"""List all access policies. Optionally filter by role_id."""
policies = await AccessPolicyCRUD.get_all(db, role_id=role_id)
return [await _policy_to_response(db, p) for p in policies]
@router.post('', response_model=PolicyResponse, status_code=status.HTTP_201_CREATED)
async def create_policy(
payload: PolicyCreateRequest,
admin: User = Depends(require_permission('roles:create')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Create a new access policy (ABAC rule)."""
# Validate role_id if provided
if payload.role_id is not None:
role = await AdminRoleCRUD.get_by_id(db, payload.role_id)
if not role:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Referenced role not found',
)
policy = await AccessPolicyCRUD.create(
db,
name=payload.name,
description=payload.description,
role_id=payload.role_id,
priority=payload.priority,
effect=payload.effect,
conditions=payload.conditions,
resource=payload.resource,
actions=payload.actions,
created_by=admin.id,
)
await db.commit()
logger.info(
'Admin created access policy',
admin_id=admin.id,
policy_id=policy.id,
policy_name=policy.name,
effect=policy.effect,
)
return await _policy_to_response(db, policy)
@router.put('/{policy_id}', response_model=PolicyResponse)
async def update_policy(
policy_id: int,
payload: PolicyUpdateRequest,
admin: User = Depends(require_permission('roles:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update an existing access policy."""
existing = await AccessPolicyCRUD.get_by_id(db, policy_id)
if not existing:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Policy not found',
)
update_data = payload.model_dump(exclude_unset=True)
# Validate role_id if changing
if 'role_id' in update_data and update_data['role_id'] is not None:
role = await AdminRoleCRUD.get_by_id(db, update_data['role_id'])
if not role:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Referenced role not found',
)
updated = await AccessPolicyCRUD.update(db, policy_id, **update_data)
if not updated:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Policy not found',
)
await db.commit()
logger.info(
'Admin updated access policy',
admin_id=admin.id,
policy_id=policy_id,
fields=list(update_data.keys()),
)
return await _policy_to_response(db, updated)
@router.delete('/{policy_id}')
async def delete_policy(
policy_id: int,
admin: User = Depends(require_permission('roles:delete')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Delete an access policy."""
existing = await AccessPolicyCRUD.get_by_id(db, policy_id)
if not existing:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Policy not found',
)
deleted = await AccessPolicyCRUD.delete(db, policy_id)
if not deleted:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Failed to delete policy',
)
await db.commit()
logger.info(
'Admin deleted access policy',
admin_id=admin.id,
policy_id=policy_id,
policy_name=existing.name,
)
return {'message': 'Policy deleted', 'policy_id': policy_id}
+638
View File
@@ -0,0 +1,638 @@
"""Admin promo offers routes for cabinet."""
from __future__ import annotations
import asyncio
from datetime import datetime
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, validator
from sqlalchemy.ext.asyncio import AsyncSession
from app.bot_factory import create_bot
from app.database.crud.discount_offer import (
count_discount_offers,
list_discount_offers,
upsert_discount_offer,
)
from app.database.crud.promo_offer_log import list_promo_offer_logs
from app.database.crud.promo_offer_template import (
ensure_default_templates,
get_promo_offer_template_by_id,
list_promo_offer_templates,
update_promo_offer_template,
)
from app.database.crud.user import get_user_by_email, get_user_by_telegram_id
from app.database.models import DiscountOffer, PromoOfferLog, PromoOfferTemplate, User
from app.handlers.admin.messages import get_custom_users, get_target_users
from app.utils.miniapp_buttons import build_miniapp_or_callback_button
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/promo-offers', tags=['Admin Promo Offers'])
# ============== Schemas ==============
class PromoOfferUserInfo(BaseModel):
id: int
telegram_id: int | None = None # Can be None for email-only users
email: str | None = None
username: str | None = None
first_name: str | None = None
last_name: str | None = None
full_name: str | None = None
class PromoOfferResponse(BaseModel):
id: int
user_id: int
subscription_id: int | None = None
notification_type: str | None = None
discount_percent: int | None = None
bonus_amount_kopeks: int | None = None
expires_at: datetime | None = None
claimed_at: datetime | None = None
is_active: bool
effect_type: str | None = None
extra_data: dict[str, Any] = Field(default_factory=dict)
created_at: datetime | None = None
updated_at: datetime | None = None
user: PromoOfferUserInfo | None = None
class PromoOfferListResponse(BaseModel):
items: list[PromoOfferResponse]
total: int
limit: int
offset: int
class PromoOfferTemplateResponse(BaseModel):
id: int
name: str
offer_type: str
message_text: str
button_text: str
valid_hours: int
discount_percent: int
bonus_amount_kopeks: int
active_discount_hours: int | None = None
test_duration_hours: int | None = None
test_squad_uuids: list[str] = Field(default_factory=list)
is_active: bool
created_by: int | None = None
created_at: datetime | None = None
updated_at: datetime | None = None
class PromoOfferTemplateListResponse(BaseModel):
items: list[PromoOfferTemplateResponse]
class PromoOfferTemplateUpdateRequest(BaseModel):
name: str | None = None
message_text: str | None = None
button_text: str | None = None
valid_hours: int | None = Field(None, ge=1)
discount_percent: int | None = Field(None, ge=0)
bonus_amount_kopeks: int | None = Field(None, ge=0)
active_discount_hours: int | None = Field(None, ge=1)
test_duration_hours: int | None = Field(None, ge=1)
test_squad_uuids: list[str] | None = None
is_active: bool | None = None
class PromoOfferBroadcastRequest(BaseModel):
notification_type: str = Field(..., min_length=1)
valid_hours: int = Field(..., ge=1)
discount_percent: int = Field(0, ge=0)
bonus_amount_kopeks: int = Field(0, ge=0)
effect_type: str = Field('percent_discount', min_length=1)
extra_data: dict[str, Any] = Field(default_factory=dict)
target: str | None = None
user_id: int | None = None
telegram_id: int | None = None
email: str | None = Field(None, description='User email (for email-only users)')
# Telegram notification options
send_notification: bool = Field(False, description='Send Telegram notification to users')
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
user_ids: list[int]
target: str | None = None
notifications_sent: int = 0
notifications_failed: int = 0
class PromoOfferLogOfferInfo(BaseModel):
id: int
notification_type: str | None = None
discount_percent: int | None = None
bonus_amount_kopeks: int | None = None
effect_type: str | None = None
expires_at: datetime | None = None
claimed_at: datetime | None = None
is_active: bool | None = None
class PromoOfferLogResponse(BaseModel):
id: int
user_id: int | None = None
offer_id: int | None = None
action: str
source: str | None = None
percent: int | None = None
effect_type: str | None = None
details: dict[str, Any] = Field(default_factory=dict)
created_at: datetime
user: PromoOfferUserInfo | None = None
offer: PromoOfferLogOfferInfo | None = None
class PromoOfferLogListResponse(BaseModel):
items: list[PromoOfferLogResponse]
total: int
limit: int
offset: int
# ============== Helpers ==============
def _serialize_user(user: User | None) -> PromoOfferUserInfo | None:
if not user:
return None
return PromoOfferUserInfo(
id=user.id,
telegram_id=user.telegram_id,
email=user.email,
username=user.username,
first_name=user.first_name,
last_name=user.last_name,
full_name=getattr(user, 'full_name', None),
)
def _serialize_offer(offer: DiscountOffer) -> PromoOfferResponse:
return PromoOfferResponse(
id=offer.id,
user_id=offer.user_id,
subscription_id=offer.subscription_id,
notification_type=offer.notification_type,
discount_percent=offer.discount_percent,
bonus_amount_kopeks=offer.bonus_amount_kopeks,
expires_at=offer.expires_at,
claimed_at=offer.claimed_at,
is_active=offer.is_active,
effect_type=offer.effect_type,
extra_data=offer.extra_data or {},
created_at=offer.created_at,
updated_at=offer.updated_at,
user=_serialize_user(getattr(offer, 'user', None)),
)
def _serialize_template(template: PromoOfferTemplate) -> PromoOfferTemplateResponse:
return PromoOfferTemplateResponse(
id=template.id,
name=template.name,
offer_type=template.offer_type,
message_text=template.message_text,
button_text=template.button_text,
valid_hours=template.valid_hours,
discount_percent=template.discount_percent,
bonus_amount_kopeks=template.bonus_amount_kopeks,
active_discount_hours=template.active_discount_hours,
test_duration_hours=template.test_duration_hours,
test_squad_uuids=[str(uuid) for uuid in (template.test_squad_uuids or [])],
is_active=template.is_active,
created_by=template.created_by,
created_at=template.created_at,
updated_at=template.updated_at,
)
def _serialize_log(entry: PromoOfferLog) -> PromoOfferLogResponse:
user_info = _serialize_user(getattr(entry, 'user', None))
offer = getattr(entry, 'offer', None)
offer_info: PromoOfferLogOfferInfo | None = None
if offer:
offer_info = PromoOfferLogOfferInfo(
id=offer.id,
notification_type=offer.notification_type,
discount_percent=offer.discount_percent,
bonus_amount_kopeks=offer.bonus_amount_kopeks,
effect_type=offer.effect_type,
expires_at=offer.expires_at,
claimed_at=offer.claimed_at,
is_active=offer.is_active,
)
return PromoOfferLogResponse(
id=entry.id,
user_id=entry.user_id,
offer_id=entry.offer_id,
action=entry.action,
source=entry.source,
percent=entry.percent,
effect_type=entry.effect_type,
details=entry.details or {},
created_at=entry.created_at,
user=user_info,
offer=offer_info,
)
async def _resolve_target_users(db: AsyncSession, target: str) -> list[User]:
normalized = target.strip().lower()
if normalized.startswith('custom_'):
criteria = normalized[len('custom_') :]
return await get_custom_users(db, criteria)
return await get_target_users(db, normalized)
# ============== Template Endpoints ==============
@router.get('/templates', response_model=PromoOfferTemplateListResponse)
async def list_templates(
admin: User = Depends(require_permission('promo_offers:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromoOfferTemplateListResponse:
"""Get list of promo offer templates."""
templates = await list_promo_offer_templates(db)
# Initialize default templates if none exist
if not templates:
templates = await ensure_default_templates(db, created_by=admin.id)
return PromoOfferTemplateListResponse(items=[_serialize_template(template) for template in templates])
@router.get('/templates/{template_id}', response_model=PromoOfferTemplateResponse)
async def get_template(
template_id: int,
admin: User = Depends(require_permission('promo_offers:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromoOfferTemplateResponse:
"""Get a promo offer template."""
template = await get_promo_offer_template_by_id(db, template_id)
if not template:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Template not found')
return _serialize_template(template)
@router.patch('/templates/{template_id}', response_model=PromoOfferTemplateResponse)
async def update_template(
template_id: int,
payload: PromoOfferTemplateUpdateRequest,
admin: User = Depends(require_permission('promo_offers:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromoOfferTemplateResponse:
"""Update a promo offer template."""
template = await get_promo_offer_template_by_id(db, template_id)
if not template:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Template not found')
if payload.test_squad_uuids is not None:
normalized_squads = [str(uuid).strip() for uuid in payload.test_squad_uuids if str(uuid).strip()]
else:
normalized_squads = None
updated_template = await update_promo_offer_template(
db,
template,
name=payload.name,
message_text=payload.message_text,
button_text=payload.button_text,
valid_hours=payload.valid_hours,
discount_percent=payload.discount_percent,
bonus_amount_kopeks=payload.bonus_amount_kopeks,
active_discount_hours=payload.active_discount_hours,
test_duration_hours=payload.test_duration_hours,
test_squad_uuids=normalized_squads,
is_active=payload.is_active,
)
return _serialize_template(updated_template)
# ============== Offer Endpoints ==============
@router.get('', response_model=PromoOfferListResponse)
async def list_offers(
admin: User = Depends(require_permission('promo_offers:read')),
db: AsyncSession = Depends(get_cabinet_db),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
user_id: int | None = Query(None, ge=1),
is_active: bool | None = Query(None),
) -> PromoOfferListResponse:
"""Get list of promo offers."""
offers = await list_discount_offers(
db,
offset=offset,
limit=limit,
user_id=user_id,
is_active=is_active,
)
total = await count_discount_offers(
db,
user_id=user_id,
is_active=is_active,
)
return PromoOfferListResponse(
items=[_serialize_offer(offer) for offer in offers],
total=total,
limit=limit,
offset=offset,
)
def _get_bot() -> Bot:
"""Create bot instance for sending notifications."""
return create_bot()
def _build_default_promo_message(
discount_percent: int,
bonus_amount_kopeks: int,
valid_hours: int,
) -> str:
"""Build default promo notification message."""
lines = ['🎁 <b>Специальное предложение для вас!</b>\n']
if discount_percent > 0:
lines.append(f'🔥 Скидка <b>{discount_percent}%</b> на подписку')
if bonus_amount_kopeks > 0:
bonus_rub = bonus_amount_kopeks / 100
lines.append(f'💰 Бонус <b>{bonus_rub:.0f}₽</b> на баланс')
lines.append(f'\n⏰ Предложение действует <b>{valid_hours} ч.</b>')
lines.append('\nНажмите кнопку ниже, чтобы активировать!')
return '\n'.join(lines)
async def _send_promo_notifications(
offers_to_notify: list[tuple[User, DiscountOffer]],
message_text: str | None,
button_text: str | None,
discount_percent: int,
bonus_amount_kopeks: int,
valid_hours: int,
) -> tuple[int, int]:
"""Send Telegram notifications for promo offers.
Returns:
Tuple of (sent_count, failed_count)
"""
if not offers_to_notify:
return 0, 0
bot = _get_bot()
sent = 0
failed = 0
# Build message text
text = message_text or _build_default_promo_message(
discount_percent=discount_percent,
bonus_amount_kopeks=bonus_amount_kopeks,
valid_hours=valid_hours,
)
# Default button text
btn_text = button_text or '🎁 Получить'
semaphore = asyncio.Semaphore(20)
async def send_single(user: User, offer: DiscountOffer) -> bool:
# Skip email-only users (no telegram_id)
if not user.telegram_id:
logger.debug('Skipping promo notification for email-only user', user_id=user.id)
return False
async with semaphore:
try:
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
build_miniapp_or_callback_button(
text=btn_text,
callback_data=f'claim_discount_{offer.id}',
)
],
[
InlineKeyboardButton(
text='❌ Закрыть',
callback_data='promo_offer_close',
)
],
]
)
await bot.send_message(
chat_id=user.telegram_id,
text=text,
reply_markup=keyboard,
)
return True
except (TelegramForbiddenError, TelegramBadRequest) as exc:
logger.warning('Failed to send promo notification to user', telegram_id=user.telegram_id, exc=exc)
return False
except Exception as exc:
logger.error('Error sending promo notification to user', telegram_id=user.telegram_id, exc=exc)
return False
# Send in batches
batch_size = 50
for i in range(0, len(offers_to_notify), batch_size):
batch = offers_to_notify[i : i + batch_size]
tasks = [send_single(user, offer) for user, offer in batch]
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, bool) and result:
sent += 1
else:
failed += 1
# Small delay between batches
if i + batch_size < len(offers_to_notify):
await asyncio.sleep(0.1)
# Close bot session
await bot.session.close()
return sent, failed
@router.post('/broadcast', response_model=PromoOfferBroadcastResponse, status_code=status.HTTP_201_CREATED)
async def broadcast_offer(
payload: PromoOfferBroadcastRequest,
admin: User = Depends(require_permission('promo_offers:send')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromoOfferBroadcastResponse:
"""Broadcast promo offer to users with optional Telegram notification."""
recipients: dict[int, User] = {}
# Resolve target segment
if payload.target:
users = await _resolve_target_users(db, payload.target)
recipients.update({user.id: user for user in users if user and user.id})
# Resolve specific user
target_user_id = payload.user_id
user: User | None = None
if payload.telegram_id is not None:
user = await get_user_by_telegram_id(db, payload.telegram_id)
if not user:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'User not found by telegram_id')
if target_user_id and target_user_id != user.id:
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
'Provided user_id does not match telegram_id',
)
target_user_id = user.id
# Support email lookup for email-only users
if payload.email is not None and user is None:
user = await get_user_by_email(db, payload.email)
if not user:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'User not found by email')
if target_user_id and target_user_id != user.id:
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
'Provided user_id does not match email',
)
target_user_id = user.id
if target_user_id is not None:
if user is None:
user = await db.get(User, target_user_id)
if not user:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'User not found')
recipients[target_user_id] = user
if not recipients:
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
'No recipients: specify target or user',
)
# Create offers for all recipients and collect (user, offer) pairs
created_offers = 0
offers_to_notify: list[tuple[User, DiscountOffer]] = []
for recipient in recipients.values():
offer = await upsert_discount_offer(
db,
user_id=recipient.id,
subscription_id=None,
notification_type=payload.notification_type.strip(),
discount_percent=payload.discount_percent,
bonus_amount_kopeks=payload.bonus_amount_kopeks,
valid_hours=payload.valid_hours,
effect_type=payload.effect_type,
extra_data=payload.extra_data,
)
if offer:
created_offers += 1
offers_to_notify.append((recipient, offer))
# Send Telegram notifications if requested
notifications_sent = 0
notifications_failed = 0
if payload.send_notification and offers_to_notify:
# Render placeholders in custom message text
rendered_message_text = payload.message_text
if rendered_message_text:
extra = payload.extra_data or {}
try:
rendered_message_text = rendered_message_text.format(
discount_percent=payload.discount_percent,
valid_hours=payload.valid_hours,
active_discount_hours=extra.get('active_discount_hours') or payload.valid_hours,
test_duration_hours=extra.get('test_duration_hours') or 0,
server_name=extra.get('server_name', ''),
)
except (KeyError, ValueError, IndexError):
logger.warning('Failed to render promo message placeholders')
notifications_sent, notifications_failed = await _send_promo_notifications(
offers_to_notify=offers_to_notify,
message_text=rendered_message_text,
button_text=payload.button_text,
discount_percent=payload.discount_percent,
bonus_amount_kopeks=payload.bonus_amount_kopeks,
valid_hours=payload.valid_hours,
)
return PromoOfferBroadcastResponse(
created_offers=created_offers,
user_ids=list(recipients.keys()),
target=payload.target,
notifications_sent=notifications_sent,
notifications_failed=notifications_failed,
)
# ============== Log Endpoints ==============
@router.get('/logs', response_model=PromoOfferLogListResponse)
async def get_logs(
admin: User = Depends(require_permission('promo_offers:read')),
db: AsyncSession = Depends(get_cabinet_db),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
user_id: int | None = Query(None, ge=1),
action: str | None = Query(None, min_length=1),
) -> PromoOfferLogListResponse:
"""Get promo offer logs."""
logs, total = await list_promo_offer_logs(
db,
offset=offset,
limit=limit,
user_id=user_id,
action=action,
)
return PromoOfferLogListResponse(
items=[_serialize_log(entry) for entry in logs],
total=int(total),
limit=limit,
offset=offset,
)
+697
View File
@@ -0,0 +1,697 @@
"""Admin promocodes routes for cabinet."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.promo_group import (
count_promo_group_members,
count_promo_groups,
create_promo_group,
delete_promo_group,
get_promo_group_by_id,
get_promo_groups_with_counts,
update_promo_group,
)
from app.database.crud.promocode import (
create_promocode,
delete_promocode,
get_promocode_by_code,
get_promocode_by_id,
get_promocode_statistics,
get_promocodes_count,
get_promocodes_list,
update_promocode,
)
from app.database.crud.tariff import get_tariff_by_id
from app.database.models import PromoCode, PromoCodeType, PromoCodeUse, PromoGroup, User
from ..dependencies import get_cabinet_db, require_permission
router = APIRouter(prefix='/admin/promocodes', tags=['Admin Promocodes'])
# ============== Schemas ==============
class PromoCodeResponse(BaseModel):
id: int
code: str
type: PromoCodeType
balance_bonus_kopeks: int
balance_bonus_rubles: float
subscription_days: int
max_uses: int
current_uses: int
uses_left: int
is_active: bool
is_valid: bool
first_purchase_only: bool
valid_from: datetime
valid_until: datetime | None = None
promo_group_id: int | None = None
tariff_id: int | None = None
tariff_name: str | None = None
created_by: int | None = None
created_at: datetime
updated_at: datetime
class PromoCodeListResponse(BaseModel):
items: list[PromoCodeResponse]
total: int
limit: int
offset: int
class PromoCodeRecentUse(BaseModel):
id: int
user_id: int
user_username: str | None = None
user_full_name: str | None = None
user_telegram_id: int | None = None
used_at: datetime
class PromoCodeDetailResponse(PromoCodeResponse):
total_uses: int
today_uses: int
recent_uses: list[PromoCodeRecentUse] = Field(default_factory=list)
class PromoCodeCreateRequest(BaseModel):
code: str = Field(..., min_length=1, max_length=50)
type: PromoCodeType
balance_bonus_kopeks: int = 0
subscription_days: int = 0
max_uses: int = Field(default=1, ge=0)
valid_from: datetime | None = None
valid_until: datetime | None = None
is_active: bool = True
first_purchase_only: bool = False
promo_group_id: int | None = None
tariff_id: int | None = None
class PromoCodeUpdateRequest(BaseModel):
code: str | None = Field(default=None, min_length=1, max_length=50)
type: PromoCodeType | None = None
balance_bonus_kopeks: int | None = None
subscription_days: int | None = None
max_uses: int | None = Field(default=None, ge=0)
valid_from: datetime | None = None
valid_until: datetime | None = None
is_active: bool | None = None
first_purchase_only: bool | None = None
promo_group_id: int | None = None
tariff_id: int | None = None
# ============== PromoGroup Schemas ==============
class PromoGroupResponse(BaseModel):
id: int
name: str
server_discount_percent: int
traffic_discount_percent: int
device_discount_percent: int
period_discounts: dict[int, int] = Field(default_factory=dict)
auto_assign_total_spent_kopeks: int | None = None
apply_discounts_to_addons: bool
is_default: bool
members_count: int = 0
created_at: datetime | None = None
updated_at: datetime | None = None
class PromoGroupListResponse(BaseModel):
items: list[PromoGroupResponse]
total: int
limit: int
offset: int
class PromoGroupCreateRequest(BaseModel):
name: str
server_discount_percent: int = 0
traffic_discount_percent: int = 0
device_discount_percent: int = 0
period_discounts: dict[int, int] | None = None
auto_assign_total_spent_kopeks: int | None = None
apply_discounts_to_addons: bool = True
is_default: bool = False
class PromoGroupUpdateRequest(BaseModel):
name: str | None = None
server_discount_percent: int | None = None
traffic_discount_percent: int | None = None
device_discount_percent: int | None = None
period_discounts: dict[int, int] | None = None
auto_assign_total_spent_kopeks: int | None = None
apply_discounts_to_addons: bool | None = None
is_default: bool | None = None
# ============== Helpers ==============
def _normalize_datetime(value: datetime | None) -> datetime | None:
if value is None:
return None
if value.tzinfo is not None and value.utcoffset() is not None:
return value.astimezone(UTC)
if value.tzinfo is not None:
return value
return value
async def _serialize_promocode(db: AsyncSession, promocode: PromoCode) -> PromoCodeResponse:
tariff_name = None
if promocode.tariff_id:
tariff = await get_tariff_by_id(db, promocode.tariff_id)
tariff_name = tariff.name if tariff else None
promo_type = PromoCodeType(promocode.type)
return PromoCodeResponse(
id=promocode.id,
code=promocode.code,
type=promo_type,
balance_bonus_kopeks=promocode.balance_bonus_kopeks,
balance_bonus_rubles=round(promocode.balance_bonus_kopeks / 100, 2),
subscription_days=promocode.subscription_days,
max_uses=promocode.max_uses,
current_uses=promocode.current_uses,
uses_left=promocode.uses_left,
is_active=promocode.is_active,
is_valid=promocode.is_valid,
first_purchase_only=promocode.first_purchase_only,
valid_from=promocode.valid_from,
valid_until=promocode.valid_until,
promo_group_id=promocode.promo_group_id,
tariff_id=promocode.tariff_id,
tariff_name=tariff_name,
created_by=promocode.created_by,
created_at=promocode.created_at,
updated_at=promocode.updated_at,
)
def _serialize_recent_use(use: PromoCodeUse) -> PromoCodeRecentUse:
return PromoCodeRecentUse(
id=use.id,
user_id=use.user_id,
user_username=getattr(use, 'user_username', None),
user_full_name=getattr(use, 'user_full_name', None),
user_telegram_id=getattr(use, 'user_telegram_id', None),
used_at=use.used_at,
)
def _normalize_period_discounts(group: PromoGroup) -> dict[int, int]:
raw = group.period_discounts or {}
normalized: dict[int, int] = {}
if isinstance(raw, dict):
for key, value in raw.items():
try:
normalized[int(key)] = int(value)
except (TypeError, ValueError):
continue
return normalized
def _serialize_promo_group(group: PromoGroup, members_count: int = 0) -> PromoGroupResponse:
return PromoGroupResponse(
id=group.id,
name=group.name,
server_discount_percent=group.server_discount_percent,
traffic_discount_percent=group.traffic_discount_percent,
device_discount_percent=group.device_discount_percent,
period_discounts=_normalize_period_discounts(group),
auto_assign_total_spent_kopeks=group.auto_assign_total_spent_kopeks,
apply_discounts_to_addons=group.apply_discounts_to_addons,
is_default=group.is_default,
members_count=members_count,
created_at=getattr(group, 'created_at', None),
updated_at=getattr(group, 'updated_at', None),
)
def _validate_create_payload(payload: PromoCodeCreateRequest) -> None:
code = payload.code.strip()
if not code:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Code must not be empty')
normalized_valid_from = _normalize_datetime(payload.valid_from)
normalized_valid_until = _normalize_datetime(payload.valid_until)
if payload.type == PromoCodeType.BALANCE and payload.balance_bonus_kopeks <= 0:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Balance bonus must be positive for balance promo codes')
if payload.type in {PromoCodeType.SUBSCRIPTION_DAYS, PromoCodeType.TRIAL_SUBSCRIPTION}:
if payload.subscription_days <= 0:
raise HTTPException(
status.HTTP_400_BAD_REQUEST, 'Subscription days must be positive for this promo code type'
)
if payload.type == PromoCodeType.DISCOUNT:
if payload.balance_bonus_kopeks <= 0 or payload.balance_bonus_kopeks > 100:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Discount percent must be between 1 and 100')
if payload.subscription_days <= 0:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Discount validity hours must be positive')
if normalized_valid_from and normalized_valid_until and normalized_valid_from > normalized_valid_until:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'valid_from cannot be greater than valid_until')
def _validate_update_payload(payload: PromoCodeUpdateRequest, promocode: PromoCode) -> None:
if payload.code is not None and not payload.code.strip():
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Code must not be empty')
if payload.type is not None:
new_type = payload.type
else:
new_type = PromoCodeType(promocode.type)
balance_bonus = (
payload.balance_bonus_kopeks if payload.balance_bonus_kopeks is not None else promocode.balance_bonus_kopeks
)
subscription_days = (
payload.subscription_days if payload.subscription_days is not None else promocode.subscription_days
)
if new_type == PromoCodeType.BALANCE and balance_bonus <= 0:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Balance bonus must be positive for balance promo codes')
if new_type in {PromoCodeType.SUBSCRIPTION_DAYS, PromoCodeType.TRIAL_SUBSCRIPTION}:
if subscription_days <= 0:
raise HTTPException(
status.HTTP_400_BAD_REQUEST, 'Subscription days must be positive for this promo code type'
)
if new_type == PromoCodeType.DISCOUNT:
if balance_bonus <= 0 or balance_bonus > 100:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Discount percent must be between 1 and 100')
if subscription_days <= 0:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Discount validity hours must be positive')
valid_from = _normalize_datetime(payload.valid_from) if payload.valid_from is not None else promocode.valid_from
valid_until = _normalize_datetime(payload.valid_until) if payload.valid_until is not None else promocode.valid_until
if valid_from and valid_until and valid_from > valid_until:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'valid_from cannot be greater than valid_until')
if payload.max_uses is not None and payload.max_uses != 0 and payload.max_uses < promocode.current_uses:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'max_uses cannot be less than current uses')
# ============== Promocode Endpoints ==============
@router.get('', response_model=PromoCodeListResponse)
async def list_promocodes(
admin: User = Depends(require_permission('promocodes:read')),
db: AsyncSession = Depends(get_cabinet_db),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
is_active: bool | None = Query(default=None),
) -> PromoCodeListResponse:
"""Get list of all promocodes."""
total = await get_promocodes_count(db, is_active=is_active) or 0
promocodes = await get_promocodes_list(db, offset=offset, limit=limit, is_active=is_active)
serialized = [await _serialize_promocode(db, p) for p in promocodes]
return PromoCodeListResponse(
items=serialized,
total=int(total),
limit=limit,
offset=offset,
)
@router.get('/{promocode_id}', response_model=PromoCodeDetailResponse)
async def get_promocode(
promocode_id: int,
admin: User = Depends(require_permission('promocodes:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromoCodeDetailResponse:
"""Get promocode details with usage statistics."""
promocode = await get_promocode_by_id(db, promocode_id)
if not promocode:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Promo code not found')
stats = await get_promocode_statistics(db, promocode_id)
base = await _serialize_promocode(db, promocode)
recent_uses = [_serialize_recent_use(use) for use in stats.get('recent_uses', [])]
return PromoCodeDetailResponse(
**base.model_dump(),
total_uses=stats.get('total_uses', 0),
today_uses=stats.get('today_uses', 0),
recent_uses=recent_uses,
)
@router.post('', response_model=PromoCodeResponse, status_code=status.HTTP_201_CREATED)
async def create_promocode_endpoint(
payload: PromoCodeCreateRequest,
admin: User = Depends(require_permission('promocodes:create')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromoCodeResponse:
"""Create a new promocode."""
_validate_create_payload(payload)
normalized_code = payload.code.strip().upper()
normalized_valid_from = _normalize_datetime(payload.valid_from)
normalized_valid_until = _normalize_datetime(payload.valid_until)
existing = await get_promocode_by_code(db, normalized_code)
if existing:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Promo code with this code already exists')
# 0 means unlimited — convert to large number for is_valid check (current_uses < max_uses)
effective_max_uses = 999999 if payload.max_uses == 0 else payload.max_uses
promocode = await create_promocode(
db,
code=normalized_code,
type=payload.type,
balance_bonus_kopeks=payload.balance_bonus_kopeks,
subscription_days=payload.subscription_days,
max_uses=effective_max_uses,
valid_until=normalized_valid_until,
created_by=admin.id,
)
update_fields = {}
if normalized_valid_from is not None:
update_fields['valid_from'] = normalized_valid_from
if payload.is_active is not None and payload.is_active != promocode.is_active:
update_fields['is_active'] = payload.is_active
if normalized_valid_until is not None:
update_fields['valid_until'] = normalized_valid_until
if payload.first_purchase_only:
update_fields['first_purchase_only'] = payload.first_purchase_only
if payload.promo_group_id is not None:
update_fields['promo_group_id'] = payload.promo_group_id
if payload.tariff_id is not None:
update_fields['tariff_id'] = payload.tariff_id
if update_fields:
promocode = await update_promocode(db, promocode, **update_fields)
return await _serialize_promocode(db, promocode)
@router.patch('/{promocode_id}', response_model=PromoCodeResponse)
async def update_promocode_endpoint(
promocode_id: int,
payload: PromoCodeUpdateRequest,
admin: User = Depends(require_permission('promocodes:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromoCodeResponse:
"""Update an existing promocode."""
promocode = await get_promocode_by_id(db, promocode_id)
if not promocode:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Promo code not found')
_validate_update_payload(payload, promocode)
updates: dict[str, Any] = {}
if payload.code is not None:
normalized_code = payload.code.strip().upper()
if normalized_code != promocode.code:
existing = await get_promocode_by_code(db, normalized_code)
if existing and existing.id != promocode_id:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Promo code with this code already exists')
updates['code'] = normalized_code
if payload.type is not None:
updates['type'] = payload.type.value
if payload.balance_bonus_kopeks is not None:
updates['balance_bonus_kopeks'] = payload.balance_bonus_kopeks
if payload.subscription_days is not None:
updates['subscription_days'] = payload.subscription_days
if payload.max_uses is not None:
updates['max_uses'] = 999999 if payload.max_uses == 0 else payload.max_uses
if payload.valid_from is not None:
updates['valid_from'] = _normalize_datetime(payload.valid_from)
if payload.valid_until is not None:
updates['valid_until'] = _normalize_datetime(payload.valid_until)
if payload.is_active is not None:
updates['is_active'] = payload.is_active
if payload.first_purchase_only is not None:
updates['first_purchase_only'] = payload.first_purchase_only
if payload.promo_group_id is not None:
updates['promo_group_id'] = payload.promo_group_id
if payload.tariff_id is not None:
updates['tariff_id'] = payload.tariff_id if payload.tariff_id != 0 else None
if not updates:
return await _serialize_promocode(db, promocode)
promocode = await update_promocode(db, promocode, **updates)
return await _serialize_promocode(db, promocode)
@router.delete(
'/{promocode_id}',
status_code=status.HTTP_204_NO_CONTENT,
response_class=Response,
)
async def delete_promocode_endpoint(
promocode_id: int,
admin: User = Depends(require_permission('promocodes:delete')),
db: AsyncSession = Depends(get_cabinet_db),
) -> Response:
"""Delete a promocode."""
promocode = await get_promocode_by_id(db, promocode_id)
if not promocode:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Promo code not found')
success = await delete_promocode(db, promocode)
if not success:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Failed to delete promo code')
return Response(status_code=status.HTTP_204_NO_CONTENT)
class DeactivateDiscountResponse(BaseModel):
success: bool
message: str
deactivated_code: str | None = None
discount_percent: int = 0
user_id: int
@router.post('/deactivate-discount/{user_id}', response_model=DeactivateDiscountResponse)
async def admin_deactivate_discount_promocode(
user_id: int,
admin: User = Depends(require_permission('promocodes:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> DeactivateDiscountResponse:
"""Admin: deactivate a user's active discount (promo code or promo offer)."""
from app.database.crud.user import get_user_by_id as get_user
target_user = await get_user(db, user_id)
if not target_user:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'User not found')
current_discount = getattr(target_user, 'promo_offer_discount_percent', 0) or 0
source = getattr(target_user, 'promo_offer_discount_source', None)
if current_discount <= 0:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'User has no active discount')
# If source is a promo code, use the service to properly rollback usage
if source and source.startswith('promocode:'):
from app.services.promocode_service import PromoCodeService
service = PromoCodeService()
result = await service.deactivate_discount_promocode(
db=db,
user_id=user_id,
admin_initiated=True,
)
if result['success']:
return DeactivateDiscountResponse(
success=True,
message=f'Discount promo code deactivated for user {user_id}',
deactivated_code=result.get('deactivated_code'),
discount_percent=result.get('discount_percent', 0),
user_id=user_id,
)
error_messages = {
'user_not_found': 'User not found',
'no_active_discount_promocode': 'User has no active discount from a promo code',
'discount_already_expired': 'Discount has already expired (cleaned up)',
'server_error': 'Server error occurred',
}
error_code = result.get('error', 'server_error')
raise HTTPException(status.HTTP_400_BAD_REQUEST, error_messages.get(error_code, 'Failed to deactivate'))
# For non-promocode offers (admin offers, etc.) — just clear the fields
old_percent = target_user.promo_offer_discount_percent
target_user.promo_offer_discount_percent = 0
target_user.promo_offer_discount_source = None
target_user.promo_offer_discount_expires_at = None
target_user.updated_at = datetime.now(UTC)
await db.commit()
return DeactivateDiscountResponse(
success=True,
message=f'Promo offer deactivated for user {user_id}',
deactivated_code=None,
discount_percent=old_percent,
user_id=user_id,
)
# ============== PromoGroup Endpoints ==============
promo_groups_router = APIRouter(prefix='/admin/promo-groups', tags=['Admin Promo Groups'])
@promo_groups_router.get('', response_model=PromoGroupListResponse)
async def list_promo_groups(
admin: User = Depends(require_permission('promo_groups:read')),
db: AsyncSession = Depends(get_cabinet_db),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
) -> PromoGroupListResponse:
"""Get list of all promo groups."""
total = await count_promo_groups(db)
groups_with_counts = await get_promo_groups_with_counts(
db,
offset=offset,
limit=limit,
)
return PromoGroupListResponse(
items=[_serialize_promo_group(group, members_count=count) for group, count in groups_with_counts],
total=total,
limit=limit,
offset=offset,
)
@promo_groups_router.get('/{group_id}', response_model=PromoGroupResponse)
async def get_promo_group(
group_id: int,
admin: User = Depends(require_permission('promo_groups:read')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromoGroupResponse:
"""Get promo group details."""
group = await get_promo_group_by_id(db, group_id)
if not group:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Promo group not found')
members_count = await count_promo_group_members(db, group_id)
return _serialize_promo_group(group, members_count=members_count)
@promo_groups_router.post('', response_model=PromoGroupResponse, status_code=status.HTTP_201_CREATED)
async def create_promo_group_endpoint(
payload: PromoGroupCreateRequest,
admin: User = Depends(require_permission('promo_groups:create')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromoGroupResponse:
"""Create a new promo group."""
from sqlalchemy.exc import IntegrityError
try:
group = await create_promo_group(
db,
name=payload.name,
server_discount_percent=payload.server_discount_percent,
traffic_discount_percent=payload.traffic_discount_percent,
device_discount_percent=payload.device_discount_percent,
period_discounts=payload.period_discounts,
auto_assign_total_spent_kopeks=payload.auto_assign_total_spent_kopeks,
apply_discounts_to_addons=payload.apply_discounts_to_addons,
is_default=payload.is_default,
)
except IntegrityError:
await db.rollback()
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
'Promo group with this name already exists',
)
return _serialize_promo_group(group, members_count=0)
@promo_groups_router.patch('/{group_id}', response_model=PromoGroupResponse)
async def update_promo_group_endpoint(
group_id: int,
payload: PromoGroupUpdateRequest,
admin: User = Depends(require_permission('promo_groups:edit')),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromoGroupResponse:
"""Update a promo group."""
from sqlalchemy.exc import IntegrityError
group = await get_promo_group_by_id(db, group_id)
if not group:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Promo group not found')
try:
group = await update_promo_group(
db,
group,
name=payload.name,
server_discount_percent=payload.server_discount_percent,
traffic_discount_percent=payload.traffic_discount_percent,
device_discount_percent=payload.device_discount_percent,
period_discounts=payload.period_discounts,
auto_assign_total_spent_kopeks=payload.auto_assign_total_spent_kopeks,
apply_discounts_to_addons=payload.apply_discounts_to_addons,
is_default=payload.is_default,
)
except IntegrityError:
await db.rollback()
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
'Promo group with this name already exists',
)
members_count = await count_promo_group_members(db, group_id)
return _serialize_promo_group(group, members_count=members_count)
@promo_groups_router.delete('/{group_id}', status_code=status.HTTP_204_NO_CONTENT)
async def delete_promo_group_endpoint(
group_id: int,
admin: User = Depends(require_permission('promo_groups:delete')),
db: AsyncSession = Depends(get_cabinet_db),
) -> Response:
"""Delete a promo group."""
group = await get_promo_group_by_id(db, group_id)
if not group:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Promo group not found')
success = await delete_promo_group(db, group)
if not success:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Cannot delete default promo group')
return Response(status_code=status.HTTP_204_NO_CONTENT)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+558
View File
@@ -0,0 +1,558 @@
"""Admin RBAC roles management routes."""
from __future__ import annotations
from datetime import datetime
import sqlalchemy as sa
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.rbac import SUPERADMIN_LEVEL, AdminRoleCRUD, UserRoleCRUD
from app.database.models import User
from app.services.permission_service import PERMISSION_REGISTRY, get_all_permissions
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/rbac', tags=['Admin RBAC'])
# ============ Schemas ============
class RoleResponse(BaseModel):
"""Admin role with user count."""
id: int
name: str
description: str | None = None
level: int
permissions: list[str] = Field(default_factory=list)
color: str | None = None
icon: str | None = None
is_system: bool
is_active: bool
user_count: int = 0
created_at: datetime | None = None
class RoleCreateRequest(BaseModel):
"""Create a new custom role."""
name: str = Field(min_length=1, max_length=100)
description: str | None = None
level: int = Field(ge=0, le=998)
permissions: list[str] = Field(default_factory=list)
color: str | None = Field(default=None, max_length=7)
icon: str | None = Field(default=None, max_length=50)
class RoleUpdateRequest(BaseModel):
"""Update role fields (all optional)."""
name: str | None = Field(default=None, min_length=1, max_length=100)
description: str | None = None
level: int | None = Field(default=None, ge=0, le=998)
permissions: list[str] | None = None
color: str | None = Field(default=None, max_length=7)
icon: str | None = Field(default=None, max_length=50)
is_active: bool | None = None
class RoleAssignRequest(BaseModel):
"""Assign a role to a user."""
user_id: int
role_id: int
expires_at: datetime | None = None
class PermissionSection(BaseModel):
"""Permission section with available actions."""
section: str
actions: list[str]
class UserRoleResponse(BaseModel):
"""User-role assignment details."""
id: int
user_id: int
role_id: int
role_name: str | None = None
user_telegram_id: int | None = None
user_username: str | None = None
user_first_name: str | None = None
user_email: str | None = None
assigned_by: int | None = None
assigned_at: datetime | None = None
expires_at: datetime | None = None
is_active: bool
class AdminWithRolesResponse(BaseModel):
"""User that has at least one admin role."""
user_id: int
telegram_id: int | None = None
username: str | None = None
first_name: str | None = None
last_name: str | None = None
email: str | None = None
role_names: list[str] = Field(default_factory=list)
# ============ Helper Functions ============
async def _role_to_response(db: AsyncSession, role) -> RoleResponse:
"""Convert AdminRole model to RoleResponse with user count."""
user_count = await AdminRoleCRUD.count_users(db, role.id)
return RoleResponse(
id=role.id,
name=role.name,
description=role.description,
level=role.level,
permissions=role.permissions or [],
color=role.color,
icon=role.icon,
is_system=role.is_system,
is_active=role.is_active,
user_count=user_count,
created_at=role.created_at,
)
async def _get_admin_level(db: AsyncSession, admin: User) -> int:
"""Get the effective management level of the current admin.
Superadmin-tier users (DB level 999 or legacy ADMIN_IDS) are promoted to
level 1000 so they can manage peer Superadmins. Without this, the ``>=``
hierarchy guard would block 999-vs-999 operations.
"""
from app.config import settings
_perms, _names, max_level = await UserRoleCRUD.get_user_permissions(db, admin.id)
# DB-assigned Superadmins can manage peers
if max_level >= SUPERADMIN_LEVEL:
max_level = SUPERADMIN_LEVEL + 1
# Legacy config-based admins always get the highest level
if settings.is_admin(
telegram_id=admin.telegram_id,
email=admin.email if admin.email_verified else None,
):
max_level = max(max_level, SUPERADMIN_LEVEL + 1)
return max_level
def _validate_permissions(permissions: list[str]) -> None:
"""Validate that all provided permissions exist in the registry."""
all_valid = set(get_all_permissions())
# Also allow wildcard patterns
all_valid.add('*:*')
for section in PERMISSION_REGISTRY:
all_valid.add(f'{section}:*')
invalid = [p for p in permissions if p not in all_valid]
if invalid:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid permissions: {", ".join(invalid)}',
)
# ============ Routes ============
@router.get('/permissions', response_model=list[PermissionSection])
async def get_permission_registry(
admin: User = Depends(require_permission('roles:read')),
):
"""Get all available permissions grouped by section."""
return [
PermissionSection(section=section, actions=list(actions)) for section, actions in PERMISSION_REGISTRY.items()
]
@router.get('/users', response_model=list[AdminWithRolesResponse])
async def list_rbac_users(
admin: User = Depends(require_permission('roles:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""List all users that have at least one active RBAC role."""
from sqlalchemy import select as _sa_select
from sqlalchemy.orm import selectinload as _sel
from app.database.models import UserRole as _UserRole
result = await db.execute(
_sa_select(_UserRole)
.options(_sel(_UserRole.user), _sel(_UserRole.role))
.where(_UserRole.is_active.is_(True))
.order_by(_UserRole.user_id)
)
assignments = result.scalars().all()
users_map: dict[int, AdminWithRolesResponse] = {}
for a in assignments:
if not a.user:
continue
if a.user_id not in users_map:
users_map[a.user_id] = AdminWithRolesResponse(
user_id=a.user_id,
telegram_id=a.user.telegram_id,
username=a.user.username,
first_name=a.user.first_name,
last_name=a.user.last_name,
email=a.user.email,
role_names=[],
)
if a.role:
users_map[a.user_id].role_names.append(a.role.name)
return list(users_map.values())
@router.get('/roles/{role_id}/users', response_model=list[UserRoleResponse])
async def list_role_users(
role_id: int,
admin: User = Depends(require_permission('roles:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""List user-role assignments for a specific role."""
from sqlalchemy.orm import selectinload as _sel
role = await AdminRoleCRUD.get_by_id(db, role_id)
if not role:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='Role not found')
from sqlalchemy import select as _sa_select
from app.database.models import UserRole as _UserRole
result = await db.execute(
_sa_select(_UserRole)
.options(_sel(_UserRole.user), _sel(_UserRole.role))
.where(_UserRole.role_id == role_id, _UserRole.is_active.is_(True))
.order_by(_UserRole.assigned_at.desc())
)
assignments = result.scalars().all()
return [
UserRoleResponse(
id=a.id,
user_id=a.user_id,
role_id=a.role_id,
role_name=a.role.name if a.role else None,
user_telegram_id=a.user.telegram_id if a.user else None,
user_username=a.user.username if a.user else None,
user_first_name=a.user.first_name if a.user else None,
user_email=a.user.email if a.user else None,
assigned_by=a.assigned_by,
assigned_at=a.assigned_at,
expires_at=a.expires_at,
is_active=a.is_active,
)
for a in assignments
]
@router.get('/roles', response_model=list[RoleResponse])
async def list_roles(
admin: User = Depends(require_permission('roles:read')),
db: AsyncSession = Depends(get_cabinet_db),
include_inactive: bool = False,
):
"""List all admin roles with user counts."""
roles = await AdminRoleCRUD.get_all(db, include_inactive=include_inactive)
return [await _role_to_response(db, role) for role in roles]
@router.post('/roles', response_model=RoleResponse, status_code=status.HTTP_201_CREATED)
async def create_role(
payload: RoleCreateRequest,
admin: User = Depends(require_permission('roles:create')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Create a new custom admin role."""
# Validate permissions list
_validate_permissions(payload.permissions)
# Hierarchy enforcement: cannot create role with level >= own level
admin_level = await _get_admin_level(db, admin)
if payload.level >= admin_level:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Cannot create a role with level >= your own role level',
)
# Check name uniqueness
existing = await AdminRoleCRUD.get_by_name(db, payload.name)
if existing:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='Role with this name already exists',
)
role = await AdminRoleCRUD.create(
db,
name=payload.name,
description=payload.description,
level=payload.level,
permissions=payload.permissions,
color=payload.color,
icon=payload.icon,
created_by=admin.id,
)
await db.commit()
logger.info('Admin created role', admin_id=admin.id, role_id=role.id, role_name=role.name)
return await _role_to_response(db, role)
@router.put('/roles/{role_id}', response_model=RoleResponse)
async def update_role(
role_id: int,
payload: RoleUpdateRequest,
admin: User = Depends(require_permission('roles:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update an existing admin role."""
role = await AdminRoleCRUD.get_by_id(db, role_id)
if not role:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Role not found',
)
admin_level = await _get_admin_level(db, admin)
# Cannot edit a role at or above own level
if role.level >= admin_level:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Cannot edit a role at or above your own level',
)
update_data = payload.model_dump(exclude_unset=True)
# System roles: only permissions can be extended, block is_active/level changes
if role.is_system:
blocked = {'is_active', 'level'} & update_data.keys()
if blocked:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail=f'Cannot change {", ".join(sorted(blocked))} on a system role',
)
# Validate level change
if 'level' in update_data and update_data['level'] >= admin_level:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Cannot set role level >= your own role level',
)
# Validate permissions
if 'permissions' in update_data and update_data['permissions'] is not None:
_validate_permissions(update_data['permissions'])
# Check name uniqueness if name is changing
if 'name' in update_data and update_data['name'] != role.name:
existing = await AdminRoleCRUD.get_by_name(db, update_data['name'])
if existing:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='Role with this name already exists',
)
updated = await AdminRoleCRUD.update(db, role_id, **update_data)
if not updated:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Role not found',
)
await db.commit()
logger.info('Admin updated role', admin_id=admin.id, role_id=role_id, fields=list(update_data.keys()))
return await _role_to_response(db, updated)
@router.delete('/roles/{role_id}')
async def delete_role(
role_id: int,
admin: User = Depends(require_permission('roles:delete')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Delete a custom admin role. System roles cannot be deleted."""
role = await AdminRoleCRUD.get_by_id(db, role_id)
if not role:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Role not found',
)
if role.is_system:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Cannot delete a system role',
)
admin_level = await _get_admin_level(db, admin)
if role.level >= admin_level:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Cannot delete a role at or above your own level',
)
deleted = await AdminRoleCRUD.delete(db, role_id)
if not deleted:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Failed to delete role',
)
await db.commit()
logger.info('Admin deleted role', admin_id=admin.id, role_id=role_id, role_name=role.name)
return {'message': 'Role deleted', 'role_id': role_id}
@router.post('/assignments', response_model=UserRoleResponse, status_code=status.HTTP_201_CREATED)
async def assign_role(
payload: RoleAssignRequest,
admin: User = Depends(require_permission('roles:assign')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Assign a role to a user. Hierarchy enforcement applies."""
role = await AdminRoleCRUD.get_by_id(db, payload.role_id)
if not role:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Role not found',
)
# Superadmin role is managed exclusively via ADMIN_IDS/ADMIN_EMAILS env config
if role.level >= SUPERADMIN_LEVEL:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Superadmin role is managed via ADMIN_IDS/ADMIN_EMAILS environment variables. '
'Add the user there and restart the bot.',
)
admin_level = await _get_admin_level(db, admin)
# Cannot assign a role with level >= own level
if role.level >= admin_level:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Cannot assign a role with level >= your own role level',
)
# Verify target user exists
from app.database.crud.user import get_user_by_id
target_user = await get_user_by_id(db, payload.user_id)
if not target_user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Target user not found',
)
user_role = await UserRoleCRUD.assign_role(
db,
user_id=payload.user_id,
role_id=payload.role_id,
assigned_by=admin.id,
expires_at=payload.expires_at,
)
await db.commit()
logger.info(
'Admin assigned role',
admin_id=admin.id,
target_user_id=payload.user_id,
role_id=payload.role_id,
role_name=role.name,
)
return UserRoleResponse(
id=user_role.id,
user_id=user_role.user_id,
role_id=user_role.role_id,
role_name=role.name,
user_telegram_id=target_user.telegram_id,
user_username=target_user.username,
user_first_name=target_user.first_name,
user_email=target_user.email,
assigned_by=user_role.assigned_by,
assigned_at=user_role.assigned_at,
expires_at=user_role.expires_at,
is_active=user_role.is_active,
)
@router.delete('/assignments/{assignment_id}')
async def revoke_role(
assignment_id: int,
admin: User = Depends(require_permission('roles:assign')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Revoke a role assignment. Superadmin roles are managed via env config."""
from app.database.models import UserRole
# Lock the assignment row (FOR UPDATE held until commit)
result = await db.execute(sa.select(UserRole).where(UserRole.id == assignment_id).with_for_update())
user_role = result.scalar_one_or_none()
if not user_role:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Role assignment not found',
)
role = await AdminRoleCRUD.get_by_id(db, user_role.role_id)
if not role:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Associated role not found',
)
# Superadmin role is managed exclusively via env config
if role.level >= SUPERADMIN_LEVEL:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Superadmin role is managed via ADMIN_IDS/ADMIN_EMAILS environment variables. '
'Remove the user from env and restart the bot.',
)
admin_level = await _get_admin_level(db, admin)
# Cannot revoke a role at or above own level
if role.level >= admin_level:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Cannot revoke a role at or above your own level',
)
# Revoke directly on the locked object (avoid CRUD re-fetch without FOR UPDATE)
user_role.is_active = False
await db.flush()
await db.commit()
logger.info(
'Admin revoked role assignment',
admin_id=admin.id,
assignment_id=assignment_id,
target_user_id=user_role.user_id,
role_name=role.name,
)
return {'message': 'Role revoked', 'assignment_id': assignment_id}
File diff suppressed because it is too large Load Diff
+329
View File
@@ -0,0 +1,329 @@
"""Admin routes for managing servers in cabinet."""
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import String, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.server_squad import (
count_active_users_for_squad,
get_all_server_squads,
get_server_squad_by_id,
sync_with_remnawave,
update_server_squad,
update_server_squad_promo_groups,
)
from app.database.models import PromoGroup, ServerSquad, Subscription, Tariff, User
from app.services.subscription_service import SubscriptionService
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.servers import (
PromoGroupInfo,
ServerDetailResponse,
ServerListItem,
ServerListResponse,
ServerStatsResponse,
ServerSyncResponse,
ServerToggleResponse,
ServerTrialToggleResponse,
ServerUpdateRequest,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/servers', tags=['Cabinet Admin Servers'])
async def _get_server_promo_groups(db: AsyncSession, server: ServerSquad) -> list[PromoGroupInfo]:
"""Get promo group info for server."""
result = await db.execute(select(PromoGroup).order_by(PromoGroup.name))
all_groups = result.scalars().all()
selected_ids = {pg.id for pg in server.allowed_promo_groups} if server.allowed_promo_groups else set()
return [
PromoGroupInfo(
id=pg.id,
name=pg.name,
is_selected=pg.id in selected_ids,
)
for pg in all_groups
]
async def _get_tariffs_using_server(db: AsyncSession, squad_uuid: str) -> list[str]:
"""Get list of tariff names using this server."""
# Get all tariffs and filter in Python since JSON array queries are DB-specific
result = await db.execute(select(Tariff.name, Tariff.allowed_squads))
tariff_names = []
for name, allowed_squads in result.fetchall():
if allowed_squads and squad_uuid in allowed_squads:
tariff_names.append(name)
return tariff_names
@router.get('', response_model=ServerListResponse)
async def list_servers(
include_unavailable: bool = True,
admin: User = Depends(require_permission('servers:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of all servers."""
servers, total = await get_all_server_squads(
db,
available_only=not include_unavailable,
)
items = []
for server in servers:
items.append(
ServerListItem(
id=server.id,
squad_uuid=server.squad_uuid,
display_name=server.display_name,
original_name=server.original_name,
country_code=server.country_code,
is_available=server.is_available,
is_trial_eligible=server.is_trial_eligible,
price_kopeks=server.price_kopeks,
price_rubles=server.price_kopeks / 100,
max_users=server.max_users,
current_users=server.current_users or 0,
sort_order=server.sort_order,
is_full=server.is_full,
availability_status=server.availability_status,
created_at=server.created_at,
)
)
return ServerListResponse(servers=items, total=total)
@router.get('/{server_id}', response_model=ServerDetailResponse)
async def get_server(
server_id: int,
admin: User = Depends(require_permission('servers:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get detailed server info."""
server = await get_server_squad_by_id(db, server_id)
if not server:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Server not found',
)
promo_groups = await _get_server_promo_groups(db, server)
tariffs_using = await _get_tariffs_using_server(db, server.squad_uuid)
active_subs = await count_active_users_for_squad(db, server.squad_uuid)
return ServerDetailResponse(
id=server.id,
squad_uuid=server.squad_uuid,
display_name=server.display_name,
original_name=server.original_name,
country_code=server.country_code,
description=server.description,
is_available=server.is_available,
is_trial_eligible=server.is_trial_eligible,
price_kopeks=server.price_kopeks,
price_rubles=server.price_kopeks / 100,
max_users=server.max_users,
current_users=server.current_users or 0,
sort_order=server.sort_order,
is_full=server.is_full,
availability_status=server.availability_status,
promo_groups=promo_groups,
active_subscriptions=active_subs,
tariffs_using=tariffs_using,
created_at=server.created_at,
updated_at=server.updated_at,
)
@router.put('/{server_id}', response_model=ServerDetailResponse)
async def update_existing_server(
server_id: int,
request: ServerUpdateRequest,
admin: User = Depends(require_permission('servers:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update an existing server."""
server = await get_server_squad_by_id(db, server_id)
if not server:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Server not found',
)
# Build updates dict
updates = {}
if request.display_name is not None:
updates['display_name'] = request.display_name
if request.description is not None:
updates['description'] = request.description
if request.country_code is not None:
updates['country_code'] = request.country_code
if request.is_available is not None:
updates['is_available'] = request.is_available
if request.is_trial_eligible is not None:
updates['is_trial_eligible'] = request.is_trial_eligible
if request.price_kopeks is not None:
updates['price_kopeks'] = request.price_kopeks
if request.max_users is not None:
updates['max_users'] = request.max_users if request.max_users > 0 else None
if request.sort_order is not None:
updates['sort_order'] = request.sort_order
if updates:
await update_server_squad(db, server_id, **updates)
# Update promo groups separately
if request.promo_group_ids is not None:
await update_server_squad_promo_groups(db, server_id, request.promo_group_ids)
logger.info('Admin updated server', admin_id=admin.id, server_id=server_id)
return await get_server(server_id, admin, db)
@router.post('/{server_id}/toggle', response_model=ServerToggleResponse)
async def toggle_server(
server_id: int,
admin: User = Depends(require_permission('servers:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Toggle server availability."""
server = await get_server_squad_by_id(db, server_id)
if not server:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Server not found',
)
new_status = not server.is_available
await update_server_squad(db, server_id, is_available=new_status)
status_text = 'enabled' if new_status else 'disabled'
logger.info('Admin server', admin_id=admin.id, status_text=status_text, server_id=server_id)
return ServerToggleResponse(
id=server_id,
is_available=new_status,
message=f'Server {status_text}',
)
@router.post('/{server_id}/trial', response_model=ServerTrialToggleResponse)
async def toggle_server_trial(
server_id: int,
admin: User = Depends(require_permission('servers:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Toggle server trial eligibility."""
server = await get_server_squad_by_id(db, server_id)
if not server:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Server not found',
)
new_status = not server.is_trial_eligible
await update_server_squad(db, server_id, is_trial_eligible=new_status)
status_text = 'enabled for trial' if new_status else 'disabled for trial'
logger.info('Admin server', admin_id=admin.id, status_text=status_text, server_id=server_id)
return ServerTrialToggleResponse(
id=server_id,
is_trial_eligible=new_status,
message=f'Server {status_text}',
)
@router.get('/{server_id}/stats', response_model=ServerStatsResponse)
async def get_server_stats(
server_id: int,
admin: User = Depends(require_permission('servers:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get server statistics."""
server = await get_server_squad_by_id(db, server_id)
if not server:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Server not found',
)
active_subs = await count_active_users_for_squad(db, server.squad_uuid)
# Count trial subscriptions on this server
# Use LIKE query for JSON array since .contains() is DB-specific
trial_result = await db.execute(
select(func.count(Subscription.id)).where(
Subscription.is_trial == True,
Subscription.status == 'active',
func.cast(Subscription.connected_squads, String).like(f'%"{server.squad_uuid}"%'),
)
)
trial_count = trial_result.scalar() or 0
usage_percent = None
if server.max_users and server.max_users > 0:
usage_percent = round((server.current_users or 0) / server.max_users * 100, 1)
return ServerStatsResponse(
id=server_id,
display_name=server.display_name,
squad_uuid=server.squad_uuid,
current_users=server.current_users or 0,
max_users=server.max_users,
active_subscriptions=active_subs,
trial_subscriptions=trial_count,
usage_percent=usage_percent,
)
@router.post('/sync', response_model=ServerSyncResponse)
async def sync_servers(
admin: User = Depends(require_permission('servers:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Sync servers with RemnaWave."""
try:
subscription_service = SubscriptionService()
if not subscription_service.is_configured:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='RemnaWave is not configured',
)
# Get squads from RemnaWave
squads = await subscription_service.get_remnawave_squads()
if squads is None:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to fetch squads from RemnaWave',
)
# Sync with database
created, updated, removed = await sync_with_remnawave(db, squads)
logger.info('Admin synced servers: + ~', admin_id=admin.id, created=created, updated=updated, removed=removed)
return ServerSyncResponse(
created=created,
updated=updated,
removed=removed,
message=f'Synced: {created} created, {updated} updated, {removed} removed',
)
except HTTPException:
raise
except Exception as e:
logger.error('Failed to sync servers', error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f'Sync failed: {e!s}',
)
+274
View File
@@ -0,0 +1,274 @@
"""Admin settings routes for cabinet - system configuration management."""
from typing import Any
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import User
from app.services.system_settings_service import (
ReadOnlySettingError,
bot_configuration_service,
)
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/settings', tags=['Admin Settings'])
# ============ Schemas ============
class SettingCategoryRef(BaseModel):
"""Reference to category."""
key: str
label: str
class SettingCategorySummary(BaseModel):
"""Category summary."""
key: str
label: str
description: str = ''
items: int
class SettingChoice(BaseModel):
"""Choice option for setting."""
value: Any
label: str
description: str | None = None
class SettingHint(BaseModel):
"""Setting hints and guidance."""
description: str = ''
format: str = ''
example: str = ''
warning: str = ''
class SettingDefinition(BaseModel):
"""Full setting definition with current state."""
key: str
name: str
category: SettingCategoryRef
type: str
is_optional: bool
current: Any = Field(default=None)
original: Any = Field(default=None)
has_override: bool
read_only: bool = Field(default=False)
choices: list[SettingChoice] = Field(default_factory=list)
hint: SettingHint | None = None
class SettingUpdateRequest(BaseModel):
"""Request to update setting value."""
value: Any
# ============ Helper Functions ============
def _coerce_value(key: str, value: Any) -> Any:
"""Convert and validate value for a setting."""
definition = bot_configuration_service.get_definition(key)
if value is None:
if definition.is_optional:
return None
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Value is required')
python_type = definition.python_type
try:
if python_type is bool:
if isinstance(value, bool):
normalized = value
elif isinstance(value, str):
lowered = value.strip().lower()
if lowered in {'true', '1', 'yes', 'on', 'да'}:
normalized = True
elif lowered in {'false', '0', 'no', 'off', 'нет'}:
normalized = False
else:
raise ValueError('invalid bool')
else:
raise ValueError('invalid bool')
elif python_type is int:
normalized = int(value)
elif python_type is float:
normalized = float(value)
else:
normalized = str(value)
except ValueError:
raise HTTPException(status.HTTP_400_BAD_REQUEST, 'Invalid value type') from None
choices = bot_configuration_service.get_choice_options(key)
if choices:
allowed_values = {option.value for option in choices}
if normalized not in allowed_values:
readable = ', '.join(bot_configuration_service.format_value(opt.value) for opt in choices)
raise HTTPException(
status.HTTP_400_BAD_REQUEST,
detail=f'Value must be one of: {readable}',
)
return normalized
def _serialize_definition(definition, include_choices: bool = True) -> SettingDefinition:
"""Serialize setting definition to response model."""
current = bot_configuration_service.get_current_value(definition.key)
original = bot_configuration_service.get_original_value(definition.key)
has_override = bot_configuration_service.has_override(definition.key)
choices: list[SettingChoice] = []
if include_choices:
choices = [
SettingChoice(
value=option.value,
label=option.label,
description=option.description,
)
for option in bot_configuration_service.get_choice_options(definition.key)
]
# Get setting hints
guidance = bot_configuration_service.get_setting_guidance(definition.key)
hint = SettingHint(
description=guidance.get('description', ''),
format=guidance.get('format', ''),
example=guidance.get('example', ''),
warning=guidance.get('warning', ''),
)
return SettingDefinition(
key=definition.key,
name=definition.display_name,
category=SettingCategoryRef(
key=definition.category_key,
label=definition.category_label,
),
type=definition.type_label,
is_optional=definition.is_optional,
current=current,
original=original,
has_override=has_override,
read_only=bot_configuration_service.is_read_only(definition.key),
choices=choices,
hint=hint,
)
# ============ Routes ============
@router.get('/categories', response_model=list[SettingCategorySummary])
async def list_categories(
admin: User = Depends(require_permission('settings:read')),
):
"""Get list of setting categories."""
categories = bot_configuration_service.get_categories()
return [
SettingCategorySummary(
key=key,
label=label,
description=bot_configuration_service.get_category_description(key),
items=count,
)
for key, label, count in categories
]
@router.get('', response_model=list[SettingDefinition])
async def list_settings(
admin: User = Depends(require_permission('settings:read')),
category: str | None = Query(default=None, alias='category_key'),
):
"""Get list of all settings or settings for a specific category."""
items: list[SettingDefinition] = []
if category:
definitions = bot_configuration_service.get_settings_for_category(category)
items.extend(_serialize_definition(defn) for defn in definitions)
return items
for category_key, _, _ in bot_configuration_service.get_categories():
definitions = bot_configuration_service.get_settings_for_category(category_key)
items.extend(_serialize_definition(defn) for defn in definitions)
return items
@router.get('/{key}', response_model=SettingDefinition)
async def get_setting(
key: str,
admin: User = Depends(require_permission('settings:read')),
):
"""Get a specific setting by key."""
try:
definition = bot_configuration_service.get_definition(key)
except KeyError as error:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Setting not found') from error
return _serialize_definition(definition)
@router.put('/{key}', response_model=SettingDefinition)
async def update_setting(
key: str,
payload: SettingUpdateRequest,
admin: User = Depends(require_permission('settings:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update a setting value."""
try:
definition = bot_configuration_service.get_definition(key)
except KeyError as error:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Setting not found') from error
value = _coerce_value(key, payload.value)
try:
await bot_configuration_service.set_value(db, key, value)
except ReadOnlySettingError as error:
raise HTTPException(status.HTTP_403_FORBIDDEN, str(error)) from error
await db.commit()
logger.info('Admin updated setting to', telegram_id=admin.telegram_id, key=key, value=value)
return _serialize_definition(definition)
@router.delete('/{key}', response_model=SettingDefinition)
async def reset_setting(
key: str,
admin: User = Depends(require_permission('settings:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Reset a setting to its default value."""
try:
definition = bot_configuration_service.get_definition(key)
except KeyError as error:
raise HTTPException(status.HTTP_404_NOT_FOUND, 'Setting not found') from error
try:
await bot_configuration_service.reset_value(db, key)
except ReadOnlySettingError as error:
raise HTTPException(status.HTTP_403_FORBIDDEN, str(error)) from error
await db.commit()
logger.info('Admin reset setting', telegram_id=admin.telegram_id, key=key)
return _serialize_definition(definition)
+965
View File
@@ -0,0 +1,965 @@
"""Admin routes for statistics dashboard in cabinet."""
import sys
import time
from datetime import UTC, datetime, timedelta
from typing import Any
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy import and_, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.campaign import get_campaign_statistics, get_campaigns_count, get_campaigns_list
from app.database.crud.server_squad import get_server_statistics
from app.database.crud.subscription import get_subscriptions_statistics
from app.database.crud.transaction import REAL_PAYMENT_METHODS, get_revenue_by_period, get_transactions_statistics
from app.database.models import (
ReferralEarning,
Subscription,
SubscriptionStatus,
Tariff,
Transaction,
TransactionType,
User,
)
from app.services.remnawave_service import RemnaWaveService
from app.services.version_service import version_service
from ..dependencies import get_cabinet_db, require_permission
logger = structlog.get_logger(__name__)
_start_time = time.time()
router = APIRouter(prefix='/admin/stats', tags=['Cabinet Admin Stats'])
# ============ Schemas ============
class NodeStatus(BaseModel):
"""Node status info."""
uuid: str
name: str
address: str
is_connected: bool
is_disabled: bool
users_online: int
traffic_used_bytes: int | None = None
last_status_message: str | None = None
xray_uptime: int = 0
is_xray_running: bool | None = None
versions: dict[str, str] | None = None
system: dict[str, Any] | None = None
country_code: str | None = None
class NodesOverview(BaseModel):
"""Overview of all nodes."""
total: int
online: int
offline: int
disabled: int
total_users_online: int
nodes: list[NodeStatus]
class RevenueData(BaseModel):
"""Revenue data point."""
date: str
amount_kopeks: int
amount_rubles: float
class SubscriptionStats(BaseModel):
"""Subscription statistics."""
total: int
active: int
trial: int
paid: int
expired: int
purchased_today: int
purchased_week: int
purchased_month: int
trial_to_paid_conversion: float
class FinancialStats(BaseModel):
"""Financial statistics."""
income_today_kopeks: int
income_today_rubles: float
income_month_kopeks: int
income_month_rubles: float
income_total_kopeks: int
income_total_rubles: float
subscription_income_kopeks: int
subscription_income_rubles: float
class ServerStats(BaseModel):
"""Server statistics."""
total_servers: int
available_servers: int
servers_with_connections: int
total_revenue_kopeks: int
total_revenue_rubles: float
class TariffStatItem(BaseModel):
"""Statistics for a single tariff."""
tariff_id: int
tariff_name: str
active_subscriptions: int
trial_subscriptions: int
purchased_today: int
purchased_week: int
purchased_month: int
class TariffStats(BaseModel):
"""Tariff statistics."""
tariffs: list[TariffStatItem]
total_tariff_subscriptions: int
class DashboardStats(BaseModel):
"""Complete dashboard statistics."""
nodes: NodesOverview
subscriptions: SubscriptionStats
financial: FinancialStats
servers: ServerStats
revenue_chart: list[RevenueData]
tariff_stats: TariffStats | None = None
class SystemInfoResponse(BaseModel):
"""System information for admin dashboard."""
bot_version: str
python_version: str
uptime_seconds: int
users_total: int
subscriptions_active: int
# ============ Extended Stats Schemas ============
class TopReferrerItem(BaseModel):
"""Single referrer in top list."""
user_id: int
telegram_id: int | None = None # Can be None for email-only users
email: str | None = None
username: str | None = None
display_name: str
invited_count: int
invited_today: int = 0
invited_week: int = 0
invited_month: int = 0
earnings_today_kopeks: int = 0
earnings_week_kopeks: int = 0
earnings_month_kopeks: int = 0
earnings_total_kopeks: int = 0
class TopReferrersResponse(BaseModel):
"""Top referrers response."""
by_earnings: list[TopReferrerItem]
by_invited: list[TopReferrerItem]
total_referrers: int
total_referrals: int
total_earnings_kopeks: int
class TopCampaignItem(BaseModel):
"""Single campaign in top list."""
id: int
name: str
start_parameter: str
bonus_type: str
is_active: bool
registrations: int
conversions: int
conversion_rate: float
total_revenue_kopeks: int
avg_revenue_per_user_kopeks: int
created_at: str | None = None
class TopCampaignsResponse(BaseModel):
"""Top campaigns response."""
campaigns: list[TopCampaignItem]
total_campaigns: int
total_registrations: int
total_revenue_kopeks: int
class RecentPaymentItem(BaseModel):
"""Single recent payment."""
id: int
user_id: int
telegram_id: int | None = None # Can be None for email-only users
email: str | None = None
username: str | None = None
display_name: str
amount_kopeks: int
amount_rubles: float
type: str
type_display: str
payment_method: str | None = None
description: str | None = None
created_at: str
is_completed: bool
class RecentPaymentsResponse(BaseModel):
"""Recent payments response."""
payments: list[RecentPaymentItem]
total_count: int
total_today_kopeks: int
total_week_kopeks: int
# ============ Routes ============
@router.get('/dashboard', response_model=DashboardStats)
async def get_dashboard_stats(
admin: User = Depends(require_permission('stats:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get complete dashboard statistics for admin panel."""
try:
# Get nodes status from RemnaWave
nodes_data = await _get_nodes_overview()
# Get subscription statistics
sub_stats = await get_subscriptions_statistics(db)
# Get financial statistics
now = datetime.now(UTC)
month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
trans_stats = await get_transactions_statistics(db, month_start, now)
all_time_stats = await get_transactions_statistics(
db, start_date=datetime(2020, 1, 1, tzinfo=UTC), end_date=now
)
# Get revenue chart data (last 30 days)
revenue_data = await get_revenue_by_period(db, days=30)
# Get server statistics
server_stats = await get_server_statistics(db)
# Get tariff statistics
tariff_stats = await _get_tariff_stats(db)
# Derive income_today from revenue_chart to ensure consistency with chart
today_str = now.date().isoformat()
income_today_from_chart = sum(
item.get('amount_kopeks', 0) for item in revenue_data if str(item.get('date', '')) == today_str
)
# Use chart-derived value if available, otherwise fall back to trans_stats
income_today_kopeks = income_today_from_chart or trans_stats.get('today', {}).get('income_kopeks', 0)
# Build response
return DashboardStats(
nodes=nodes_data,
subscriptions=SubscriptionStats(
total=sub_stats.get('total_subscriptions', 0),
active=sub_stats.get('active_subscriptions', 0),
trial=sub_stats.get('trial_subscriptions', 0),
paid=sub_stats.get('paid_subscriptions', 0),
expired=sub_stats.get('total_subscriptions', 0) - sub_stats.get('active_subscriptions', 0),
purchased_today=sub_stats.get('purchased_today', 0),
purchased_week=sub_stats.get('purchased_week', 0),
purchased_month=sub_stats.get('purchased_month', 0),
trial_to_paid_conversion=sub_stats.get('trial_to_paid_conversion', 0.0),
),
financial=FinancialStats(
income_today_kopeks=income_today_kopeks,
income_today_rubles=income_today_kopeks / 100,
income_month_kopeks=trans_stats.get('totals', {}).get('income_kopeks', 0),
income_month_rubles=trans_stats.get('totals', {}).get('income_kopeks', 0) / 100,
income_total_kopeks=all_time_stats.get('totals', {}).get('income_kopeks', 0),
income_total_rubles=all_time_stats.get('totals', {}).get('income_kopeks', 0) / 100,
subscription_income_kopeks=abs(all_time_stats.get('totals', {}).get('subscription_income_kopeks', 0)),
subscription_income_rubles=abs(all_time_stats.get('totals', {}).get('subscription_income_kopeks', 0))
/ 100,
),
servers=ServerStats(
total_servers=server_stats.get('total_servers', 0),
available_servers=server_stats.get('available_servers', 0),
servers_with_connections=server_stats.get('servers_with_connections', 0),
total_revenue_kopeks=server_stats.get('total_revenue_kopeks', 0),
total_revenue_rubles=server_stats.get('total_revenue_rubles', 0.0),
),
revenue_chart=[
RevenueData(
date=item.get('date', '').isoformat()
if hasattr(item.get('date', ''), 'isoformat')
else str(item.get('date', '')),
amount_kopeks=item.get('amount_kopeks', 0),
amount_rubles=item.get('amount_kopeks', 0) / 100,
)
for item in revenue_data
],
tariff_stats=tariff_stats,
)
except Exception as e:
logger.error('Failed to get dashboard stats', error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load dashboard statistics',
)
@router.get('/system-info', response_model=SystemInfoResponse)
async def get_system_info(
admin: User = Depends(require_permission('stats:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get system information for admin dashboard."""
try:
users_total_result = await db.execute(select(func.count()).select_from(User))
users_total = users_total_result.scalar() or 0
subs_active_result = await db.execute(
select(func.count(Subscription.id)).where(
Subscription.status == SubscriptionStatus.ACTIVE.value,
)
)
subscriptions_active = subs_active_result.scalar() or 0
return SystemInfoResponse(
bot_version=version_service.current_version,
python_version=sys.version.split()[0],
uptime_seconds=int(time.time() - _start_time),
users_total=users_total,
subscriptions_active=subscriptions_active,
)
except Exception as e:
logger.error('Failed to get system info', error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load system information',
)
@router.get('/nodes', response_model=NodesOverview)
async def get_nodes_status(
admin: User = Depends(require_permission('stats:read')),
):
"""Get status of all nodes."""
try:
return await _get_nodes_overview()
except Exception as e:
logger.error('Failed to get nodes status', error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load nodes status',
)
@router.post('/nodes/{node_uuid}/restart')
async def restart_node(
node_uuid: str,
admin: User = Depends(require_permission('remnawave:manage')),
):
"""Restart a node."""
try:
service = RemnaWaveService()
success = await service.manage_node(node_uuid, 'restart')
if success:
logger.info('Admin restarted node', admin_id=admin.id, node_uuid=node_uuid)
return {'success': True, 'message': 'Node restart initiated'}
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Failed to restart node',
)
except HTTPException:
raise
except Exception as e:
logger.error('Failed to restart node', node_uuid=node_uuid, error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to restart node',
)
@router.post('/nodes/{node_uuid}/toggle')
async def toggle_node(
node_uuid: str,
admin: User = Depends(require_permission('remnawave:manage')),
):
"""Enable or disable a node."""
try:
service = RemnaWaveService()
nodes = await service.get_all_nodes()
node = next((n for n in nodes if n.get('uuid') == node_uuid), None)
if not node:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Node not found',
)
is_disabled = node.get('is_disabled', False)
action = 'enable' if is_disabled else 'disable'
success = await service.manage_node(node_uuid, action)
if success:
logger.info('Admin d node', admin_id=admin.id, action=action, node_uuid=node_uuid)
return {'success': True, 'message': f'Node {action}d', 'is_disabled': not is_disabled}
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Failed to {action} node',
)
except HTTPException:
raise
except Exception as e:
logger.error('Failed to toggle node', node_uuid=node_uuid, error=e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to toggle node',
)
async def _get_nodes_overview() -> NodesOverview:
"""Get overview of all nodes."""
try:
service = RemnaWaveService()
nodes = await service.get_all_nodes()
total = len(nodes)
online = sum(1 for n in nodes if n.get('is_connected') and not n.get('is_disabled'))
disabled = sum(1 for n in nodes if n.get('is_disabled'))
offline = total - online - disabled
total_users_online = sum(n.get('users_online', 0) or 0 for n in nodes)
node_statuses = [
NodeStatus(
uuid=n.get('uuid', ''),
name=n.get('name', 'Unknown'),
address=n.get('address', ''),
is_connected=n.get('is_connected', False),
is_disabled=n.get('is_disabled', False),
users_online=n.get('users_online', 0) or 0,
traffic_used_bytes=n.get('traffic_used_bytes'),
last_status_message=n.get('last_status_message'),
xray_uptime=n.get('xray_uptime', 0) or 0,
is_xray_running=n.get('is_xray_running'),
versions=n.get('versions'),
system=n.get('system'),
country_code=n.get('country_code'),
)
for n in nodes
]
return NodesOverview(
total=total,
online=online,
offline=offline,
disabled=disabled,
total_users_online=total_users_online,
nodes=node_statuses,
)
except Exception as e:
logger.warning('Failed to get nodes from RemnaWave', error=e)
# Return empty data if RemnaWave is unavailable
return NodesOverview(
total=0,
online=0,
offline=0,
disabled=0,
total_users_online=0,
nodes=[],
)
async def _get_tariff_stats(db: AsyncSession) -> TariffStats | None:
"""Get statistics for all tariffs."""
try:
# Получаем ВСЕ тарифы (включая неактивные) для статистики
tariffs_result = await db.execute(select(Tariff).order_by(Tariff.display_order))
tariffs = tariffs_result.scalars().all()
if not tariffs:
logger.info('📊 Нет тарифов в системе, пропускаем статистику')
return None
now = datetime.now(UTC)
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
week_ago = now - timedelta(days=7)
month_ago = now - timedelta(days=30)
tariff_items = []
total_tariff_subscriptions = 0
for tariff in tariffs:
# Активные подписки на этом тарифе
active_result = await db.execute(
select(func.count(Subscription.id)).where(
Subscription.tariff_id == tariff.id, Subscription.status == SubscriptionStatus.ACTIVE.value
)
)
active_count = active_result.scalar() or 0
# Триальные подписки на этом тарифе
trial_result = await db.execute(
select(func.count(Subscription.id)).where(
Subscription.tariff_id == tariff.id,
Subscription.status == SubscriptionStatus.ACTIVE.value,
Subscription.is_trial == True,
)
)
trial_count = trial_result.scalar() or 0
# Куплено сегодня (не триальные)
today_result = await db.execute(
select(func.count(Subscription.id)).where(
Subscription.tariff_id == tariff.id,
Subscription.created_at >= today_start,
Subscription.is_trial == False,
)
)
purchased_today = today_result.scalar() or 0
# Куплено за неделю
week_result = await db.execute(
select(func.count(Subscription.id)).where(
Subscription.tariff_id == tariff.id,
Subscription.created_at >= week_ago,
Subscription.is_trial == False,
)
)
purchased_week = week_result.scalar() or 0
# Куплено за месяц
month_result = await db.execute(
select(func.count(Subscription.id)).where(
Subscription.tariff_id == tariff.id,
Subscription.created_at >= month_ago,
Subscription.is_trial == False,
)
)
purchased_month = month_result.scalar() or 0
logger.info(
'📊 Тариф активных=, триал', tariff_name=tariff.name, active_count=active_count, trial_count=trial_count
)
tariff_items.append(
TariffStatItem(
tariff_id=tariff.id,
tariff_name=tariff.name,
active_subscriptions=active_count,
trial_subscriptions=trial_count,
purchased_today=purchased_today,
purchased_week=purchased_week,
purchased_month=purchased_month,
)
)
total_tariff_subscriptions += active_count
logger.info('📊 Всего подписок по тарифам', total_tariff_subscriptions=total_tariff_subscriptions)
return TariffStats(
tariffs=tariff_items,
total_tariff_subscriptions=total_tariff_subscriptions,
)
except Exception as e:
logger.error('Failed to get tariff stats', error=e, exc_info=True)
return None
# ============ Extended Stats Routes ============
@router.get('/referrals/top', response_model=TopReferrersResponse)
async def get_top_referrers(
limit: int = 20,
admin: User = Depends(require_permission('stats:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get top referrers with earnings breakdown by period."""
try:
now = datetime.now(UTC)
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
week_ago = now - timedelta(days=7)
month_ago = now - timedelta(days=30)
# Get all referrers with their stats
referrers_query = await db.execute(
select(User.referred_by_id.label('referrer_id'), func.count(User.id).label('total_invited'))
.where(User.referred_by_id.isnot(None))
.group_by(User.referred_by_id)
)
referrers_data = {row.referrer_id: {'total_invited': row.total_invited} for row in referrers_query}
# Get invited counts by period for each referrer
# Today
today_invited_query = await db.execute(
select(User.referred_by_id.label('referrer_id'), func.count(User.id).label('count'))
.where(and_(User.referred_by_id.isnot(None), User.created_at >= today_start))
.group_by(User.referred_by_id)
)
for row in today_invited_query:
if row.referrer_id in referrers_data:
referrers_data[row.referrer_id]['invited_today'] = row.count
# Week
week_invited_query = await db.execute(
select(User.referred_by_id.label('referrer_id'), func.count(User.id).label('count'))
.where(and_(User.referred_by_id.isnot(None), User.created_at >= week_ago))
.group_by(User.referred_by_id)
)
for row in week_invited_query:
if row.referrer_id in referrers_data:
referrers_data[row.referrer_id]['invited_week'] = row.count
# Month
month_invited_query = await db.execute(
select(User.referred_by_id.label('referrer_id'), func.count(User.id).label('count'))
.where(and_(User.referred_by_id.isnot(None), User.created_at >= month_ago))
.group_by(User.referred_by_id)
)
for row in month_invited_query:
if row.referrer_id in referrers_data:
referrers_data[row.referrer_id]['invited_month'] = row.count
# Get earnings from ReferralEarning table
# Total earnings
total_earnings_query = await db.execute(
select(
ReferralEarning.user_id.label('referrer_id'), func.sum(ReferralEarning.amount_kopeks).label('total')
).group_by(ReferralEarning.user_id)
)
for row in total_earnings_query:
if row.referrer_id in referrers_data:
referrers_data[row.referrer_id]['earnings_total'] = row.total or 0
# Today earnings
today_earnings_query = await db.execute(
select(ReferralEarning.user_id.label('referrer_id'), func.sum(ReferralEarning.amount_kopeks).label('total'))
.where(ReferralEarning.created_at >= today_start)
.group_by(ReferralEarning.user_id)
)
for row in today_earnings_query:
if row.referrer_id in referrers_data:
referrers_data[row.referrer_id]['earnings_today'] = row.total or 0
# Week earnings
week_earnings_query = await db.execute(
select(ReferralEarning.user_id.label('referrer_id'), func.sum(ReferralEarning.amount_kopeks).label('total'))
.where(ReferralEarning.created_at >= week_ago)
.group_by(ReferralEarning.user_id)
)
for row in week_earnings_query:
if row.referrer_id in referrers_data:
referrers_data[row.referrer_id]['earnings_week'] = row.total or 0
# Month earnings
month_earnings_query = await db.execute(
select(ReferralEarning.user_id.label('referrer_id'), func.sum(ReferralEarning.amount_kopeks).label('total'))
.where(ReferralEarning.created_at >= month_ago)
.group_by(ReferralEarning.user_id)
)
for row in month_earnings_query:
if row.referrer_id in referrers_data:
referrers_data[row.referrer_id]['earnings_month'] = row.total or 0
# Get user info for all referrers
referrer_ids = list(referrers_data.keys())
if referrer_ids:
users_query = await db.execute(
select(User.id, User.telegram_id, User.username, User.first_name, User.last_name, User.email).where(
User.id.in_(referrer_ids)
)
)
users_info = {u.id: u for u in users_query}
else:
users_info = {}
# Build referrer items
referrer_items = []
for referrer_id, data in referrers_data.items():
user = users_info.get(referrer_id)
if not user:
continue
display_name = ''
if user.first_name:
display_name = user.first_name
if user.last_name:
display_name += f' {user.last_name}'
elif user.username:
display_name = f'@{user.username}'
elif user.telegram_id:
display_name = f'ID{user.telegram_id}'
elif user.email:
display_name = user.email.split('@')[0]
else:
display_name = f'User#{user.id}'
referrer_items.append(
TopReferrerItem(
user_id=user.id,
telegram_id=user.telegram_id,
email=user.email,
username=user.username,
display_name=display_name,
invited_count=data.get('total_invited', 0),
invited_today=data.get('invited_today', 0),
invited_week=data.get('invited_week', 0),
invited_month=data.get('invited_month', 0),
earnings_today_kopeks=data.get('earnings_today', 0),
earnings_week_kopeks=data.get('earnings_week', 0),
earnings_month_kopeks=data.get('earnings_month', 0),
earnings_total_kopeks=data.get('earnings_total', 0),
)
)
# Sort by earnings and by invited
by_earnings = sorted(referrer_items, key=lambda x: x.earnings_total_kopeks, reverse=True)[:limit]
by_invited = sorted(referrer_items, key=lambda x: x.invited_count, reverse=True)[:limit]
# Calculate totals
total_referrers = len(referrer_items)
total_referrals = sum(r.invited_count for r in referrer_items)
total_earnings = sum(r.earnings_total_kopeks for r in referrer_items)
return TopReferrersResponse(
by_earnings=by_earnings,
by_invited=by_invited,
total_referrers=total_referrers,
total_referrals=total_referrals,
total_earnings_kopeks=total_earnings,
)
except Exception as e:
logger.error('Failed to get top referrers', error=e, exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load referrers statistics',
)
@router.get('/campaigns/top', response_model=TopCampaignsResponse)
async def get_top_campaigns(
limit: int = 20,
admin: User = Depends(require_permission('stats:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get top advertising campaigns with statistics."""
try:
# Get all campaigns
campaigns = await get_campaigns_list(db, offset=0, limit=100, include_inactive=True)
campaign_items = []
total_registrations = 0
total_revenue = 0
for campaign in campaigns:
stats = await get_campaign_statistics(db, campaign.id)
campaign_items.append(
TopCampaignItem(
id=campaign.id,
name=campaign.name,
start_parameter=campaign.start_parameter,
bonus_type=campaign.bonus_type,
is_active=campaign.is_active,
registrations=stats.get('registrations', 0),
conversions=stats.get('conversion_count', 0),
conversion_rate=stats.get('conversion_rate', 0.0),
total_revenue_kopeks=stats.get('total_revenue_kopeks', 0),
avg_revenue_per_user_kopeks=stats.get('avg_revenue_per_user_kopeks', 0),
created_at=campaign.created_at.isoformat() if campaign.created_at else None,
)
)
total_registrations += stats.get('registrations', 0)
total_revenue += stats.get('total_revenue_kopeks', 0)
# Sort by revenue
campaign_items.sort(key=lambda x: x.total_revenue_kopeks, reverse=True)
total_campaigns = await get_campaigns_count(db)
return TopCampaignsResponse(
campaigns=campaign_items[:limit],
total_campaigns=total_campaigns,
total_registrations=total_registrations,
total_revenue_kopeks=total_revenue,
)
except Exception as e:
logger.error('Failed to get top campaigns', error=e, exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load campaigns statistics',
)
@router.get('/payments/recent', response_model=RecentPaymentsResponse)
async def get_recent_payments(
limit: int = 50,
admin: User = Depends(require_permission('stats:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get recent payments with user info."""
try:
now = datetime.now(UTC)
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
week_ago = now - timedelta(days=7)
# Get recent transactions (deposits and subscription payments)
transactions_query = await db.execute(
select(Transaction)
.where(
Transaction.type.in_(
[
TransactionType.DEPOSIT.value,
TransactionType.SUBSCRIPTION_PAYMENT.value,
]
)
)
.order_by(Transaction.created_at.desc())
.limit(limit)
)
transactions = transactions_query.scalars().all()
# Get user info for all transactions
user_ids = list({t.user_id for t in transactions})
if user_ids:
users_query = await db.execute(
select(User.id, User.telegram_id, User.username, User.first_name, User.last_name, User.email).where(
User.id.in_(user_ids)
)
)
users_info = {u.id: u for u in users_query}
else:
users_info = {}
# Type display names
type_display = {
TransactionType.DEPOSIT.value: 'Пополнение',
TransactionType.SUBSCRIPTION_PAYMENT.value: 'Оплата подписки',
TransactionType.WITHDRAWAL.value: 'Вывод',
TransactionType.REFUND.value: 'Возврат',
TransactionType.REFERRAL_REWARD.value: 'Реферальный бонус',
TransactionType.POLL_REWARD.value: 'Награда за опрос',
}
payment_items = []
for trans in transactions:
user = users_info.get(trans.user_id)
if not user:
continue
display_name = ''
if user.first_name:
display_name = user.first_name
if user.last_name:
display_name += f' {user.last_name}'
elif user.username:
display_name = f'@{user.username}'
elif user.telegram_id:
display_name = f'ID{user.telegram_id}'
elif user.email:
display_name = user.email.split('@')[0]
else:
display_name = f'User#{user.id}'
payment_items.append(
RecentPaymentItem(
id=trans.id,
user_id=user.id,
telegram_id=user.telegram_id,
email=user.email,
username=user.username,
display_name=display_name,
amount_kopeks=abs(trans.amount_kopeks),
amount_rubles=abs(trans.amount_kopeks) / 100,
type=trans.type,
type_display=type_display.get(trans.type, trans.type),
payment_method=trans.payment_method,
description=trans.description,
created_at=trans.created_at.isoformat() if trans.created_at else '',
is_completed=trans.is_completed,
)
)
# Calculate totals
total_count_result = await db.execute(
select(func.count(Transaction.id)).where(
Transaction.type.in_(
[
TransactionType.DEPOSIT.value,
TransactionType.SUBSCRIPTION_PAYMENT.value,
]
)
)
)
total_count = total_count_result.scalar() or 0
today_total_result = await db.execute(
select(func.coalesce(func.sum(func.abs(Transaction.amount_kopeks)), 0)).where(
and_(
Transaction.type.in_([TransactionType.DEPOSIT.value, TransactionType.SUBSCRIPTION_PAYMENT.value]),
Transaction.is_completed == True,
Transaction.created_at >= today_start,
Transaction.payment_method.in_(REAL_PAYMENT_METHODS),
)
)
)
total_today = today_total_result.scalar() or 0
week_total_result = await db.execute(
select(func.coalesce(func.sum(func.abs(Transaction.amount_kopeks)), 0)).where(
and_(
Transaction.type.in_([TransactionType.DEPOSIT.value, TransactionType.SUBSCRIPTION_PAYMENT.value]),
Transaction.is_completed == True,
Transaction.created_at >= week_ago,
Transaction.payment_method.in_(REAL_PAYMENT_METHODS),
)
)
)
total_week = week_total_result.scalar() or 0
return RecentPaymentsResponse(
payments=payment_items,
total_count=total_count,
total_today_kopeks=total_today,
total_week_kopeks=total_week,
)
except Exception as e:
logger.error('Failed to get recent payments', error=e, exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load recent payments',
)
+839
View File
@@ -0,0 +1,839 @@
"""Admin routes for managing tariffs in cabinet."""
import asyncio
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import and_, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload
from app.config import settings
from app.database.crud.server_squad import get_all_server_squads
from app.database.crud.tariff import (
create_tariff,
delete_tariff,
get_all_tariffs,
get_tariff_by_id,
get_tariff_subscriptions_count,
load_period_prices_from_db,
reorder_tariffs,
set_tariff_promo_groups,
update_tariff,
)
from app.database.models import PromoGroup, Subscription, SubscriptionStatus, Tariff, Transaction, TransactionType, User
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.tariffs import (
ExternalSquadInfoResponse,
PeriodPrice,
PromoGroupInfo,
ServerInfo,
ServerTrafficLimit,
SyncSquadsResponse,
TariffCreateRequest,
TariffDetailResponse,
TariffListItem,
TariffListResponse,
TariffSortOrderRequest,
TariffStatsResponse,
TariffToggleResponse,
TariffTrialResponse,
TariffUpdateRequest,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/tariffs', tags=['Cabinet Admin Tariffs'])
async def _get_tariff_servers(
db: AsyncSession, allowed_squads: list[str], server_traffic_limits: dict = None
) -> list[ServerInfo]:
"""Get server info for tariff."""
servers, _ = await get_all_server_squads(db, available_only=False)
limits = server_traffic_limits or {}
result = []
for server in servers:
# Получаем индивидуальный лимит трафика для сервера
server_limit = None
if server.squad_uuid in limits:
limit_data = limits[server.squad_uuid]
if isinstance(limit_data, dict) and 'traffic_limit_gb' in limit_data:
server_limit = limit_data['traffic_limit_gb']
elif isinstance(limit_data, int):
server_limit = limit_data
result.append(
ServerInfo(
id=server.id,
squad_uuid=server.squad_uuid,
display_name=server.display_name,
country_code=server.country_code,
is_selected=server.squad_uuid in allowed_squads,
traffic_limit_gb=server_limit,
)
)
return result
async def _get_tariff_promo_groups(db: AsyncSession, tariff: Tariff) -> list[PromoGroupInfo]:
"""Get promo group info for tariff."""
result = await db.execute(select(PromoGroup).order_by(PromoGroup.name))
all_groups = result.scalars().all()
selected_ids = {pg.id for pg in tariff.allowed_promo_groups} if tariff.allowed_promo_groups else set()
return [
PromoGroupInfo(
id=pg.id,
name=pg.name,
is_selected=pg.id in selected_ids,
)
for pg in all_groups
]
def _period_prices_to_list(period_prices: dict) -> list[PeriodPrice]:
"""Convert period_prices dict to list."""
if not period_prices:
return []
return [
PeriodPrice(days=int(days), price_kopeks=price)
for days, price in sorted(period_prices.items(), key=lambda x: int(x[0]))
]
def _period_prices_to_dict(period_prices: list[PeriodPrice]) -> dict:
"""Convert period_prices list to dict."""
return {str(pp.days): pp.price_kopeks for pp in period_prices}
@router.get('', response_model=TariffListResponse)
async def list_tariffs(
include_inactive: bool = True,
admin: User = Depends(require_permission('tariffs:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of all tariffs."""
tariffs = await get_all_tariffs(db, include_inactive=include_inactive)
items = []
for tariff in tariffs:
subs_count = await get_tariff_subscriptions_count(db, tariff.id)
items.append(
TariffListItem(
id=tariff.id,
name=tariff.name,
description=tariff.description,
is_active=tariff.is_active,
is_trial_available=tariff.is_trial_available,
is_daily=tariff.is_daily,
daily_price_kopeks=tariff.daily_price_kopeks,
allow_traffic_topup=tariff.allow_traffic_topup,
show_in_gift=tariff.show_in_gift,
traffic_limit_gb=tariff.traffic_limit_gb,
device_limit=tariff.device_limit,
tier_level=tariff.tier_level,
display_order=tariff.display_order,
servers_count=len(tariff.allowed_squads or []),
subscriptions_count=subs_count,
created_at=tariff.created_at,
)
)
return TariffListResponse(tariffs=items, total=len(items))
@router.get('/available-servers', response_model=list[ServerInfo])
async def get_available_servers(
admin: User = Depends(require_permission('tariffs:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of all servers for tariff selection."""
servers, _ = await get_all_server_squads(db, available_only=False)
return [
ServerInfo(
id=server.id,
squad_uuid=server.squad_uuid,
display_name=server.display_name,
country_code=server.country_code,
is_selected=False,
)
for server in servers
]
@router.get('/available-external-squads', response_model=list[ExternalSquadInfoResponse])
async def get_available_external_squads(
admin: User = Depends(require_permission('tariffs:read')),
):
"""Fetch external squads from RemnaWave panel."""
from app.services.remnawave_service import RemnaWaveService
try:
service = RemnaWaveService()
async with service.get_api_client() as api:
squads = await api.get_external_squads()
return [
{
'uuid': s.uuid,
'name': s.name,
'members_count': s.members_count,
}
for s in squads
]
except Exception:
logger.warning('Failed to fetch external squads from RemnaWave', exc_info=True)
return []
@router.put('/order')
async def update_tariff_order(
request: TariffSortOrderRequest,
admin: User = Depends(require_permission('tariffs:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update the display order of tariffs."""
await reorder_tariffs(db, request.tariff_ids)
await db.commit()
logger.info('Admin updated tariff order', admin_id=admin.id, tariff_ids=request.tariff_ids)
return {'message': 'Tariff order updated successfully'}
@router.get('/{tariff_id}', response_model=TariffDetailResponse)
async def get_tariff(
tariff_id: int,
admin: User = Depends(require_permission('tariffs:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get detailed tariff info."""
tariff = await get_tariff_by_id(db, tariff_id)
if not tariff:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Tariff not found',
)
allowed_squads = tariff.allowed_squads or []
server_traffic_limits = tariff.server_traffic_limits or {}
servers = await _get_tariff_servers(db, allowed_squads, server_traffic_limits)
promo_groups = await _get_tariff_promo_groups(db, tariff)
subs_count = await get_tariff_subscriptions_count(db, tariff.id)
# Преобразуем server_traffic_limits в формат для схемы
server_limits_response = {}
for uuid, limit_data in server_traffic_limits.items():
if isinstance(limit_data, dict):
server_limits_response[uuid] = ServerTrafficLimit(**limit_data)
elif isinstance(limit_data, int):
server_limits_response[uuid] = ServerTrafficLimit(traffic_limit_gb=limit_data)
return TariffDetailResponse(
id=tariff.id,
name=tariff.name,
description=tariff.description,
is_active=tariff.is_active,
is_trial_available=tariff.is_trial_available,
allow_traffic_topup=tariff.allow_traffic_topup,
traffic_topup_enabled=tariff.traffic_topup_enabled,
traffic_topup_packages=tariff.traffic_topup_packages or {},
max_topup_traffic_gb=tariff.max_topup_traffic_gb,
traffic_limit_gb=tariff.traffic_limit_gb,
device_limit=tariff.device_limit,
device_price_kopeks=tariff.device_price_kopeks,
max_device_limit=tariff.max_device_limit,
tier_level=tariff.tier_level,
display_order=tariff.display_order,
period_prices=_period_prices_to_list(tariff.period_prices),
allowed_squads=allowed_squads,
server_traffic_limits=server_limits_response,
servers=servers,
promo_groups=promo_groups,
subscriptions_count=subs_count,
# Произвольное количество дней
custom_days_enabled=tariff.custom_days_enabled,
price_per_day_kopeks=tariff.price_per_day_kopeks,
min_days=tariff.min_days,
max_days=tariff.max_days,
# Произвольный трафик при покупке
custom_traffic_enabled=tariff.custom_traffic_enabled,
traffic_price_per_gb_kopeks=tariff.traffic_price_per_gb_kopeks,
min_traffic_gb=tariff.min_traffic_gb,
max_traffic_gb=tariff.max_traffic_gb,
# Дневной тариф
is_daily=tariff.is_daily,
daily_price_kopeks=tariff.daily_price_kopeks,
# Режим сброса трафика
traffic_reset_mode=tariff.traffic_reset_mode,
# Внешний сквад
external_squad_uuid=tariff.external_squad_uuid,
# Показывать в подарках
show_in_gift=tariff.show_in_gift,
created_at=tariff.created_at,
updated_at=tariff.updated_at,
)
@router.post('', response_model=TariffDetailResponse)
async def create_new_tariff(
request: TariffCreateRequest,
admin: User = Depends(require_permission('tariffs:create')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Create a new tariff."""
period_prices_dict = _period_prices_to_dict(request.period_prices)
# Преобразуем ServerTrafficLimit в dict для хранения
server_limits_dict = (
{uuid: limit.model_dump() for uuid, limit in request.server_traffic_limits.items()}
if request.server_traffic_limits
else {}
)
tariff = await create_tariff(
db=db,
name=request.name,
description=request.description,
is_active=request.is_active,
allow_traffic_topup=request.allow_traffic_topup,
traffic_topup_enabled=request.traffic_topup_enabled,
traffic_topup_packages=request.traffic_topup_packages,
max_topup_traffic_gb=request.max_topup_traffic_gb,
traffic_limit_gb=request.traffic_limit_gb,
device_limit=request.device_limit,
device_price_kopeks=request.device_price_kopeks,
max_device_limit=request.max_device_limit,
tier_level=request.tier_level,
period_prices=period_prices_dict,
allowed_squads=request.allowed_squads,
server_traffic_limits=server_limits_dict,
promo_group_ids=request.promo_group_ids or None,
# Произвольное количество дней
custom_days_enabled=request.custom_days_enabled,
price_per_day_kopeks=request.price_per_day_kopeks,
min_days=request.min_days,
max_days=request.max_days,
# Произвольный трафик при покупке
custom_traffic_enabled=request.custom_traffic_enabled,
traffic_price_per_gb_kopeks=request.traffic_price_per_gb_kopeks,
min_traffic_gb=request.min_traffic_gb,
max_traffic_gb=request.max_traffic_gb,
# Дневной тариф
is_daily=request.is_daily,
daily_price_kopeks=request.daily_price_kopeks,
# Режим сброса трафика
traffic_reset_mode=request.traffic_reset_mode,
# Внешний сквад
external_squad_uuid=request.external_squad_uuid,
# Показывать в подарках
show_in_gift=request.show_in_gift,
)
logger.info('Admin created tariff', admin_id=admin.id, tariff_id=tariff.id, tariff_name=tariff.name)
# Перезагружаем периоды из БД для синхронизации с ботом
await load_period_prices_from_db(db)
# Return full detail
return await get_tariff(tariff.id, admin, db)
@router.put('/{tariff_id}', response_model=TariffDetailResponse)
async def update_existing_tariff(
tariff_id: int,
request: TariffUpdateRequest,
admin: User = Depends(require_permission('tariffs:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update an existing tariff."""
tariff = await get_tariff_by_id(db, tariff_id)
if not tariff:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Tariff not found',
)
# Capture old values for change detection
old_squads = list(tariff.allowed_squads) if tariff.allowed_squads else []
old_external_squad = tariff.external_squad_uuid
# Build updates dict
updates = {}
if request.name is not None:
updates['name'] = request.name
if request.description is not None:
updates['description'] = request.description
if request.is_active is not None:
updates['is_active'] = request.is_active
if request.allow_traffic_topup is not None:
updates['allow_traffic_topup'] = request.allow_traffic_topup
if request.traffic_topup_enabled is not None:
updates['traffic_topup_enabled'] = request.traffic_topup_enabled
if request.traffic_topup_packages is not None:
updates['traffic_topup_packages'] = request.traffic_topup_packages
if request.max_topup_traffic_gb is not None:
updates['max_topup_traffic_gb'] = request.max_topup_traffic_gb
if request.traffic_limit_gb is not None:
updates['traffic_limit_gb'] = request.traffic_limit_gb
if request.device_limit is not None:
updates['device_limit'] = request.device_limit
if request.device_price_kopeks is not None:
updates['device_price_kopeks'] = request.device_price_kopeks
if request.max_device_limit is not None:
updates['max_device_limit'] = request.max_device_limit
if request.tier_level is not None:
updates['tier_level'] = request.tier_level
if request.display_order is not None:
updates['display_order'] = request.display_order
if request.period_prices is not None:
updates['period_prices'] = _period_prices_to_dict(request.period_prices)
if request.allowed_squads is not None:
updates['allowed_squads'] = request.allowed_squads
if request.server_traffic_limits is not None:
# Преобразуем ServerTrafficLimit в dict для хранения
updates['server_traffic_limits'] = {
uuid: limit.model_dump() for uuid, limit in request.server_traffic_limits.items()
}
# Произвольное количество дней
if request.custom_days_enabled is not None:
updates['custom_days_enabled'] = request.custom_days_enabled
if request.price_per_day_kopeks is not None:
updates['price_per_day_kopeks'] = request.price_per_day_kopeks
if request.min_days is not None:
updates['min_days'] = request.min_days
if request.max_days is not None:
updates['max_days'] = request.max_days
# Произвольный трафик при покупке
if request.custom_traffic_enabled is not None:
updates['custom_traffic_enabled'] = request.custom_traffic_enabled
if request.traffic_price_per_gb_kopeks is not None:
updates['traffic_price_per_gb_kopeks'] = request.traffic_price_per_gb_kopeks
if request.min_traffic_gb is not None:
updates['min_traffic_gb'] = request.min_traffic_gb
if request.max_traffic_gb is not None:
updates['max_traffic_gb'] = request.max_traffic_gb
# Дневной тариф
if request.is_daily is not None:
updates['is_daily'] = request.is_daily
if request.daily_price_kopeks is not None:
updates['daily_price_kopeks'] = request.daily_price_kopeks
# Режим сброса трафика (None допускается как значение для сброса к глобальной настройке)
if 'traffic_reset_mode' in request.model_fields_set:
updates['traffic_reset_mode'] = request.traffic_reset_mode
# Внешний сквад (None допускается для сброса)
if 'external_squad_uuid' in request.model_fields_set:
updates['external_squad_uuid'] = request.external_squad_uuid
# Показывать в подарках
if request.show_in_gift is not None:
updates['show_in_gift'] = request.show_in_gift
if updates:
await update_tariff(db, tariff, **updates)
# Update promo groups separately
if request.promo_group_ids is not None:
await set_tariff_promo_groups(db, tariff, request.promo_group_ids)
logger.info('Admin updated tariff', admin_id=admin.id, tariff_id=tariff_id)
# Перезагружаем периоды из БД для синхронизации с ботом
await load_period_prices_from_db(db)
# Auto-sync squads to active subscriptions in Remnawave when squads changed
new_squads = tariff.allowed_squads or []
squads_changed = request.allowed_squads is not None and sorted(old_squads) != sorted(new_squads)
ext_squad_changed = (
'external_squad_uuid' in request.model_fields_set and tariff.external_squad_uuid != old_external_squad
)
if squads_changed or ext_squad_changed:
asyncio.create_task(
_background_sync_squads(tariff_id, admin.id),
name=f'sync-squads-tariff-{tariff_id}',
)
return await get_tariff(tariff_id, admin, db)
@router.delete('/{tariff_id}')
async def delete_existing_tariff(
tariff_id: int,
admin: User = Depends(require_permission('tariffs:delete')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Delete a tariff."""
tariff = await get_tariff_by_id(db, tariff_id)
if not tariff:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Tariff not found',
)
subs_count = await get_tariff_subscriptions_count(db, tariff_id)
await delete_tariff(db, tariff)
logger.info(
'Admin deleted tariff (affected subscriptions: )',
admin_id=admin.id,
tariff_id=tariff_id,
tariff_name=tariff.name,
subs_count=subs_count,
)
# Перезагружаем периоды из БД для синхронизации с ботом
await load_period_prices_from_db(db)
return {'message': 'Tariff deleted successfully', 'affected_subscriptions': subs_count}
@router.post('/{tariff_id}/toggle', response_model=TariffToggleResponse)
async def toggle_tariff(
tariff_id: int,
admin: User = Depends(require_permission('tariffs:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Toggle tariff active status."""
tariff = await get_tariff_by_id(db, tariff_id)
if not tariff:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Tariff not found',
)
new_status = not tariff.is_active
await update_tariff(db, tariff, is_active=new_status)
status_text = 'activated' if new_status else 'deactivated'
logger.info('Admin tariff', admin_id=admin.id, status_text=status_text, tariff_id=tariff_id)
# Перезагружаем периоды из БД для синхронизации с ботом
await load_period_prices_from_db(db)
return TariffToggleResponse(
id=tariff_id,
is_active=new_status,
message=f'Tariff {status_text}',
)
@router.post('/{tariff_id}/trial', response_model=TariffTrialResponse)
async def toggle_trial_tariff(
tariff_id: int,
admin: User = Depends(require_permission('tariffs:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Toggle tariff trial availability.
When enabling trial on a tariff, removes trial flag from all other tariffs
(only one tariff can be the trial tariff at a time).
"""
tariff = await get_tariff_by_id(db, tariff_id)
if not tariff:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Tariff not found',
)
new_status = not tariff.is_trial_available
if new_status:
# При включении триала - снимаем флаг со ВСЕХ тарифов, затем ставим на текущий
# Это гарантирует, что триальным будет только один тариф
await db.execute(Tariff.__table__.update().values(is_trial_available=False))
await db.commit()
# Обновляем объект тарифа после массового обновления
await db.refresh(tariff)
await update_tariff(db, tariff, is_trial_available=new_status)
status_text = 'set as trial' if new_status else 'removed from trial'
logger.info('Admin tariff', admin_id=admin.id, status_text=status_text, tariff_id=tariff_id)
return TariffTrialResponse(
id=tariff_id,
is_trial_available=new_status,
message=f'Tariff {status_text}',
)
@router.get('/{tariff_id}/stats', response_model=TariffStatsResponse)
async def get_tariff_stats(
tariff_id: int,
admin: User = Depends(require_permission('tariffs:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get tariff statistics."""
tariff = await get_tariff_by_id(db, tariff_id)
if not tariff:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Tariff not found',
)
# Count subscriptions
total_result = await db.execute(select(func.count(Subscription.id)).where(Subscription.tariff_id == tariff_id))
total_count = total_result.scalar() or 0
# Count active subscriptions
active_result = await db.execute(
select(func.count(Subscription.id)).where(
Subscription.tariff_id == tariff_id,
Subscription.status == 'active',
)
)
active_count = active_result.scalar() or 0
# Count trial subscriptions
trial_result = await db.execute(
select(func.count(Subscription.id)).where(
Subscription.tariff_id == tariff_id,
Subscription.is_trial == True,
)
)
trial_count = trial_result.scalar() or 0
# Calculate revenue from subscription payments for users on this tariff
revenue_result = await db.execute(
select(func.coalesce(func.sum(func.abs(Transaction.amount_kopeks)), 0))
.join(Subscription, Transaction.user_id == Subscription.user_id)
.where(
Subscription.tariff_id == tariff_id,
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
Transaction.is_completed == True,
)
)
revenue_kopeks = revenue_result.scalar() or 0
return TariffStatsResponse(
id=tariff_id,
name=tariff.name,
subscriptions_count=total_count,
active_subscriptions=active_count,
trial_subscriptions=trial_count,
revenue_kopeks=revenue_kopeks,
revenue_rubles=revenue_kopeks / 100,
)
async def _background_sync_squads(tariff_id: int, admin_id: int) -> None:
"""Run squad sync in background with its own DB session (fire-and-forget)."""
from app.database.database import AsyncSessionLocal
from app.services.remnawave_service import RemnaWaveService
try:
async with AsyncSessionLocal() as db:
tariff = await get_tariff_by_id(db, tariff_id)
if not tariff:
return
result = await db.execute(
select(Subscription)
.join(User, Subscription.user_id == User.id)
.options(joinedload(Subscription.user))
.where(
and_(
Subscription.tariff_id == tariff_id,
Subscription.status.in_([SubscriptionStatus.ACTIVE.value, SubscriptionStatus.TRIAL.value]),
User.remnawave_uuid.isnot(None),
)
)
)
subscriptions = list(result.unique().scalars().all())
if not subscriptions:
return
new_squads = tariff.allowed_squads or []
ext_squad_uuid = tariff.external_squad_uuid
service = RemnaWaveService()
updated = 0
failed = 0
async with service.get_api_client() as api:
semaphore = asyncio.Semaphore(5)
async def _sync_one(sub: Subscription) -> None:
nonlocal updated, failed
remnawave_uuid = (
getattr(sub, 'remnawave_uuid', None)
if settings.is_multi_tariff_enabled()
else (sub.user.remnawave_uuid if sub.user else None)
)
if not remnawave_uuid:
return
async with semaphore:
try:
await api.update_user(
uuid=remnawave_uuid,
active_internal_squads=new_squads,
external_squad_uuid=ext_squad_uuid,
)
sub.connected_squads = new_squads
updated += 1
except Exception as e:
failed += 1
logger.warning(
'Background sync: failed to sync squads for user',
user_id=sub.user_id,
error=str(e),
)
await asyncio.gather(*[_sync_one(sub) for sub in subscriptions])
await db.commit()
logger.info(
'Background squad sync completed after tariff update',
admin_id=admin_id,
tariff_id=tariff_id,
tariff_name=tariff.name,
total=len(subscriptions),
updated=updated,
failed=failed,
)
except Exception:
logger.exception('Background squad sync failed', tariff_id=tariff_id)
_SYNC_SQUADS_CONCURRENCY = 5
_SYNC_SQUADS_MAX_CONSECUTIVE_FAILURES = 10
@router.post('/{tariff_id}/sync-squads', response_model=SyncSquadsResponse)
async def sync_tariff_squads(
tariff_id: int,
admin: User = Depends(require_permission('tariffs:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Sync squads from tariff to all active/trial subscriptions in Remnawave panel.
Updates connected_squads and external_squad_uuid for every active or trial
subscription linked to this tariff. Only users that have a remnawave_uuid
(i.e. already exist in the panel) are touched.
"""
tariff = await get_tariff_by_id(db, tariff_id)
if not tariff:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Tariff not found',
)
# Fetch active + trial subscriptions for this tariff whose users exist in Remnawave
result = await db.execute(
select(Subscription)
.join(User, Subscription.user_id == User.id)
.options(joinedload(Subscription.user))
.where(
and_(
Subscription.tariff_id == tariff_id,
Subscription.status.in_([SubscriptionStatus.ACTIVE.value, SubscriptionStatus.TRIAL.value]),
User.remnawave_uuid.isnot(None),
)
)
)
subscriptions = list(result.unique().scalars().all())
if not subscriptions:
return SyncSquadsResponse(
tariff_id=tariff_id,
tariff_name=tariff.name,
total_subscriptions=0,
updated_count=0,
failed_count=0,
skipped_count=0,
)
new_squads = tariff.allowed_squads or []
# None means "clear external squad" — intentional when tariff has none
ext_squad_uuid = tariff.external_squad_uuid
# Sync to Remnawave panel with concurrency limit and circuit breaker
from app.services.remnawave_service import RemnaWaveService
service = RemnaWaveService()
updated_count = 0
failed_count = 0
skipped_count = 0
consecutive_failures = 0
errors: list[str] = []
aborted = False
async with service.get_api_client() as api:
semaphore = asyncio.Semaphore(_SYNC_SQUADS_CONCURRENCY)
async def _sync_one(sub: Subscription) -> str:
# Counter mutations are safe: no `await` between read-modify-write
# and the check within each branch (single-threaded asyncio event loop).
nonlocal updated_count, failed_count, skipped_count, consecutive_failures, aborted
if aborted:
skipped_count += 1
return 'skipped'
remnawave_uuid = (
getattr(sub, 'remnawave_uuid', None)
if settings.is_multi_tariff_enabled()
else (sub.user.remnawave_uuid if sub.user else None)
)
if not remnawave_uuid:
skipped_count += 1
return 'skipped'
async with semaphore:
if aborted:
skipped_count += 1
return 'skipped'
try:
await api.update_user(
uuid=remnawave_uuid,
active_internal_squads=new_squads,
external_squad_uuid=ext_squad_uuid,
)
# Update local DB only on successful API call
sub.connected_squads = new_squads
updated_count += 1
consecutive_failures = 0
return 'ok'
except Exception as e:
failed_count += 1
consecutive_failures += 1
errors.append(f'user_id={sub.user_id}: sync failed')
logger.warning(
'Failed to sync squads for user in Remnawave',
user_id=sub.user_id,
remnawave_uuid=remnawave_uuid,
error=str(e),
)
if consecutive_failures >= _SYNC_SQUADS_MAX_CONSECUTIVE_FAILURES:
aborted = True
errors.append(f'Aborted after {_SYNC_SQUADS_MAX_CONSECUTIVE_FAILURES} consecutive failures')
return 'error'
await asyncio.gather(*[_sync_one(sub) for sub in subscriptions])
# Commit local DB changes only for successfully synced subscriptions
await db.commit()
logger.info(
'Admin synced squads for tariff',
admin_id=admin.id,
tariff_id=tariff_id,
tariff_name=tariff.name,
total=len(subscriptions),
updated=updated_count,
failed=failed_count,
skipped=skipped_count,
)
return SyncSquadsResponse(
tariff_id=tariff_id,
tariff_name=tariff.name,
total_subscriptions=len(subscriptions),
updated_count=updated_count,
failed_count=failed_count,
skipped_count=skipped_count,
errors=errors[:20],
)
+642
View File
@@ -0,0 +1,642 @@
"""Admin tickets routes for cabinet."""
import math
from datetime import UTC, datetime
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field, model_validator
from sqlalchemy import desc, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.cabinet.routes.websocket import notify_user_ticket_reply
from app.config import settings
from app.database.crud.ticket import TicketCRUD
from app.database.crud.ticket_notification import TicketNotificationCRUD
from app.database.models import Ticket, TicketMessage, User
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.tickets import TicketMediaItem, TicketMessageResponse, _validate_media_bundle
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/tickets', tags=['Cabinet Admin Tickets'])
# Admin-specific schemas
class AdminTicketUserInfo(BaseModel):
"""User info for admin view."""
id: int
telegram_id: int | None = None # Can be None for email-only users
email: str | None = None
username: str | None = None
first_name: str | None = None
last_name: str | None = None
class Config:
from_attributes = True
class AdminTicketResponse(BaseModel):
"""Ticket data for admin."""
id: int
title: str
status: str
priority: str
created_at: datetime
updated_at: datetime
closed_at: datetime | None = None
messages_count: int = 0
user: AdminTicketUserInfo | None = None
last_message: TicketMessageResponse | None = None
class Config:
from_attributes = True
class AdminTicketDetailResponse(BaseModel):
"""Ticket with all messages for admin."""
id: int
title: str
status: str
priority: str
created_at: datetime
updated_at: datetime
closed_at: datetime | None = None
is_reply_blocked: bool = False
user: AdminTicketUserInfo | None = None
messages: list[TicketMessageResponse] = []
class Config:
from_attributes = True
class AdminTicketListResponse(BaseModel):
"""Paginated ticket list for admin."""
items: list[AdminTicketResponse]
total: int
page: int
per_page: int
pages: int
class AdminReplyRequest(BaseModel):
"""Admin reply to ticket."""
message: str = Field(default='', max_length=4000, description='Reply message')
media_type: str | None = Field(None, description='Media type: photo, video, or document')
media_file_id: str | None = Field(None, max_length=255, description='Telegram file_id from media upload')
media_caption: str | None = Field(None, max_length=1000, description='Caption for media')
media_items: list[TicketMediaItem] | None = Field(None, description='Multi-media gallery attachments')
@model_validator(mode='after')
def validate_media_fields(self) -> 'AdminReplyRequest':
_validate_media_bundle(self.media_type, self.media_file_id, self.media_items)
has_text = bool(self.message.strip())
has_media = bool(self.media_file_id) or bool(self.media_items)
if not has_text and not has_media:
raise ValueError('message or media is required')
return self
class AdminStatusUpdateRequest(BaseModel):
"""Update ticket status."""
status: str = Field(..., description='New status: open, answered, pending, closed')
class AdminPriorityUpdateRequest(BaseModel):
"""Update ticket priority."""
priority: str = Field(..., description='New priority: low, normal, high, urgent')
class AdminStatsResponse(BaseModel):
"""Ticket statistics for admin."""
total: int
open: int
pending: int
answered: int
closed: int
class TicketSettingsResponse(BaseModel):
"""Ticket system settings."""
sla_enabled: bool
sla_minutes: int
sla_check_interval_seconds: int
sla_reminder_cooldown_minutes: int
support_system_mode: str # tickets, contact, both
# Cabinet notifications settings
cabinet_user_notifications_enabled: bool = True
cabinet_admin_notifications_enabled: bool = True
class TicketSettingsUpdateRequest(BaseModel):
"""Update ticket settings."""
sla_enabled: bool | None = None
sla_minutes: int | None = Field(None, ge=1, le=1440, description='SLA time in minutes (1-1440)')
sla_check_interval_seconds: int | None = Field(None, ge=30, le=600, description='Check interval (30-600 seconds)')
sla_reminder_cooldown_minutes: int | None = Field(
None, ge=1, le=120, description='Reminder cooldown (1-120 minutes)'
)
support_system_mode: str | None = Field(None, description='Support mode: tickets, contact, both')
# Cabinet notifications settings
cabinet_user_notifications_enabled: bool | None = Field(None, description='Enable user notifications in cabinet')
cabinet_admin_notifications_enabled: bool | None = Field(None, description='Enable admin notifications in cabinet')
def _message_to_response(message: TicketMessage) -> TicketMessageResponse:
"""Convert TicketMessage to response."""
raw_items = getattr(message, 'media_items', None) or None
items = None
if raw_items:
try:
items = [TicketMediaItem(**it) for it in raw_items]
except (TypeError, KeyError, ValueError) as exc:
logger.warning('Failed to parse media_items', message_id=message.id, error=str(exc))
items = None
return TicketMessageResponse(
id=message.id,
message_text=message.message_text or '',
is_from_admin=message.is_from_admin,
has_media=bool(message.media_file_id) or bool(items),
media_type=message.media_type,
media_file_id=message.media_file_id,
media_caption=message.media_caption,
media_items=items,
created_at=message.created_at,
)
def _user_to_info(user: User) -> AdminTicketUserInfo:
"""Convert User to admin info."""
return AdminTicketUserInfo(
id=user.id,
telegram_id=user.telegram_id,
email=user.email,
username=user.username,
first_name=user.first_name,
last_name=user.last_name,
)
def _ticket_to_admin_response(ticket: Ticket, include_messages: bool = False) -> AdminTicketResponse:
"""Convert Ticket to admin response."""
last_message = None
messages_count = len(ticket.messages) if ticket.messages else 0
if ticket.messages:
last_msg = max(ticket.messages, key=lambda m: m.created_at)
last_message = _message_to_response(last_msg)
user_info = None
if hasattr(ticket, 'user') and ticket.user:
user_info = _user_to_info(ticket.user)
return AdminTicketResponse(
id=ticket.id,
title=ticket.title or f'Ticket #{ticket.id}',
status=ticket.status,
priority=ticket.priority or 'normal',
created_at=ticket.created_at,
updated_at=ticket.updated_at or ticket.created_at,
closed_at=ticket.closed_at,
messages_count=messages_count,
user=user_info,
last_message=last_message,
)
@router.get('/stats', response_model=AdminStatsResponse)
async def get_ticket_stats(
admin: User = Depends(require_permission('tickets:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get ticket statistics."""
# Total count
total_result = await db.execute(select(func.count()).select_from(Ticket))
total = total_result.scalar() or 0
# Count by status
statuses = {}
for status_name in ['open', 'pending', 'answered', 'closed']:
result = await db.execute(select(func.count()).select_from(Ticket).where(Ticket.status == status_name))
statuses[status_name] = result.scalar() or 0
return AdminStatsResponse(
total=total,
open=statuses.get('open', 0),
pending=statuses.get('pending', 0),
answered=statuses.get('answered', 0),
closed=statuses.get('closed', 0),
)
@router.get('/settings', response_model=TicketSettingsResponse)
async def get_ticket_settings(
admin: User = Depends(require_permission('tickets:settings')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get ticket system settings."""
from app.services.support_settings_service import SupportSettingsService
return TicketSettingsResponse(
sla_enabled=settings.SUPPORT_TICKET_SLA_ENABLED,
sla_minutes=settings.SUPPORT_TICKET_SLA_MINUTES,
sla_check_interval_seconds=settings.SUPPORT_TICKET_SLA_CHECK_INTERVAL_SECONDS,
sla_reminder_cooldown_minutes=settings.SUPPORT_TICKET_SLA_REMINDER_COOLDOWN_MINUTES,
support_system_mode=settings.get_support_system_mode(),
cabinet_user_notifications_enabled=SupportSettingsService.get_cabinet_user_notifications_enabled(),
cabinet_admin_notifications_enabled=SupportSettingsService.get_cabinet_admin_notifications_enabled(),
)
@router.patch('/settings', response_model=TicketSettingsResponse)
async def update_ticket_settings(
request: TicketSettingsUpdateRequest,
admin: User = Depends(require_permission('tickets:settings')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update ticket system settings."""
import asyncio
from pathlib import Path
from app.services.support_settings_service import SupportSettingsService
# Validate support_system_mode
if request.support_system_mode is not None:
mode = request.support_system_mode.strip().lower()
if mode not in {'tickets', 'contact', 'both'}:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid support_system_mode. Must be: tickets, contact, or both',
)
# Update in-memory settings
if request.sla_enabled is not None:
settings.SUPPORT_TICKET_SLA_ENABLED = request.sla_enabled
if request.sla_minutes is not None:
settings.SUPPORT_TICKET_SLA_MINUTES = request.sla_minutes
if request.sla_check_interval_seconds is not None:
settings.SUPPORT_TICKET_SLA_CHECK_INTERVAL_SECONDS = request.sla_check_interval_seconds
if request.sla_reminder_cooldown_minutes is not None:
settings.SUPPORT_TICKET_SLA_REMINDER_COOLDOWN_MINUTES = request.sla_reminder_cooldown_minutes
if request.support_system_mode is not None:
SupportSettingsService.set_system_mode(request.support_system_mode.strip().lower())
# Update cabinet notification settings
if request.cabinet_user_notifications_enabled is not None:
SupportSettingsService.set_cabinet_user_notifications_enabled(request.cabinet_user_notifications_enabled)
if request.cabinet_admin_notifications_enabled is not None:
SupportSettingsService.set_cabinet_admin_notifications_enabled(request.cabinet_admin_notifications_enabled)
# Try to persist to .env file
try:
env_file = Path('.env')
if await asyncio.to_thread(env_file.exists):
lines = (await asyncio.to_thread(env_file.read_text)).splitlines()
updates = {}
if request.sla_enabled is not None:
updates['SUPPORT_TICKET_SLA_ENABLED'] = str(request.sla_enabled).lower()
if request.sla_minutes is not None:
updates['SUPPORT_TICKET_SLA_MINUTES'] = str(request.sla_minutes)
if request.sla_check_interval_seconds is not None:
updates['SUPPORT_TICKET_SLA_CHECK_INTERVAL_SECONDS'] = str(request.sla_check_interval_seconds)
if request.sla_reminder_cooldown_minutes is not None:
updates['SUPPORT_TICKET_SLA_REMINDER_COOLDOWN_MINUTES'] = str(request.sla_reminder_cooldown_minutes)
if request.support_system_mode is not None:
updates['SUPPORT_SYSTEM_MODE'] = request.support_system_mode.strip().lower()
new_lines = []
updated_keys = set()
for line in lines:
updated = False
for key, value in updates.items():
if line.startswith(f'{key}='):
new_lines.append(f'{key}={value}')
updated_keys.add(key)
updated = True
break
if not updated:
new_lines.append(line)
# Add any keys that weren't found
for key, value in updates.items():
if key not in updated_keys:
new_lines.append(f'{key}={value}')
await asyncio.to_thread(env_file.write_text, '\n'.join(new_lines) + '\n')
logger.info('Updated ticket settings in .env file')
except Exception as e:
logger.warning('Failed to update .env file', error=e)
return TicketSettingsResponse(
sla_enabled=settings.SUPPORT_TICKET_SLA_ENABLED,
sla_minutes=settings.SUPPORT_TICKET_SLA_MINUTES,
sla_check_interval_seconds=settings.SUPPORT_TICKET_SLA_CHECK_INTERVAL_SECONDS,
sla_reminder_cooldown_minutes=settings.SUPPORT_TICKET_SLA_REMINDER_COOLDOWN_MINUTES,
support_system_mode=settings.get_support_system_mode(),
cabinet_user_notifications_enabled=SupportSettingsService.get_cabinet_user_notifications_enabled(),
cabinet_admin_notifications_enabled=SupportSettingsService.get_cabinet_admin_notifications_enabled(),
)
@router.get('', response_model=AdminTicketListResponse)
async def get_all_tickets(
page: int = Query(1, ge=1, description='Page number'),
per_page: int = Query(20, ge=1, le=100, description='Items per page'),
status_filter: str | None = Query(None, alias='status', description='Filter by status'),
priority_filter: str | None = Query(None, alias='priority', description='Filter by priority'),
user_id: int | None = Query(None, description='Filter by user ID'),
admin: User = Depends(require_permission('tickets:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get all tickets for admin."""
# Base query with user relationship
query = select(Ticket).options(selectinload(Ticket.messages), selectinload(Ticket.user))
# Build count query
count_query = select(func.count()).select_from(Ticket)
# Apply filters
if status_filter:
query = query.where(Ticket.status == status_filter)
count_query = count_query.where(Ticket.status == status_filter)
if priority_filter:
query = query.where(Ticket.priority == priority_filter)
count_query = count_query.where(Ticket.priority == priority_filter)
if user_id:
query = query.where(Ticket.user_id == user_id)
count_query = count_query.where(Ticket.user_id == user_id)
# Get total count
total_result = await db.execute(count_query)
total = total_result.scalar() or 0
# Paginate - order by updated_at desc (newest first)
offset = (page - 1) * per_page
query = query.order_by(desc(Ticket.updated_at)).offset(offset).limit(per_page)
result = await db.execute(query)
tickets = result.scalars().all()
items = [_ticket_to_admin_response(t) for t in tickets]
pages = math.ceil(total / per_page) if total > 0 else 1
return AdminTicketListResponse(
items=items,
total=total,
page=page,
per_page=per_page,
pages=pages,
)
@router.get('/{ticket_id}', response_model=AdminTicketDetailResponse)
async def get_ticket_detail(
ticket_id: int,
admin: User = Depends(require_permission('tickets:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get ticket with all messages for admin."""
query = (
select(Ticket).where(Ticket.id == ticket_id).options(selectinload(Ticket.messages), selectinload(Ticket.user))
)
result = await db.execute(query)
ticket = result.scalar_one_or_none()
if not ticket:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Ticket not found',
)
messages = sorted(ticket.messages or [], key=lambda m: m.created_at)
messages_response = [_message_to_response(m) for m in messages]
user_info = None
if ticket.user:
user_info = _user_to_info(ticket.user)
return AdminTicketDetailResponse(
id=ticket.id,
title=ticket.title or f'Ticket #{ticket.id}',
status=ticket.status,
priority=ticket.priority or 'normal',
created_at=ticket.created_at,
updated_at=ticket.updated_at or ticket.created_at,
closed_at=ticket.closed_at,
is_reply_blocked=ticket.is_reply_blocked if hasattr(ticket, 'is_reply_blocked') else False,
user=user_info,
messages=messages_response,
)
@router.post('/{ticket_id}/reply', response_model=TicketMessageResponse)
async def reply_to_ticket(
ticket_id: int,
request: AdminReplyRequest,
admin: User = Depends(require_permission('tickets:reply')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Reply to a ticket as admin."""
# Get ticket
ticket = await TicketCRUD.get_ticket_by_id(db, ticket_id, load_messages=False, load_user=True)
if not ticket:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Ticket not found',
)
# Resolve media payload: prefer media_items, fall back to legacy single-media fields
items_payload = None
primary_type = request.media_type
primary_file_id = request.media_file_id
primary_caption = request.media_caption
if request.media_items:
items_payload = [it.model_dump() for it in request.media_items]
first = request.media_items[0]
primary_type = first.type
primary_file_id = first.file_id
primary_caption = primary_caption or first.caption
has_media = bool(primary_file_id)
message = TicketMessage(
ticket_id=ticket.id,
user_id=ticket.user_id,
message_text=request.message,
is_from_admin=True,
has_media=has_media,
media_type=primary_type if has_media else None,
media_file_id=primary_file_id if has_media else None,
media_caption=primary_caption if has_media else None,
media_items=items_payload,
created_at=datetime.now(UTC),
)
db.add(message)
# Update ticket status to answered
ticket.status = 'answered'
ticket.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(message)
# Try to notify user via Telegram
try:
from app.bot_factory import create_bot
bot = create_bot()
try:
from app.handlers.admin.tickets import notify_user_about_ticket_reply
await notify_user_about_ticket_reply(bot, ticket, request.message, db)
except Exception as e:
logger.warning('Failed to notify user about ticket reply', error=e)
finally:
await bot.session.close()
except Exception as e:
logger.warning('Failed to send Telegram notification', error=e)
# Уведомить пользователя в кабинете
try:
notification = await TicketNotificationCRUD.create_user_notification_for_admin_reply(
db, ticket, request.message
)
if notification:
# Отправить WebSocket уведомление
await notify_user_ticket_reply(ticket.user_id, ticket.id, (request.message or '')[:100])
except Exception as e:
logger.warning('Failed to create cabinet notification for admin reply', error=e)
return _message_to_response(message)
@router.post('/{ticket_id}/status', response_model=AdminTicketDetailResponse)
async def update_ticket_status(
ticket_id: int,
request: AdminStatusUpdateRequest,
admin: User = Depends(require_permission('tickets:close')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update ticket status."""
allowed_statuses = {'open', 'pending', 'answered', 'closed'}
if request.status not in allowed_statuses:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid status. Allowed: {", ".join(allowed_statuses)}',
)
query = (
select(Ticket).where(Ticket.id == ticket_id).options(selectinload(Ticket.messages), selectinload(Ticket.user))
)
result = await db.execute(query)
ticket = result.scalar_one_or_none()
if not ticket:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Ticket not found',
)
ticket.status = request.status
ticket.updated_at = datetime.now(UTC)
if request.status == 'closed':
ticket.closed_at = datetime.now(UTC)
else:
ticket.closed_at = None
await db.commit()
await db.refresh(ticket)
messages = sorted(ticket.messages or [], key=lambda m: m.created_at)
messages_response = [_message_to_response(m) for m in messages]
user_info = None
if ticket.user:
user_info = _user_to_info(ticket.user)
return AdminTicketDetailResponse(
id=ticket.id,
title=ticket.title or f'Ticket #{ticket.id}',
status=ticket.status,
priority=ticket.priority or 'normal',
created_at=ticket.created_at,
updated_at=ticket.updated_at or ticket.created_at,
closed_at=ticket.closed_at,
is_reply_blocked=ticket.is_reply_blocked if hasattr(ticket, 'is_reply_blocked') else False,
user=user_info,
messages=messages_response,
)
@router.post('/{ticket_id}/priority', response_model=AdminTicketDetailResponse)
async def update_ticket_priority(
ticket_id: int,
request: AdminPriorityUpdateRequest,
admin: User = Depends(require_permission('tickets:close')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update ticket priority."""
allowed_priorities = {'low', 'normal', 'high', 'urgent'}
if request.priority not in allowed_priorities:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid priority. Allowed: {", ".join(allowed_priorities)}',
)
query = (
select(Ticket).where(Ticket.id == ticket_id).options(selectinload(Ticket.messages), selectinload(Ticket.user))
)
result = await db.execute(query)
ticket = result.scalar_one_or_none()
if not ticket:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Ticket not found',
)
ticket.priority = request.priority
ticket.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(ticket)
messages = sorted(ticket.messages or [], key=lambda m: m.created_at)
messages_response = [_message_to_response(m) for m in messages]
user_info = None
if ticket.user:
user_info = _user_to_info(ticket.user)
return AdminTicketDetailResponse(
id=ticket.id,
title=ticket.title or f'Ticket #{ticket.id}',
status=ticket.status,
priority=ticket.priority or 'normal',
created_at=ticket.created_at,
updated_at=ticket.updated_at or ticket.created_at,
closed_at=ticket.closed_at,
is_reply_blocked=ticket.is_reply_blocked if hasattr(ticket, 'is_reply_blocked') else False,
user=user_info,
messages=messages_response,
)
+761
View File
@@ -0,0 +1,761 @@
"""Admin routes for traffic usage statistics."""
import asyncio
import csv
import io
import time
from datetime import UTC, datetime, timedelta
import structlog
from aiogram.types import BufferedInputFile
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import and_, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.bot_factory import create_bot
from app.database.models import Subscription, Transaction, TransactionType, User
from app.services.remnawave_service import RemnaWaveService
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.traffic import (
ExportCsvRequest,
ExportCsvResponse,
SubscriptionEnrichmentInfo,
SubscriptionTrafficInfo,
TrafficEnrichmentResponse,
TrafficNodeInfo,
TrafficUsageResponse,
UserTrafficEnrichment,
UserTrafficItem,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/traffic', tags=['Admin Traffic'])
_ALLOWED_PERIODS = frozenset({1, 3, 7, 14, 30})
_CONCURRENCY_LIMIT = 5 # Max parallel API calls to avoid rate limiting
# In-memory cache: {(start_str, end_str): (timestamp, aggregated_data, nodes_info)}
_traffic_cache: dict[tuple[str, str], tuple[float, dict[str, dict[str, int]], list[TrafficNodeInfo]]] = {}
_CACHE_TTL = 300 # 5 minutes
_cache_lock = asyncio.Lock()
# Valid sort fields for the GET endpoint
_SORT_FIELDS = frozenset({'total_bytes', 'full_name', 'tariff_name', 'device_limit', 'traffic_limit_gb'})
_ENRICHMENT_SORT_FIELDS = frozenset({'connected', 'total_spent', 'sub_start', 'sub_end', 'last_node'})
def _get_status(sub) -> str | None:
"""Get subscription status via actual_status property."""
return sub.actual_status
def _validate_period(period: int) -> None:
if period not in _ALLOWED_PERIODS:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Period must be one of: {sorted(_ALLOWED_PERIODS)}',
)
async def _aggregate_traffic(
start_str: str, end_str: str, user_uuids: list[str]
) -> tuple[dict[str, dict[str, int]], list[TrafficNodeInfo]]:
"""Aggregate per-user traffic across all nodes for a given date range.
Uses legacy per-node endpoint to fetch all users' traffic per node —
O(nodes) API calls instead of O(users). The legacy endpoint returns
{userUuid, nodeUuid, total} per entry (non-legacy only returns topUsers
without userUuid).
Returns (user_traffic, nodes_info) where:
user_traffic = {remnawave_uuid: {node_uuid: total_bytes, ...}}
nodes_info = [TrafficNodeInfo, ...]
"""
cache_key = (start_str, end_str)
# Quick check without lock
now = time.time()
cached = _traffic_cache.get(cache_key)
if cached and (now - cached[0]) < _CACHE_TTL:
return cached[1], cached[2]
# Acquire lock for the slow path
async with _cache_lock:
# Re-check after acquiring lock
now = time.time()
cached = _traffic_cache.get(cache_key)
if cached and (now - cached[0]) < _CACHE_TTL:
return cached[1], cached[2]
service = RemnaWaveService()
if not service.is_configured:
return {}, []
user_uuids_set = set(user_uuids)
async with service.get_api_client() as api:
try:
nodes = await api.get_all_nodes()
except Exception:
logger.warning('Failed to fetch nodes for traffic aggregation', exc_info=True)
# Cache empty result to avoid hammering the failing API
_traffic_cache[cache_key] = (now, {}, [])
return {}, []
# Fetch per-node user stats — O(nodes) calls instead of O(users)
semaphore = asyncio.Semaphore(_CONCURRENCY_LIMIT)
async def fetch_node_users(node):
async with semaphore:
try:
stats = await api.get_bandwidth_stats_node_users_legacy(node.uuid, start_str, end_str)
return node.uuid, stats
except Exception:
logger.warning('Failed to get traffic for node', node_name=node.name, exc_info=True)
return node.uuid, None
results = await asyncio.gather(*(fetch_node_users(n) for n in nodes))
nodes_info: list[TrafficNodeInfo] = [
TrafficNodeInfo(node_uuid=node.uuid, node_name=node.name, country_code=node.country_code) for node in nodes
]
nodes_info.sort(key=lambda n: n.node_name)
# Legacy response: [{userUuid, username, nodeUuid, total, date}, ...]
user_traffic: dict[str, dict[str, int]] = {}
for node_uuid, entries in results:
if not isinstance(entries, list):
continue
for entry in entries:
uid = entry.get('userUuid', '')
total = int(entry.get('total', 0))
if uid and total > 0 and uid in user_uuids_set:
user_traffic.setdefault(uid, {})[node_uuid] = user_traffic.get(uid, {}).get(node_uuid, 0) + total
_traffic_cache[cache_key] = (now, user_traffic, nodes_info)
# Evict expired entries to prevent unbounded growth
expired = [k for k, (ts, _, _) in _traffic_cache.items() if (now - ts) >= _CACHE_TTL]
for k in expired:
del _traffic_cache[k]
return user_traffic, nodes_info
def _compute_date_range(period_days: int) -> tuple[str, str]:
"""Compute ISO date-time range from period days.
Truncates to 5-minute intervals for stable cache keys.
"""
end_dt = datetime.now(UTC).replace(second=0, microsecond=0)
end_dt = end_dt.replace(minute=(end_dt.minute // 5) * 5)
start_dt = end_dt - timedelta(days=period_days)
return start_dt.strftime('%Y-%m-%dT%H:%M:%SZ'), end_dt.strftime('%Y-%m-%dT%H:%M:%SZ')
async def _load_user_map(db: AsyncSession) -> dict[str, User]:
"""Load all users with remnawave_uuid, eagerly loading subscription + tariff.
In multi-tariff mode UUIDs live on Subscription rows, not on User.
Both sources are merged so the caller gets a complete uuid User map.
"""
from app.config import settings
# Build user map from both user-level and subscription-level UUIDs
user_map: dict[str, User] = {}
# Legacy: user-level UUIDs
stmt_users = (
select(User)
.where(User.remnawave_uuid.isnot(None))
.options(selectinload(User.subscriptions).selectinload(Subscription.tariff))
)
result_users = await db.execute(stmt_users)
users = result_users.scalars().all()
for u in users:
if u.remnawave_uuid:
user_map[u.remnawave_uuid] = u
# Multi-tariff: subscription-level UUIDs
if settings.is_multi_tariff_enabled():
stmt_subs = (
select(Subscription)
.where(Subscription.remnawave_uuid.isnot(None))
.options(selectinload(Subscription.user).selectinload(User.subscriptions).selectinload(Subscription.tariff))
)
result_subs = await db.execute(stmt_subs)
subs = result_subs.scalars().all()
for sub in subs:
if sub.remnawave_uuid and sub.user and sub.remnawave_uuid not in user_map:
user_map[sub.remnawave_uuid] = sub.user
return user_map
def _build_traffic_items(
user_traffic: dict[str, dict[str, int]],
user_map: dict[str, User],
nodes_info: list[TrafficNodeInfo],
search: str = '',
sort_by: str = 'total_bytes',
sort_desc: bool = True,
tariff_filter: set[str] | None = None,
status_filter: set[str] | None = None,
node_filter: set[str] | None = None,
) -> list[UserTrafficItem]:
"""Merge traffic data with user data, apply search/tariff/status/node filters, return sorted list."""
items: list[UserTrafficItem] = []
search_lower = search.lower().strip()
all_uuids = set(user_traffic.keys()) | set(user_map.keys())
for uuid in all_uuids:
user = user_map.get(uuid)
if not user:
continue
traffic = user_traffic.get(uuid, {})
full_name = user.full_name
username = user.username
email = user.email
if search_lower:
if (
search_lower not in (full_name or '').lower()
and search_lower not in (username or '').lower()
and search_lower not in (email or '').lower()
):
continue
subs = getattr(user, 'subscriptions', None) or []
# Primary subscription for backward-compat top-level fields
primary_sub = next((s for s in subs if s.is_active), subs[0] if subs else None)
tariff_name = None
subscription_status = None
traffic_limit_gb = 0.0
device_limit = 1
if primary_sub:
subscription_status = _get_status(primary_sub)
traffic_limit_gb = float(primary_sub.traffic_limit_gb or 0)
device_limit = primary_sub.device_limit or 1
if primary_sub.tariff:
tariff_name = primary_sub.tariff.name
# Filtering uses primary sub values (keeps existing filter semantics)
if tariff_filter is not None:
if (tariff_name or '') not in tariff_filter:
continue
if status_filter is not None:
if (subscription_status or '') not in status_filter:
continue
# Apply node filter: keep only selected nodes, recalculate total
if node_filter is not None:
traffic = {k: v for k, v in traffic.items() if k in node_filter}
total_bytes = sum(traffic.values())
# Build per-subscription detail list for multi-subscription display
subscriptions_traffic = [
SubscriptionTrafficInfo(
subscription_id=sub.id,
tariff_name=sub.tariff.name if sub.tariff else None,
status=_get_status(sub),
traffic_limit_gb=float(sub.traffic_limit_gb or 0),
device_limit=sub.device_limit or 1,
)
for sub in subs
]
items.append(
UserTrafficItem(
user_id=user.id,
telegram_id=user.telegram_id,
username=username,
email=email,
full_name=full_name,
tariff_name=tariff_name,
subscription_status=subscription_status,
traffic_limit_gb=traffic_limit_gb,
device_limit=device_limit,
node_traffic=traffic,
total_bytes=total_bytes,
subscriptions=subscriptions_traffic,
)
)
# Sort by the requested field; node columns use 'node_<uuid>' prefix
if sort_by.startswith('node_'):
node_uuid = sort_by[5:]
items.sort(key=lambda x: x.node_traffic.get(node_uuid, 0), reverse=sort_desc)
elif sort_by in ('full_name', 'tariff_name'):
items.sort(key=lambda x: (getattr(x, sort_by, None) or '').lower(), reverse=sort_desc)
else:
items.sort(key=lambda x: getattr(x, sort_by, 0) or 0, reverse=sort_desc)
return items
@router.get('', response_model=TrafficUsageResponse)
async def get_traffic_usage(
admin: User = Depends(require_permission('traffic:read')),
db: AsyncSession = Depends(get_cabinet_db),
period: int = Query(30, ge=1, le=30),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
search: str = Query('', max_length=100),
sort_by: str = Query('total_bytes', max_length=100),
sort_desc: bool = Query(True),
tariffs: str = Query('', max_length=500),
statuses: str = Query('', max_length=500),
nodes: str = Query('', max_length=2000),
start_date: str = Query('', max_length=10),
end_date: str = Query('', max_length=10),
):
"""Get paginated per-user traffic usage by node."""
# Determine date range: custom dates or period-based
if start_date.strip() and end_date.strip():
try:
start_dt = datetime.strptime(start_date.strip(), '%Y-%m-%d').replace(tzinfo=UTC)
end_dt = datetime.strptime(end_date.strip(), '%Y-%m-%d').replace(tzinfo=UTC, hour=23, minute=59, second=59)
except ValueError:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Invalid date format. Use YYYY-MM-DD.')
now = datetime.now(UTC)
end_dt = min(end_dt, now)
if start_dt > end_dt:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='start_date must be before end_date.')
if (end_dt - start_dt).days > 31:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Date range cannot exceed 31 days.')
start_str = start_dt.strftime('%Y-%m-%dT%H:%M:%SZ')
end_str = end_dt.strftime('%Y-%m-%dT%H:%M:%SZ')
effective_period = (end_dt - start_dt).days or 1
else:
_validate_period(period)
start_str, end_str = _compute_date_range(period)
effective_period = period
user_map = await _load_user_map(db)
user_traffic, nodes_info = await _aggregate_traffic(start_str, end_str, list(user_map.keys()))
# Collect all available tariff names (before filtering)
available_tariffs = sorted(
{
sub.tariff.name
for u in user_map.values()
for sub in (getattr(u, 'subscriptions', None) or [])
if sub.tariff and sub.tariff.name
}
)
# Collect all available statuses (before filtering)
available_statuses = sorted(
{
_get_status(sub)
for u in user_map.values()
for sub in (getattr(u, 'subscriptions', None) or [])
if _get_status(sub)
}
)
# Parse tariff filter
tariff_filter: set[str] | None = None
if tariffs.strip():
tariff_filter = {t.strip() for t in tariffs.split(',') if t.strip()}
# Parse status filter
status_filter: set[str] | None = None
if statuses.strip():
status_filter = {s.strip() for s in statuses.split(',') if s.strip()}
# Parse node filter
node_filter: set[str] | None = None
all_node_uuids = {n.node_uuid for n in nodes_info}
if nodes.strip():
node_filter = {n.strip() for n in nodes.split(',') if n.strip()} & all_node_uuids
if not node_filter:
node_filter = None # No valid nodes matched, treat as "all nodes"
# Validate sort_by: allow known fields + enrichment fields + 'node_<uuid>'
is_node_sort = sort_by.startswith('node_') and sort_by[5:] in all_node_uuids
is_enrichment_sort = sort_by in _ENRICHMENT_SORT_FIELDS
if sort_by not in _SORT_FIELDS and not is_node_sort and not is_enrichment_sort:
sort_by = 'total_bytes'
# For enrichment sort, build items unsorted then sort by enrichment field
effective_sort = 'total_bytes' if is_enrichment_sort else sort_by
items = _build_traffic_items(
user_traffic, user_map, nodes_info, search, effective_sort, sort_desc, tariff_filter, status_filter, node_filter
)
if is_enrichment_sort:
enrichment_data = await _build_enrichment(db, user_map)
enr_key_map = {
'connected': lambda e: e.devices_connected,
'total_spent': lambda e: e.total_spent_kopeks,
'sub_start': lambda e: e.subscription_start_date or '',
'sub_end': lambda e: e.subscription_end_date or '',
'last_node': lambda e: e.last_node_name or '',
}
key_fn = enr_key_map[sort_by]
empty = UserTrafficEnrichment()
items.sort(key=lambda x: key_fn(enrichment_data.get(x.user_id, empty)), reverse=sort_desc)
total = len(items)
paginated = items[offset : offset + limit]
return TrafficUsageResponse(
items=paginated,
nodes=nodes_info,
total=total,
offset=offset,
limit=limit,
period_days=effective_period,
available_tariffs=available_tariffs,
available_statuses=available_statuses,
)
# ============== Enrichment endpoint ==============
_enrichment_cache: dict[str, tuple[float, dict[int, UserTrafficEnrichment]]] = {}
_ENRICHMENT_CACHE_TTL = 300 # 5 minutes
_enrichment_lock = asyncio.Lock()
async def _get_bulk_spending(db: AsyncSession, user_ids: list[int]) -> dict[int, int]:
"""Get total spent kopeks for multiple users in a single query."""
if not user_ids:
return {}
result = await db.execute(
select(Transaction.user_id, func.coalesce(func.sum(func.abs(Transaction.amount_kopeks)), 0))
.where(
and_(
Transaction.user_id.in_(user_ids),
Transaction.is_completed.is_(True),
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
)
)
.group_by(Transaction.user_id)
)
return {row[0]: int(row[1]) for row in result.all()}
async def _build_enrichment(db: AsyncSession, user_map: dict[str, User]) -> dict[int, UserTrafficEnrichment]:
"""Build enrichment data for all users: devices, spending, dates, last node."""
uuid_to_user_id: dict[str, int] = {}
for uuid, user in user_map.items():
uuid_to_user_id[uuid] = user.id
service = RemnaWaveService()
devices_by_user: dict[int, int] = {}
last_node_uuid_by_user: dict[int, str] = {}
node_uuid_to_name: dict[str, str] = {}
if service.is_configured:
async with service.get_api_client() as api:
# 3 bulk calls: nodes + users (paginated) + devices
try:
nodes_list = await api.get_all_nodes()
except Exception:
logger.warning('Failed to fetch nodes for enrichment', exc_info=True)
nodes_list = []
for node in nodes_list:
node_uuid_to_name[node.uuid] = node.name
# Fetch all panel users (paginated) for last connected node
panel_users = []
try:
first_page = await api.get_all_users(start=0, size=500)
panel_users.extend(first_page['users'])
total_panel = first_page['total']
if total_panel > 500:
remaining_tasks = [
api.get_all_users(start=offset, size=500) for offset in range(500, total_panel, 500)
]
pages = await asyncio.gather(*remaining_tasks, return_exceptions=True)
for page in pages:
if isinstance(page, dict):
panel_users.extend(page['users'])
except Exception:
logger.warning('Failed to fetch panel users for enrichment', exc_info=True)
for pu in panel_users:
uid = uuid_to_user_id.get(pu.uuid)
if uid is None:
continue
if pu.user_traffic and pu.user_traffic.last_connected_node_uuid:
last_node_uuid_by_user[uid] = pu.user_traffic.last_connected_node_uuid
# Bulk device fetch — single API call (paginated with start/size)
try:
devices_data = await api.get_all_hwid_devices()
for device in devices_data.get('devices', []):
user_uuid = device.get('userUuid', '')
uid = uuid_to_user_id.get(user_uuid)
if uid is not None:
devices_by_user[uid] = devices_by_user.get(uid, 0) + 1
except Exception:
logger.warning('Failed to fetch bulk devices for enrichment', exc_info=True)
# Bulk spending stats
all_user_ids = [u.id for u in user_map.values()]
spending_map = await _get_bulk_spending(db, all_user_ids)
# Build enrichment data
enrichment: dict[int, UserTrafficEnrichment] = {}
for uuid, user in user_map.items():
uid = user.id
subs_list = getattr(user, 'subscriptions', None) or []
# Primary subscription for backward-compat top-level date fields
primary_sub = next((s for s in subs_list if s.is_active), subs_list[0] if subs_list else None)
start_date = None
end_date = None
if primary_sub:
if primary_sub.start_date:
start_date = primary_sub.start_date.isoformat()
if primary_sub.end_date:
end_date = primary_sub.end_date.isoformat()
last_node_name = None
last_uuid = last_node_uuid_by_user.get(uid)
if last_uuid:
last_node_name = node_uuid_to_name.get(last_uuid)
# Build per-subscription enrichment list for multi-subscription display
subscriptions_enrichment = [
SubscriptionEnrichmentInfo(
subscription_id=sub.id,
tariff_name=sub.tariff.name if sub.tariff else None,
start_date=sub.start_date.isoformat() if sub.start_date else None,
end_date=sub.end_date.isoformat() if sub.end_date else None,
)
for sub in subs_list
]
enrichment[uid] = UserTrafficEnrichment(
devices_connected=devices_by_user.get(uid, 0),
total_spent_kopeks=spending_map.get(uid, 0),
subscription_start_date=start_date,
subscription_end_date=end_date,
last_node_name=last_node_name,
subscriptions=subscriptions_enrichment,
)
return enrichment
@router.get('/enrichment', response_model=TrafficEnrichmentResponse)
async def get_traffic_enrichment(
admin: User = Depends(require_permission('traffic:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Return enrichment data: device counts, spending, dates, last node."""
cache_key = 'enrichment'
now = time.time()
cached = _enrichment_cache.get(cache_key)
if cached and (now - cached[0]) < _ENRICHMENT_CACHE_TTL:
return TrafficEnrichmentResponse(data=cached[1])
async with _enrichment_lock:
now = time.time()
cached = _enrichment_cache.get(cache_key)
if cached and (now - cached[0]) < _ENRICHMENT_CACHE_TTL:
return TrafficEnrichmentResponse(data=cached[1])
user_map = await _load_user_map(db)
enrichment = await _build_enrichment(db, user_map)
_enrichment_cache[cache_key] = (now, enrichment)
# Evict expired
expired = [k for k, (ts, _) in _enrichment_cache.items() if (now - ts) >= _ENRICHMENT_CACHE_TTL]
for k in expired:
del _enrichment_cache[k]
return TrafficEnrichmentResponse(data=enrichment)
@router.post('/export-csv', response_model=ExportCsvResponse)
async def export_traffic_csv(
request: ExportCsvRequest,
admin: User = Depends(require_permission('traffic:export')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Generate CSV with traffic usage and send to admin's Telegram DM."""
if not admin.telegram_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Admin has no Telegram ID configured',
)
# Determine date range: custom dates or period-based
if request.start_date and request.end_date:
try:
start_dt = datetime.strptime(request.start_date.strip(), '%Y-%m-%d').replace(tzinfo=UTC)
end_dt = datetime.strptime(request.end_date.strip(), '%Y-%m-%d').replace(
tzinfo=UTC, hour=23, minute=59, second=59
)
except ValueError:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Invalid date format. Use YYYY-MM-DD.')
now = datetime.now(UTC)
end_dt = min(end_dt, now)
if start_dt > end_dt:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='start_date must be before end_date.')
if (end_dt - start_dt).days > 31:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Date range cannot exceed 31 days.')
start_str = start_dt.strftime('%Y-%m-%dT%H:%M:%SZ')
end_str = end_dt.strftime('%Y-%m-%dT%H:%M:%SZ')
period_label = f'{request.start_date}_{request.end_date}'
else:
_validate_period(request.period)
start_str, end_str = _compute_date_range(request.period)
period_label = f'{request.period}d'
user_map = await _load_user_map(db)
user_traffic, nodes_info = await _aggregate_traffic(start_str, end_str, list(user_map.keys()))
enrichment = await _build_enrichment(db, user_map)
# Parse filters
tariff_filter: set[str] | None = None
if request.tariffs and request.tariffs.strip():
tariff_filter = {t.strip() for t in request.tariffs.split(',') if t.strip()}
status_filter: set[str] | None = None
if request.statuses and request.statuses.strip():
status_filter = {s.strip() for s in request.statuses.split(',') if s.strip()}
node_filter: set[str] | None = None
all_node_uuids = {n.node_uuid for n in nodes_info}
if request.nodes and request.nodes.strip():
node_filter = {n.strip() for n in request.nodes.split(',') if n.strip()} & all_node_uuids
if not node_filter:
node_filter = None
items = _build_traffic_items(
user_traffic,
user_map,
nodes_info,
sort_by='total_bytes',
sort_desc=True,
tariff_filter=tariff_filter,
status_filter=status_filter,
node_filter=node_filter,
)
# Determine which nodes to include in CSV columns
csv_nodes = [n for n in nodes_info if n.node_uuid in node_filter] if node_filter else nodes_info
# Compute period days for risk calculation
if request.start_date and request.end_date:
period_days = max((end_dt - start_dt).days, 1)
else:
period_days = request.period
total_thr = request.total_threshold_gb or 0
node_thr = request.node_threshold_gb or 0
has_risk = total_thr > 0 or node_thr > 0
# Build CSV rows
rows: list[dict] = []
for item in items:
row: dict = {
'User ID': item.user_id,
'Telegram ID': item.telegram_id or '',
'Username': item.username or '',
'Email': item.email or '',
'Full Name': item.full_name,
'Tariff': item.tariff_name or '',
'Status': item.subscription_status or '',
'Traffic Limit (GB)': item.traffic_limit_gb,
'Device Limit': item.device_limit,
}
# Enrichment columns
enr = enrichment.get(item.user_id)
row['Connected Devices'] = enr.devices_connected if enr else 0
row['Total Spent (RUB)'] = round(enr.total_spent_kopeks / 100, 2) if enr else 0
row['Sub Start'] = enr.subscription_start_date or '' if enr else ''
row['Sub End'] = enr.subscription_end_date or '' if enr else ''
row['Last Node'] = enr.last_node_name or '' if enr else ''
for node in csv_nodes:
row[f'{node.node_name} (bytes)'] = item.node_traffic.get(node.node_uuid, 0)
row['Total (bytes)'] = item.total_bytes
row['Total (GB)'] = round(item.total_bytes / (1024**3), 2) if item.total_bytes else 0
if has_risk:
daily_total = item.total_bytes / period_days / (1024**3) if period_days > 0 else 0
row['Total GB/day'] = round(daily_total, 4)
total_ratio = daily_total / total_thr if total_thr > 0 else 0
max_node_ratio = 0.0
worst_node_daily = 0.0
for node_bytes in item.node_traffic.values():
if node_bytes > 0 and node_thr > 0:
daily_node = node_bytes / period_days / (1024**3) if period_days > 0 else 0
ratio = daily_node / node_thr
if ratio > max_node_ratio:
max_node_ratio = ratio
worst_node_daily = daily_node
ratio = max(total_ratio, max_node_ratio)
if ratio < 0.5:
risk_level = 'low'
elif ratio < 0.8:
risk_level = 'medium'
elif ratio < 1.2:
risk_level = 'high'
else:
risk_level = 'critical'
row['Risk Level'] = risk_level
row['Risk Ratio'] = round(ratio, 3)
row['Risk GB/day'] = round(daily_total if total_ratio >= max_node_ratio else worst_node_daily, 4)
rows.append(row)
# Generate CSV
output = io.StringIO()
if rows:
writer = csv.DictWriter(output, fieldnames=rows[0].keys())
writer.writeheader()
writer.writerows(rows)
csv_bytes = output.getvalue().encode('utf-8-sig')
timestamp = datetime.now(UTC).strftime('%Y%m%d_%H%M%S')
filename = f'traffic_usage_{period_label}_{timestamp}.csv'
try:
bot = create_bot()
async with bot:
await bot.send_document(
chat_id=admin.telegram_id,
document=BufferedInputFile(csv_bytes, filename=filename),
caption=f'Traffic usage report ({period_label})\nUsers: {len(rows)}',
)
except Exception:
logger.error('Failed to send CSV to admin', telegram_id=admin.telegram_id, exc_info=True)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to send CSV report. Please try again later.',
)
return ExportCsvResponse(success=True, message=f'CSV sent ({len(rows)} users)')
+139
View File
@@ -0,0 +1,139 @@
"""Admin routes for version and release information."""
from datetime import UTC, datetime, timedelta
import aiohttp
import structlog
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from app.database.models import User
from app.services.version_service import version_service
from ..dependencies import require_permission
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/updates', tags=['Cabinet Admin Updates'])
# ============ Schemas ============
class ReleaseItem(BaseModel):
tag_name: str
name: str
body: str
published_at: str
prerelease: bool
class ProjectReleasesInfo(BaseModel):
current_version: str
has_updates: bool
releases: list[ReleaseItem]
repo_url: str
class ReleasesResponse(BaseModel):
bot: ProjectReleasesInfo
cabinet: ProjectReleasesInfo
# ============ Cabinet releases cache ============
CABINET_REPO = 'BEDOLAGA-DEV/bedolaga-cabinet'
_cabinet_cache: dict = {}
_cabinet_last_check: datetime | None = None
_CACHE_TTL = 3600
async def _fetch_cabinet_releases(force: bool = False) -> list[dict]:
global _cabinet_last_check
if not force and _cabinet_cache.get('releases') and _cabinet_last_check:
if datetime.now(UTC) - _cabinet_last_check < timedelta(seconds=_CACHE_TTL):
return _cabinet_cache['releases']
url = f'https://api.github.com/repos/{CABINET_REPO}/releases'
try:
timeout = aiohttp.ClientTimeout(total=10)
async with aiohttp.ClientSession(timeout=timeout) as session, session.get(url) as response:
if response.status == 200:
data = await response.json()
releases = []
for item in data[:20]:
releases.append(
{
'tag_name': item['tag_name'],
'name': item.get('name') or item['tag_name'],
'body': item.get('body') or '',
'published_at': item['published_at'],
'prerelease': item.get('prerelease', False),
}
)
_cabinet_cache['releases'] = releases
_cabinet_last_check = datetime.now(UTC)
logger.info('Fetched cabinet releases from GitHub', releases_count=len(releases))
return releases
logger.warning('GitHub API returned status for cabinet releases', response_status=response.status)
return _cabinet_cache.get('releases', [])
except TimeoutError:
logger.warning('Timeout fetching cabinet releases from GitHub')
return _cabinet_cache.get('releases', [])
except Exception as e:
logger.error('Error fetching cabinet releases', e=e)
return _cabinet_cache.get('releases', [])
# ============ Routes ============
@router.get('/releases', response_model=ReleasesResponse)
async def get_releases(
current_user: User = Depends(require_permission('updates:read')),
) -> ReleasesResponse:
"""Get release information for bot and cabinet."""
# Bot releases
bot_releases_raw = await version_service._fetch_releases()
has_updates, _ = await version_service.check_for_updates()
bot_releases = [
ReleaseItem(
tag_name=r.tag_name,
name=r.name,
body=r.full_description,
published_at=r.published_at.isoformat(),
prerelease=r.prerelease,
)
for r in bot_releases_raw[:10]
]
bot_info = ProjectReleasesInfo(
current_version=version_service.current_version,
has_updates=has_updates,
releases=bot_releases,
repo_url=f'https://github.com/{version_service.repo}',
)
# Cabinet releases
cabinet_releases_raw = await _fetch_cabinet_releases()
cabinet_releases = [ReleaseItem(**r) for r in cabinet_releases_raw[:10]]
# Current version = latest non-prerelease tag
cabinet_current = ''
for r in cabinet_releases_raw:
if not r.get('prerelease', False):
cabinet_current = r['tag_name']
break
cabinet_info = ProjectReleasesInfo(
current_version=cabinet_current,
has_updates=False,
releases=cabinet_releases,
repo_url=f'https://github.com/{CABINET_REPO}',
)
return ReleasesResponse(bot=bot_info, cabinet=cabinet_info)
File diff suppressed because it is too large Load Diff
+387
View File
@@ -0,0 +1,387 @@
"""
API роуты колеса удачи для администраторов.
"""
import math
from datetime import datetime
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.cabinet.dependencies import get_cabinet_db, require_permission
from app.cabinet.schemas.wheel import (
AdminSpinItem,
AdminSpinsResponse,
AdminWheelConfigResponse,
CreatePrizeRequest,
ReorderPrizesRequest,
UpdatePrizeRequest,
UpdateWheelConfigRequest,
WheelPrizeAdminResponse,
WheelStatisticsResponse,
)
from app.database.crud.wheel import (
create_wheel_prize,
delete_wheel_prize,
get_all_spins,
get_or_create_wheel_config,
get_wheel_prizes,
reorder_wheel_prizes,
update_wheel_config,
update_wheel_prize,
)
from app.database.models import User
from app.services.wheel_service import wheel_service
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/wheel', tags=['Admin Fortune Wheel'])
@router.get('/config', response_model=AdminWheelConfigResponse)
async def get_admin_wheel_config(
admin: User = Depends(require_permission('wheel:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Получить полную конфигурацию колеса."""
config = await get_or_create_wheel_config(db)
prizes = await get_wheel_prizes(db, config.id, active_only=False)
prizes_response = [
WheelPrizeAdminResponse(
id=p.id,
config_id=p.config_id,
prize_type=p.prize_type,
prize_value=p.prize_value,
display_name=p.display_name,
emoji=p.emoji,
color=p.color,
prize_value_kopeks=p.prize_value_kopeks,
sort_order=p.sort_order,
manual_probability=p.manual_probability,
is_active=p.is_active,
promo_balance_bonus_kopeks=p.promo_balance_bonus_kopeks or 0,
promo_subscription_days=p.promo_subscription_days or 0,
promo_traffic_gb=p.promo_traffic_gb or 0,
created_at=p.created_at,
updated_at=p.updated_at,
)
for p in prizes
]
return AdminWheelConfigResponse(
id=config.id,
is_enabled=config.is_enabled,
name=config.name,
spin_cost_stars=config.spin_cost_stars,
spin_cost_days=config.spin_cost_days,
spin_cost_stars_enabled=config.spin_cost_stars_enabled,
spin_cost_days_enabled=config.spin_cost_days_enabled,
rtp_percent=config.rtp_percent,
daily_spin_limit=config.daily_spin_limit,
min_subscription_days_for_day_payment=config.min_subscription_days_for_day_payment,
promo_prefix=config.promo_prefix,
promo_validity_days=config.promo_validity_days,
prizes=prizes_response,
created_at=config.created_at,
updated_at=config.updated_at,
)
@router.put('/config', response_model=AdminWheelConfigResponse)
async def update_admin_wheel_config(
request: UpdateWheelConfigRequest,
admin: User = Depends(require_permission('wheel:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Обновить конфигурацию колеса."""
update_data = request.model_dump(exclude_unset=True)
if not update_data:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='No fields to update',
)
config = await update_wheel_config(db, **update_data)
logger.info('🎡 Admin updated wheel config', telegram_id=admin.telegram_id, update_data=update_data)
# Возвращаем полную конфигурацию
prizes = await get_wheel_prizes(db, config.id, active_only=False)
prizes_response = [
WheelPrizeAdminResponse(
id=p.id,
config_id=p.config_id,
prize_type=p.prize_type,
prize_value=p.prize_value,
display_name=p.display_name,
emoji=p.emoji,
color=p.color,
prize_value_kopeks=p.prize_value_kopeks,
sort_order=p.sort_order,
manual_probability=p.manual_probability,
is_active=p.is_active,
promo_balance_bonus_kopeks=p.promo_balance_bonus_kopeks or 0,
promo_subscription_days=p.promo_subscription_days or 0,
promo_traffic_gb=p.promo_traffic_gb or 0,
created_at=p.created_at,
updated_at=p.updated_at,
)
for p in prizes
]
return AdminWheelConfigResponse(
id=config.id,
is_enabled=config.is_enabled,
name=config.name,
spin_cost_stars=config.spin_cost_stars,
spin_cost_days=config.spin_cost_days,
spin_cost_stars_enabled=config.spin_cost_stars_enabled,
spin_cost_days_enabled=config.spin_cost_days_enabled,
rtp_percent=config.rtp_percent,
daily_spin_limit=config.daily_spin_limit,
min_subscription_days_for_day_payment=config.min_subscription_days_for_day_payment,
promo_prefix=config.promo_prefix,
promo_validity_days=config.promo_validity_days,
prizes=prizes_response,
created_at=config.created_at,
updated_at=config.updated_at,
)
@router.get('/prizes', response_model=list[WheelPrizeAdminResponse])
async def get_prizes(
admin: User = Depends(require_permission('wheel:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Получить список призов."""
config = await get_or_create_wheel_config(db)
prizes = await get_wheel_prizes(db, config.id, active_only=False)
return [
WheelPrizeAdminResponse(
id=p.id,
config_id=p.config_id,
prize_type=p.prize_type,
prize_value=p.prize_value,
display_name=p.display_name,
emoji=p.emoji,
color=p.color,
prize_value_kopeks=p.prize_value_kopeks,
sort_order=p.sort_order,
manual_probability=p.manual_probability,
is_active=p.is_active,
promo_balance_bonus_kopeks=p.promo_balance_bonus_kopeks or 0,
promo_subscription_days=p.promo_subscription_days or 0,
promo_traffic_gb=p.promo_traffic_gb or 0,
created_at=p.created_at,
updated_at=p.updated_at,
)
for p in prizes
]
@router.post('/prizes', response_model=WheelPrizeAdminResponse, status_code=status.HTTP_201_CREATED)
async def create_prize(
request: CreatePrizeRequest,
admin: User = Depends(require_permission('wheel:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Создать новый приз."""
config = await get_or_create_wheel_config(db)
prize = await create_wheel_prize(
db=db,
config_id=config.id,
prize_type=request.prize_type.value,
prize_value=request.prize_value,
display_name=request.display_name,
prize_value_kopeks=request.prize_value_kopeks,
emoji=request.emoji,
color=request.color,
sort_order=request.sort_order,
manual_probability=request.manual_probability,
is_active=request.is_active,
promo_balance_bonus_kopeks=request.promo_balance_bonus_kopeks,
promo_subscription_days=request.promo_subscription_days,
promo_traffic_gb=request.promo_traffic_gb,
)
logger.info('🎁 Admin created prize', telegram_id=admin.telegram_id, display_name=prize.display_name)
return WheelPrizeAdminResponse(
id=prize.id,
config_id=prize.config_id,
prize_type=prize.prize_type,
prize_value=prize.prize_value,
display_name=prize.display_name,
emoji=prize.emoji,
color=prize.color,
prize_value_kopeks=prize.prize_value_kopeks,
sort_order=prize.sort_order,
manual_probability=prize.manual_probability,
is_active=prize.is_active,
promo_balance_bonus_kopeks=prize.promo_balance_bonus_kopeks or 0,
promo_subscription_days=prize.promo_subscription_days or 0,
promo_traffic_gb=prize.promo_traffic_gb or 0,
created_at=prize.created_at,
updated_at=prize.updated_at,
)
@router.put('/prizes/{prize_id}', response_model=WheelPrizeAdminResponse)
async def update_prize(
prize_id: int,
request: UpdatePrizeRequest,
admin: User = Depends(require_permission('wheel:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Обновить приз."""
update_data = request.model_dump(exclude_unset=True)
# Конвертируем enum в строку если есть
if update_data.get('prize_type'):
update_data['prize_type'] = update_data['prize_type'].value
if not update_data:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='No fields to update',
)
prize = await update_wheel_prize(db, prize_id, **update_data)
if not prize:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Prize not found',
)
logger.info('🎁 Admin updated prize', telegram_id=admin.telegram_id, prize_id=prize_id, update_data=update_data)
return WheelPrizeAdminResponse(
id=prize.id,
config_id=prize.config_id,
prize_type=prize.prize_type,
prize_value=prize.prize_value,
display_name=prize.display_name,
emoji=prize.emoji,
color=prize.color,
prize_value_kopeks=prize.prize_value_kopeks,
sort_order=prize.sort_order,
manual_probability=prize.manual_probability,
is_active=prize.is_active,
promo_balance_bonus_kopeks=prize.promo_balance_bonus_kopeks or 0,
promo_subscription_days=prize.promo_subscription_days or 0,
promo_traffic_gb=prize.promo_traffic_gb or 0,
created_at=prize.created_at,
updated_at=prize.updated_at,
)
@router.delete('/prizes/{prize_id}', status_code=status.HTTP_204_NO_CONTENT)
async def delete_prize_endpoint(
prize_id: int,
admin: User = Depends(require_permission('wheel:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Удалить приз."""
success = await delete_wheel_prize(db, prize_id)
if not success:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Prize not found',
)
logger.info('🗑️ Admin deleted prize', telegram_id=admin.telegram_id, prize_id=prize_id)
@router.post('/prizes/reorder', status_code=status.HTTP_200_OK)
async def reorder_prizes(
request: ReorderPrizesRequest,
admin: User = Depends(require_permission('wheel:edit')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Переупорядочить призы."""
await reorder_wheel_prizes(db, request.prize_ids)
logger.info('🔄 Admin reordered prizes', telegram_id=admin.telegram_id, prize_ids=request.prize_ids)
return {'success': True}
@router.get('/statistics', response_model=WheelStatisticsResponse)
async def get_statistics(
date_from: datetime | None = Query(None),
date_to: datetime | None = Query(None),
admin: User = Depends(require_permission('wheel:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Получить статистику колеса."""
stats = await wheel_service.get_statistics(db, date_from, date_to)
return WheelStatisticsResponse(
total_spins=stats['total_spins'],
total_revenue_kopeks=stats['total_revenue_kopeks'],
total_payout_kopeks=stats['total_payout_kopeks'],
actual_rtp_percent=stats['actual_rtp_percent'],
configured_rtp_percent=stats['configured_rtp_percent'],
spins_by_payment_type=stats['spins_by_payment_type'],
prizes_distribution=stats['prizes_distribution'],
top_wins=stats['top_wins'],
period_from=stats['period_from'],
period_to=stats['period_to'],
)
@router.get('/spins', response_model=AdminSpinsResponse)
async def get_all_spins_endpoint(
user_id: int | None = Query(None),
date_from: datetime | None = Query(None),
date_to: datetime | None = Query(None),
page: int = Query(1, ge=1),
per_page: int = Query(50, ge=1, le=100),
admin: User = Depends(require_permission('wheel:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Получить все спины с фильтрами."""
offset = (page - 1) * per_page
spins, total = await get_all_spins(
db,
user_id=user_id,
date_from=date_from,
date_to=date_to,
limit=per_page,
offset=offset,
)
items = [
AdminSpinItem(
id=spin.id,
user_id=spin.user_id,
username=spin.user.username if spin.user else None,
payment_type=spin.payment_type,
payment_amount=spin.payment_amount,
payment_value_kopeks=spin.payment_value_kopeks,
prize_type=spin.prize_type,
prize_value=spin.prize_value,
prize_display_name=spin.prize_display_name,
prize_value_kopeks=spin.prize_value_kopeks,
is_applied=spin.is_applied,
created_at=spin.created_at,
)
for spin in spins
]
pages = math.ceil(total / per_page) if total > 0 else 1
return AdminSpinsResponse(
items=items,
total=total,
page=page,
per_page=per_page,
pages=pages,
)
+300
View File
@@ -0,0 +1,300 @@
"""Admin routes for managing withdrawal requests in cabinet."""
import json
from typing import Literal
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy import desc, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import (
ReferralEarning,
User,
WithdrawalRequest,
WithdrawalRequestStatus,
)
from app.services.referral_withdrawal_service import referral_withdrawal_service
from ..dependencies import get_cabinet_db, require_permission
from ..schemas.withdrawals import (
AdminApproveWithdrawalRequest,
AdminRejectWithdrawalRequest,
AdminWithdrawalDetailResponse,
AdminWithdrawalItem,
AdminWithdrawalListResponse,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/admin/withdrawals', tags=['Cabinet Admin Withdrawals'])
def _get_risk_level(risk_score: int) -> str:
"""Get risk level from score."""
if risk_score >= 70:
return 'critical'
if risk_score >= 50:
return 'high'
if risk_score >= 30:
return 'medium'
return 'low'
@router.get('', response_model=AdminWithdrawalListResponse)
async def list_withdrawals(
withdrawal_status: Literal['pending', 'approved', 'rejected', 'completed', 'cancelled'] | None = Query(
None, alias='status'
),
offset: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=100),
admin: User = Depends(require_permission('withdrawals:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""List all withdrawal requests."""
query = select(WithdrawalRequest)
count_query = select(func.count()).select_from(WithdrawalRequest)
if withdrawal_status:
query = query.where(WithdrawalRequest.status == withdrawal_status)
count_query = count_query.where(WithdrawalRequest.status == withdrawal_status)
total_result = await db.execute(count_query)
total = total_result.scalar() or 0
# Pending stats
pending_count_result = await db.execute(
select(func.count())
.select_from(WithdrawalRequest)
.where(WithdrawalRequest.status == WithdrawalRequestStatus.PENDING.value)
)
pending_count = pending_count_result.scalar() or 0
pending_total_result = await db.execute(
select(func.coalesce(func.sum(WithdrawalRequest.amount_kopeks), 0)).where(
WithdrawalRequest.status == WithdrawalRequestStatus.PENDING.value
)
)
pending_total = pending_total_result.scalar() or 0
query = query.order_by(desc(WithdrawalRequest.created_at)).offset(offset).limit(limit)
result = await db.execute(query)
withdrawals = result.scalars().all()
# Batch-fetch users to avoid N+1
user_ids = list({w.user_id for w in withdrawals})
if user_ids:
users_result = await db.execute(select(User).where(User.id.in_(user_ids)))
users_map = {u.id: u for u in users_result.scalars().all()}
else:
users_map = {}
items = []
for w in withdrawals:
user = users_map.get(w.user_id)
items.append(
AdminWithdrawalItem(
id=w.id,
user_id=w.user_id,
username=user.username if user else None,
first_name=user.first_name if user else None,
telegram_id=user.telegram_id if user else None,
amount_kopeks=w.amount_kopeks,
amount_rubles=w.amount_kopeks / 100,
status=w.status,
risk_score=w.risk_score or 0,
risk_level=_get_risk_level(w.risk_score or 0),
payment_details=w.payment_details,
admin_comment=w.admin_comment,
created_at=w.created_at,
processed_at=w.processed_at,
)
)
return AdminWithdrawalListResponse(
items=items,
total=total,
pending_count=pending_count,
pending_total_kopeks=pending_total,
)
@router.get('/{withdrawal_id}', response_model=AdminWithdrawalDetailResponse)
async def get_withdrawal_detail(
withdrawal_id: int,
admin: User = Depends(require_permission('withdrawals:read')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get detailed withdrawal request with risk analysis."""
withdrawal = await db.get(WithdrawalRequest, withdrawal_id)
if not withdrawal:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Заявка не найдена',
)
user = await db.get(User, withdrawal.user_id)
# Parse risk analysis
risk_analysis = None
if withdrawal.risk_analysis:
try:
risk_analysis = json.loads(withdrawal.risk_analysis)
except (json.JSONDecodeError, TypeError):
pass
# Get referral stats
referral_count = await db.execute(
select(func.count()).select_from(User).where(User.referred_by_id == withdrawal.user_id)
)
total_earnings = await db.execute(
select(func.coalesce(func.sum(ReferralEarning.amount_kopeks), 0)).where(
ReferralEarning.user_id == withdrawal.user_id
)
)
return AdminWithdrawalDetailResponse(
id=withdrawal.id,
user_id=withdrawal.user_id,
username=user.username if user else None,
first_name=user.first_name if user else None,
telegram_id=user.telegram_id if user else None,
amount_kopeks=withdrawal.amount_kopeks,
amount_rubles=withdrawal.amount_kopeks / 100,
status=withdrawal.status,
risk_score=withdrawal.risk_score or 0,
risk_level=_get_risk_level(withdrawal.risk_score or 0),
risk_analysis=risk_analysis,
payment_details=withdrawal.payment_details,
admin_comment=withdrawal.admin_comment,
balance_kopeks=user.balance_kopeks if user else 0,
total_referrals=referral_count.scalar() or 0,
total_earnings_kopeks=total_earnings.scalar() or 0,
created_at=withdrawal.created_at,
processed_at=withdrawal.processed_at,
)
@router.post('/{withdrawal_id}/approve')
async def approve_withdrawal(
withdrawal_id: int,
request: AdminApproveWithdrawalRequest,
admin: User = Depends(require_permission('withdrawals:approve')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Approve a withdrawal request."""
success, error = await referral_withdrawal_service.approve_request(
db,
request_id=withdrawal_id,
admin_id=admin.id,
comment=request.comment,
)
if not success:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error,
)
# Notify user about approval
try:
from app.bot_factory import create_bot
from app.config import settings
from app.services.notification_delivery_service import notification_delivery_service
if settings.BOT_TOKEN:
withdrawal = await db.get(WithdrawalRequest, withdrawal_id)
user = await db.get(User, withdrawal.user_id) if withdrawal else None
if user and withdrawal:
formatted_amount = settings.format_price(withdrawal.amount_kopeks)
comment_text = f'\n{request.comment}' if request.comment else ''
tg_message = f'✅ Ваш запрос на вывод {formatted_amount} одобрен.{comment_text}'
bot = create_bot()
try:
await notification_delivery_service.notify_withdrawal_approved(
user=user,
amount_kopeks=withdrawal.amount_kopeks,
comment=request.comment,
bot=bot,
telegram_message=tg_message,
)
finally:
await bot.session.close()
except Exception as e:
logger.error('Failed to send withdrawal approval notification', error=e)
return {'success': True}
@router.post('/{withdrawal_id}/reject')
async def reject_withdrawal(
withdrawal_id: int,
request: AdminRejectWithdrawalRequest,
admin: User = Depends(require_permission('withdrawals:reject')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Reject a withdrawal request."""
success, error = await referral_withdrawal_service.reject_request(
db,
request_id=withdrawal_id,
admin_id=admin.id,
comment=request.comment,
)
if not success:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error or 'Не удалось отклонить заявку',
)
# Notify user about rejection
try:
from app.bot_factory import create_bot
from app.config import settings
from app.services.notification_delivery_service import notification_delivery_service
if settings.BOT_TOKEN:
withdrawal = await db.get(WithdrawalRequest, withdrawal_id)
user = await db.get(User, withdrawal.user_id) if withdrawal else None
if user and withdrawal:
formatted_amount = settings.format_price(withdrawal.amount_kopeks)
comment_text = f'\nПричина: {request.comment}' if request.comment else ''
tg_message = f'❌ Ваш запрос на вывод {formatted_amount} отклонён.{comment_text}'
bot = create_bot()
try:
await notification_delivery_service.notify_withdrawal_rejected(
user=user,
amount_kopeks=withdrawal.amount_kopeks,
comment=request.comment,
bot=bot,
telegram_message=tg_message,
)
finally:
await bot.session.close()
except Exception as e:
logger.error('Failed to send withdrawal rejection notification', error=e)
return {'success': True}
@router.post('/{withdrawal_id}/complete')
async def complete_withdrawal(
withdrawal_id: int,
admin: User = Depends(require_permission('withdrawals:approve')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Mark a withdrawal as completed (money transferred)."""
success, error = await referral_withdrawal_service.complete_request(
db,
request_id=withdrawal_id,
admin_id=admin.id,
)
if not success:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error or 'Не удалось завершить заявку',
)
return {'success': True}
+267
View File
@@ -0,0 +1,267 @@
"""Apple In-App Purchase cabinet route."""
from datetime import UTC, datetime
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.apple_iap import (
create_apple_transaction,
)
from app.database.crud.transaction import create_transaction as create_trans
from app.database.crud.user import lock_user_for_update
from app.database.models import PaymentMethod, TransactionType, User
from app.external.apple_iap import AppleIAPService
from app.utils.user_utils import format_referrer_info
from ..dependencies import get_cabinet_db, get_current_cabinet_user
from ..schemas.apple_iap import ApplePurchaseRequest, ApplePurchaseResponse
logger = structlog.get_logger(__name__)
router = APIRouter(tags=['Cabinet Apple IAP'])
def get_apple_iap_service() -> AppleIAPService:
return AppleIAPService()
@router.post('/apple-purchase', response_model=ApplePurchaseResponse)
async def apple_purchase(
request: ApplePurchaseRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
apple_iap_service: AppleIAPService = Depends(get_apple_iap_service),
):
"""Verify an Apple In-App Purchase and credit the user's balance.
The iOS app calls this endpoint after a successful StoreKit transaction.
If the backend returns success=false, the iOS app will NOT finish the
transaction and will retry on next launch.
"""
if not settings.is_apple_iap_enabled():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Apple In-App Purchase is not enabled',
)
# Validate product ID
products = settings.get_apple_iap_products()
if request.product_id not in products:
logger.warning(
'Unknown Apple product ID',
product_id=request.product_id,
user_id=user.id,
)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Unknown product ID',
)
amount_kopeks = products[request.product_id]
# Verify transaction with Apple Server API (no DB lock needed).
# verify_transaction automatically falls back Sandbox<->Production.
txn_info = await apple_iap_service.verify_transaction(request.transaction_id, settings.APPLE_IAP_ENVIRONMENT)
if not txn_info:
logger.warning(
'Apple transaction verification failed',
transaction_id=request.transaction_id,
user_id=user.id,
)
return ApplePurchaseResponse(success=False)
# Validate transaction fields
validation_error = apple_iap_service.validate_transaction_info(txn_info, request.product_id)
if validation_error:
logger.warning(
'Apple transaction validation failed',
error=validation_error,
transaction_id=request.transaction_id,
user_id=user.id,
)
return ApplePurchaseResponse(success=False)
# FIX 4: appAccountToken is mandatory -- reject if missing
app_account_token = txn_info.get('appAccountToken')
if not app_account_token:
logger.warning(
'Apple appAccountToken missing -- rejecting transaction',
transaction_id=request.transaction_id,
user_id=user.id,
)
return ApplePurchaseResponse(success=False)
if app_account_token != str(user.id):
logger.warning(
'Apple appAccountToken mismatch -- possible replay',
expected=str(user.id),
received=app_account_token,
transaction_id=request.transaction_id,
user_id=user.id,
)
return ApplePurchaseResponse(success=False)
# Detect sandbox transactions -- store actual environment from Apple's response
actual_environment = txn_info.get('environment', settings.APPLE_IAP_ENVIRONMENT)
is_sandbox = actual_environment == 'Sandbox'
if is_sandbox and settings.APPLE_IAP_ENVIRONMENT == 'Production':
# Sandbox transaction on a production server (e.g. App Review).
# Record it for audit but do NOT credit real balance.
logger.info(
'Apple sandbox transaction on production -- storing without balance credit',
transaction_id=request.transaction_id,
product_id=request.product_id,
user_id=user.id,
)
try:
async with db.begin_nested():
await create_apple_transaction(
db=db,
user_id=user.id,
transaction_id=request.transaction_id,
original_transaction_id=txn_info.get('originalTransactionId'),
product_id=request.product_id,
bundle_id=txn_info.get('bundleId', settings.APPLE_IAP_BUNDLE_ID),
amount_kopeks=amount_kopeks,
environment='Sandbox',
)
except IntegrityError:
pass # already stored
await db.commit()
return ApplePurchaseResponse(success=True)
# Atomically insert transaction record -- unique constraint on transaction_id
# prevents double-spend even under concurrent requests.
apple_txn = None
try:
async with db.begin_nested():
apple_txn = await create_apple_transaction(
db=db,
user_id=user.id,
transaction_id=request.transaction_id,
original_transaction_id=txn_info.get('originalTransactionId'),
product_id=request.product_id,
bundle_id=txn_info.get('bundleId', settings.APPLE_IAP_BUNDLE_ID),
amount_kopeks=amount_kopeks,
environment=actual_environment,
)
except IntegrityError:
logger.info(
'Apple transaction already processed (idempotent)',
transaction_id=request.transaction_id,
user_id=user.id,
)
return ApplePurchaseResponse(success=True)
# Create financial transaction record
transaction = await create_trans(
db=db,
user_id=user.id,
type=TransactionType.DEPOSIT,
amount_kopeks=amount_kopeks,
description=f'Пополнение через Apple IAP: {request.product_id}',
payment_method=PaymentMethod.APPLE_IAP,
external_id=request.transaction_id,
is_completed=True,
commit=False,
)
# FIX 9: Link AppleTransaction to financial Transaction via FK
if apple_txn and transaction:
apple_txn.transaction_id_fk = transaction.id
apple_txn.updated_at = datetime.now(UTC)
# Lock user row and credit balance
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 += amount_kopeks
# FIX 10: Update user.updated_at when modifying balance
user.updated_at = datetime.now(UTC)
promo_group = user.get_primary_promo_group()
subscription = getattr(user, 'subscription', None)
referrer_info = format_referrer_info(user)
topup_status = 'Первое пополнение' if was_first_topup else 'Пополнение'
await db.commit()
# --- Post-payment side-effects (after atomic commit) ---
from app.database.crud.transaction import emit_transaction_side_effects
try:
await emit_transaction_side_effects(
db,
transaction,
amount_kopeks=amount_kopeks,
user_id=user.id,
type=TransactionType.DEPOSIT,
payment_method=PaymentMethod.APPLE_IAP,
external_id=request.transaction_id,
)
except Exception as error:
logger.error('Ошибка emit_transaction_side_effects Apple IAP', error=error)
try:
from app.services.referral_service import process_referral_topup
await process_referral_topup(db, user.id, amount_kopeks, bot=None)
except Exception as error:
logger.error('Ошибка обработки реферального пополнения Apple IAP', 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)
# Admin notification + cart auto-purchase
try:
from app.bot_factory import create_bot
bot = create_bot()
try:
from app.services.admin_notification_service import AdminNotificationService
notification_service = AdminNotificationService(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('Ошибка отправки админ уведомления Apple IAP', error=error)
try:
from app.services.payment.common import send_cart_notification_after_topup
await send_cart_notification_after_topup(user, amount_kopeks, db, bot)
except Exception as error:
logger.error('Ошибка при работе с сохраненной корзиной Apple IAP', user_id=user.id, error=error)
finally:
await bot.session.close()
except Exception as error:
logger.error('Ошибка создания бота для уведомлений Apple IAP', error=error)
logger.info(
'Apple IAP purchase credited',
transaction_id=request.transaction_id,
product_id=request.product_id,
amount_kopeks=amount_kopeks,
user_id=user.id,
)
return ApplePurchaseResponse(success=True)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+441
View File
@@ -0,0 +1,441 @@
"""Contests routes for cabinet - user participation in games/contests."""
import random
from datetime import UTC, datetime, timedelta
from typing import Any
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.contest import (
create_attempt,
get_active_rounds,
get_attempt,
increment_winner_count,
)
from app.database.crud.subscription import get_active_subscriptions_by_user_id, get_subscription_by_user_id
from app.database.models import SubscriptionStatus, User
async def _resolve_subscription_for_prize(db, user_id: int):
"""Resolve best subscription for applying contest prize (days/traffic)."""
if settings.is_multi_tariff_enabled():
active_subs = await get_active_subscriptions_by_user_id(db, user_id)
# Prefer non-daily with most days left
non_daily = [s for s in active_subs if not (s.tariff and getattr(s.tariff, 'is_daily', False))]
eligible = non_daily or active_subs
return max(eligible, key=lambda s: s.days_left) if eligible else None
return await get_subscription_by_user_id(db, user_id)
from app.services.contest_rotation_service import (
GAME_ANAGRAM,
GAME_BLITZ,
GAME_CIPHER,
GAME_EMOJI,
GAME_LOCKS,
GAME_QUEST,
GAME_SERVER,
)
from ..dependencies import get_cabinet_db, get_current_cabinet_user
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/contests', tags=['Cabinet Contests'])
# ============ Schemas ============
class ContestInfo(BaseModel):
"""Contest/game info."""
id: int
slug: str
name: str
description: str | None = None
prize_type: str
prize_value: str
is_available: bool
already_played: bool = False
class ContestGameData(BaseModel):
"""Data for playing a contest game."""
round_id: int
game_type: str
game_data: dict[str, Any]
instructions: str
class ContestAnswerRequest(BaseModel):
"""Request to submit contest answer."""
round_id: int
answer: str
class ContestResult(BaseModel):
"""Result of contest attempt."""
is_winner: bool
message: str
prize_type: str | None = None
prize_value: str | None = None
# ============ Helpers ============
def _user_allowed(subscription) -> bool:
"""Check if user is allowed to participate in contests."""
if not subscription:
return False
return subscription.status in {
SubscriptionStatus.ACTIVE.value,
SubscriptionStatus.TRIAL.value,
SubscriptionStatus.LIMITED.value,
}
async def _award_prize(db: AsyncSession, user_id: int, prize_type: str, prize_value: str) -> str:
"""Award prize to winner."""
if prize_type == 'days':
try:
days = int(prize_value)
except ValueError:
return 'Error: invalid prize value'
subscription = await _resolve_subscription_for_prize(db, user_id)
if not subscription:
return 'Error: subscription not found'
subscription.end_date = subscription.end_date + timedelta(days=days)
subscription.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(subscription)
logger.info('🎁 Extended subscription for user by days (contest prize)', user_id=user_id, days=days)
return f'Subscription extended by {days} days'
if prize_type == 'balance':
from app.database.crud.user import get_user_by_id
try:
amount = float(prize_value)
except ValueError:
return 'Error: invalid prize value'
user = await get_user_by_id(db, user_id)
if not user:
return 'Error: user not found'
from app.database.crud.user import lock_user_for_update
user = await lock_user_for_update(db, user)
user.balance_kopeks += int(round(amount * 100))
await db.commit()
await db.refresh(user)
logger.info('🎁 Added to balance for user (contest prize)', amount=amount, user_id=user_id)
return f'Balance increased by {amount}'
logger.warning('Unknown prize type', prize_type=prize_type)
return f"Prize type '{prize_type}' not supported"
# ============ Routes ============
class ContestsCountResponse(BaseModel):
"""Count of available contests."""
count: int
@router.get('/count', response_model=ContestsCountResponse)
async def get_contests_count(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get count of contests available for the user."""
subscription = await _resolve_subscription_for_prize(db, user.id)
if not _user_allowed(subscription):
return ContestsCountResponse(count=0)
active_rounds = await get_active_rounds(db)
# Count unique available contests (not yet played)
count = 0
seen_templates = set()
for rnd in active_rounds:
if not rnd.template or not rnd.template.is_enabled:
continue
tpl_slug = rnd.template.slug if rnd.template else ''
if tpl_slug in seen_templates:
continue
seen_templates.add(tpl_slug)
# Check if user already played this round
attempt = await get_attempt(db, rnd.id, user.id)
if not attempt:
count += 1
return ContestsCountResponse(count=count)
@router.get('', response_model=list[ContestInfo])
async def get_contests(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of available contests/games."""
subscription = await _resolve_subscription_for_prize(db, user.id)
if not _user_allowed(subscription):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Contests are only available for users with active or trial subscriptions',
)
active_rounds = await get_active_rounds(db)
# Group by template to avoid duplicates
unique_templates = {}
for rnd in active_rounds:
if not rnd.template or not rnd.template.is_enabled:
continue
tpl_slug = rnd.template.slug if rnd.template else ''
if tpl_slug not in unique_templates:
unique_templates[tpl_slug] = rnd
contests = []
for tpl_slug, rnd in unique_templates.items():
# Check if user already played this round
attempt = await get_attempt(db, rnd.id, user.id)
contests.append(
ContestInfo(
id=rnd.id,
slug=tpl_slug,
name=rnd.template.name if rnd.template else tpl_slug,
description=rnd.template.description if rnd.template else None,
prize_type=rnd.template.prize_type if rnd.template else 'days',
prize_value=rnd.template.prize_value if rnd.template else '1',
is_available=True,
already_played=attempt is not None,
)
)
return contests
@router.get('/{round_id}', response_model=ContestGameData)
async def get_contest_game(
round_id: int,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get game data for a specific contest round."""
subscription = await _resolve_subscription_for_prize(db, user.id)
if not _user_allowed(subscription):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Contests are only available for users with active or trial subscriptions',
)
active_rounds = await get_active_rounds(db)
round_obj = next((r for r in active_rounds if r.id == round_id), None)
if not round_obj:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Contest round not found or already finished',
)
if not round_obj.template or not round_obj.template.is_enabled:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='This contest is disabled',
)
# Check if already played
attempt = await get_attempt(db, round_id, user.id)
if attempt:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='You have already played this round',
)
tpl = round_obj.template
game_type = tpl.slug
game_data = {}
instructions = ''
if game_type == GAME_QUEST:
rows = round_obj.payload.get('rows', 3)
cols = round_obj.payload.get('cols', 3)
secret = random.randint(0, rows * cols - 1)
game_data = {
'rows': rows,
'cols': cols,
'secret': secret,
'grid_size': rows * cols,
}
instructions = 'Select one of the nodes in the grid. Find the hidden server!'
elif game_type == GAME_LOCKS:
total = round_obj.payload.get('total', 20)
secret = random.randint(0, total - 1)
game_data = {
'total': total,
'secret': secret,
}
instructions = 'Find the unlocked button among the locks!'
elif game_type == GAME_SERVER:
flags = round_obj.payload.get('flags') or []
shuffled_flags = flags.copy()
random.shuffle(shuffled_flags)
game_data = {
'flags': shuffled_flags,
}
instructions = 'Choose a server by clicking on a flag!'
elif game_type == GAME_CIPHER:
question = round_obj.payload.get('question', '')
game_data = {
'question': question,
'input_type': 'text',
}
instructions = 'Decrypt the cipher and enter the answer!'
elif game_type == GAME_EMOJI:
question = round_obj.payload.get('question', '🤔')
emoji_list = question.split()
random.shuffle(emoji_list)
game_data = {
'question': ' '.join(emoji_list),
'input_type': 'text',
}
instructions = 'Guess the service by emojis!'
elif game_type == GAME_ANAGRAM:
letters = round_obj.payload.get('letters', '')
game_data = {
'letters': letters,
'input_type': 'text',
}
instructions = 'Make a word from the given letters!'
elif game_type == GAME_BLITZ:
game_data = {
'button_text': "I'm here!",
}
instructions = 'Click the button as fast as you can!'
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Unknown contest type',
)
return ContestGameData(
round_id=round_id,
game_type=game_type,
game_data=game_data,
instructions=instructions,
)
@router.post('/{round_id}/answer', response_model=ContestResult)
async def submit_contest_answer(
round_id: int,
request: ContestAnswerRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Submit answer for a contest round."""
subscription = await _resolve_subscription_for_prize(db, user.id)
if not _user_allowed(subscription):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Contests are only available for users with active or trial subscriptions',
)
active_rounds = await get_active_rounds(db)
round_obj = next((r for r in active_rounds if r.id == round_id), None)
if not round_obj:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Contest round not found or already finished',
)
# Check if already played
attempt = await get_attempt(db, round_id, user.id)
if attempt:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='You have already played this round',
)
tpl = round_obj.template
answer = request.answer
is_winner = False
# Determine if winner based on game type
if tpl.slug == GAME_SERVER:
flags = round_obj.payload.get('flags') or []
secret_idx = round_obj.payload.get('secret_idx')
correct_flag = flags[secret_idx] if secret_idx is not None and secret_idx < len(flags) else ''
is_winner = answer == correct_flag
elif tpl.slug in {GAME_QUEST, GAME_LOCKS}:
try:
parts = answer.split('_')
if len(parts) >= 2:
idx = int(parts[0])
secret = int(parts[1])
is_winner = idx == secret
except (ValueError, IndexError):
is_winner = False
elif tpl.slug == GAME_BLITZ:
is_winner = answer.lower() == 'blitz'
elif tpl.slug in {GAME_CIPHER, GAME_EMOJI, GAME_ANAGRAM}:
correct = (round_obj.payload.get('answer') or '').upper()
is_winner = correct and answer.upper() == correct
# Record attempt
await create_attempt(db, round_id=round_obj.id, user_id=user.id, answer=str(answer), is_winner=is_winner)
if is_winner:
await increment_winner_count(db, round_obj)
prize_text = await _award_prize(db, user.id, tpl.prize_type, tpl.prize_value)
return ContestResult(
is_winner=True,
message=f'🎉 Congratulations! You won! {prize_text}',
prize_type=tpl.prize_type,
prize_value=tpl.prize_value,
)
lose_messages = {
GAME_QUEST: ['Empty node', 'Wrong server', 'Try another'],
GAME_LOCKS: ['Locked', 'No access', 'Try again'],
GAME_SERVER: ['Server overloaded', 'No response', 'Try tomorrow'],
}
messages = lose_messages.get(tpl.slug, ['Incorrect', 'Try again next round'])
return ContestResult(
is_winner=False,
message=random.choice(messages),
)
+806
View File
@@ -0,0 +1,806 @@
"""Gift subscription routes for cabinet."""
import asyncio
import re
from datetime import UTC, datetime
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.config import settings
from app.database.crud.system_setting import get_setting_value
from app.database.crud.tariff import get_tariff_by_id
from app.database.crud.transaction import create_transaction, emit_transaction_side_effects
from app.database.crud.user import subtract_user_balance
from app.database.models import (
GuestPurchase,
GuestPurchaseStatus,
PaymentMethod,
Tariff,
TransactionType,
User,
)
from app.services.guest_purchase_service import (
GuestPurchaseError,
create_purchase,
fulfill_purchase,
)
from app.services.payment_method_config_service import get_enabled_methods_for_user
from app.utils.cache import RateLimitCache
from app.utils.promo_offer import get_user_active_promo_discount_percent
from ..dependencies import get_cabinet_db, get_current_cabinet_user
from ..schemas.gift import (
ActivateGiftRequest,
ActivateGiftResponse,
GiftConfigPaymentMethod,
GiftConfigResponse,
GiftConfigSubOption,
GiftConfigTariff,
GiftConfigTariffPeriod,
GiftPurchaseRequest,
GiftPurchaseResponse,
GiftPurchaseStatusResponse,
PendingGiftResponse,
ReceivedGiftResponse,
SentGiftResponse,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/gift', tags=['Cabinet Gift'])
GIFT_ENABLED_KEY = 'CABINET_GIFT_ENABLED'
_EMAIL_RE = re.compile(r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$')
_TELEGRAM_RE = re.compile(r'^@?[a-zA-Z][a-zA-Z0-9_]{4,31}$')
async def _is_gift_enabled(db: AsyncSession) -> bool:
"""Check if the gift feature is enabled via system settings."""
value = await get_setting_value(db, GIFT_ENABLED_KEY)
if value is not None:
return value.lower() == 'true'
return False
@router.get('/config', response_model=GiftConfigResponse)
async def get_gift_config(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get gift subscription configuration: tariffs, payment methods, balance."""
enabled = await _is_gift_enabled(db)
if not enabled:
return GiftConfigResponse(
is_enabled=False,
balance_kopeks=user.balance_kopeks,
)
# Load active tariffs visible in gift section
result = await db.execute(
select(Tariff)
.where(Tariff.is_active.is_(True), Tariff.show_in_gift.is_(True))
.order_by(Tariff.display_order, Tariff.id)
)
tariffs_db = result.scalars().all()
# Get user's promo group for discount calculation
promo_group = user.get_primary_promo_group() if hasattr(user, 'get_primary_promo_group') else None
if promo_group is None:
promo_group = getattr(user, 'promo_group', None)
promo_group_name = promo_group.name if promo_group else None
# Get active promo offer discount
promo_offer_discount_percent = get_user_active_promo_discount_percent(user)
tariffs: list[GiftConfigTariff] = []
for tariff in tariffs_db:
period_days_list = tariff.get_available_periods()
periods: list[GiftConfigTariffPeriod] = []
for days in period_days_list:
base_price = tariff.get_price_for_period(days)
if base_price is None:
continue
original_price = base_price
price = base_price
# Apply promo group discount
from app.services.pricing_engine import PricingEngine
promo_group_discount = 0
if promo_group:
promo_group_discount = promo_group.get_discount_percent('period', days)
if promo_group_discount > 0:
price = PricingEngine.apply_discount(price, promo_group_discount)
# Apply active promo offer discount (stacks on top)
if promo_offer_discount_percent > 0:
price = PricingEngine.apply_discount(price, promo_offer_discount_percent)
# Ensure minimum price of 1 kopek after all discounts
price = max(1, price)
# Calculate combined discount percent
combined_discount = 0
if original_price > 0 and original_price != price:
combined_discount = int((original_price - price) * 100 / original_price)
periods.append(
GiftConfigTariffPeriod(
days=days,
price_kopeks=price,
price_label=settings.format_price(price),
original_price_kopeks=original_price if combined_discount > 0 else None,
discount_percent=combined_discount if combined_discount > 0 else None,
)
)
if not periods:
continue
tariffs.append(
GiftConfigTariff(
id=tariff.id,
name=tariff.name,
description=tariff.description,
traffic_limit_gb=tariff.traffic_limit_gb,
device_limit=tariff.device_limit,
periods=periods,
)
)
# Load payment methods available for this user
enabled_methods = await get_enabled_methods_for_user(db, user=user)
payment_methods: list[GiftConfigPaymentMethod] = []
for method_data in enabled_methods:
sub_options = None
raw_options = method_data.get('options')
if raw_options:
sub_options = [GiftConfigSubOption(id=opt['id'], name=opt.get('name', opt['id'])) for opt in raw_options]
payment_methods.append(
GiftConfigPaymentMethod(
method_id=method_data['id'],
display_name=method_data['name'],
min_amount_kopeks=method_data.get('min_amount_kopeks'),
max_amount_kopeks=method_data.get('max_amount_kopeks'),
sub_options=sub_options,
)
)
return GiftConfigResponse(
is_enabled=True,
tariffs=tariffs,
payment_methods=payment_methods,
balance_kopeks=user.balance_kopeks,
currency_symbol=getattr(settings, 'CURRENCY_SYMBOL', '\u20bd'),
promo_group_name=promo_group_name,
active_discount_percent=promo_offer_discount_percent if promo_offer_discount_percent > 0 else None,
active_discount_expires_at=(
getattr(user, 'promo_offer_discount_expires_at', None) if promo_offer_discount_percent > 0 else None
),
)
@router.post('/purchase', response_model=GiftPurchaseResponse)
async def create_gift_purchase(
body: GiftPurchaseRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Create a gift subscription purchase from the cabinet."""
enabled = await _is_gift_enabled(db)
if not enabled:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Gift feature is not enabled',
)
# Rate limit: 5 gift purchases per 60 seconds per user
is_limited = await RateLimitCache.is_rate_limited(user.id, 'gift_purchase', limit=5, window=60)
if is_limited:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
# Check if user has purchase restrictions
if getattr(user, 'restriction_subscription', False):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Purchases are restricted for this account',
)
# Recipient is optional — when omitted, buyer gets a code to share manually
has_recipient = bool(body.recipient_type and body.recipient_value)
if has_recipient:
# Validate recipient format
if body.recipient_type == 'email' and not _EMAIL_RE.match(body.recipient_value):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid email format',
)
if body.recipient_type == 'telegram' and not _TELEGRAM_RE.match(body.recipient_value):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid Telegram username format',
)
# Prevent self-gift
if body.recipient_type == 'telegram':
normalized_recipient = body.recipient_value.lstrip('@').lower()
if user.username and user.username.lower() == normalized_recipient:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Cannot gift to yourself',
)
elif body.recipient_type == 'email':
if user.email and user.email.lower() == body.recipient_value.lower():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Cannot gift to yourself',
)
# Find tariff and validate period
tariff = await get_tariff_by_id(db, body.tariff_id)
if tariff is None or not tariff.is_active or not tariff.show_in_gift:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Tariff not found or inactive',
)
# Validate that period has a configured price before locking
if tariff.get_price_for_period(body.period_days) is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Price is not configured for this period',
)
# Lock user BEFORE price computation to prevent TOCTOU on promo offer
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
from app.services.pricing_engine import pricing_engine
pricing_result = await pricing_engine.calculate_tariff_purchase_price(
tariff,
body.period_days,
device_limit=tariff.device_limit,
user=user,
)
price_kopeks = max(1, pricing_result.final_total)
consume_promo = pricing_result.promo_offer_discount > 0
# Determine buyer contact info
if user.email:
buyer_contact_type = 'email'
buyer_contact_value = user.email
elif user.username:
buyer_contact_type = 'telegram'
buyer_contact_value = f'@{user.username}'
else:
buyer_contact_type = 'telegram'
buyer_contact_value = f'id:{user.telegram_id or user.id}'
# Pre-check: try to resolve Telegram username — DB first, then Bot API.
# Only relevant when a recipient is explicitly specified.
recipient_warning: str | None = None
pre_resolved_telegram_id: int | None = None
if has_recipient and body.recipient_type == 'telegram':
tg_username = body.recipient_value.lstrip('@')
normalized_username = tg_username.lower()
# 1) Check local DB — user may already be registered in the bot
db_result = await db.execute(
select(User.telegram_id).where(
func.lower(User.username) == normalized_username,
User.telegram_id.isnot(None),
)
)
db_telegram_id = db_result.scalar_one_or_none()
if db_telegram_id is not None:
pre_resolved_telegram_id = db_telegram_id
else:
# 2) Fall back to Bot API (works for public usernames the bot has seen)
try:
from app.bot_factory import create_bot
async with create_bot() as bot:
chat = await asyncio.wait_for(bot.get_chat(chat_id=f'@{tg_username}'), timeout=5.0)
pre_resolved_telegram_id = chat.id
except Exception:
recipient_warning = 'telegram_unresolvable'
logger.warning(
'Telegram username not resolvable for gift',
username=tg_username,
buyer_id=user.id,
)
# Gateway mode: create payment via external provider
if body.payment_mode == 'gateway':
if not body.payment_method:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='payment_method is required for gateway mode',
)
purchase_kwargs: dict = (
{
'gift_recipient_type': body.recipient_type,
'gift_recipient_value': body.recipient_value,
'gift_message': body.gift_message,
}
if has_recipient
else {
'gift_message': body.gift_message,
}
)
try:
purchase = await create_purchase(
db,
landing=None,
tariff=tariff,
period_days=body.period_days,
amount_kopeks=price_kopeks,
contact_type=buyer_contact_type,
contact_value=buyer_contact_value,
payment_method=body.payment_method,
is_gift=True,
source='cabinet',
buyer_user_id=user.id,
commit=False,
**purchase_kwargs,
)
except GuestPurchaseError as exc:
raise HTTPException(status_code=exc.status_code, detail=exc.message) from exc
# Persist warning so it survives the gateway redirect
if recipient_warning:
purchase.recipient_warning = recipient_warning
# Build return URL for after payment
cabinet_base = (settings.CABINET_URL or '').rstrip('/')
return_url = f'{cabinet_base}/gift/result?token={purchase.token[:12]}'
from app.services.payment_service import PaymentService
# Stars payments need a Bot instance to create invoice links
bot = None
if body.payment_method == 'telegram_stars':
from app.bot_factory import create_bot
bot = create_bot()
try:
payment_service = PaymentService(bot=bot)
payment_result = await payment_service.create_guest_payment(
db=db,
amount_kopeks=price_kopeks,
payment_method=body.payment_method,
description=f'Gift: {tariff.name} ({body.period_days}d)',
purchase_token=purchase.token,
return_url=return_url,
)
finally:
if bot:
await bot.session.close()
if payment_result is None:
await db.rollback()
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail='Payment provider is unavailable, please try again later',
)
payment_url = payment_result.get('payment_url')
if not payment_url:
await db.rollback()
logger.error(
'Gift payment created but no payment_url returned',
purchase_token=purchase.token[:5],
provider=payment_result.get('provider'),
)
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail='Payment provider returned an invalid response',
)
# Consume promo offer discount before committing gateway purchase
if consume_promo and getattr(user, 'promo_offer_discount_percent', 0):
user.promo_offer_discount_percent = 0
user.promo_offer_discount_source = None
user.promo_offer_discount_expires_at = None
await db.commit()
await db.refresh(purchase)
return GiftPurchaseResponse(
status='created',
purchase_token=purchase.token[:12],
payment_url=payment_url,
warning=recipient_warning,
)
# 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',
)
# Create purchase record
balance_purchase_kwargs: dict = (
{
'gift_recipient_type': body.recipient_type,
'gift_recipient_value': body.recipient_value,
'gift_message': body.gift_message,
}
if has_recipient
else {
'gift_message': body.gift_message,
}
)
try:
purchase = await create_purchase(
db,
landing=None,
tariff=tariff,
period_days=body.period_days,
amount_kopeks=price_kopeks,
contact_type=buyer_contact_type,
contact_value=buyer_contact_value,
payment_method='balance',
is_gift=True,
source='cabinet',
buyer_user_id=user.id,
commit=False,
**balance_purchase_kwargs,
)
except GuestPurchaseError as exc:
raise HTTPException(status_code=exc.status_code, detail=exc.message) from exc
# Persist warning on purchase record
if recipient_warning:
purchase.recipient_warning = recipient_warning
# Subtract balance (consume promo offer if one was applied)
balance_ok = await subtract_user_balance(
db,
user,
price_kopeks,
description=f'Gift: {tariff.name} ({body.period_days}d)',
create_transaction=False,
consume_promo_offer=consume_promo,
)
if not balance_ok:
await db.rollback()
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Insufficient balance',
)
# Transaction description: include recipient when specified
tx_description = f'Gift: {tariff.name} ({body.period_days}d)'
if has_recipient:
tx_description += f' -> {body.recipient_value}'
# Create transaction record
transaction = await create_transaction(
db,
user_id=user.id,
type=TransactionType.GIFT_PAYMENT,
amount_kopeks=price_kopeks,
description=tx_description,
payment_method=PaymentMethod.BALANCE,
commit=False,
)
# Mark purchase as paid
purchase.status = GuestPurchaseStatus.PAID.value
purchase.paid_at = datetime.now(UTC)
await db.commit()
# Emit deferred side-effects after atomic commit
await emit_transaction_side_effects(
db,
transaction,
amount_kopeks=price_kopeks,
user_id=user.id,
type=TransactionType.GIFT_PAYMENT,
payment_method=PaymentMethod.BALANCE,
description=tx_description,
)
# Capture token before fulfill_purchase — session state may change after rollback inside fulfill
purchase_token = purchase.token
# Only fulfill immediately when a specific recipient was provided.
# Code-only gifts (no recipient) stay in PAID status until someone activates via code.
if has_recipient:
try:
await fulfill_purchase(db, purchase_token, pre_resolved_telegram_id=pre_resolved_telegram_id)
except Exception:
logger.exception(
'Gift purchase fulfillment failed (purchase is paid, will retry)',
purchase_id=purchase.id,
)
return GiftPurchaseResponse(
status='ok',
purchase_token=purchase_token[:12],
warning=recipient_warning,
)
@router.get('/pending', response_model=list[PendingGiftResponse])
async def get_pending_gifts(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get pending gift purchases that the current user can activate."""
result = await db.execute(
select(GuestPurchase)
.options(selectinload(GuestPurchase.tariff))
.where(
GuestPurchase.user_id == user.id,
GuestPurchase.is_gift.is_(True),
GuestPurchase.status == GuestPurchaseStatus.PENDING_ACTIVATION.value,
)
.order_by(GuestPurchase.created_at.desc())
.limit(100)
)
purchases = result.scalars().all()
pending: list[PendingGiftResponse] = []
for p in purchases:
# Determine sender display name
sender_display = None
if p.contact_value:
sender_display = p.contact_value
pending.append(
PendingGiftResponse(
token=p.token[:12],
tariff_name=p.tariff.name if p.tariff else None,
period_days=p.period_days,
gift_message=p.gift_message,
sender_display=sender_display,
created_at=p.created_at,
)
)
return pending
@router.get('/purchase/{token}', response_model=GiftPurchaseStatusResponse)
async def get_gift_purchase_status(
token: str,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get the status of a cabinet gift purchase."""
if len(token) >= 64:
token_filter = GuestPurchase.token == token
else:
token_filter = GuestPurchase.token.startswith(token)
result = await db.execute(select(GuestPurchase).options(selectinload(GuestPurchase.tariff)).where(token_filter))
purchase = result.scalars().first()
if purchase is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Purchase not found',
)
# Uniform 404 prevents token existence oracle
if purchase.buyer_user_id != user.id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Purchase not found',
)
tariff_name = purchase.tariff.name if purchase.tariff else None
recipient_contact_value = None
if purchase.gift_recipient_value:
recipient_contact_value = purchase.gift_recipient_value
is_code_only = purchase.is_gift and not purchase.gift_recipient_type
return GiftPurchaseStatusResponse(
status=purchase.status,
is_gift=True,
is_code_only=is_code_only,
purchase_token=purchase.token[:12] if is_code_only else None,
recipient_contact_value=recipient_contact_value,
gift_message=purchase.gift_message,
tariff_name=tariff_name,
period_days=purchase.period_days,
warning=purchase.recipient_warning,
)
@router.get('/sent', response_model=list[SentGiftResponse])
async def get_sent_gifts(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get all gifts the current user has sent."""
result = await db.execute(
select(GuestPurchase)
.options(selectinload(GuestPurchase.tariff), selectinload(GuestPurchase.user))
.where(
GuestPurchase.buyer_user_id == user.id,
GuestPurchase.is_gift.is_(True),
)
.order_by(GuestPurchase.created_at.desc())
.limit(100)
)
purchases = result.scalars().all()
sent: list[SentGiftResponse] = []
for p in purchases:
activated_by_username = None
if p.status == GuestPurchaseStatus.DELIVERED.value and p.user and p.user.username:
activated_by_username = f'@{p.user.username}'
sent.append(
SentGiftResponse(
token=p.token[:12],
tariff_name=p.tariff.name if p.tariff else None,
period_days=p.period_days,
device_limit=p.tariff.device_limit if p.tariff else 1,
status=p.status,
gift_recipient_value=p.gift_recipient_value,
gift_message=p.gift_message,
activated_by_username=activated_by_username,
created_at=p.created_at,
)
)
return sent
@router.get('/received', response_model=list[ReceivedGiftResponse])
async def get_received_gifts(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get all gifts the current user has received."""
result = await db.execute(
select(GuestPurchase)
.options(selectinload(GuestPurchase.tariff), selectinload(GuestPurchase.buyer))
.where(
GuestPurchase.user_id == user.id,
GuestPurchase.is_gift.is_(True),
)
.order_by(GuestPurchase.created_at.desc())
.limit(100)
)
purchases = result.scalars().all()
received: list[ReceivedGiftResponse] = []
for p in purchases:
sender_display = None
if p.buyer and p.buyer.username:
sender_display = f'@{p.buyer.username}'
elif p.contact_value:
sender_display = p.contact_value
received.append(
ReceivedGiftResponse(
token=p.token[:12],
tariff_name=p.tariff.name if p.tariff else None,
period_days=p.period_days,
device_limit=p.tariff.device_limit if p.tariff else 1,
status=p.status,
sender_display=sender_display,
gift_message=p.gift_message,
created_at=p.created_at,
)
)
return received
@router.post('/activate', response_model=ActivateGiftResponse)
async def activate_gift_by_code(
body: ActivateGiftRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Activate a gift subscription by its code (token)."""
from app.services.guest_purchase_service import activate_purchase as svc_activate
# Bug 2 fix: rate limit activation attempts to prevent brute-force token enumeration
is_limited = await RateLimitCache.is_rate_limited(user.id, 'gift_activate', limit=10, window=60)
if is_limited:
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
code = body.code.strip()
if code.upper().startswith('GIFT-') or code.upper().startswith('GIFT_'):
code = code[5:]
if len(code) < 8:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail='Code too short')
# Support both full token and prefix-based lookup (displayed codes are truncated)
if len(code) >= 64:
# Full token — exact match
token_filter = GuestPurchase.token == code
else:
# Prefix match — for short display codes like GIFT-XXXXXXXXXXXX
token_filter = GuestPurchase.token.startswith(code)
result = await db.execute(
select(GuestPurchase)
.options(selectinload(GuestPurchase.tariff))
.where(token_filter, GuestPurchase.is_gift.is_(True))
.with_for_update()
)
purchase = result.scalars().first()
if purchase is None or not purchase.is_gift:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Gift not found',
)
# Bug 1 fix: check ownership BEFORE leaking any status/tariff info
if purchase.user_id is not None and purchase.user_id != user.id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Gift not found',
)
# Prevent self-activation: buyer cannot activate their own gift
if purchase.buyer_user_id is not None and purchase.buyer_user_id == user.id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Cannot activate your own gift',
)
if purchase.status == GuestPurchaseStatus.DELIVERED.value:
return ActivateGiftResponse(
status='activated',
tariff_name=purchase.tariff.name if purchase.tariff else None,
period_days=purchase.period_days,
)
# Code-only gifts are in PAID status; directed gifts are in PENDING_ACTIVATION
activatable_statuses = {
GuestPurchaseStatus.PENDING_ACTIVATION.value,
GuestPurchaseStatus.PAID.value,
}
if purchase.status not in activatable_statuses:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='This gift cannot be activated',
)
# For code-only gifts (user_id is None), link the purchase to the activating user
if purchase.user_id is None:
purchase.user_id = user.id
# Transition PAID → PENDING_ACTIVATION so activate_purchase() accepts it
if purchase.status == GuestPurchaseStatus.PAID.value:
purchase.status = GuestPurchaseStatus.PENDING_ACTIVATION.value
await db.flush()
try:
await svc_activate(db, purchase.token, skip_notification=True)
except GuestPurchaseError as exc:
raise HTTPException(status_code=exc.status_code, detail=exc.message) from exc
return ActivateGiftResponse(
status='activated',
tariff_name=purchase.tariff.name if purchase.tariff else None,
period_days=purchase.period_days,
)
+309
View File
@@ -0,0 +1,309 @@
"""Info pages routes for cabinet - FAQ, rules, privacy policy, etc."""
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.rules import get_current_rules_content, get_rules_by_language
from app.database.models import User
from app.services.faq_service import FaqService
from app.services.privacy_policy_service import PrivacyPolicyService
from app.services.public_offer_service import PublicOfferService
from ..dependencies import get_cabinet_db, get_current_cabinet_user
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/info', tags=['Cabinet Info'])
_LANGUAGE_META: dict[str, tuple[str, str]] = {
'ru': ('Русский', '🇷🇺'),
'en': ('English', '🇬🇧'),
'ua': ('Українська', '🇺🇦'),
'zh': ('中文', '🇨🇳'),
'fa': ('فارسی', '🇮🇷'),
}
def _normalize_language_code(value: str | None) -> str:
return (value or '').strip().lower().split('-', 1)[0]
def _get_available_language_codes() -> list[str]:
codes: list[str] = []
seen: set[str] = set()
for code in settings.get_available_languages():
normalized = _normalize_language_code(code)
if not normalized or normalized in seen:
continue
seen.add(normalized)
codes.append(normalized)
return codes
# ============ Schemas ============
class FaqPageResponse(BaseModel):
"""FAQ page."""
id: int
title: str
content: str
order: int
class RulesResponse(BaseModel):
"""Service rules."""
content: str
updated_at: str | None = None
class PrivacyPolicyResponse(BaseModel):
"""Privacy policy."""
content: str
updated_at: str | None = None
class PublicOfferResponse(BaseModel):
"""Public offer."""
content: str
updated_at: str | None = None
class ServiceInfoResponse(BaseModel):
"""General service info."""
name: str
description: str | None = None
support_email: str | None = None
support_telegram: str | None = None
website: str | None = None
class SupportConfigResponse(BaseModel):
"""Support/tickets configuration for miniapp."""
tickets_enabled: bool
support_type: str # "tickets", "profile", "url", "both"
support_url: str | None = None
support_username: str | None = None
# ============ Routes ============
@router.get('/faq', response_model=list[FaqPageResponse])
async def get_faq_pages(
language: str = Query('ru', min_length=2, max_length=10),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of FAQ pages."""
requested_lang = FaqService.normalize_language(language)
pages = await FaqService.get_pages(
db,
requested_lang,
include_inactive=False, # Only active pages for cabinet
fallback=True,
)
return [
FaqPageResponse(
id=page.id,
title=page.title,
content=page.content or '',
order=page.display_order or 0,
)
for page in pages
]
@router.get('/faq/{page_id}', response_model=FaqPageResponse)
async def get_faq_page(
page_id: int,
language: str = Query('ru', min_length=2, max_length=10),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get a specific FAQ page by ID."""
requested_lang = FaqService.normalize_language(language)
page = await FaqService.get_page(
db,
page_id,
requested_lang,
include_inactive=False,
fallback=True,
)
if not page:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='FAQ page not found',
)
return FaqPageResponse(
id=page.id,
title=page.title,
content=page.content or '',
order=page.display_order or 0,
)
@router.get('/rules', response_model=RulesResponse)
async def get_rules(
language: str = Query('ru', min_length=2, max_length=10),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get service rules - uses same function as bot."""
requested_lang = language.split('-', maxsplit=1)[0].lower()
# Use the same function as bot to ensure consistent content
content = await get_current_rules_content(db, requested_lang)
# Try to get updated_at from DB record
rules = await get_rules_by_language(db, requested_lang)
updated_at = None
if rules and rules.updated_at:
updated_at = rules.updated_at.isoformat()
return RulesResponse(content=content, updated_at=updated_at)
@router.get('/privacy-policy', response_model=PrivacyPolicyResponse)
async def get_privacy_policy(
language: str = Query('ru', min_length=2, max_length=10),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get privacy policy."""
requested_lang = PrivacyPolicyService.normalize_language(language)
policy = await PrivacyPolicyService.get_policy(db, requested_lang, fallback=True)
if policy and policy.content:
updated_at = policy.updated_at.isoformat() if policy.updated_at else None
return PrivacyPolicyResponse(content=policy.content, updated_at=updated_at)
# Return default policy if none found
return PrivacyPolicyResponse(
content="""# Политика конфиденциальности
Мы уважаем вашу конфиденциальность и защищаем ваши персональные данные.
""",
updated_at=None,
)
@router.get('/public-offer', response_model=PublicOfferResponse)
async def get_public_offer(
language: str = Query('ru', min_length=2, max_length=10),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get public offer."""
requested_lang = PublicOfferService.normalize_language(language)
offer = await PublicOfferService.get_offer(db, requested_lang, fallback=True)
if offer and offer.content:
updated_at = offer.updated_at.isoformat() if offer.updated_at else None
return PublicOfferResponse(content=offer.content, updated_at=updated_at)
# Return default offer if none found
return PublicOfferResponse(
content="""# Публичная оферта
Условия использования сервиса.
""",
updated_at=None,
)
@router.get('/service', response_model=ServiceInfoResponse)
async def get_service_info():
"""Get general service information."""
return ServiceInfoResponse(
name=getattr(settings, 'SERVICE_NAME', None) or getattr(settings, 'BOT_NAME', 'VPN Service'),
description=getattr(settings, 'SERVICE_DESCRIPTION', None),
support_email=getattr(settings, 'SUPPORT_EMAIL', None),
support_telegram=getattr(settings, 'SUPPORT_USERNAME', None) or getattr(settings, 'SUPPORT_TELEGRAM', None),
website=getattr(settings, 'WEBSITE_URL', None),
)
@router.get('/languages')
async def get_available_languages():
"""Get list of available languages."""
codes = _get_available_language_codes()
default_language = _normalize_language_code(getattr(settings, 'DEFAULT_LANGUAGE', 'ru') or 'ru')
return {
'languages': [
{
'code': code,
'name': _LANGUAGE_META.get(code, (code.upper(), '🌐'))[0],
'flag': _LANGUAGE_META.get(code, (code.upper(), '🌐'))[1],
}
for code in codes
],
'default': default_language,
}
@router.get('/user/language')
async def get_user_language(
user: User = Depends(get_current_cabinet_user),
):
"""Get current user's language."""
return {'language': user.language or 'ru'}
@router.patch('/user/language')
async def update_user_language(
request: dict[str, str],
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update user's language preference."""
requested_language = _normalize_language_code(request.get('language', 'ru'))
available_languages = _get_available_language_codes()
if requested_language not in available_languages:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Invalid language. Supported: {", ".join(available_languages)}',
)
user.language = requested_language
await db.commit()
await db.refresh(user)
return {'language': user.language}
@router.get('/support-config', response_model=SupportConfigResponse)
async def get_support_config():
"""Get support/tickets configuration for cabinet."""
# Use SUPPORT_SYSTEM_MODE setting (configurable from admin panel)
support_mode = settings.get_support_system_mode() # returns: tickets, contact, or both
# Map support mode to support type for frontend
# - "tickets" mode -> tickets only, no contact
# - "contact" mode -> contact only (profile), no tickets
# - "both" mode -> tickets enabled, contact available as fallback
if support_mode == 'tickets':
tickets_enabled = True
support_type = 'tickets'
elif support_mode == 'contact':
tickets_enabled = False
support_type = 'profile'
else: # both
tickets_enabled = True
support_type = 'both'
return SupportConfigResponse(
tickets_enabled=tickets_enabled,
support_type=support_type,
support_url=None, # Cabinet doesn't use custom URLs
support_username=settings.SUPPORT_USERNAME, # Always return for fallback
)
+68
View File
@@ -0,0 +1,68 @@
"""Public info page routes for cabinet."""
import structlog
from fastapi import APIRouter, Depends, HTTPException, Path, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.info_pages import get_all_info_pages, get_info_page_by_slug, get_tab_replacements
from ..dependencies import get_cabinet_db
from ..schemas.info_pages import InfoPageListItem, InfoPageResponse
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/info-pages', tags=['Cabinet Info Pages'])
@router.get('', response_model=list[InfoPageListItem])
async def list_active_info_pages(
page_type: str | None = Query(None, pattern=r'^(page|faq)$'),
db: AsyncSession = Depends(get_cabinet_db),
) -> list[InfoPageListItem]:
"""Get all active info pages (public, no auth required)."""
try:
pages = await get_all_info_pages(db, include_inactive=False, page_type=page_type)
return [InfoPageListItem.model_validate(p) for p in pages]
except Exception:
logger.exception('Failed to list active info pages')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load info pages',
)
@router.get('/tab-replacements')
async def get_info_page_tab_replacements(
db: AsyncSession = Depends(get_cabinet_db),
) -> dict[str, str | None]:
"""Get tab replacement mapping (public, no auth required).
Returns a dict mapping each replaceable tab to the info page slug that replaces it,
or null if no replacement is set: ``{faq: slug_or_null, ...}``.
"""
try:
return await get_tab_replacements(db)
except Exception:
logger.exception('Failed to get tab replacements')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load tab replacements',
)
@router.get('/{slug}', response_model=InfoPageResponse)
async def get_info_page_by_slug_public(
slug: str = Path(..., max_length=200, pattern=r'^[a-z0-9\-]+$'),
db: AsyncSession = Depends(get_cabinet_db),
) -> InfoPageResponse:
"""Get a single info page by slug (public, no auth required)."""
page = await get_info_page_by_slug(db, slug)
if not page or not page.is_active:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Info page not found',
)
return InfoPageResponse.model_validate(page)
+731
View File
@@ -0,0 +1,731 @@
"""Public landing page routes for guest quick-purchase flow."""
import re
from datetime import UTC, datetime, timedelta
import structlog
from fastapi import APIRouter, Depends, HTTPException, Path, Query, Request, status
from pydantic import BaseModel, Field, model_validator
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.cabinet.dependencies import get_cabinet_db
from app.cabinet.ip_utils import get_client_ip
from app.cabinet.utils.locale import DEFAULT_LOCALE, resolve_locale_text
from app.config import settings
from app.database.crud.landing import get_active_landing_by_slug, get_purchase_by_token
from app.database.models import GuestPurchase, GuestPurchaseStatus, LandingPage, Tariff
from app.services.guest_purchase_service import (
GuestPurchaseError,
activate_purchase as activate_guest_purchase,
create_purchase,
validate_and_calculate,
)
from app.services.payment_method_config_service import _get_method_defaults
from app.services.payment_service import PaymentService
from app.utils.cache import RateLimitCache, cache
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/landing', tags=['Landing Pages'])
# ============ Schemas ============
class LandingFeature(BaseModel):
icon: str = ''
title: str = ''
description: str = ''
class LandingTariffPeriod(BaseModel):
days: int
label: str
price_kopeks: int
price_label: str
original_price_kopeks: int | None = None # set if discount active
original_price_label: str | None = None
discount_percent: int | None = None # effective discount for this tariff
class LandingTariff(BaseModel):
id: int
name: str
description: str | None = None
traffic_limit_gb: int
device_limit: int
tier_level: int
periods: list[LandingTariffPeriod]
class LandingPaymentMethodSubOption(BaseModel):
id: str
name: str
class LandingPaymentMethod(BaseModel):
method_id: str
display_name: str
description: str | None = None
icon_url: str | None = None
sort_order: int = 0
min_amount_kopeks: int | None = None
max_amount_kopeks: int | None = None
currency: str | None = None
# Enabled sub-options with display labels (e.g. СБП, Карта).
# None or empty means no sub-option selection needed.
sub_options: list[LandingPaymentMethodSubOption] | None = None
class LandingDiscountInfo(BaseModel):
percent: int # default discount
ends_at: str # ISO datetime
badge_text: str | None = None # resolved locale text
class LandingConfigResponse(BaseModel):
slug: str
title: str
subtitle: str | None = None
features: list[LandingFeature]
footer_text: str | None = None
tariffs: list[LandingTariff]
payment_methods: list[LandingPaymentMethod]
gift_enabled: bool
custom_css: str | None = None
meta_title: str | None = None
meta_description: str | None = None
discount: LandingDiscountInfo | None = None # null if no active discount
background_config: dict | None = None
sticky_pay_button: bool = False
analytics_view_enabled: bool = False
analytics_view_goal: str | None = None
analytics_click_enabled: bool = False
analytics_click_goal: str | None = None
_EMAIL_RE = re.compile(r'^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$')
_TELEGRAM_RE = re.compile(r'^@?[a-zA-Z][a-zA-Z0-9_]{4,31}$')
def _validate_contact(contact_type: str, contact_value: str) -> None:
"""Validate contact value matches the declared type format."""
if contact_type == 'email' and not _EMAIL_RE.match(contact_value):
raise ValueError('Invalid email format')
if contact_type == 'telegram' and not _TELEGRAM_RE.match(contact_value):
raise ValueError('Invalid Telegram username format')
class PurchaseRequest(BaseModel):
tariff_id: int
period_days: int
contact_type: str = Field(pattern=r'^(email|telegram)$')
contact_value: str = Field(min_length=1, max_length=255)
payment_method: str = Field(min_length=1, max_length=50, pattern=r'^[a-z0-9_]+$')
is_gift: bool = False
gift_recipient_type: str | None = Field(default=None, pattern=r'^(email|telegram)$')
gift_recipient_value: str | None = Field(default=None, max_length=255)
gift_message: str | None = Field(default=None, max_length=1000)
yandex_cid: str | None = Field(default=None, max_length=128, pattern=r'^[A-Za-z0-9._:-]{4,128}$')
referrer: str | None = Field(default=None, max_length=500)
subid: str | None = Field(default=None, max_length=255)
@model_validator(mode='after')
def validate_contacts(self) -> 'PurchaseRequest':
_validate_contact(self.contact_type, self.contact_value)
if self.is_gift:
if not self.gift_recipient_type or not self.gift_recipient_value:
raise ValueError('Gift recipient type and value are required for gift purchases')
_validate_contact(self.gift_recipient_type, self.gift_recipient_value)
return self
class PurchaseResponse(BaseModel):
purchase_token: str
payment_url: str
class PurchaseStatusResponse(BaseModel):
status: str
subscription_url: str | None = None
subscription_crypto_link: str | None = None
is_gift: bool = False
contact_value: str | None = None
recipient_contact_value: str | None = None
period_days: int | None = None
tariff_name: str | None = None
gift_message: str | None = None
contact_type: str | None = None
cabinet_email: str | None = None
cabinet_password: str | None = None
auto_login_token: str | None = None
recipient_in_bot: bool | None = None
bot_link: str | None = None
# ============ Helpers ============
def _mask_contact(value: str) -> str:
"""Mask contact value to avoid leaking PII in API responses."""
if '@' in value and not value.startswith('@'):
# Email: show first 2 chars + mask + domain
local, domain = value.rsplit('@', 1)
return f'{local[:2]}***@{domain}'
if value.startswith('@'):
# Telegram: show first 3 chars + mask
return f'{value[:3]}***'
return value[:3] + '***'
_SUBSCRIPTION_URL_EXPIRY_HOURS = 24
def _build_purchase_status_response(purchase: GuestPurchase) -> PurchaseStatusResponse:
"""Build a PurchaseStatusResponse from a GuestPurchase record."""
tariff_name = purchase.tariff.name if purchase.tariff else None
within_ttl = False
subscription_url = None
subscription_crypto_link = None
if purchase.delivered_at and purchase.subscription_url and not purchase.is_gift:
age = datetime.now(UTC) - purchase.delivered_at
if age < timedelta(hours=_SUBSCRIPTION_URL_EXPIRY_HOURS):
within_ttl = True
subscription_url = purchase.subscription_url
subscription_crypto_link = purchase.subscription_crypto_link
masked_contact = _mask_contact(purchase.contact_value) if purchase.contact_value else None
recipient_contact_value = None
gift_message = None
if purchase.is_gift:
if purchase.gift_recipient_value:
recipient_contact_value = _mask_contact(purchase.gift_recipient_value)
gift_message = purchase.gift_message
# Determine effective contact type for the recipient
if purchase.is_gift and purchase.gift_recipient_type:
effective_contact_type = purchase.gift_recipient_type
else:
effective_contact_type = purchase.contact_type
# Cabinet credentials for email self-purchases (not gifts)
cabinet_email = None
cabinet_password = None
auto_login_token = None
is_terminal = purchase.status in (GuestPurchaseStatus.DELIVERED.value, GuestPurchaseStatus.PENDING_ACTIVATION.value)
is_email_self_purchase = effective_contact_type == 'email' and not purchase.is_gift
if is_terminal and is_email_self_purchase:
cabinet_email = purchase.contact_value
# For PENDING_ACTIVATION: cap credential exposure at 72h from paid_at
pending_within_ttl = (
purchase.status == GuestPurchaseStatus.PENDING_ACTIVATION.value
and purchase.paid_at
and (datetime.now(UTC) - purchase.paid_at) < timedelta(hours=72)
)
if within_ttl or pending_within_ttl:
cabinet_password = purchase.cabinet_password
auto_login_token = purchase.auto_login_token
# For telegram gifts: indicate whether recipient is known to the bot
recipient_in_bot: bool | None = None
bot_link: str | None = None
if purchase.is_gift and effective_contact_type == 'telegram':
recipient_in_bot = purchase.user is not None and purchase.user.telegram_id is not None
if not recipient_in_bot:
bot_username = settings.get_bot_username()
if bot_username:
bot_link = f'https://t.me/{bot_username}'
return PurchaseStatusResponse(
status=purchase.status,
subscription_url=subscription_url,
subscription_crypto_link=subscription_crypto_link,
is_gift=purchase.is_gift,
contact_value=masked_contact,
recipient_contact_value=recipient_contact_value,
period_days=purchase.period_days,
tariff_name=tariff_name,
gift_message=gift_message,
contact_type=effective_contact_type,
cabinet_email=cabinet_email,
cabinet_password=cabinet_password,
auto_login_token=auto_login_token,
recipient_in_bot=recipient_in_bot,
bot_link=bot_link,
)
def _period_label(days: int) -> str:
"""Human-readable label for a period in days."""
if days == 1:
return '1 day'
if days <= 6:
return f'{days} days'
if days == 7:
return '1 week'
if days == 14:
return '2 weeks'
if days == 30:
return '1 month'
if days == 60:
return '2 months'
if days == 90:
return '3 months'
if days == 180:
return '6 months'
if days == 365:
return '1 year'
if days == 456:
return '1 year + 3 mo.'
months = days // 30
remainder = days % 30
if months > 0 and remainder == 0:
return f'{months} mo.'
if months > 0:
return f'{months} mo. + {remainder} d.'
return f'{days} days'
def _get_active_discount(landing: LandingPage, lang: str) -> LandingDiscountInfo | None:
"""Return discount info if currently active, else None."""
if not landing.discount_percent or not landing.discount_starts_at or not landing.discount_ends_at:
return None
now = datetime.now(UTC)
if not (landing.discount_starts_at <= now < landing.discount_ends_at):
return None
badge = resolve_locale_text(landing.discount_badge_text, lang) if landing.discount_badge_text else None
return LandingDiscountInfo(
percent=landing.discount_percent,
ends_at=landing.discount_ends_at.isoformat(),
badge_text=badge or None,
)
async def _load_landing_tariffs(
db: AsyncSession, landing: LandingPage, discount: LandingDiscountInfo | None = None
) -> list[LandingTariff]:
"""Load tariffs for a landing page, filtered by allowed IDs and periods."""
allowed_ids = landing.allowed_tariff_ids or []
if not allowed_ids:
return []
result = await db.execute(
select(Tariff)
.where(Tariff.id.in_(allowed_ids), Tariff.is_active.is_(True))
.order_by(Tariff.display_order, Tariff.id)
)
tariffs = result.scalars().all()
allowed_periods = landing.allowed_periods or {}
landing_tariffs = []
for tariff in tariffs:
# Determine which periods to show
tariff_period_override = allowed_periods.get(str(tariff.id))
if tariff_period_override is not None:
period_days_list = sorted(tariff_period_override)
else:
period_days_list = tariff.get_available_periods()
periods = []
for days in period_days_list:
price = tariff.get_price_for_period(days)
if price is None:
continue
original_price_kopeks = None
original_price_label = None
effective_discount = None
if discount:
# Per-tariff override takes priority (read from landing model, not response DTO)
overrides = landing.discount_overrides or {}
tariff_override = overrides.get(str(tariff.id))
effective_discount = tariff_override if tariff_override is not None else discount.percent
original_price_kopeks = price
original_price_label = settings.format_price(price)
from app.services.pricing_engine import PricingEngine
price = max(1, PricingEngine.apply_discount(price, effective_discount))
periods.append(
LandingTariffPeriod(
days=days,
label=_period_label(days),
price_kopeks=price,
price_label=settings.format_price(price),
original_price_kopeks=original_price_kopeks,
original_price_label=original_price_label,
discount_percent=effective_discount,
)
)
if not periods:
continue
landing_tariffs.append(
LandingTariff(
id=tariff.id,
name=tariff.name,
description=tariff.description,
traffic_limit_gb=tariff.traffic_limit_gb,
device_limit=tariff.device_limit,
tier_level=tariff.tier_level,
periods=periods,
)
)
return landing_tariffs
# ============ Routes ============
# IMPORTANT: /purchase/{token} must come BEFORE /{slug} to avoid shadowing
# (FastAPI checks routes in definition order; "purchase" would match {slug})
@router.get('/purchase/{token}', response_model=PurchaseStatusResponse)
async def get_purchase_status(
token: str,
raw_request: Request,
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get the status of a guest purchase by token.
No authentication required.
"""
client_ip = get_client_ip(raw_request)
if await RateLimitCache.is_ip_rate_limited(client_ip, 'purchase_status', limit=30, window=60, fail_closed=True):
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
purchase = await get_purchase_by_token(db, token)
if purchase is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Purchase not found',
)
response = _build_purchase_status_response(purchase)
# Cleanup: null expired credentials from DB
needs_cleanup = False
if purchase.delivered_at and (purchase.cabinet_password or purchase.auto_login_token):
age = datetime.now(UTC) - purchase.delivered_at
if age >= timedelta(hours=_SUBSCRIPTION_URL_EXPIRY_HOURS):
needs_cleanup = True
elif (
purchase.status == GuestPurchaseStatus.PENDING_ACTIVATION.value
and purchase.paid_at
and (purchase.cabinet_password or purchase.auto_login_token)
and (datetime.now(UTC) - purchase.paid_at) >= timedelta(hours=72)
):
needs_cleanup = True
if needs_cleanup:
purchase.cabinet_password = None
purchase.auto_login_token = None
await db.commit()
return response
@router.post('/activate/{token}', response_model=PurchaseStatusResponse)
async def activate_purchase(
token: str,
raw_request: Request,
db: AsyncSession = Depends(get_cabinet_db),
):
"""Activate a pending guest purchase, replacing the user's current subscription.
No authentication required (token is the secret).
"""
client_ip = get_client_ip(raw_request)
if await RateLimitCache.is_ip_rate_limited(client_ip, 'activate_purchase', limit=5, window=60, fail_closed=True):
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
try:
purchase = await activate_guest_purchase(db, token)
except GuestPurchaseError as exc:
raise HTTPException(status_code=exc.status_code, detail=exc.message) from exc
return _build_purchase_status_response(purchase)
@router.get('/{slug}', response_model=LandingConfigResponse)
async def get_landing_config(
raw_request: Request,
slug: str = Path(max_length=100),
lang: str = Query(DEFAULT_LOCALE, max_length=5, description='Locale: ru, en, zh, fa'),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get public landing page configuration with tariffs and payment methods.
No authentication required. Pass ``?lang=en`` to get localized text.
"""
client_ip = get_client_ip(raw_request)
if await RateLimitCache.is_ip_rate_limited(client_ip, 'landing_config', limit=60, window=60, fail_closed=True):
raise HTTPException(status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail='Too many requests')
landing = await get_active_landing_by_slug(db, slug)
if landing is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Landing page not found',
)
discount = _get_active_discount(landing, lang)
tariffs = await _load_landing_tariffs(db, landing, discount)
# Build payment methods from landing config
raw_methods = landing.payment_methods or []
method_defaults = _get_method_defaults()
payment_methods: list[LandingPaymentMethod] = []
for m in raw_methods:
method_id = m.get('method_id', '')
raw_sub_options = m.get('sub_options') # dict[str, bool] | None
# Resolve sub-options: filter enabled ones and attach display names
resolved_sub_options: list[LandingPaymentMethodSubOption] | None = None
method_def = method_defaults.get(method_id)
available = method_def.get('available_sub_options') if method_def else None
if available:
resolved = []
for opt in available:
opt_id = opt['id']
# If landing has explicit sub_options config, respect it; otherwise all enabled
if raw_sub_options is None or raw_sub_options.get(opt_id, True):
resolved.append(LandingPaymentMethodSubOption(id=opt_id, name=opt['name']))
if resolved:
resolved_sub_options = resolved
payment_methods.append(
LandingPaymentMethod(
method_id=method_id,
display_name=m.get('display_name', ''),
description=m.get('description'),
icon_url=m.get('icon_url'),
sort_order=m.get('sort_order', 0),
min_amount_kopeks=m.get('min_amount_kopeks'),
max_amount_kopeks=m.get('max_amount_kopeks'),
currency=m.get('currency'),
sub_options=resolved_sub_options,
)
)
# Resolve locale dicts to flat strings for the requested language
features = [
LandingFeature(
icon=f.get('icon', ''),
title=resolve_locale_text(f.get('title'), lang),
description=resolve_locale_text(f.get('description'), lang),
)
for f in (landing.features or [])
]
return LandingConfigResponse(
slug=landing.slug,
title=resolve_locale_text(landing.title, lang),
subtitle=resolve_locale_text(landing.subtitle, lang) or None,
features=features,
footer_text=resolve_locale_text(landing.footer_text, lang) or None,
tariffs=tariffs,
payment_methods=payment_methods,
gift_enabled=landing.gift_enabled,
custom_css=landing.custom_css,
meta_title=resolve_locale_text(landing.meta_title, lang) or None,
meta_description=resolve_locale_text(landing.meta_description, lang) or None,
discount=discount,
background_config=landing.background_config,
sticky_pay_button=landing.sticky_pay_button,
analytics_view_enabled=landing.analytics_view_enabled,
analytics_view_goal=landing.analytics_view_goal,
analytics_click_enabled=landing.analytics_click_enabled,
analytics_click_goal=landing.analytics_click_goal,
)
@router.post('/{slug}/purchase', response_model=PurchaseResponse)
async def create_landing_purchase(
slug: str,
body: PurchaseRequest,
raw_request: Request,
db: AsyncSession = Depends(get_cabinet_db),
):
"""Create a guest purchase on a landing page.
No authentication required.
"""
client_ip = get_client_ip(raw_request)
if await RateLimitCache.is_ip_rate_limited(client_ip, 'landing_purchase', limit=30, window=60, fail_closed=True):
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail='Too many purchase attempts, please try again later',
)
landing = await get_active_landing_by_slug(db, slug)
if landing is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Landing page not found',
)
if body.is_gift and not landing.gift_enabled:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Gift purchases are not enabled for this landing page',
)
# Validate payment method is available on this landing.
# The frontend may send a suffixed method ID (e.g. "platega_2", "yookassa_sbp")
# to select a specific sub-option. We match against the base method_id and
# validate the suffix against known & enabled sub-options.
raw_methods = landing.payment_methods or []
method_defaults = _get_method_defaults()
method_config = next((m for m in raw_methods if m.get('method_id') == body.payment_method), None)
if method_config is None:
# Try matching by prefix: "platega_2" → base "platega"
# Sort by length descending so "freekassa_sbp" is checked before "freekassa"
sorted_methods = sorted(raw_methods, key=lambda m: len(m.get('method_id', '')), reverse=True)
for m in sorted_methods:
mid = m.get('method_id', '')
if body.payment_method.startswith(mid + '_'):
suffix = body.payment_method[len(mid) + 1 :]
# Validate suffix is a known sub-option
method_def = method_defaults.get(mid)
available = (method_def.get('available_sub_options') if method_def else None) or []
valid_ids = {opt['id'] for opt in available}
if suffix not in valid_ids:
break # invalid suffix → reject
# Validate suffix is enabled on this landing
raw_sub_options = m.get('sub_options') # dict[str, bool] | None
if raw_sub_options is not None and not raw_sub_options.get(suffix, True):
break # disabled sub-option → reject
method_config = m
break
if method_config is None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Payment method is not available on this landing page',
)
# Validate tariff + period + calculate price
try:
tariff, amount_kopeks = await validate_and_calculate(db, landing, body.tariff_id, body.period_days)
except GuestPurchaseError as exc:
raise HTTPException(status_code=exc.status_code, detail=exc.message) from exc
# Gift purchases require the tariff to be visible in the gift section
if body.is_gift and not tariff.show_in_gift:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='This tariff is not available for gift purchases',
)
# Validate amount against per-method min/max limits (before creating purchase record)
min_amount = method_config.get('min_amount_kopeks')
max_amount = method_config.get('max_amount_kopeks')
if min_amount is not None and amount_kopeks < min_amount:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Amount is below the minimum ({settings.format_price(min_amount)}) for this payment method',
)
if max_amount is not None and amount_kopeks > max_amount:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Amount exceeds the maximum ({settings.format_price(max_amount)}) for this payment method',
)
# Create purchase record (no commit yet — wait for payment creation)
purchase = await create_purchase(
db,
landing=landing,
tariff=tariff,
period_days=body.period_days,
amount_kopeks=amount_kopeks,
contact_type=body.contact_type,
contact_value=body.contact_value,
payment_method=body.payment_method,
is_gift=body.is_gift,
gift_recipient_type=body.gift_recipient_type,
gift_recipient_value=body.gift_recipient_value,
gift_message=body.gift_message,
subid=body.subid,
referrer=body.referrer,
commit=False,
)
# Fallback to HTTP Referer header if body did not supply one
if not purchase.referrer:
http_referrer = raw_request.headers.get('referer') or raw_request.headers.get('referrer')
if http_referrer and len(http_referrer) <= 500:
purchase.referrer = http_referrer
# Determine return URL: per-method override → default cabinet URL
cabinet_base = (settings.CABINET_URL or '').rstrip('/')
default_return_url = f'{cabinet_base}/buy/success/{purchase.token}'
method_return_url = method_config.get('return_url')
if method_return_url:
# Allow {token} placeholder in custom return URLs
return_url = method_return_url.replace('{token}', purchase.token)
else:
return_url = default_return_url
payment_service = PaymentService()
payment_result = await payment_service.create_guest_payment(
db=db,
amount_kopeks=amount_kopeks,
payment_method=body.payment_method,
description=f'{tariff.name}{body.period_days}d',
purchase_token=purchase.token,
return_url=return_url,
)
if payment_result is None:
await db.rollback()
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail='Payment provider is unavailable, please try again later',
)
payment_url = payment_result.get('payment_url')
if not payment_url:
await db.rollback()
logger.error(
'Payment created but no payment_url returned',
purchase_token=purchase.token[:5],
provider=payment_result.get('provider'),
)
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail='Payment provider returned an invalid response',
)
await db.commit()
await db.refresh(purchase)
# Persist Yandex CID in cache so fulfill_purchase can link it to the user later
if body.yandex_cid and settings.YANDEX_OFFLINE_CONV_ENABLED:
try:
await cache.set(f'yacid:purchase:{purchase.token}', body.yandex_cid, expire=86400)
except Exception:
pass
# Persist subid in cache for S2S postback
if body.subid:
try:
await cache.set(f'subid:purchase:{purchase.token}', body.subid, expire=86400)
except Exception:
pass
return PurchaseResponse(
purchase_token=purchase.token,
payment_url=payment_url,
)
+203
View File
@@ -0,0 +1,203 @@
"""Media upload/download routes for cabinet tickets."""
import mimetypes
import structlog
from aiogram.types import BufferedInputFile
from fastapi import APIRouter, Depends, File, Form, HTTPException, Request, Response, UploadFile, status
from pydantic import BaseModel
from app.bot_factory import create_bot
from app.config import settings
from app.database.models import User
from ..dependencies import get_current_cabinet_user
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/media', tags=['Cabinet Media'])
ALLOWED_MEDIA_TYPES = {'photo', 'video', 'document'}
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
class MediaUploadResponse(BaseModel):
"""Response after successful media upload."""
media_type: str
file_id: str
file_unique_id: str | None = None
media_url: str
def _resolve_target_chat_id() -> int:
"""Get chat ID for uploading files (notification channel or first admin)."""
chat_id = settings.get_admin_notifications_chat_id()
if chat_id is not None:
return chat_id
admin_ids = settings.get_admin_ids()
if admin_ids:
return admin_ids[0]
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='No chat configured for file uploads',
)
def _build_media_url(request: Request, file_id: str) -> str:
"""Build URL for downloading media."""
return str(request.url_for('cabinet_download_media', file_id=file_id))
@router.post('/upload', response_model=MediaUploadResponse, status_code=status.HTTP_201_CREATED)
async def upload_media(
request: Request,
user: User = Depends(get_current_cabinet_user),
file: UploadFile = File(...),
media_type: str = Form('photo', description='File type: photo, video, or document'),
):
"""
Upload media file for use in ticket messages.
Returns file_id that can be used when creating ticket or adding message.
"""
media_type_normalized = (media_type or '').strip().lower()
if media_type_normalized not in ALLOWED_MEDIA_TYPES:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'Unsupported media type. Allowed: {", ".join(ALLOWED_MEDIA_TYPES)}',
)
# Read and validate file
file_bytes = await file.read()
if not file_bytes:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='File is empty',
)
if len(file_bytes) > MAX_FILE_SIZE:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f'File too large. Maximum size: {MAX_FILE_SIZE // 1024 // 1024}MB',
)
# Validate content type for photos
if media_type_normalized == 'photo':
allowed_image_types = {'image/jpeg', 'image/png', 'image/gif', 'image/webp'}
if file.content_type and file.content_type not in allowed_image_types:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid image type. Allowed: JPEG, PNG, GIF, WebP',
)
target_chat_id = _resolve_target_chat_id()
upload = BufferedInputFile(file_bytes, filename=file.filename or 'upload')
bot = create_bot()
try:
# Send with disable_notification to avoid pinging admins — this is just staging
if media_type_normalized == 'photo':
message = await bot.send_photo(
chat_id=target_chat_id,
photo=upload,
disable_notification=True,
)
media = message.photo[-1]
elif media_type_normalized == 'video':
message = await bot.send_video(
chat_id=target_chat_id,
video=upload,
disable_notification=True,
)
media = message.video
else:
message = await bot.send_document(
chat_id=target_chat_id,
document=upload,
disable_notification=True,
)
media = message.document
# Delete the staging message immediately — file_id persists after deletion
try:
await bot.delete_message(chat_id=target_chat_id, message_id=message.message_id)
except Exception:
pass # Best-effort cleanup — file_id is already captured
media_url = _build_media_url(request, media.file_id)
logger.info(
'User uploaded',
telegram_id=user.telegram_id,
media_type_normalized=media_type_normalized,
file_id=media.file_id,
)
return MediaUploadResponse(
media_type=media_type_normalized,
file_id=media.file_id,
file_unique_id=getattr(media, 'file_unique_id', None),
media_url=media_url,
)
except HTTPException:
raise
except Exception as error:
logger.error('Failed to upload media for user', telegram_id=user.telegram_id, error=error)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to upload media',
) from error
finally:
await bot.session.close()
@router.get('/{file_id}', name='cabinet_download_media')
async def download_media(
file_id: str,
) -> Response:
"""
Download media file by file_id.
Used to display images/documents in ticket messages.
"""
bot = create_bot()
try:
file = await bot.get_file(file_id)
if not file.file_path:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Media file not found',
)
buffer = await bot.download_file(file.file_path)
if hasattr(buffer, 'seek'):
buffer.seek(0)
content = buffer.read() if hasattr(buffer, 'read') else bytes(buffer)
filename = file.file_path.split('/')[-1]
media_type = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
return Response(
content=content,
media_type=media_type,
headers={
'Content-Disposition': f'inline; filename={filename}',
'Cache-Control': 'public, max-age=86400', # Cache for 24 hours
},
)
except HTTPException:
raise
except Exception as error:
logger.error('Failed to download media', file_id=file_id, error=error)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to download media',
) from error
finally:
await bot.session.close()
+177
View File
@@ -0,0 +1,177 @@
"""Public news routes for cabinet - user-facing news/blog section."""
import time
from typing import Any
import structlog
from fastapi import APIRouter, Depends, HTTPException, Path, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.news import (
get_news_article_by_slug,
get_news_categories,
get_published_news,
get_published_news_count,
increment_views,
)
from app.database.models import NewsArticle, User
from ..dependencies import get_cabinet_db, get_current_cabinet_user
from ..schemas.news import (
NewsArticleListItem,
NewsArticleResponse,
NewsListResponse,
)
logger = structlog.get_logger(__name__)
# Slug constraint: alphanumeric, hyphens, underscores, max 500 chars
_SLUG_MAX_LENGTH: int = 500
_SLUG_PATTERN: str = r'^[a-zA-Z0-9_-]+$'
# --- View counter deduplication ---
# In-memory TTL cache to prevent a single user from inflating view counts.
# Key: (user_id, article_id), Value: timestamp of last counted view.
# Views from the same user on the same article within _VIEW_DEDUP_SECONDS are ignored.
_VIEW_DEDUP_SECONDS: int = 300 # 5 minutes
_VIEW_DEDUP_MAX_SIZE: int = 10_000 # max entries before eviction
_view_dedup_cache: dict[tuple[int, int], float] = {}
def _should_count_view(user_id: int, article_id: int) -> bool:
"""Return True if this view should be counted (not a duplicate within TTL)."""
now = time.monotonic()
key = (user_id, article_id)
last_seen = _view_dedup_cache.get(key)
if last_seen is not None and (now - last_seen) < _VIEW_DEDUP_SECONDS:
return False
# Evict stale entries if cache grows too large
if len(_view_dedup_cache) >= _VIEW_DEDUP_MAX_SIZE:
cutoff = now - _VIEW_DEDUP_SECONDS
stale_keys = [k for k, v in _view_dedup_cache.items() if v < cutoff]
for k in stale_keys:
del _view_dedup_cache[k]
_view_dedup_cache[key] = now
return True
router = APIRouter(prefix='/news', tags=['Cabinet News'])
def _article_to_response(article: NewsArticle, *, include_content: bool = True) -> dict[str, Any]:
"""Convert NewsArticle ORM instance to response dict.
``author_name`` is only resolved when ``include_content=True`` (single-article
detail view) because the author relationship is not eagerly loaded for list
queries -- accessing it there would trigger a lazy-load or raise
``MissingGreenlet`` in async context.
"""
data: dict[str, Any] = {
'id': article.id,
'title': article.title,
'slug': article.slug,
'excerpt': article.excerpt,
'category': article.category,
'category_color': article.category_color,
'tag': article.tag,
'featured_image_url': article.featured_image_url,
'is_published': article.is_published,
'is_featured': article.is_featured,
'published_at': article.published_at,
'read_time_minutes': article.read_time_minutes,
'views_count': article.views_count,
}
if include_content:
author_name: str | None = None
if article.author:
author_name = article.author.first_name or article.author.username or f'#{article.author.id}'
data['content'] = article.content
data['author_name'] = author_name
data['created_at'] = article.created_at
data['updated_at'] = article.updated_at
return data
# NOTE: /categories MUST be declared before /{slug} to avoid route conflict
@router.get('/categories', response_model=list[str])
async def list_categories(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> list[str]:
"""Get list of distinct news categories."""
try:
return await get_news_categories(db)
except Exception:
logger.exception('Failed to get news categories')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load categories',
)
@router.get('', response_model=NewsListResponse)
async def list_published_news(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
category: str | None = Query(None, max_length=100),
limit: int = Query(20, ge=1, le=100),
offset: int = Query(0, ge=0),
) -> NewsListResponse:
"""Get paginated list of published news articles.
SQLAlchemy AsyncSession does not support concurrent operations, so
queries run sequentially.
"""
try:
articles = await get_published_news(db, category=category, limit=limit, offset=offset)
total = await get_published_news_count(db, category=category)
categories = await get_news_categories(db)
items = [NewsArticleListItem(**_article_to_response(a, include_content=False)) for a in articles]
return NewsListResponse(items=items, total=total, categories=categories)
except HTTPException:
raise
except Exception:
logger.exception('Failed to list published news')
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to load news',
)
@router.get('/{slug}', response_model=NewsArticleResponse)
async def get_article_by_slug(
slug: str = Path(..., max_length=_SLUG_MAX_LENGTH, pattern=_SLUG_PATTERN),
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> NewsArticleResponse:
"""Get a single published news article by slug. Increments view count."""
article = await get_news_article_by_slug(db, slug)
if not article or not article.is_published:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Article not found',
)
# Build response dict while session attributes are still loaded.
# increment_views() calls db.commit() which expires all ORM attributes;
# accessing them afterwards triggers lazy-load → MissingGreenlet in async.
response_data = _article_to_response(article, include_content=True)
# Increment views with per-user deduplication (5-min TTL).
if _should_count_view(user.id, article.id):
try:
new_count = await increment_views(db, article.id)
response_data['views_count'] = new_count
except Exception:
logger.warning('Failed to increment views', article_id=article.id)
return NewsArticleResponse(**response_data)
+151
View File
@@ -0,0 +1,151 @@
"""Notification settings routes for cabinet."""
from datetime import UTC, datetime
from typing import Any
import structlog
from fastapi import APIRouter, Depends
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import User
from ..dependencies import get_cabinet_db, get_current_cabinet_user
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/notifications', tags=['Cabinet Notifications'])
# ============ Schemas ============
class NotificationSettingsResponse(BaseModel):
"""User notification settings."""
subscription_expiry_enabled: bool = True
subscription_expiry_days: int = 3
traffic_warning_enabled: bool = True
traffic_warning_percent: int = 80
balance_low_enabled: bool = False
balance_low_threshold: int = 100 # kopeks
news_enabled: bool = True
promo_offers_enabled: bool = True
class NotificationSettingsUpdate(BaseModel):
"""Update notification settings."""
subscription_expiry_enabled: bool | None = None
subscription_expiry_days: int | None = Field(None, ge=1, le=30)
traffic_warning_enabled: bool | None = None
traffic_warning_percent: int | None = Field(None, ge=50, le=99)
balance_low_enabled: bool | None = None
balance_low_threshold: int | None = Field(None, ge=0)
news_enabled: bool | None = None
promo_offers_enabled: bool | None = None
# ============ Helpers ============
def _get_notification_settings(user: User) -> dict[str, Any]:
"""Get notification settings from user object."""
# Try to get from user's settings field or use defaults
settings_data = getattr(user, 'notification_settings', None) or {}
return {
'subscription_expiry_enabled': settings_data.get('subscription_expiry_enabled', True),
'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', 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),
}
def _update_notification_settings(user: User, updates: dict[str, Any]) -> dict[str, Any]:
"""Update notification settings on user object."""
current_settings = _get_notification_settings(user)
for key, value in updates.items():
if value is not None:
current_settings[key] = value
return current_settings
# ============ Routes ============
@router.get('', response_model=NotificationSettingsResponse)
async def get_notification_settings(
user: User = Depends(get_current_cabinet_user),
):
"""Get user's notification settings."""
settings = _get_notification_settings(user)
return NotificationSettingsResponse(**settings)
@router.patch('', response_model=NotificationSettingsResponse)
async def update_notification_settings(
request: NotificationSettingsUpdate,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Update user's notification settings."""
updates = request.model_dump(exclude_unset=True)
if not updates:
# No updates provided, return current settings
settings = _get_notification_settings(user)
return NotificationSettingsResponse(**settings)
# Update settings
new_settings = _update_notification_settings(user, updates)
# Store in user object
if not hasattr(user, 'notification_settings') or user.notification_settings is None:
user.notification_settings = {}
user.notification_settings = new_settings
user.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(user)
return NotificationSettingsResponse(**new_settings)
@router.post('/test')
async def send_test_notification(
user: User = Depends(get_current_cabinet_user),
):
"""Send a test notification to the user."""
# This would typically trigger a notification via Telegram bot
# For now, just return success
return {
'success': True,
'message': 'Test notification request received. You will receive a test message shortly.',
}
@router.get('/history')
async def get_notification_history(
limit: int = 20,
offset: int = 0,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get user's notification history."""
# For now, return empty list - notification history can be implemented later
# when there's a notification log table
return {
'notifications': [],
'total': 0,
'limit': limit,
'offset': offset,
}
+252
View File
@@ -0,0 +1,252 @@
"""OAuth 2.0 authentication routes for cabinet."""
from datetime import UTC, datetime
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.user import (
create_user_by_oauth,
get_user_by_email,
get_user_by_oauth_provider,
get_user_by_referral_code,
set_user_oauth_provider_id,
)
from app.database.models import User
from ..auth.oauth_providers import (
OAuthUserInfo,
generate_oauth_state,
get_provider,
validate_oauth_state,
)
from ..dependencies import get_cabinet_db
from ..routes.account_linking import OAuthProviderName
from ..schemas.auth import AuthResponse
from .auth import _create_auth_response, _process_campaign_bonus, _store_refresh_token
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/auth/oauth', tags=['Cabinet OAuth'])
async def _finalize_oauth_login(
db: AsyncSession,
user: User,
provider: str,
campaign_slug: str | None = None,
referral_code: str | None = None,
*,
is_new_user: bool = False,
) -> AuthResponse:
"""Update last login, create tokens, store refresh token."""
user.cabinet_last_login = datetime.now(UTC)
await db.commit()
auth_response = await _create_auth_response(user, db)
await _store_refresh_token(db, user.id, auth_response.refresh_token, device_info=f'oauth:{provider}')
# Process referral code (only for new users — existing users cannot be assigned a referrer)
from .auth import _process_referral_code, _user_to_response
await _process_referral_code(db, user, referral_code, is_new_user=is_new_user)
auth_response.campaign_bonus = await _process_campaign_bonus(db, user, campaign_slug)
if auth_response.campaign_bonus:
auth_response.user = _user_to_response(user)
return auth_response
# --- Schemas ---
class OAuthProviderInfo(BaseModel):
name: str
display_name: str
class OAuthProvidersResponse(BaseModel):
providers: list[OAuthProviderInfo]
class OAuthAuthorizeResponse(BaseModel):
authorize_url: str
state: str
class OAuthCallbackRequest(BaseModel):
code: str = Field(..., min_length=1, max_length=2048, description='Authorization code from provider')
state: str = Field(..., min_length=1, max_length=128, description='CSRF state token')
device_id: str | None = Field(None, max_length=256, description='Device ID from VK ID callback')
campaign_slug: str | None = Field(
None, min_length=1, max_length=64, pattern=r'^[a-zA-Z0-9_-]+$', description='Campaign slug from web link'
)
referral_code: str | None = Field(
None, max_length=32, pattern=r'^[a-zA-Z0-9_-]+$', description='Referral code of inviter'
)
# --- Endpoints ---
@router.get('/providers', response_model=OAuthProvidersResponse)
async def get_oauth_providers():
"""Get list of enabled OAuth providers."""
providers_config = settings.get_oauth_providers_config()
providers = [
OAuthProviderInfo(name=name, display_name=cfg['display_name'])
for name, cfg in providers_config.items()
if cfg['enabled']
]
return OAuthProvidersResponse(providers=providers)
@router.get('/{provider}/authorize', response_model=OAuthAuthorizeResponse)
async def get_oauth_authorize_url(provider: OAuthProviderName):
"""Get authorization URL for an OAuth provider."""
oauth_provider = get_provider(provider)
if not oauth_provider:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Requested OAuth provider is not available',
)
# Generate extra state data (e.g., PKCE code_verifier for VK)
auth_extra = oauth_provider.prepare_auth_state()
state = await generate_oauth_state(provider, extra_data=auth_extra or None)
# Only pass URL-safe params (prefixed with _) to authorize URL; exclude secrets like code_verifier
url_params = {k: v for k, v in auth_extra.items() if k.startswith('_')} if auth_extra else {}
authorize_url = oauth_provider.get_authorization_url(state, **url_params)
return OAuthAuthorizeResponse(authorize_url=authorize_url, state=state)
@router.post('/{provider}/callback', response_model=AuthResponse)
async def oauth_callback(
provider: OAuthProviderName,
request: OAuthCallbackRequest,
db: AsyncSession = Depends(get_cabinet_db),
):
"""Handle OAuth callback: exchange code, find/create user, return JWT."""
# 1. Validate CSRF state and retrieve stored data (e.g., PKCE code_verifier)
state_data = await validate_oauth_state(request.state, provider)
if not state_data:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid or expired OAuth state',
)
# 1b. Reject linking-flow state tokens (must use link_provider_callback instead)
if state_data.get('linking') == 'true':
logger.warning('Linking-flow state token used in login callback', provider=provider)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='OAuth state was initiated for account linking, not login',
)
# 2. Get provider instance
oauth_provider = get_provider(provider)
if not oauth_provider:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Requested OAuth provider is not available',
)
# 3. Exchange code for tokens (pass PKCE code_verifier and device_id if present)
exchange_kwargs: dict[str, str] = {'state': request.state}
code_verifier = state_data.get('code_verifier')
if code_verifier:
exchange_kwargs['code_verifier'] = code_verifier
if request.device_id:
exchange_kwargs['device_id'] = request.device_id
try:
token_data = await oauth_provider.exchange_code(request.code, **exchange_kwargs)
except Exception as exc:
logger.error('OAuth code exchange failed', provider=provider, exc_info=True)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Failed to exchange authorization code',
) from exc
# 4. Fetch user info from provider
try:
user_info: OAuthUserInfo = await oauth_provider.get_user_info(token_data)
except Exception as exc:
logger.error('OAuth user info fetch failed', provider=provider, exc_info=True)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Failed to fetch user information from provider',
) from exc
# 5. Find user by provider ID
user = await get_user_by_oauth_provider(db, provider, user_info.provider_id)
if user:
logger.info('OAuth login for existing user', provider=provider, user_id=user.id)
return await _finalize_oauth_login(db, user, provider, request.campaign_slug, request.referral_code)
# 6. Find user by email (if verified) and link provider
if user_info.email and user_info.email_verified:
user = await get_user_by_email(db, user_info.email)
if user:
await set_user_oauth_provider_id(db, user, provider, user_info.provider_id)
logger.info('OAuth provider linked to existing email user', provider=provider, user_id=user.id)
return await _finalize_oauth_login(db, user, provider, request.campaign_slug, request.referral_code)
# 7. Resolve referral code for new user
referrer_id = None
if request.referral_code:
try:
referrer = await get_user_by_referral_code(db, request.referral_code)
if referrer:
# Self-referral protection by email
if (
user_info.email
and user_info.email_verified
and referrer.email
and referrer.email.lower() == user_info.email.lower()
):
logger.warning(
'Self-referral attempt blocked via OAuth',
referral_code=request.referral_code,
email=user_info.email,
)
else:
referrer_id = referrer.id
except Exception:
logger.warning(
'Failed to resolve referral code during OAuth', referral_code=request.referral_code, exc_info=True
)
# 8. Create new user
user = await create_user_by_oauth(
db=db,
provider=provider,
provider_id=user_info.provider_id,
email=user_info.email if user_info.email_verified else None,
email_verified=user_info.email_verified,
first_name=user_info.first_name,
last_name=user_info.last_name,
username=user_info.username,
referred_by_id=referrer_id,
)
logger.info('New OAuth user created', provider=provider, user_id=user.id)
# Commit user before panel sync (sync does its own commit/rollback)
await db.commit()
# Sync existing panel subscriptions by email (if verified)
if user_info.email and user_info.email_verified:
try:
from app.cabinet.routes.auth import _sync_subscription_from_panel_by_email
await _sync_subscription_from_panel_by_email(db, user)
except Exception:
logger.warning('Failed to sync panel subscription for new OAuth user', user_id=user.id, exc_info=True)
return await _finalize_oauth_login(
db, user, provider, request.campaign_slug, request.referral_code, is_new_user=True
)
+217
View File
@@ -0,0 +1,217 @@
"""User-facing partner application routes for cabinet."""
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.cabinet.utils.links import get_campaign_deep_link, get_campaign_web_link
from app.config import settings
from app.database.models import AdvertisingCampaign, User
from app.services.partner_application_service import partner_application_service
from app.services.partner_stats_service import PartnerStatsService
from ..dependencies import get_cabinet_db, get_current_cabinet_user
from ..schemas.partners import (
CampaignReferralItem,
DailyStatItem,
PartnerApplicationInfo,
PartnerApplicationRequest,
PartnerCampaignDetailedStats,
PartnerCampaignInfo,
PartnerStatusResponse,
PeriodChange,
PeriodComparison,
PeriodStats,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/referral/partner', tags=['Cabinet Partner'])
@router.get('/status', response_model=PartnerStatusResponse)
async def get_partner_status(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get partner status and latest application for current user."""
latest_app = await partner_application_service.get_latest_application(db, user.id)
app_info = None
if latest_app:
app_info = PartnerApplicationInfo(
id=latest_app.id,
status=latest_app.status,
company_name=latest_app.company_name,
website_url=latest_app.website_url,
telegram_channel=latest_app.telegram_channel,
description=latest_app.description,
expected_monthly_referrals=latest_app.expected_monthly_referrals,
desired_commission_percent=latest_app.desired_commission_percent,
admin_comment=latest_app.admin_comment,
approved_commission_percent=latest_app.approved_commission_percent,
created_at=latest_app.created_at,
processed_at=latest_app.processed_at,
)
commission = user.referral_commission_percent
if commission is None and user.is_partner:
commission = settings.REFERRAL_COMMISSION_PERCENT
# Fetch campaigns assigned to this partner
campaigns: list[PartnerCampaignInfo] = []
if user.is_partner:
result = await db.execute(
select(AdvertisingCampaign).where(
AdvertisingCampaign.partner_user_id == user.id,
AdvertisingCampaign.is_active.is_(True),
)
)
campaign_models = result.scalars().all()
# Fetch per-campaign stats in one batch
campaign_ids = [c.id for c in campaign_models]
campaign_stats = await PartnerStatsService.get_per_campaign_stats(db, user.id, campaign_ids)
for c in campaign_models:
stats = campaign_stats.get(c.id, {})
campaigns.append(
PartnerCampaignInfo(
id=c.id,
name=c.name,
start_parameter=c.start_parameter,
bonus_type=c.bonus_type,
balance_bonus_kopeks=c.balance_bonus_kopeks or 0,
subscription_duration_days=c.subscription_duration_days,
subscription_traffic_gb=c.subscription_traffic_gb,
deep_link=get_campaign_deep_link(c.start_parameter),
web_link=get_campaign_web_link(c.start_parameter),
registrations_count=stats.get('registrations_count', 0),
referrals_count=stats.get('referrals_count', 0),
earnings_kopeks=stats.get('earnings_kopeks', 0),
)
)
return PartnerStatusResponse(
partner_status=user.partner_status,
commission_percent=commission,
latest_application=app_info,
campaigns=campaigns,
)
@router.get('/campaigns/{campaign_id}/stats', response_model=PartnerCampaignDetailedStats)
async def get_campaign_stats(
campaign_id: int,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get detailed stats for a single campaign belonging to the current partner."""
if not user.is_partner:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Partner status required',
)
# Verify campaign belongs to this partner
campaign_result = await db.execute(
select(AdvertisingCampaign).where(
AdvertisingCampaign.id == campaign_id,
AdvertisingCampaign.partner_user_id == user.id,
)
)
campaign = campaign_result.scalar_one_or_none()
if not campaign:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Campaign not found or not assigned to you',
)
raw = await PartnerStatsService.get_campaign_detailed_stats(db, user.id, campaign_id)
return PartnerCampaignDetailedStats(
campaign_id=raw['campaign_id'],
campaign_name=campaign.name,
registrations_count=raw['registrations_count'],
referrals_count=raw['referrals_count'],
earnings_kopeks=raw['earnings_kopeks'],
conversion_rate=raw['conversion_rate'],
earnings_today=raw['earnings_today'],
earnings_week=raw['earnings_week'],
earnings_month=raw['earnings_month'],
daily_stats=[DailyStatItem(**d) for d in raw['daily_stats']],
period_comparison=PeriodComparison(
current=PeriodStats(**raw['period_comparison']['current']),
previous=PeriodStats(**raw['period_comparison']['previous']),
referrals_change=PeriodChange(**raw['period_comparison']['referrals_change']),
earnings_change=PeriodChange(**raw['period_comparison']['earnings_change']),
),
top_referrals=[CampaignReferralItem(**r) for r in raw['top_referrals']],
)
@router.post('/apply', response_model=PartnerApplicationInfo)
async def apply_for_partner(
request: PartnerApplicationRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Submit partner application."""
application, error = await partner_application_service.submit_application(
db,
user_id=user.id,
company_name=request.company_name,
website_url=request.website_url,
telegram_channel=request.telegram_channel,
description=request.description,
expected_monthly_referrals=request.expected_monthly_referrals,
desired_commission_percent=request.desired_commission_percent,
)
if not application:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error,
)
# Уведомляем админов о новой заявке
try:
from app.bot_factory import create_bot
from app.services.admin_notification_service import AdminNotificationService
if getattr(settings, 'ADMIN_NOTIFICATIONS_ENABLED', False) and settings.BOT_TOKEN:
bot = create_bot()
try:
notification_service = AdminNotificationService(bot)
await notification_service.send_partner_application_notification(
user=user,
application_data={
'company_name': request.company_name,
'telegram_channel': request.telegram_channel,
'website_url': request.website_url,
'description': request.description,
'expected_monthly_referrals': request.expected_monthly_referrals,
'desired_commission_percent': request.desired_commission_percent,
},
)
finally:
await bot.session.close()
except Exception as e:
logger.error('Failed to send admin notification for partner application', error=e)
return PartnerApplicationInfo(
id=application.id,
status=application.status,
company_name=application.company_name,
website_url=application.website_url,
telegram_channel=application.telegram_channel,
description=application.description,
expected_monthly_referrals=application.expected_monthly_referrals,
desired_commission_percent=application.desired_commission_percent,
admin_comment=application.admin_comment,
approved_commission_percent=application.approved_commission_percent,
created_at=application.created_at,
processed_at=application.processed_at,
)
+365
View File
@@ -0,0 +1,365 @@
"""Polls routes for cabinet - user participation in polls/surveys."""
from datetime import UTC, datetime
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.config import settings
from app.database.crud.poll import (
get_poll_response_by_id,
record_poll_answer,
)
from app.database.models import Poll, PollQuestion, PollResponse, User
from app.services.poll_service import get_next_question, get_question_option, reward_user_for_poll
from ..dependencies import get_cabinet_db, get_current_cabinet_user
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/polls', tags=['Cabinet Polls'])
# ============ Schemas ============
class PollOptionResponse(BaseModel):
"""Poll option."""
id: int
text: str
order: int
class PollQuestionResponse(BaseModel):
"""Poll question with options."""
id: int
text: str
order: int
options: list[PollOptionResponse]
class PollInfo(BaseModel):
"""Poll info for user."""
id: int
response_id: int
title: str
description: str | None = None
total_questions: int
answered_questions: int
is_completed: bool
reward_amount: int | None = None
class PollStartResponse(BaseModel):
"""Response when starting a poll."""
response_id: int
current_question_index: int
total_questions: int
question: PollQuestionResponse
class AnswerRequest(BaseModel):
"""Request to answer a poll question."""
option_id: int
class AnswerResponse(BaseModel):
"""Response after answering."""
success: bool
is_completed: bool
next_question: PollQuestionResponse | None = None
current_question_index: int | None = None
total_questions: int
reward_granted: int | None = None
message: str | None = None
# ============ Helpers ============
def _question_to_response(question: PollQuestion) -> PollQuestionResponse:
"""Convert question model to response."""
options = [
PollOptionResponse(
id=opt.id,
text=opt.text,
order=opt.order,
)
for opt in sorted(question.options, key=lambda o: o.order)
]
return PollQuestionResponse(
id=question.id,
text=question.text,
order=question.order,
options=options,
)
# ============ Routes ============
class PollsCountResponse(BaseModel):
"""Count of available polls."""
count: int
@router.get('/count', response_model=PollsCountResponse)
async def get_polls_count(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get count of polls available for the user."""
result = await db.execute(
select(PollResponse)
.where(PollResponse.user_id == user.id)
.where(PollResponse.completed_at.is_(None)) # Only incomplete polls
)
responses = result.scalars().all()
return PollsCountResponse(count=len(responses))
@router.get('', response_model=list[PollInfo])
async def get_available_polls(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of polls available for the user."""
# Get user's poll responses with eager loading of relationships
result = await db.execute(
select(PollResponse)
.where(PollResponse.user_id == user.id)
.options(
selectinload(PollResponse.poll).selectinload(Poll.questions),
selectinload(PollResponse.answers),
)
.order_by(PollResponse.sent_at.desc())
)
responses = result.scalars().all()
polls = []
for response in responses:
if not response.poll:
continue
answered_count = len(response.answers) if response.answers else 0
total_questions = len(response.poll.questions) if response.poll.questions else 0
# Convert kopeks to rubles for display
reward_amount = None
if response.poll.reward_amount_kopeks:
reward_amount = response.poll.reward_amount_kopeks // 100
polls.append(
PollInfo(
id=response.poll.id,
response_id=response.id,
title=response.poll.title,
description=response.poll.description,
total_questions=total_questions,
answered_questions=answered_count,
is_completed=response.completed_at is not None,
reward_amount=reward_amount,
)
)
return polls
@router.get('/{response_id}', response_model=PollInfo)
async def get_poll_details(
response_id: int,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get details of a specific poll response."""
response = await get_poll_response_by_id(db, response_id)
if not response or response.user_id != user.id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Poll not found',
)
if not response.poll:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Poll data not available',
)
answered_count = len(response.answers) if response.answers else 0
total_questions = len(response.poll.questions) if response.poll.questions else 0
# Convert kopeks to rubles for display
reward_amount = None
if response.poll.reward_amount_kopeks:
reward_amount = response.poll.reward_amount_kopeks // 100
return PollInfo(
id=response.poll.id,
response_id=response.id,
title=response.poll.title,
description=response.poll.description,
total_questions=total_questions,
answered_questions=answered_count,
is_completed=response.completed_at is not None,
reward_amount=reward_amount,
)
@router.post('/{response_id}/start', response_model=PollStartResponse)
async def start_poll(
response_id: int,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Start or continue a poll."""
response = await get_poll_response_by_id(db, response_id)
if not response or response.user_id != user.id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Poll not found',
)
if response.completed_at:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='This poll has already been completed',
)
if not response.poll or not response.poll.questions:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Poll is not available',
)
# Mark as started if not already
if not response.started_at:
response.started_at = datetime.now(UTC)
await db.commit()
# Get next unanswered question
index, question = await get_next_question(response)
if not question:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='No questions available',
)
return PollStartResponse(
response_id=response.id,
current_question_index=index,
total_questions=len(response.poll.questions),
question=_question_to_response(question),
)
@router.post('/{response_id}/questions/{question_id}/answer', response_model=AnswerResponse)
async def answer_question(
response_id: int,
question_id: int,
request: AnswerRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Submit answer for a poll question."""
response = await get_poll_response_by_id(db, response_id)
if not response or response.user_id != user.id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Poll not found',
)
if response.completed_at:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='This poll has already been completed',
)
if not response.poll:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Poll is not available',
)
# Find the question
question = next((q for q in response.poll.questions if q.id == question_id), None)
if not question:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Question not found',
)
# Validate option
option = await get_question_option(question, request.option_id)
if not option:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid answer option',
)
# Record the answer
await record_poll_answer(
db,
response_id=response.id,
question_id=question.id,
option_id=option.id,
)
# Refresh to get updated answers
try:
await db.refresh(response, attribute_names=['answers'])
except Exception:
response = await get_poll_response_by_id(db, response_id)
if not response:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to process answer',
)
# Get next question
index, next_question = await get_next_question(response)
total_questions = len(response.poll.questions)
if next_question:
# More questions to answer
return AnswerResponse(
success=True,
is_completed=False,
next_question=_question_to_response(next_question),
current_question_index=index,
total_questions=total_questions,
)
# Poll completed
response.completed_at = datetime.now(UTC)
await db.commit()
# Award reward if any
reward_amount = await reward_user_for_poll(db, response)
message = 'Thank you for completing the poll!'
if reward_amount:
message += f' Reward of {settings.format_price(reward_amount)} has been added to your balance.'
return AnswerResponse(
success=True,
is_completed=True,
total_questions=total_questions,
reward_granted=reward_amount,
message=message,
)
+420
View File
@@ -0,0 +1,420 @@
"""Promo offers routes for cabinet - personal discounts and offers."""
from datetime import UTC, datetime, timedelta
from typing import Any
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy import and_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.crud.discount_offer import (
get_offer_by_id,
mark_offer_claimed,
)
from app.database.crud.promo_group import get_auto_assign_promo_groups
from app.database.crud.promo_offer_template import get_promo_offer_template_by_id
from app.database.crud.transaction import get_user_total_spent_kopeks
from app.database.models import DiscountOffer, User
from app.services.promo_offer_service import promo_offer_service
from ..dependencies import get_cabinet_db, get_current_cabinet_user
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/promo', tags=['Cabinet Promo'])
# ============ Schemas ============
class PromoOfferInfo(BaseModel):
"""Promo offer info."""
id: int
notification_type: str
discount_percent: int | None = None
effect_type: str
expires_at: datetime
is_active: bool
is_claimed: bool
claimed_at: datetime | None = None
extra_data: dict[str, Any] | None = None
class ActiveDiscountInfo(BaseModel):
"""User's active discount info."""
discount_percent: int
source: str | None = None
expires_at: datetime | None = None
is_active: bool
class ClaimOfferRequest(BaseModel):
"""Request to claim an offer."""
offer_id: int
class ClaimOfferResponse(BaseModel):
"""Response after claiming offer."""
success: bool
message: str
discount_percent: int | None = None
expires_at: datetime | None = None
class PromoGroupDiscounts(BaseModel):
"""User's promo group discounts."""
group_name: str | None = None
server_discount_percent: int = 0
traffic_discount_percent: int = 0
device_discount_percent: int = 0
period_discounts: dict[str, int] = {}
class LoyaltyTierInfo(BaseModel):
"""Info about a single loyalty tier (promo group)."""
id: int
name: str
threshold_rubles: float
server_discount_percent: int = 0
traffic_discount_percent: int = 0
device_discount_percent: int = 0
period_discounts: dict[str, int] = {}
is_current: bool = False
is_achieved: bool = False
class LoyaltyTiersResponse(BaseModel):
"""Response with all loyalty tiers and user progress."""
tiers: list[LoyaltyTierInfo]
current_spent_rubles: float
current_tier_name: str | None = None
next_tier_name: str | None = None
next_tier_threshold_rubles: float | None = None
progress_percent: float = 0
# ============ Routes ============
@router.get('/offers', response_model=list[PromoOfferInfo])
async def get_promo_offers(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of available promo offers for the user."""
now = datetime.now(UTC)
result = await db.execute(
select(DiscountOffer)
.where(
and_(
DiscountOffer.user_id == user.id,
DiscountOffer.expires_at > now,
)
)
.order_by(DiscountOffer.created_at.desc())
)
offers = result.scalars().all()
return [
PromoOfferInfo(
id=offer.id,
notification_type=offer.notification_type or '',
discount_percent=offer.discount_percent,
effect_type=offer.effect_type or 'percent_discount',
expires_at=offer.expires_at,
is_active=offer.is_active and offer.claimed_at is None,
is_claimed=offer.claimed_at is not None,
claimed_at=offer.claimed_at,
extra_data=offer.extra_data,
)
for offer in offers
]
@router.get('/active-discount', response_model=ActiveDiscountInfo)
async def get_active_discount(
user: User = Depends(get_current_cabinet_user),
):
"""Get user's currently active discount."""
discount_percent = user.promo_offer_discount_percent or 0
expires_at = user.promo_offer_discount_expires_at
source = user.promo_offer_discount_source
now = datetime.now(UTC)
is_active = discount_percent > 0 and (expires_at is None or expires_at > now)
return ActiveDiscountInfo(
discount_percent=discount_percent if is_active else 0,
source=source,
expires_at=expires_at,
is_active=is_active,
)
@router.get('/group-discounts', response_model=PromoGroupDiscounts)
async def get_promo_group_discounts(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get user's promo group discounts."""
await db.refresh(user, ['promo_group', 'user_promo_groups'])
promo_group = user.get_primary_promo_group() if hasattr(user, 'get_primary_promo_group') else None
if not promo_group:
return PromoGroupDiscounts()
# Get period discounts
period_discounts = {}
raw_period_discounts = getattr(promo_group, 'period_discounts', None)
if isinstance(raw_period_discounts, dict):
for key, value in raw_period_discounts.items():
try:
period_discounts[str(key)] = int(value)
except (TypeError, ValueError):
continue
return PromoGroupDiscounts(
group_name=promo_group.name,
server_discount_percent=promo_group.server_discount_percent or 0,
traffic_discount_percent=promo_group.traffic_discount_percent or 0,
device_discount_percent=promo_group.device_discount_percent or 0,
period_discounts=period_discounts,
)
@router.get('/loyalty-tiers', response_model=LoyaltyTiersResponse)
async def get_loyalty_tiers(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get all loyalty tiers (promo groups with auto-assign thresholds) and user's progress."""
# Get user's total spent
total_spent_kopeks = await get_user_total_spent_kopeks(db, user.id)
total_spent_rubles = total_spent_kopeks / 100
# Get all auto-assign promo groups (sorted by threshold ascending)
auto_groups = await get_auto_assign_promo_groups(db)
tiers: list[LoyaltyTierInfo] = []
current_tier_name: str | None = None
next_tier_name: str | None = None
next_tier_threshold: float | None = None
for group in auto_groups:
threshold_kopeks = group.auto_assign_total_spent_kopeks or 0
threshold_rubles = threshold_kopeks / 100
is_achieved = total_spent_kopeks >= threshold_kopeks
# Track highest achieved tier as "current" (by spending, not by assignment)
if is_achieved:
current_tier_name = group.name
# Find next tier (first not achieved)
if not is_achieved and next_tier_name is None:
next_tier_name = group.name
next_tier_threshold = threshold_rubles
# Get period discounts
period_discounts = {}
raw_period_discounts = getattr(group, 'period_discounts', None)
if isinstance(raw_period_discounts, dict):
for key, value in raw_period_discounts.items():
try:
period_discounts[str(key)] = int(value)
except (TypeError, ValueError):
continue
tiers.append(
LoyaltyTierInfo(
id=group.id,
name=group.name,
threshold_rubles=threshold_rubles,
server_discount_percent=group.server_discount_percent or 0,
traffic_discount_percent=group.traffic_discount_percent or 0,
device_discount_percent=group.device_discount_percent or 0,
period_discounts=period_discounts,
is_current=False,
is_achieved=is_achieved,
)
)
# Mark only the highest achieved tier as "current"
for tier in reversed(tiers):
if tier.is_achieved:
tier.is_current = True
break
# Calculate progress to next tier
progress_percent = 0.0
if next_tier_threshold and next_tier_threshold > 0:
progress_percent = min(100.0, (total_spent_rubles / next_tier_threshold) * 100)
elif tiers and all(t.is_achieved for t in tiers):
# All tiers achieved
progress_percent = 100.0
return LoyaltyTiersResponse(
tiers=tiers,
current_spent_rubles=total_spent_rubles,
current_tier_name=current_tier_name,
next_tier_name=next_tier_name,
next_tier_threshold_rubles=next_tier_threshold,
progress_percent=progress_percent,
)
@router.post('/claim', response_model=ClaimOfferResponse)
async def claim_promo_offer(
request: ClaimOfferRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Claim a promo offer."""
offer = await get_offer_by_id(db, request.offer_id)
if not offer or offer.user_id != user.id:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Offer not found',
)
now = datetime.now(UTC)
if offer.claimed_at is not None:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='This offer has already been claimed',
)
if not offer.is_active or offer.expires_at <= now:
offer.is_active = False
await db.commit()
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='This offer has expired',
)
effect_type = (offer.effect_type or 'percent_discount').lower()
# Handle test access offers
if effect_type == 'test_access':
await db.refresh(user, ['subscriptions'])
success, newly_added, expires_at, error_code = await promo_offer_service.grant_test_access(
db,
user,
offer,
)
if not success:
error_messages = {
'subscription_missing': 'Active subscription required for this offer',
'squads_missing': 'Could not determine servers for test access',
'already_connected': 'These servers are already connected',
'remnawave_sync_failed': 'Failed to connect servers. Please try again later',
}
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error_messages.get(error_code, 'Failed to activate offer'),
)
await mark_offer_claimed(
db,
offer,
details={
'context': 'test_access_claim',
'new_squads': newly_added,
'expires_at': expires_at.isoformat() if expires_at else None,
},
)
return ClaimOfferResponse(
success=True,
message=f'Test access activated until {expires_at.strftime("%Y-%m-%d %H:%M") if expires_at else "unlimited"}',
expires_at=expires_at,
)
# Handle discount offers
discount_percent = int(offer.discount_percent or 0)
if discount_percent <= 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Invalid offer',
)
user.promo_offer_discount_percent = discount_percent
user.promo_offer_discount_source = offer.notification_type
user.updated_at = now
# Calculate expiration
extra_data = offer.extra_data or {}
raw_duration = extra_data.get('active_discount_hours')
template_id = extra_data.get('template_id')
if raw_duration in (None, '') and template_id:
try:
template = await get_promo_offer_template_by_id(db, int(template_id))
except (ValueError, TypeError):
template = None
if template and template.active_discount_hours:
raw_duration = template.active_discount_hours
try:
duration_hours = int(raw_duration) if raw_duration is not None else None
except (TypeError, ValueError):
duration_hours = None
if duration_hours and duration_hours > 0:
discount_expires_at = now + timedelta(hours=duration_hours)
else:
discount_expires_at = None
user.promo_offer_discount_expires_at = discount_expires_at
await mark_offer_claimed(
db,
offer,
details={
'context': 'discount_claim',
'discount_percent': discount_percent,
'discount_expires_at': discount_expires_at.isoformat() if discount_expires_at else None,
},
)
await db.refresh(user)
expires_text = ''
if discount_expires_at:
expires_text = f' Valid until {discount_expires_at.strftime("%Y-%m-%d %H:%M")}'
return ClaimOfferResponse(
success=True,
message=f'Discount of {discount_percent}% activated!{expires_text}',
discount_percent=discount_percent,
expires_at=discount_expires_at,
)
@router.delete('/active-discount')
async def clear_active_discount(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Clear user's active discount."""
user.promo_offer_discount_percent = 0
user.promo_offer_discount_source = None
user.promo_offer_discount_expires_at = None
user.updated_at = datetime.now(UTC)
await db.commit()
return {'message': 'Active discount cleared'}
+163
View File
@@ -0,0 +1,163 @@
"""Promo code routes for cabinet."""
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import User
from app.services.promocode_service import PromoCodeService
from ..dependencies import get_cabinet_db, get_current_cabinet_user
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/promocode', tags=['Cabinet Promocode'])
class PromocodeActivateRequest(BaseModel):
"""Request to activate a promo code."""
code: str = Field(..., min_length=1, max_length=50, description='Promo code to activate')
subscription_id: int | None = Field(None, description='Subscription ID for multi-tariff promo codes')
class PromocodeActivateResponse(BaseModel):
"""Response after activating a promo code."""
success: bool
message: str
balance_before: float = 0
balance_after: float = 0
bonus_description: str | None = None
class PromocodeDeactivateResponse(BaseModel):
"""Response after deactivating a discount promo code."""
success: bool
message: str
deactivated_code: str | None = None
discount_percent: int = 0
@router.post('/activate')
async def activate_promocode(
request: PromocodeActivateRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Activate a promo code for the current user."""
promocode_service = PromoCodeService()
result = await promocode_service.activate_promocode(
db=db, user_id=user.id, code=request.code.strip(), subscription_id=request.subscription_id
)
if result.get('error') == 'select_subscription':
return {
'success': False,
'error': 'select_subscription',
'eligible_subscriptions': result.get('eligible_subscriptions', []),
'code': result.get('code', request.code.strip()),
}
if result['success']:
balance_before_rubles = result.get('balance_before_kopeks', 0) / 100
balance_after_rubles = result.get('balance_after_kopeks', 0) / 100
# Send admin notification (same as bot handler)
if getattr(settings, 'ADMIN_NOTIFICATIONS_ENABLED', False) and settings.BOT_TOKEN:
try:
from aiogram import Bot
from app.services.admin_notification_service import AdminNotificationService
bot = Bot(token=settings.BOT_TOKEN)
try:
notification_service = AdminNotificationService(bot)
await notification_service.send_promocode_activation_notification(
db,
user,
result.get('promocode', {'code': request.code.strip()}),
result.get('description', ''),
result.get('balance_before_kopeks'),
result.get('balance_after_kopeks'),
)
finally:
await bot.session.close()
except Exception:
pass
return PromocodeActivateResponse(
success=True,
message='Promo code activated successfully',
balance_before=balance_before_rubles,
balance_after=balance_after_rubles,
bonus_description=result.get('description'),
)
# Map error codes to messages
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',
'no_subscription_for_days': 'This promo code requires an active or expired subscription',
'subscription_not_found': 'Subscription not found',
'not_first_purchase': 'This promo code is only available for first purchase',
'daily_limit': 'Too many promo code activations today',
'user_not_found': 'User not found',
'server_error': 'Server error occurred',
}
error_code = result.get('error', 'server_error')
error_message = error_messages.get(error_code, 'Failed to activate promo code')
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error_message,
)
@router.post('/deactivate-discount', response_model=PromocodeDeactivateResponse)
async def deactivate_discount_promocode(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> PromocodeDeactivateResponse:
"""Deactivate the currently active discount promo code for the current user."""
promocode_service = PromoCodeService()
result = await promocode_service.deactivate_discount_promocode(
db=db,
user_id=user.id,
admin_initiated=False,
)
if result['success']:
return PromocodeDeactivateResponse(
success=True,
message='Discount promo code deactivated successfully',
deactivated_code=result.get('deactivated_code'),
discount_percent=result.get('discount_percent', 0),
)
error_messages = {
'user_not_found': 'User not found',
'no_active_discount_promocode': 'No active discount promo code found',
'discount_already_expired': 'Discount has already expired',
'server_error': 'Server error occurred',
}
error_code = result.get('error', 'server_error')
error_message = error_messages.get(error_code, 'Failed to deactivate promo code')
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=error_message,
)
+253
View File
@@ -0,0 +1,253 @@
"""Referral program routes for cabinet."""
import math
import structlog
from fastapi import APIRouter, Depends, Query
from sqlalchemy import desc, func, select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from app.config import settings
from app.database.models import (
AdvertisingCampaign,
ReferralEarning,
Subscription,
SubscriptionStatus,
User,
WithdrawalRequest,
WithdrawalRequestStatus,
)
from ..dependencies import get_cabinet_db, get_current_cabinet_user
from ..schemas.referral import (
ReferralEarningResponse,
ReferralEarningsListResponse,
ReferralInfoResponse,
ReferralItemResponse,
ReferralListResponse,
ReferralTermsResponse,
)
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/referral', tags=['Cabinet Referral'])
@router.get('', response_model=ReferralInfoResponse)
async def get_referral_info(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get referral program info for current user."""
# Get total referrals count
total_query = select(func.count()).select_from(User).where(User.referred_by_id == user.id)
total_result = await db.execute(total_query)
total_referrals = total_result.scalar() or 0
# Get active referrals (with active subscription right now)
active_query = (
select(func.count(func.distinct(User.id)))
.join(Subscription, User.id == Subscription.user_id)
.where(
User.referred_by_id == user.id,
Subscription.status == SubscriptionStatus.ACTIVE.value,
Subscription.end_date > func.now(),
)
)
active_result = await db.execute(active_query)
active_referrals = active_result.scalar() or 0
# Get total earnings
earnings_query = select(func.coalesce(func.sum(ReferralEarning.amount_kopeks), 0)).where(
ReferralEarning.user_id == user.id
)
earnings_result = await db.execute(earnings_query)
total_earnings = earnings_result.scalar() or 0
# Get user's commission percent
commission_percent = user.referral_commission_percent
if commission_percent is None:
commission_percent = settings.REFERRAL_COMMISSION_PERCENT
# Get withdrawn amount (approved + completed withdrawal requests)
withdrawn_query = select(func.coalesce(func.sum(WithdrawalRequest.amount_kopeks), 0)).where(
WithdrawalRequest.user_id == user.id,
WithdrawalRequest.status.in_([WithdrawalRequestStatus.APPROVED.value, WithdrawalRequestStatus.COMPLETED.value]),
)
withdrawn_result = await db.execute(withdrawn_query)
withdrawn = withdrawn_result.scalar() or 0
# Get pending withdrawal amount
pending_query = select(func.coalesce(func.sum(WithdrawalRequest.amount_kopeks), 0)).where(
WithdrawalRequest.user_id == user.id,
WithdrawalRequest.status == WithdrawalRequestStatus.PENDING.value,
)
pending_result = await db.execute(pending_query)
pending = pending_result.scalar() or 0
# Доступный баланс: мин(кошелёк, заработано - выведено - в ожидании)
referral_entitlement = max(0, total_earnings - withdrawn - pending)
available_balance = min(user.balance_kopeks, referral_entitlement)
# Build referral links
referral_link = (settings.get_cabinet_referral_link(user.referral_code) or '') if user.referral_code else ''
bot_referral_link = settings.get_bot_referral_link(user.referral_code) if user.referral_code else ''
return ReferralInfoResponse(
referral_code=user.referral_code or '',
referral_link=referral_link,
bot_referral_link=bot_referral_link,
total_referrals=total_referrals,
active_referrals=active_referrals,
total_earnings_kopeks=total_earnings,
total_earnings_rubles=total_earnings / 100,
commission_percent=commission_percent,
available_balance_kopeks=available_balance,
available_balance_rubles=available_balance / 100,
withdrawn_kopeks=withdrawn,
)
@router.get('/list', response_model=ReferralListResponse)
async def get_referral_list(
page: int = Query(1, ge=1, description='Page number'),
per_page: int = Query(20, ge=1, le=100, description='Items per page'),
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get list of invited users."""
# Base query with eager loading of subscription relationship
query = (
select(User)
.options(selectinload(User.subscriptions).selectinload(Subscription.tariff))
.where(User.referred_by_id == user.id)
)
# Get total count
count_query = select(func.count()).select_from(User).where(User.referred_by_id == user.id)
total_result = await db.execute(count_query)
total = total_result.scalar() or 0
# Paginate
offset = (page - 1) * per_page
query = query.order_by(desc(User.created_at)).offset(offset).limit(per_page)
result = await db.execute(query)
referrals = result.scalars().all()
items = [
ReferralItemResponse(
id=r.id,
username=r.username,
first_name=r.first_name,
created_at=r.created_at,
has_subscription=bool(getattr(r, 'subscriptions', None)),
has_paid=r.has_had_paid_subscription,
)
for r in referrals
]
pages = math.ceil(total / per_page) if total > 0 else 1
return ReferralListResponse(
items=items,
total=total,
page=page,
per_page=per_page,
pages=pages,
)
@router.get('/earnings', response_model=ReferralEarningsListResponse)
async def get_referral_earnings(
page: int = Query(1, ge=1, description='Page number'),
per_page: int = Query(20, ge=1, le=100, description='Items per page'),
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Get referral earnings history."""
# Base query
query = select(ReferralEarning).where(ReferralEarning.user_id == user.id)
# Get total count and sum
count_query = select(func.count()).select_from(ReferralEarning).where(ReferralEarning.user_id == user.id)
total_result = await db.execute(count_query)
total = total_result.scalar() or 0
sum_query = select(func.coalesce(func.sum(ReferralEarning.amount_kopeks), 0)).where(
ReferralEarning.user_id == user.id
)
sum_result = await db.execute(sum_query)
total_amount = sum_result.scalar() or 0
# Paginate
offset = (page - 1) * per_page
query = query.order_by(desc(ReferralEarning.created_at)).offset(offset).limit(per_page)
result = await db.execute(query)
earnings = result.scalars().all()
# Batch-fetch referral users to avoid N+1
referral_ids = list({e.referral_id for e in earnings if e.referral_id})
if referral_ids:
referral_users_result = await db.execute(select(User).where(User.id.in_(referral_ids)))
referral_users_map = {u.id: u for u in referral_users_result.scalars().all()}
else:
referral_users_map = {}
# Batch-fetch campaigns to avoid N+1
campaign_ids = list({e.campaign_id for e in earnings if e.campaign_id})
if campaign_ids:
campaigns_result = await db.execute(select(AdvertisingCampaign).where(AdvertisingCampaign.id.in_(campaign_ids)))
campaigns_map = {c.id: c for c in campaigns_result.scalars().all()}
else:
campaigns_map = {}
items = []
for e in earnings:
referral_user = referral_users_map.get(e.referral_id) if e.referral_id else None
campaign = campaigns_map.get(e.campaign_id) if e.campaign_id else None
items.append(
ReferralEarningResponse(
id=e.id,
amount_kopeks=e.amount_kopeks,
amount_rubles=e.amount_kopeks / 100,
reason=e.reason or 'Referral commission',
referral_username=referral_user.username if referral_user else None,
referral_first_name=referral_user.first_name if referral_user else None,
campaign_name=campaign.name if campaign else None,
created_at=e.created_at,
)
)
pages = math.ceil(total / per_page) if total > 0 else 1
return ReferralEarningsListResponse(
items=items,
total=total,
total_amount_kopeks=total_amount,
total_amount_rubles=total_amount / 100,
page=page,
per_page=per_page,
pages=pages,
)
@router.get('/terms', response_model=ReferralTermsResponse)
async def get_referral_terms():
"""Get referral program terms."""
return ReferralTermsResponse(
is_enabled=settings.is_referral_program_enabled(),
commission_percent=settings.REFERRAL_COMMISSION_PERCENT,
minimum_topup_kopeks=settings.REFERRAL_MINIMUM_TOPUP_KOPEKS,
minimum_topup_rubles=settings.REFERRAL_MINIMUM_TOPUP_KOPEKS / 100,
first_topup_bonus_kopeks=settings.REFERRAL_FIRST_TOPUP_BONUS_KOPEKS,
first_topup_bonus_rubles=settings.REFERRAL_FIRST_TOPUP_BONUS_KOPEKS / 100,
inviter_bonus_kopeks=settings.REFERRAL_INVITER_BONUS_KOPEKS,
inviter_bonus_rubles=settings.REFERRAL_INVITER_BONUS_KOPEKS / 100,
max_commission_payments=settings.REFERRAL_MAX_COMMISSION_PAYMENTS,
partner_section_visible=settings.REFERRAL_PARTNER_SECTION_VISIBLE,
)
+54
View File
@@ -0,0 +1,54 @@
"""Subscription management routes for cabinet.
This module is a thin aggregator that includes all subscription sub-routers
from subscription_modules/. Each domain (status, purchase, traffic, devices, etc.)
lives in its own module for maintainability.
The router exported here preserves the original prefix='/subscription' and tags,
so all existing API paths remain unchanged.
"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from ..dependencies import get_cabinet_db, get_current_cabinet_user
from ..schemas.subscription import SubscriptionStatusResponse
from .subscription_modules import (
autopay_router,
daily_router,
devices_router,
purchase_router,
renewal_router,
revoke_router,
servers_router,
status_router,
tariff_switch_router,
traffic_router,
)
from .subscription_modules.status import get_subscription as _get_subscription_handler
router = APIRouter(prefix='/subscription', tags=['Cabinet Subscription'])
# Root endpoint: GET /subscription (empty path — must be on this router directly)
@router.get('', response_model=SubscriptionStatusResponse)
async def get_subscription(
user=Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
subscription_id: int | None = Query(None, description='Subscription ID for multi-tariff'),
):
return await _get_subscription_handler(user=user, db=db, subscription_id=subscription_id)
# Include all sub-routers
router.include_router(status_router)
router.include_router(renewal_router)
router.include_router(purchase_router)
router.include_router(traffic_router)
router.include_router(devices_router)
router.include_router(servers_router)
router.include_router(autopay_router)
router.include_router(daily_router)
router.include_router(tariff_switch_router)
router.include_router(revoke_router)
@@ -0,0 +1,32 @@
"""Subscription sub-modules for cabinet API.
Each module contains a subset of endpoints from the original monolithic subscription.py.
The main subscription.py includes all sub-routers for backward compatibility.
"""
from .autopay import router as autopay_router
from .daily import router as daily_router
from .devices import router as devices_router
from .multi_tariff import router as multi_tariff_router
from .purchase import router as purchase_router
from .renewal import router as renewal_router
from .revoke import router as revoke_router
from .servers import router as servers_router
from .status import router as status_router
from .tariff_switch import router as tariff_switch_router
from .traffic import router as traffic_router
__all__ = [
'autopay_router',
'daily_router',
'devices_router',
'multi_tariff_router',
'purchase_router',
'renewal_router',
'revoke_router',
'servers_router',
'status_router',
'tariff_switch_router',
'traffic_router',
]
@@ -0,0 +1,79 @@
"""Autopay settings endpoint.
PATCH /subscription/autopay
"""
from __future__ import annotations
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import User
from ...dependencies import get_cabinet_db, get_current_cabinet_user
from ...schemas.subscription import AutopayUpdateRequest
logger = structlog.get_logger(__name__)
router = APIRouter()
@router.patch('/autopay')
async def update_autopay(
request: AutopayUpdateRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
subscription_id: int | None = Query(None, description='Subscription ID for multi-tariff'),
):
"""Update autopay settings."""
from .helpers import resolve_subscription
subscription = await resolve_subscription(db, user, subscription_id)
if not subscription:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='No subscription found',
)
if request.enabled:
# Classic subscriptions cannot use autopay when tariff mode is enabled
from app.config import settings
if settings.is_tariffs_mode() and not subscription.tariff_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Autopay is not available for classic subscriptions. Please purchase a tariff.',
)
# Триальные подписки — пробник, автопродление не имеет смысла
# NULL-safe: is_trial can be None in legacy rows — treat as trial
if subscription.is_trial is not False:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Autopay is not available for trial subscriptions',
)
# Суточные подписки имеют свой механизм продления (DailySubscriptionService),
# глобальный autopay для них запрещён
await db.refresh(subscription, ['tariff'])
if subscription.tariff and getattr(subscription.tariff, 'is_daily', False):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Autopay is not available for daily subscriptions',
)
subscription.autopay_enabled = request.enabled
if request.days_before is not None:
subscription.autopay_days_before = request.days_before
await db.commit()
return {
'message': 'Autopay settings updated',
'autopay_enabled': subscription.autopay_enabled,
'autopay_days_before': subscription.autopay_days_before,
}
@@ -0,0 +1,190 @@
"""Daily subscription management endpoints.
POST /subscription/pause
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
import structlog
from fastapi import APIRouter, Depends, HTTPException, Query as QueryParam, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.tariff import get_tariff_by_id
from app.database.models import User
from app.services.subscription_service import SubscriptionService
from ...dependencies import get_cabinet_db, get_current_cabinet_user
from .helpers import resolve_subscription
logger = structlog.get_logger(__name__)
router = APIRouter()
@router.post('/pause')
async def toggle_subscription_pause(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
subscription_id: int | None = QueryParam(None, description='Subscription ID for multi-tariff'),
) -> dict[str, Any]:
"""Toggle pause/resume for daily subscription."""
subscription = await resolve_subscription(db, user, subscription_id)
if not subscription:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='No subscription found',
)
tariff_id = getattr(subscription, 'tariff_id', None)
if not tariff_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Subscription has no tariff',
)
tariff = await get_tariff_by_id(db, tariff_id)
if not tariff or not getattr(tariff, 'is_daily', False):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Pause is only available for daily tariffs',
)
# Determine current state
from app.database.models import SubscriptionStatus
is_currently_paused = getattr(subscription, 'is_daily_paused', False)
was_disabled = subscription.status in (
SubscriptionStatus.DISABLED.value,
SubscriptionStatus.EXPIRED.value,
SubscriptionStatus.LIMITED.value,
)
# System-DISABLED subs (insufficient balance) should always be treated as needing resume,
# even if is_daily_paused is False (it's set by the system, not the user)
if was_disabled and not is_currently_paused:
new_paused_state = False # Force resume path
else:
new_paused_state = not is_currently_paused
raw_daily_price = getattr(tariff, 'daily_price_kopeks', 0)
# Lock user BEFORE discount computation to prevent TOCTOU on promo group
# IMPORTANT: must happen BEFORE modifying subscription — lock_user_for_pricing
# reloads subscriptions via selectinload which resets in-memory changes
from app.database.crud.user import lock_user_for_pricing
user = await lock_user_for_pricing(db, user.id)
# Re-fetch subscription after lock (selectinload may have replaced the ORM object)
subscription = await resolve_subscription(db, user, subscription_id)
if not subscription:
raise HTTPException(status_code=404, detail='Subscription not found after lock')
subscription.is_daily_paused = new_paused_state
# Apply group discount to daily price (consistent with DailySubscriptionService and miniapp resume)
from app.services.pricing_engine import PricingEngine
promo_group = PricingEngine.resolve_promo_group(user)
daily_group_pct = promo_group.get_discount_percent('period', 1) if promo_group else 0
daily_price = (
PricingEngine.apply_discount(raw_daily_price, daily_group_pct) if daily_group_pct > 0 else raw_daily_price
)
# If resuming, check balance and charge
if not new_paused_state:
if daily_price > 0 and user.balance_kopeks < daily_price:
raise HTTPException(
status_code=status.HTTP_402_PAYMENT_REQUIRED,
detail={
'code': 'insufficient_balance',
'message': 'Insufficient balance to resume daily subscription',
'required': daily_price,
'balance': user.balance_kopeks,
},
)
# Charge daily fee FIRST, then restore ACTIVE status
if was_disabled:
if daily_price > 0:
from app.database.crud.user import subtract_user_balance
deducted = await subtract_user_balance(
db,
user,
daily_price,
f'Суточная оплата тарифа «{tariff.name}» (возобновление)',
mark_as_paid_subscription=True,
)
if not deducted:
raise HTTPException(
status_code=status.HTTP_402_PAYMENT_REQUIRED,
detail={
'code': 'insufficient_balance',
'message': 'Balance deduction failed',
'required': daily_price,
'balance': user.balance_kopeks,
},
)
from app.database.crud.transaction import create_transaction
from app.database.models import TransactionType
try:
await create_transaction(
db=db,
user_id=user.id,
type=TransactionType.SUBSCRIPTION_PAYMENT,
amount_kopeks=daily_price,
description=f'Суточная оплата тарифа «{tariff.name}» (возобновление)',
)
except Exception as exc:
logger.warning('Failed to create resume transaction', error=exc)
# Balance deducted successfully — now activate
subscription.status = SubscriptionStatus.ACTIVE.value
subscription.last_daily_charge_at = datetime.now(UTC)
subscription.end_date = datetime.now(UTC) + timedelta(days=1)
await db.commit()
await db.refresh(subscription)
await db.refresh(user)
# Sync with RemnaWave only when resuming from DISABLED state
if not new_paused_state and was_disabled:
try:
subscription_service = SubscriptionService()
await subscription_service.create_remnawave_user(
db,
subscription,
reset_traffic=False,
reset_reason=None,
)
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'
else:
message = 'Daily subscription resumed'
return {
'success': True,
'message': message,
'is_paused': new_paused_state,
'balance_kopeks': user.balance_kopeks,
'balance_label': settings.format_price(user.balance_kopeks),
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,234 @@
"""Shared helper functions for subscription modules."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Any
import structlog
from app.config import settings
if TYPE_CHECKING:
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import Subscription, User
from ...schemas.subscription import (
ServerInfo,
SubscriptionResponse,
)
logger = structlog.get_logger(__name__)
async def resolve_subscription(
db: AsyncSession,
user: User,
subscription_id: int | None,
) -> Subscription | None:
"""Resolve target subscription: by ID in multi-tariff mode, or legacy fallback.
Args:
db: Database session.
user: Current user.
subscription_id: Optional subscription ID (from query param).
Returns:
Target Subscription or None if not found.
Raises:
HTTPException: If subscription_id provided but not found for this user.
"""
from fastapi import HTTPException
from app.database.crud.subscription import get_subscription_by_id_for_user
if subscription_id and settings.is_multi_tariff_enabled():
subscription = await get_subscription_by_id_for_user(db, subscription_id, user.id)
if not subscription:
raise HTTPException(status_code=404, detail='Subscription not found')
return subscription
if settings.is_multi_tariff_enabled() and not subscription_id:
from app.database.crud.subscription import get_active_subscriptions_by_user_id
active_subs = await get_active_subscriptions_by_user_id(db, user.id)
if active_subs:
non_daily = [s for s in active_subs if not getattr(s, 'is_daily_tariff', False)]
pool = non_daily or active_subs
return max(pool, key=lambda s: s.days_left)
return None
await db.refresh(user, ['subscriptions'])
return user.subscription
def _get_addon_discount_percent(
user: User | None,
category: str,
period_days_hint: int | None = None,
) -> int:
"""Get addon discount percent for user — delegates to PricingEngine."""
from app.services.pricing_engine import PricingEngine
return PricingEngine.get_addon_discount_percent(user, category, period_days_hint)
def _apply_addon_discount(
user: User,
category: str,
amount: int,
period_days: int | None = None,
) -> dict[str, int]:
"""Apply addon discount to amount.
Returns dict with keys: discounted, discount, percent
"""
from app.utils.pricing_utils import apply_percentage_discount
percent = _get_addon_discount_percent(user, category, period_days)
if percent <= 0 or amount <= 0:
return {'discounted': amount, 'discount': 0, 'percent': 0}
discounted_amount, discount_value = apply_percentage_discount(amount, percent)
return {
'discounted': discounted_amount,
'discount': discount_value,
'percent': percent,
}
def _subscription_to_response(
subscription: Subscription,
servers: list[ServerInfo] | None = None,
tariff_name: str | None = None,
traffic_purchases: list[dict[str, Any]] | None = None,
user: User | None = None,
) -> SubscriptionResponse:
"""Convert Subscription model to response."""
now = datetime.now(UTC)
# Use actual_status property for correct status (same as bot uses)
actual_status = subscription.actual_status
is_expired = actual_status == 'expired'
is_active = actual_status in ('active', 'trial')
is_limited = actual_status == 'limited'
# Calculate time remaining
days_left = 0
hours_left = 0
minutes_left = 0
time_left_display = ''
if subscription.end_date and not is_expired:
time_delta = subscription.end_date - now
total_seconds = max(0, int(time_delta.total_seconds()))
days_left = total_seconds // 86400 # 86400 seconds in a day
remaining_seconds = total_seconds % 86400
hours_left = remaining_seconds // 3600
minutes_left = (remaining_seconds % 3600) // 60
# Create human-readable display
if days_left > 0:
time_left_display = f'{days_left}d {hours_left}h'
elif hours_left > 0:
time_left_display = f'{hours_left}h {minutes_left}m'
elif minutes_left > 0:
time_left_display = f'{minutes_left}m'
else:
time_left_display = '0m'
else:
time_left_display = '0m'
traffic_limit_gb = subscription.traffic_limit_gb or 0
traffic_used_gb = subscription.traffic_used_gb or 0.0
if traffic_limit_gb > 0:
traffic_used_percent = min(100, (traffic_used_gb / traffic_limit_gb) * 100)
else:
traffic_used_percent = 0
# Check if this is a daily tariff
is_daily_paused = getattr(subscription, 'is_daily_paused', False) or False
tariff_id = getattr(subscription, 'tariff_id', None)
# Use subscription's is_daily_tariff property if available
is_daily = False
daily_price_kopeks = None
if hasattr(subscription, 'is_daily_tariff'):
is_daily = subscription.is_daily_tariff
elif tariff_id and hasattr(subscription, 'tariff') and subscription.tariff:
is_daily = getattr(subscription.tariff, 'is_daily', False)
# Get daily_price_kopeks, tariff_name, traffic_reset_mode from tariff
traffic_reset_mode = None
if tariff_id and hasattr(subscription, 'tariff') and subscription.tariff:
daily_price_kopeks = getattr(subscription.tariff, 'daily_price_kopeks', None)
# Применяем скидку промогруппы + promo-offer для отображения
if daily_price_kopeks and daily_price_kopeks > 0 and user:
from app.services.pricing_engine import PricingEngine
from app.utils.promo_offer import get_user_active_promo_discount_percent
_promo_group = user.get_primary_promo_group() if hasattr(user, 'get_primary_promo_group') else None
_group_pct = _promo_group.get_discount_percent('period', 1) if _promo_group else 0
_offer_pct = get_user_active_promo_discount_percent(user)
if _group_pct > 0 or _offer_pct > 0:
daily_price_kopeks, _, _ = PricingEngine.apply_stacked_discounts(
daily_price_kopeks, _group_pct, _offer_pct
)
if not tariff_name: # Only set if not passed as parameter
tariff_name = getattr(subscription.tariff, 'name', None)
traffic_reset_mode = (
getattr(subscription.tariff, 'traffic_reset_mode', None) or settings.DEFAULT_TRAFFIC_RESET_STRATEGY
)
# Calculate next daily charge time (24 hours after last charge)
next_daily_charge_at = None
if is_daily and not is_daily_paused:
last_charge = getattr(subscription, 'last_daily_charge_at', None)
if last_charge:
next_charge = last_charge + timedelta(days=1)
# Если время списания уже прошло — не показываем (DailySubscriptionService обработает)
if next_charge > datetime.now(UTC):
next_daily_charge_at = next_charge
# Проверяем настройку скрытия ссылки (скрывается только текст, кнопки работают)
hide_link = settings.should_hide_subscription_link()
return SubscriptionResponse(
id=subscription.id,
status=actual_status, # Use actual_status instead of raw status
is_trial=subscription.is_trial or actual_status == 'trial',
start_date=subscription.start_date,
end_date=subscription.end_date,
days_left=days_left,
hours_left=hours_left,
minutes_left=minutes_left,
time_left_display=time_left_display,
traffic_limit_gb=traffic_limit_gb,
traffic_used_gb=round(traffic_used_gb, 2),
traffic_used_percent=round(traffic_used_percent, 1),
device_limit=subscription.device_limit or 0,
connected_squads=subscription.connected_squads or [],
servers=servers or [],
autopay_enabled=subscription.autopay_enabled or False,
autopay_days_before=subscription.autopay_days_before or 3,
subscription_url=subscription.subscription_url,
hide_subscription_link=hide_link,
is_active=is_active,
is_expired=is_expired,
is_limited=is_limited,
traffic_purchases=traffic_purchases or [],
is_daily=is_daily,
is_daily_paused=is_daily_paused,
daily_price_kopeks=daily_price_kopeks,
next_daily_charge_at=next_daily_charge_at,
tariff_id=tariff_id,
tariff_name=tariff_name,
traffic_reset_mode=traffic_reset_mode,
)
@@ -0,0 +1,156 @@
"""Multi-tariff subscription endpoints for cabinet API.
GET /subscriptions list all user subscriptions (multi-tariff)
GET /subscriptions/{id} get specific subscription details
"""
from __future__ import annotations
import structlog
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.crud.subscription import (
decrement_subscription_server_counts,
get_all_subscriptions_by_user_id,
get_subscription_by_id_for_user,
)
from app.database.models import SubscriptionStatus, User
from ...dependencies import get_cabinet_db, get_current_cabinet_user
logger = structlog.get_logger(__name__)
router = APIRouter(prefix='/subscriptions', tags=['Cabinet Multi-Tariff'], redirect_slashes=False)
class SubscriptionListItem(BaseModel):
id: int
status: str
tariff_id: int | None = None
tariff_name: str | None = None
traffic_limit_gb: int = 0
traffic_used_gb: float = 0.0
device_limit: int = 1
end_date: str | None = None
subscription_url: str | None = None
subscription_crypto_link: str | None = None
is_trial: bool = False
is_daily: bool = False
is_daily_paused: bool = False
autopay_enabled: bool = False
connected_squads: list[str] | None = None
class SubscriptionsListResponse(BaseModel):
subscriptions: list[SubscriptionListItem]
multi_tariff_enabled: bool
def _subscription_to_list_item(sub) -> SubscriptionListItem:
tariff_name = None
if sub.tariff:
tariff_name = sub.tariff.name
return SubscriptionListItem(
id=sub.id,
status=sub.actual_status,
tariff_id=sub.tariff_id,
tariff_name=tariff_name,
traffic_limit_gb=sub.traffic_limit_gb or 0,
traffic_used_gb=sub.traffic_used_gb or 0.0,
device_limit=sub.device_limit or 1,
end_date=sub.end_date.isoformat() if sub.end_date else None,
subscription_url=sub.subscription_url,
subscription_crypto_link=sub.subscription_crypto_link,
is_trial=sub.is_trial or False,
is_daily=bool(sub.tariff and getattr(sub.tariff, 'is_daily', False)),
is_daily_paused=bool(getattr(sub, 'is_daily_paused', False)),
autopay_enabled=sub.autopay_enabled or False,
connected_squads=sub.connected_squads,
)
@router.get('', response_model=SubscriptionsListResponse)
async def list_subscriptions(
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> SubscriptionsListResponse:
"""List all user subscriptions. Returns all subscriptions regardless of multi-tariff mode."""
subscriptions = await get_all_subscriptions_by_user_id(db, user.id)
items = [_subscription_to_list_item(sub) for sub in subscriptions]
return SubscriptionsListResponse(
subscriptions=items,
multi_tariff_enabled=settings.is_multi_tariff_enabled(),
)
@router.get('/{subscription_id}', response_model=SubscriptionListItem)
async def get_subscription_detail(
subscription_id: int,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> SubscriptionListItem:
"""Get specific subscription details with ownership check."""
subscription = await get_subscription_by_id_for_user(db, subscription_id, user.id)
if not subscription:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Subscription not found',
)
return _subscription_to_list_item(subscription)
@router.delete('/{subscription_id}')
async def delete_subscription(
subscription_id: int,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
) -> dict:
"""Delete an expired/disabled subscription. Active subscriptions cannot be deleted."""
subscription = await get_subscription_by_id_for_user(db, subscription_id, user.id)
if not subscription:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail='Subscription not found',
)
# Only expired/disabled subscriptions can be deleted
deletable_statuses = {
SubscriptionStatus.EXPIRED.value,
SubscriptionStatus.DISABLED.value,
}
if getattr(subscription, 'actual_status', subscription.status) not in deletable_statuses:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Only expired or disabled subscriptions can be deleted',
)
# Delete from RemnaWave panel (stops webhooks / phantom notifications)
if subscription.remnawave_uuid:
try:
from app.services.subscription_service import SubscriptionService
service = SubscriptionService()
await service.delete_remnawave_user(subscription.remnawave_uuid)
except Exception as e:
logger.warning('Failed to delete RemnaWave user on subscription delete', error=e)
# Decrement server counts
await decrement_subscription_server_counts(db, subscription)
# Delete the subscription
await db.delete(subscription)
await db.commit()
logger.info(
'Subscription deleted by user',
subscription_id=subscription_id,
user_id=user.id,
tariff_id=subscription.tariff_id,
)
return {'message': 'Subscription deleted'}

Some files were not shown because too many files have changed in this diff Show More