Compare commits

...

151 Commits

Author SHA1 Message Date
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
140 changed files with 12081 additions and 890 deletions
+84 -7
View File
@@ -13,11 +13,15 @@ SUPPORT_USERNAME=@support
# Имя пользователя бота (опционально, автоопределяется)
# BOT_USERNAME=
# ===== SOCKS5 ПРОКСИ =====
# ===== СЕТЬ И ПРОКСИ =====
# URL SOCKS5 прокси-сервера для маршрутизации трафика бота к Telegram API
# Формат: socks5://user:password@host:port или socks5://host:port
# PROXY_URL=socks5://127.0.0.1:1080
# Альтернативный URL сервера Telegram Bot API (для регионов где api.telegram.org заблокирован)
# Примеры: Cloudflare Worker, self-hosted telegram-bot-api (tdlib), любой совместимый прокси
# TELEGRAM_API_URL=https://your-telegram-proxy.workers.dev
# ===== СИСТЕМА ПОДДЕРЖКИ =====
# Включить меню поддержки в интерфейсе
SUPPORT_MENU_ENABLED=true
@@ -250,6 +254,18 @@ WEBHOOK_NOTIFY_DEVICES=true
# - Подходит для продажи готовых пакетов услуг
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
@@ -680,6 +696,70 @@ RIOPAY_WEBHOOK_PATH=/riopay-webhook
RIOPAY_SUCCESS_URL=
RIOPAY_FAIL_URL=
# ===== SEVERPAY (severpay.io) =====
SEVERPAY_ENABLED=false
# Merchant ID
SEVERPAY_MID=
# Секретный токен для HMAC-SHA256
SEVERPAY_TOKEN=
SEVERPAY_DISPLAY_NAME=SeverPay
SEVERPAY_CURRENCY=RUB
SEVERPAY_MIN_AMOUNT_KOPEKS=10000
SEVERPAY_MAX_AMOUNT_KOPEKS=10000000
SEVERPAY_WEBHOOK_PATH=/severpay-webhook
# URL возврата после оплаты
# SEVERPAY_RETURN_URL=
# Время жизни платежа в минутах (30-4320)
SEVERPAY_LIFETIME=1440
# ===== PAYPEAR (api.paypear.ru) =====
PAYPEAR_ENABLED=false
# Shop ID для HTTP Basic Auth
PAYPEAR_SHOP_ID=
# Secret Key для HTTP Basic Auth
PAYPEAR_SECRET_KEY=
PAYPEAR_DISPLAY_NAME=PayPear
PAYPEAR_CURRENCY=RUB
PAYPEAR_MIN_AMOUNT_KOPEKS=10000
PAYPEAR_MAX_AMOUNT_KOPEKS=10000000
PAYPEAR_WEBHOOK_PATH=/paypear-webhook
# URL возврата после оплаты
# PAYPEAR_RETURN_URL=
# Время жизни платежа в минутах
PAYPEAR_PAYMENT_LIFETIME_MINUTES=60
# ===== ROLLYPAY (rollypay.io) =====
ROLLYPAY_ENABLED=false
# API ключ (X-API-Key header)
ROLLYPAY_API_KEY=
# Секрет для HMAC-SHA256 верификации вебхуков
ROLLYPAY_SIGNING_SECRET=
ROLLYPAY_DISPLAY_NAME=RollyPay
ROLLYPAY_CURRENCY=RUB
ROLLYPAY_MIN_AMOUNT_KOPEKS=10000
ROLLYPAY_MAX_AMOUNT_KOPEKS=10000000
ROLLYPAY_WEBHOOK_PATH=/rollypay-webhook
# URL возврата после оплаты
# ROLLYPAY_RETURN_URL=
# ===== AURAPAY (aurapay.tech) =====
AURAPAY_ENABLED=false
# API ключ (X-ApiKey header)
AURAPAY_API_KEY=
# UUID магазина (X-ShopId header)
AURAPAY_SHOP_ID=
# Секретный ключ #2 для HMAC-SHA256 верификации вебхуков
AURAPAY_SECRET_KEY=
AURAPAY_DISPLAY_NAME=AuraPay
AURAPAY_CURRENCY=RUB
AURAPAY_MIN_AMOUNT_KOPEKS=10000
AURAPAY_MAX_AMOUNT_KOPEKS=10000000
AURAPAY_WEBHOOK_PATH=/aurapay-webhook
# URL возврата после оплаты
# AURAPAY_RETURN_URL=
# Время жизни инвойса в минутах
AURAPAY_PAYMENT_LIFETIME_MINUTES=60
# ===== WATA =====
WATA_ENABLED=false
WATA_BASE_URL=https://api.wata.pro
@@ -906,6 +986,9 @@ 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
@@ -946,10 +1029,4 @@ WEB_API_TOKEN_HASH_ALGORITHM=sha256
# Логирование запросов
WEB_API_REQUEST_LOGGING=true
# Внешний админ-токен (для интеграции с другими ботами/системами)
# Токен для доступа через API другого бота
# EXTERNAL_ADMIN_TOKEN=
# ID бота, от которого принимается токен
# EXTERNAL_ADMIN_TOKEN_BOT_ID=
MINIAPP_STATIC_PATH=miniapp
Binary file not shown.

After

Width:  |  Height:  |  Size: 822 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="v3.7.0-$(git rev-parse --short HEAD)" # x-release-please-version
VERSION="v${BASE_VERSION}-${SHORT_SHA}"
TAGS="fr1ngg/remnawave-bedolaga-telegram-bot:latest,fr1ngg/remnawave-bedolaga-telegram-bot:${VERSION}"
echo "🚀 Собираем версию из main: $VERSION"
elif [[ $GITHUB_REF == refs/heads/dev ]]; then
VERSION="v3.7.0-dev-$(git rev-parse --short HEAD)" # x-release-please-version
VERSION="v${BASE_VERSION}-dev-${SHORT_SHA}"
TAGS="fr1ngg/remnawave-bedolaga-telegram-bot:dev,fr1ngg/remnawave-bedolaga-telegram-bot:${VERSION}"
echo "🧪 Собираем dev версию: $VERSION"
else
VERSION="v3.7.0-pr-$(git rev-parse --short HEAD)" # x-release-please-version
TAGS="fr1ngg/remnawave-bedolaga-telegram-bot:pr-$(git rev-parse --short HEAD)"
VERSION="v${BASE_VERSION}-pr-${SHORT_SHA}"
TAGS="fr1ngg/remnawave-bedolaga-telegram-bot:pr-${SHORT_SHA}"
echo "🔀 Собираем PR версию: $VERSION"
fi
echo "version=$VERSION" >> $GITHUB_OUTPUT
echo "tags=$TAGS" >> $GITHUB_OUTPUT
echo "should_push=${{ github.event_name != 'pull_request' }}" >> $GITHUB_OUTPUT
echo "=== Информация о сборке ==="
echo "Версия: $VERSION"
echo "Коммит: $(git rev-parse --short HEAD)"
echo "Коммит: $SHORT_SHA"
echo "Теги: $TAGS"
echo "Push: ${{ github.event_name != 'pull_request' }}"
echo "==========================="
+10 -7
View File
@@ -42,25 +42,28 @@ jobs:
- name: Get version info
id: version
run: |
echo "short_sha=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
SHORT_SHA=$(git rev-parse --short HEAD)
echo "short_sha=$SHORT_SHA" >> $GITHUB_OUTPUT
echo "build_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
# Read base version from release-please manifest (single source of truth)
BASE_VERSION=$(jq -r '."."' .release-please-manifest.json)
if [[ $GITHUB_REF == refs/tags/* ]]; then
VERSION=${GITHUB_REF#refs/tags/}
echo "🏷️ Building release version: $VERSION"
elif [[ $GITHUB_REF == refs/heads/main ]]; then
VERSION="v3.7.0-$(git rev-parse --short HEAD)" # x-release-please-version
VERSION="v${BASE_VERSION}-${SHORT_SHA}"
echo "🚀 Building main version: $VERSION"
elif [[ $GITHUB_REF == refs/heads/dev ]]; then
VERSION="v3.7.0-dev-$(git rev-parse --short HEAD)" # x-release-please-version
VERSION="v${BASE_VERSION}-dev-${SHORT_SHA}"
echo "🧪 Building dev version: $VERSION"
else
VERSION="v3.7.0-pr-$(git rev-parse --short HEAD)" # x-release-please-version
VERSION="v${BASE_VERSION}-pr-${SHORT_SHA}"
echo "🔀 Building PR version: $VERSION"
fi
echo "version=$VERSION" >> $GITHUB_OUTPUT
# Определяем, нужно ли пушить образ
if [[ "${{ github.event_name }}" == "pull_request" ]]; then
echo "should_push=false" >> $GITHUB_OUTPUT
echo "⚠️ PR - only build without push"
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "3.46.1"
".": "3.53.0"
}
+198
View File
@@ -1,5 +1,203 @@
# Changelog
## [3.53.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.52.1...v3.53.0) (2026-04-29)
### New Features
* add bulk_actions, info_pages, news to PERMISSION_REGISTRY ([06db393](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/06db3934881bc55851e1ff171fca89abc7deebe5))
* per-category enable/disable for admin notifications ([fb857d7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/fb857d792b7dd6658df7c081ef46b4cc729cd2fa))
* protect active paid subscriptions from bulk delete ([51dfc3a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/51dfc3a1a2a31706b5c307f6394f2ef9f578cc51))
* subscription request history API + RemnaWave panel method ([e22beb7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e22beb722934779a6d10cb9a7c9a1853f68f7787))
### Bug Fixes
* add 5 missing payment providers to pending-payments model_map ([a506c6b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a506c6be004054998354286fc9dc3990aa867ccc))
* add 6 missing payment providers to payment_utils availability checks ([83efc21](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/83efc214fef7cdec438cf39e4301e6d22bceec7e))
* add RollyPay, PayPear, Overpay, AuraPay to REAL_PAYMENT_METHODS ([ff7b190](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ff7b1905271e92625c10fa22d809f27c22a496b6))
* autopay renewing trial subscriptions at classic-mode pricing ([2fbdbf5](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2fbdbf5ab0ec0c13100e330f60a2249ed866c12e))
* backup completeness — add 15 missing tables, accept .tar.gz uploads ([eafb243](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/eafb243882a2f325771e397cdcc3b258f8ec8f7a))
* backup import crash + upload handler hardening ([5cf19c7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/5cf19c76e6fa9456cee0157ac4a4c0742d0f7718))
* block/unblock endpoints — correct args, response schema, panel sync ([0bcb804](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0bcb804118fa9cb02c580eea849b6cd218d931f8))
* cabinet /block endpoint now disables panel user in RemnaWave ([735e16a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/735e16afeba70ef22e690d668e6693cdd2bac140))
* cabinet autopay endpoint — same NULL-safe is_trial guard ([29e177d](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/29e177d396796827e3970015afb5a84512612035))
* cabinet purchase fails after panel user deletion — stale UUID ([f37eb9a](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/f37eb9a1bd6a149f38458b1a4a1071efd8c03660))
* callback.answer() before heavy operations to prevent query timeout ([579e4f2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/579e4f2a695315091db7f014d6a2241852b078ae))
* create locales directory with correct permissions in Dockerfile ([74999fe](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/74999fe99dd5ef7b10814cb24ff3022aca1d1c0d))
* deadlock on user deletion — webhook handler never checked intentional mark ([62e7ecb](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/62e7ecba01601ab3d5aa6c913db064d5fa768d9a))
* device/traffic addon pricing — use ceil instead of floor for days_left ([cf60ae2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/cf60ae2967b8a5b0c42c51354e3a2513c38e7120))
* downgrade Pal24 API validation errors from error to debug ([c905fa6](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/c905fa60000c238475cdc3b253ae6e67aa670ff4))
* false subscription expiry notifications — 4 bugs fixed ([134e7fb](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/134e7fb0e1999f6404e2d06f38aebdb6af550ec1))
* handle A018 error code as user-not-found fallback to create_user ([c619dbc](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/c619dbcae2a1470d132cdd35cb9824ac801f117c))
* handle A018 error code in admin_users sync endpoints (2 more locations) ([59080f7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/59080f7392412cae848fdd3887cb25304a3a33f9))
* media upload leaks staging photo to admin chat ([1110d0c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1110d0c7810d52d4f8f789dc5383cf4a0f5fce96))
* panel sync subscription duration — ceil for days_remaining ([527c5b4](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/527c5b4498972e2806480af1d0625939eae50bee))
* PayPear webhook signature — strip signature field before hashing + IP fallback ([443a826](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/443a826402e63b021f1efc856257bbf54c79fdb4))
* PollResponse has no created_at — use sent_at for ordering ([768e0b6](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/768e0b6a7363e8b496f1e1b83fe567993dc664da))
* promo group discount applied to restricted tariffs in autopay ([4ab5928](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4ab5928b61c35b4af115ced949e373c3373c7145))
* referral links now clickable — remove &lt;code&gt; wrapping ([43dd0fd](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/43dd0fd92c433498d780ca4e8798d606f5f70dbf))
* remaining pricing-critical .days floor calculations → math.ceil ([bada41e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/bada41ecd67e81020627dc50e90d357c088471ab))
* replace all late callback.answer() with edit_text for error feedback ([c743fc8](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/c743fc81a5cb56153dbfe49e4f293277d773e948))
* retry queue action uses _should_create instead of stale subscription UUID ([422844d](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/422844d78df2865926c18d888edfb95e72c077c7))
* send admin notification on promo code activation from cabinet ([1c38b31](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1c38b31e60f2491c2366f43b792400af71cba70d))
* subscription-request-history — correct API client usage, add ownership check ([1fc04d8](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1fc04d842fe589df1ec6208d6709b5bd55c85da7))
* traffic addon discount also bypassed tariff-promo-group check ([47c7d45](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/47c7d4579336833213203f3e127d4155ed25b555))
* traffic addon price mismatch — keyboard showed prorated, handler charged full month ([a88e3c8](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a88e3c80ade1a1178270efe5e4100810da6f79b5))
* update cabinet_last_login on every request (throttled, 5 min) ([91de6d0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/91de6d03fce4d6082359e7a1ba7e7f5ec02756b6))
### Refactoring
* remove unused EXTERNAL_ADMIN_TOKEN functionality ([b9b6957](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b9b695799cb15f0f3be0116063cbf72482096b5d))
## [3.52.1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.52.0...v3.52.1) (2026-04-24)
### Bug Fixes
* broadcast preview count — add .correlate(User) to EXISTS subqueries ([63e1127](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/63e112735302cc5fc961b2da87fb1250f922fe3d))
* ignore bot's own messages in unknown message handlers ([52bf2a9](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/52bf2a9589e3e14abda78a62e45e86e022da4994))
* unpin messages in Telegram BEFORE deactivating in DB ([ab4661b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ab4661b5c643d6dad787cc499c5cff128ec21be5))
* use fresh DB session for deactivate after long unpin loop ([5ed9a0d](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/5ed9a0d4fbef5c92bfb4e7eb0daed493805c5e44))
## [3.52.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.51.0...v3.52.0) (2026-04-24)
### New Features
* admin bulk actions API — mass operations on users ([fb2773f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/fb2773fee4f36fc517624d96243b731c94a3508d))
* bulk actions — campaign/partner filters, delete_user action ([d77fd81](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/d77fd81e161a65ba848133ba4798a6a335e35c1c))
* bulk actions — SSE streaming progress, grant subscription, multi-tariff info ([c0e0756](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/c0e0756b9ac15cd926708be3f2f9c93e571ad411))
* bulk delete_subscription action — removes from bot DB + RemnaWave ([605f202](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/605f202191d0203fdc7f5ea3bb0695ece47c9cd6))
* bulk set_devices action + device info in subscription list ([be787a8](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/be787a85bfd981b70bd347c943f5cef8ec0610fc))
* FAQ support in info pages — page_type field + migration ([d394565](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/d394565fe940549d1211a1ddab37f4d002d43dd5))
* info page tab replacement — replaces_tab field + API ([bdb8cab](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/bdb8cab1c97328ff05218a9a68612418c69ccacf))
* information pages — CRUD model, admin API, public API ([e4b4a54](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e4b4a54797875b697146f8b804b3bbdfff4eb78b))
* multi-tariff bulk actions — subscription-level targeting ([e78177b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/e78177b2fc34c895ab2b74705516af2a3fcbfb70))
* support multiple tariff_ids in user list filter ([0d2b1df](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0d2b1dfdc97d2f3058ef793c89beaa8da5709a4a))
### Bug Fixes
* /reorder route unreachable — move before /{page_id} path param ([122d12d](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/122d12db20537cf0ad55cea5328f03aa3464b540))
* add subscription/tariff/promo_group filters to admin user list API ([daa4725](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/daa472570ccf6ef50441e0e173ddd1b87fe31e5e))
* always return subscriptions list in user list API ([cfbcc30](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/cfbcc3082fca3a6101604aea197e7844974ed15d))
* bulk actions review — rollback on error, multi-tariff constraint checks ([5b45d43](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/5b45d4354f6e58bd609e69a45ef100acfed3dbf4))
* bulk change_tariff not clearing squads when new tariff has none ([db7b673](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/db7b6734fdcae52397a25eb94e1b24e908fcc41c))
* bulk delete_user — pass real admin_id, sanitize error messages ([2e45a93](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2e45a93bd72c7e930fad60f7be2292596271c0dc))
* gift purchases no longer inflate promo group level ([1522d35](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1522d35f2dec0e35153c452818380f9b41b35f1d))
* info pages review — deduplicate slug index, type reorder items ([2071a68](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2071a680d3d569f67c447921370463f13c928c55))
* integrate Yandex Metrika offline conv + S2S postback hooks ([7d512d2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7d512d214a1ca184ba6601bf1ee5a39727ed41e5))
* MissingGreenlet in subscription-ids bulk actions ([2ad893b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2ad893badfec6f782ed89746b1cf2d3d7b07aa3a))
* privacy policy and offer text display HTML links as plain text ([59c54c9](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/59c54c9b39d9cb26ed518cc74c93e1da43ce2020))
* restore HTTP Referer fallback for landing purchases ([24dc8d2](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/24dc8d2a5e1be5239036acf5888acfe1e8e96444))
* restore referrer field in admin landing purchases response ([2cde38c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2cde38c63b35e52a552bf58c003a8281525a0be7))
* sanitize error messages in all bulk action catch-all handlers ([9217f41](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9217f4116f74d15133531a711cb2bc083f30dd49))
* server squad sync fails on fresh DB without default promo group ([ae7feeb](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ae7feeb726ab0a9b3074c9ed11fd45e2cc412ea0))
* stop printing tracebacks for warning-level logs inside except blocks ([68d2350](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/68d2350dfdf2f1f6964dd744a447b558a1d06267))
* suppress 'User already enabled' traceback in bulk add_traffic ([ff41ea9](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ff41ea9abbdbeb6746e23cde48a5f962b289fc48))
### Documentation
* add Overpay to README with partner block ([bcf5519](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/bcf5519880471d113833a5031cae54594e658a7b))
* add Overpay to README with partner block ([70568f8](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/70568f82c5c6c2c1041865c7109907fa9e2b8c6a))
## [3.51.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.50.0...v3.51.0) (2026-04-23)
### New Features
* integrate Overpay payment provider (pay.overpay.io) ([2c3ffc8](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2c3ffc8c8a9e6591d2356320ed0a71ab5db6cbec))
* respond to unknown media messages (photos, videos, documents) ([29ae708](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/29ae7089aa0a8a5c7ddd73622a492df6b5e67e03))
### Bug Fixes
* inactive user cleanup deletes users with paid subscriptions ([7005052](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/70050521566ab86b75fb4f64ed3b61bced5d1612))
* pad short RemnaWave usernames to meet 3-char minimum ([6f87563](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/6f875637899544d95daf8d87a30042b5347f6b41))
## [3.50.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.49.0...v3.50.0) (2026-04-22)
### New Features
* add WEBHOOK_IP to allow Telegram bypass DNS lookup for webhook ([#2894](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/issues/2894)) ([7093d36](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7093d368d3356c692bff3eddda68996579bfd036))
* landing page analytics goals and sticky pay button ([3272b4b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3272b4bb053c76c3995cd3904b085a28f741e815))
* tariff switch direction control, fix device pricing within tariff limit ([9ed4f08](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9ed4f086b0102c20d7861e03f4d212ff57e28245))
* **tickets:** multi-media message gallery (media_items JSONB) ([36571c4](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/36571c4275b76fa0bdb490ffccacc0a0e32e9bd6))
* v3.50.0 release ([a491fe3](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a491fe34bda6da86d72891fe4d05b6abd169cf2f))
* Yandex Metrika offline conversions + S2S postbacks ([1068c13](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1068c1387a03bf7c94c7b29f9bb61acc3e3e782a))
### Bug Fixes
* classic mode renewal resets device_limit to 1 via cart key mismatch ([9ca3320](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/9ca3320a0204346aac2c76601f221b0bc70226a7))
* do not reset subscription_crypto_link when cryptoLink absent in webhook ([#2891](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/issues/2891)) ([b71e58c](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b71e58c8d25a5c94c94a401a59359cab4870e3c0))
* do not update first_name/last_name from OIDC claims ([#2892](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/issues/2892)) ([1696e6f](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1696e6f8843ceaa1a3e9a6d536e0d99968e579b1))
* FSM state loss on balance topup, PayPear confirmation_url, hidden trial tariff in renewal ([7be404b](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/7be404b918640dcccdcda82802bb02a342b730d6))
* grant all available squads for unrestricted trials ([#2897](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/issues/2897)) ([905cea6](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/905cea68b48b596412d83c42de0d1dce77dcaee0))
* menu layout schema icon limit, traffic_topup_enabled condition, shadowing imports ([66f8577](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/66f8577448712786d851b1802c4a183e7acc1779))
* tariff switch pricing showing free for upgrades, admin duplicate subscription guard ([da855a7](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/da855a7c8955dcbf3543dbbaedc00e16b9c35193))
* ticket media_items review fixes ([dd17710](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/dd177101f7314c5d25120a69e04c66d74f37b18f))
* validate analytics goal is set when analytics is enabled on landing ([d316325](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/d31632534b3e1b2268a8f8b2a441214f377f23eb))
* устранить MissingGreenlet в автоплатежах и починить traceback в логах ([db79cc9](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/db79cc9eb0d7dc7a4a1ae9190f7a23c6c9e6e317))
* устранить root cause MissingGreenlet в автоплатежах через refetch по id ([3b03c25](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/3b03c253cc1603fe54fddcbc8bc374ec2c71bdfc))
## [3.49.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.48.0...v3.49.0) (2026-04-18)
### New Features
* integrate AuraPay payment provider ([9717936](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/97179360c0288940b1fa2f6c21a6e1431a27536f))
### Bug Fixes
* add missing RollyPay CRUD wrappers and guest payment flow ([0f814be](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0f814be1b7dfaec84dde9acc402b2c1790417611))
* align campaign top registrations revenue with period comparison ([16bc1d4](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/16bc1d41989d66e105724ed846fb40ccf03322fd))
* handle edge case when all tariffs are daily in legacy renewal ([29877fc](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/29877fc93bc612ee199ccb2438c90e57a3c1e9e0))
* rate-limit daily subscription insufficient balance notifications to 6 hours ([ecc4a61](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ecc4a6147dad0c8886acd48f38e567a6c7fc8916))
* redirect legacy users without tariff to tariff selection on renewal ([5986c00](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/5986c00fab8c5fe2060d296afca72d28038ff7bd))
* register PayPear and RollyPay in admin panel settings ([2aa5927](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2aa59274331610eec3cd84f90ddb49ee59da22ef))
### Documentation
* add AuraPay to README with partner block ([25ea5c6](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/25ea5c60fdaf3cac9294b6df74142c176b1d4d04))
* add PayPear and RollyPay to README with partner blocks ([1c696c6](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/1c696c69e34e668ff90c915249b7c3dc37bfd89b))
* add PayPear and RollyPay to README with partner blocks ([b531959](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/b53195998231d34b6e1c7165193e87fee6e5c293))
## [3.48.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.47.0...v3.48.0) (2026-04-16)
### New Features
* integrate PayPear payment provider ([a18f6ca](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a18f6caa9bd9c08511c464e6141fb8aa614135b0))
* integrate RollyPay payment provider (SBP via USDT) ([ccc2f4e](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/ccc2f4efecf0a3c1a943971c81a9a7d1985ae14a))
### Bug Fixes
* increase nalogo receipt queue retry window to 12 hours ([92eaf45](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/92eaf4531162e5625b938bafc43eb98abe2632e2))
* low balance alerts disabled by default, add quiet hours, expiry filter, top-up button ([2d5afe5](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/2d5afe5d75ff65f4d167a853e078943d518a881f))
* show menu buttons for limited (traffic exhausted) subscriptions ([0c54549](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/0c545490b61baec930f10adc86652a7e5cf5d378))
* show menu buttons for limited subscriptions in back-to-menu paths ([61cf495](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/61cf495fc5919e699aba7231f49222722da044b4))
* support payment_method selection for RollyPay (sbp/card/crypto) ([a598582](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/a59858227f31bd53d0ac54d693288ad52e447687))
### Documentation
* add SEVERPAY, PAYPEAR, ROLLYPAY to .env.example ([25447ed](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/25447edc9eab7c3a76ed94be52c1b341917a40c2))
## [3.47.0](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.46.1...v3.47.0) (2026-04-15)
### New Features
* multi-tariff sync fix, daily discount fix, campaign links, TELEGRAM_API_URL ([4db9e85](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/commit/4db9e850629f25cbcb11bb5ba0e0de5c580ca115))
## [3.46.1](https://github.com/BEDOLAGA-DEV/remnawave-bedolaga-telegram-bot/compare/v3.46.0...v3.46.1) (2026-04-13)
+3 -3
View File
@@ -19,7 +19,7 @@ RUN --mount=type=cache,target=/root/.cache/uv \
FROM python:3.13-slim
ARG VERSION="v3.46.1" # x-release-please-version
ARG VERSION="v3.53.0" # x-release-please-version
ARG BUILD_DATE
ARG VCS_REF
@@ -33,8 +33,8 @@ WORKDIR /app
COPY --chown=app:app . .
RUN mkdir -p logs data uploads/images uploads/videos uploads/thumbnails && \
chown -R app:app logs data uploads
RUN mkdir -p logs data uploads/images uploads/videos uploads/thumbnails locales && \
chown -R app:app logs data uploads locales
USER app
+55 -2
View File
@@ -55,7 +55,7 @@ Bedolaga — полнофункциональная платформа для п
### 💳 Платежи
- 🏦 **15 платёжных провайдеров** одновременно
- 🏦 **18 платёжных провайдеров** одновременно
- 💰 Единый баланс: пополнение любым способом → покупка с баланса
- ⚡ Автопокупка подписки после пополнения
- 💾 Рекуррентные платежи (сохранённые карты)
@@ -123,6 +123,10 @@ Bedolaga — полнофункциональная платформа для п
| 💳 | **MulenPay** | Карты | RUB |
| 💳 | **RioPay** | Карты | RUB |
| 💳 | **SeverPay** | СБП, карты | RUB |
| 🤝 | **[PayPear](https://t.me/Paymen1_Manager)** 🔸 | Карты, СБП, SberPay, T-Pay | RUB |
| 🤝 | **[RollyPay](https://rollypay.io/?utm_source=bedolaga&utm_medium=community&utm_campaign=integration)** 🔸 | СБП, карты, крипто | RUB → USDT |
| 🤝 | **[AuraPay](https://aurapay.tech/)** 🔸 | Карты, СБП | RUB |
| 🤝 | **[Overpay](https://overpay.pro/)** 🔸 | Карты, СБП | RUB |
| 📲 | **Tribute** | Telegram-платежи | RUB |
</div>
@@ -157,6 +161,55 @@ Bedolaga — официальный партнёр платёжной систе
📩 По вопросам: [@wyrz_wata](https://t.me/wyrz_wata)
</td>
</tr>
<tr>
<td align="center">
**🤝 Официальный партнёр PayPear**
Bedolaga — официальный партнёр платёжной системы **[PayPear](https://paypear.ru)**.<br>
Банковские карты, СБП, SberPay и T-Pay — всё через единый API.<br>
Подключение по **спец. условиям** через кодовое слово **`БЕДОЛАГА`**
📩 Менеджер: [@Paymen1_Manager](https://t.me/Paymen1_Manager)
</td>
<td align="center">
**🤝 Официальный партнёр RollyPay**
Bedolaga — официальный партнёр платёжного шлюза **[RollyPay](https://rollypay.io/?utm_source=bedolaga&utm_medium=community&utm_campaign=integration)**.<br>
СБП (от 5%), банковские карты РФ, крипто, вывод в USDT.<br>
Универсальная форма оплаты, высокая проходимость, стабильная работа в каскаде.<br>
Подключение по кодовому слову **`БЕДОЛАГА`** — **спец. условия**
📩 Менеджер: [@rollypay_manager](https://t.me/rollypay_manager) | 🌐 [rollypay.io](https://rollypay.io/?utm_source=bedolaga&utm_medium=community&utm_campaign=integration)
</td>
</tr>
<tr>
<td align="center">
**🤝 Официальный партнёр AuraPay**
Bedolaga — официальный партнёр платёжной системы **[AuraPay](https://aurapay.tech/)**.<br>
Банковские карты и СБП через единый API с быстрой интеграцией.<br>
Подключение по кодовому слову **`БЕДОЛАГА`** — **спец. условия**
📩 Менеджер: [@kickdownm](https://t.me/kickdownm) | 🌐 [aurapay.tech](https://aurapay.tech/)
</td>
<td align="center">
**🤝 Официальный партнёр Overpay**
Bedolaga — официальный партнёр платёжного шлюза **[Overpay](https://overpay.pro/)**.<br>
Банковские карты и СБП, mTLS-авторизация, HPP-интеграция.<br>
Подключение по кодовому слову **`БЕДОЛАГА`** — **спец. условия**
📩 Менеджер: [@A_OverPay](https://t.me/A_OverPay) | 🌐 [overpay.pro](https://overpay.pro/)
</td>
</tr>
</table>
@@ -222,7 +275,7 @@ docker compose up -d
| | Раздел | Описание |
|:---:|:---|:---|
| 🚀 | [Быстрый старт](https://docs.bedolagam.ru/getting-started/quickstart) | Развёртывание за 5 минут |
| 💳 | [Настройка платежей](https://docs.bedolagam.ru/bot/payments) | 14 провайдеров, webhook, фискализация |
| 💳 | [Настройка платежей](https://docs.bedolagam.ru/bot/payments) | 18 провайдеров, webhook, фискализация |
| 📦 | [Подписки и тарифы](https://docs.bedolagam.ru/bot/subscriptions) | Конфигурация планов и трафика |
| 👥 | [Реферальная программа](https://docs.bedolagam.ru/bot/referral-program) | Партнёрка и вывод средств |
| 🖥 | [Cabinet](https://docs.bedolagam.ru/cabinet/overview) | Настройка веб-кабинета |
+12 -4
View File
@@ -1,4 +1,4 @@
"""Factory for creating Bot instances with proxy support."""
"""Factory for creating Bot instances with proxy and custom API server support."""
from aiogram import Bot
from aiogram.client.default import DefaultBotProperties
@@ -8,13 +8,21 @@ from app.config import settings
def create_bot(token: str | None = None, **kwargs) -> Bot:
"""Create a Bot instance with SOCKS5 proxy session if PROXY_URL is configured."""
"""Create a Bot instance with SOCKS5 proxy and/or custom Telegram API server."""
proxy_url = settings.get_proxy_url()
telegram_api_url = settings.get_telegram_api_url()
session = None
if proxy_url:
if proxy_url or telegram_api_url:
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.client.telegram import TelegramAPIServer
session = AiohttpSession(proxy=proxy_url)
session_kwargs: dict = {}
if proxy_url:
session_kwargs['proxy'] = proxy_url
if telegram_api_url:
session_kwargs['api'] = TelegramAPIServer.from_base(telegram_api_url)
session = AiohttpSession(**session_kwargs)
kwargs.setdefault('default', DefaultBotProperties(parse_mode=ParseMode.HTML))
return Bot(token=token or settings.BOT_TOKEN, session=session, **kwargs)
+2 -1
View File
@@ -195,7 +195,8 @@ async def _get_jwks(force: bool = False) -> dict[str, Any]:
if not force and _jwks_cache and _jwks_cache_expiry and now < _jwks_cache_expiry:
return _jwks_cache
async with httpx.AsyncClient(timeout=10) as client:
proxy = settings.PROXY_URL if hasattr(settings, 'PROXY_URL') and settings.PROXY_URL else None
async with httpx.AsyncClient(timeout=10, proxy=proxy) as client:
response = await client.get(_JWKS_URL)
response.raise_for_status()
_jwks_cache = response.json()
+11
View File
@@ -1,5 +1,7 @@
"""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
@@ -176,6 +178,15 @@ async def get_current_cabinet_user(
},
)
# 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
+6
View File
@@ -7,10 +7,12 @@ 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
@@ -44,6 +46,7 @@ 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
@@ -93,6 +96,7 @@ 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)
@@ -118,6 +122,7 @@ 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)
@@ -140,6 +145,7 @@ 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)
File diff suppressed because it is too large Load Diff
+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)
+36
View File
@@ -205,6 +205,19 @@ class LandingCreateRequest(BaseModel):
discount_ends_at: datetime | None = None
discount_badge_text: dict[str, str] | None = None
background_config: dict | None = None
sticky_pay_button: bool = False
analytics_view_enabled: bool = False
analytics_view_goal: str | None = Field(default=None, max_length=64)
analytics_click_enabled: bool = False
analytics_click_goal: str | None = Field(default=None, max_length=64)
@model_validator(mode='after')
def validate_analytics_goals(self) -> 'LandingCreateRequest':
if self.analytics_view_enabled and not self.analytics_view_goal:
raise ValueError('analytics_view_goal is required when analytics_view_enabled is True')
if self.analytics_click_enabled and not self.analytics_click_goal:
raise ValueError('analytics_click_goal is required when analytics_click_enabled is True')
return self
@field_validator('background_config')
@classmethod
@@ -314,6 +327,11 @@ class LandingUpdateRequest(BaseModel):
discount_ends_at: datetime | None = None
discount_badge_text: dict[str, str] | None = None
background_config: dict | None = None
sticky_pay_button: bool | None = None
analytics_view_enabled: bool | None = None
analytics_view_goal: str | None = Field(default=None, max_length=64)
analytics_click_enabled: bool | None = None
analytics_click_goal: str | None = Field(default=None, max_length=64)
@field_validator('background_config')
@classmethod
@@ -461,6 +479,11 @@ class LandingDetailResponse(BaseModel):
discount_ends_at: datetime | None = None
discount_badge_text: dict[str, str] | None = None
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
created_at: datetime | None = None
updated_at: datetime | None = None
@@ -527,6 +550,7 @@ class LandingPurchaseItem(BaseModel):
currency: str
payment_method: str | None = None
status: str
referrer: str | None = None
created_at: datetime | None = None
paid_at: datetime | None = None
@@ -638,6 +662,11 @@ async def create_landing_page(
discount_ends_at=request.discount_ends_at,
discount_badge_text=request.discount_badge_text,
background_config=request.background_config,
sticky_pay_button=request.sticky_pay_button,
analytics_view_enabled=request.analytics_view_enabled,
analytics_view_goal=request.analytics_view_goal,
analytics_click_enabled=request.analytics_click_enabled,
analytics_click_goal=request.analytics_click_goal,
)
logger.info('Admin created landing page', admin_id=admin.id, slug=landing.slug, landing_id=landing.id)
@@ -979,6 +1008,7 @@ async def get_landing_purchases(
GuestPurchase.currency,
GuestPurchase.payment_method,
GuestPurchase.status,
GuestPurchase.referrer,
GuestPurchase.created_at,
GuestPurchase.paid_at,
)
@@ -1004,6 +1034,7 @@ async def get_landing_purchases(
currency=row.currency,
payment_method=row.payment_method,
status=row.status,
referrer=row.referrer,
created_at=row.created_at,
paid_at=row.paid_at,
)
@@ -1068,6 +1099,11 @@ def _landing_to_detail(landing: LandingPage) -> LandingDetailResponse:
discount_ends_at=landing.discount_ends_at,
discount_badge_text=landing.discount_badge_text,
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,
created_at=landing.created_at,
updated_at=landing.updated_at,
)
+35 -14
View File
@@ -17,7 +17,7 @@ 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 TicketMessageResponse
from ..schemas.tickets import TicketMediaItem, TicketMessageResponse, _validate_media_bundle
logger = structlog.get_logger(__name__)
@@ -89,19 +89,19 @@ class AdminTicketListResponse(BaseModel):
class AdminReplyRequest(BaseModel):
"""Admin reply to ticket."""
message: str = Field(..., min_length=1, max_length=4000, description='Reply message')
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':
if self.media_file_id and not self.media_type:
raise ValueError('media_type is required when media_file_id is provided')
if self.media_type and not self.media_file_id:
raise ValueError('media_file_id is required when media_type is provided')
if self.media_type and self.media_type not in {'photo', 'video', 'document'}:
raise ValueError('media_type must be one of: photo, video, document')
_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
@@ -157,14 +157,23 @@ class TicketSettingsUpdateRequest(BaseModel):
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),
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,
)
@@ -455,17 +464,29 @@ async def reply_to_ticket(
detail='Ticket not found',
)
# Create admin message
has_media = bool(request.media_file_id)
# 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=request.media_type if has_media else None,
media_file_id=request.media_file_id if has_media else None,
media_caption=request.media_caption if has_media else None,
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)
+220 -20
View File
@@ -1,5 +1,6 @@
"""Admin routes for managing users in cabinet."""
import math
from datetime import UTC, datetime, timedelta
import structlog
@@ -70,6 +71,7 @@ from ..schemas.users import (
ResetTrialRequest,
ResetTrialResponse,
SortByEnum,
SubscriptionListItem,
SyncFromPanelRequest,
SyncFromPanelResponse,
SyncToPanelRequest,
@@ -119,6 +121,12 @@ def _build_user_list_item(user: User, spending_stats: dict = None) -> UserListIt
subscription_is_trial = False
subscription_end_date = None
has_subscription = False
tariff_id = None
tariff_name = None
traffic_used_gb = 0.0
traffic_limit_gb = 0
device_limit = 0
days_remaining = 0
subs = getattr(user, 'subscriptions', None) or []
subscription = next((s for s in subs if s.is_active), subs[0] if subs else None)
@@ -127,6 +135,37 @@ def _build_user_list_item(user: User, spending_stats: dict = None) -> UserListIt
subscription_status = subscription.status
subscription_is_trial = subscription.is_trial
subscription_end_date = subscription.end_date
tariff_id = subscription.tariff_id
tariff_name = subscription.tariff.name if subscription.tariff else None
traffic_used_gb = subscription.traffic_used_gb or 0.0
traffic_limit_gb = subscription.traffic_limit_gb or 0
device_limit = subscription.device_limit or 0
if subscription.end_date:
delta = subscription.end_date - datetime.now(UTC)
days_remaining = max(0, delta.days)
# Build per-subscription list (always — bulk actions need it for any mode)
sub_list: list[SubscriptionListItem] = []
if subs:
for s in subs:
s_days = 0
if s.end_date:
s_delta = s.end_date - datetime.now(UTC)
s_days = max(0, s_delta.days)
sub_list.append(
SubscriptionListItem(
id=s.id,
tariff_id=s.tariff_id,
tariff_name=s.tariff.name if s.tariff else None,
status=s.status,
is_trial=bool(s.is_trial),
end_date=s.end_date,
days_remaining=s_days,
traffic_used_gb=s.traffic_used_gb or 0.0,
traffic_limit_gb=s.traffic_limit_gb or 0,
device_limit=s.device_limit or 0,
)
)
return UserListItem(
id=user.id,
@@ -144,6 +183,13 @@ def _build_user_list_item(user: User, spending_stats: dict = None) -> UserListIt
subscription_status=subscription_status,
subscription_is_trial=subscription_is_trial,
subscription_end_date=subscription_end_date,
tariff_id=tariff_id,
tariff_name=tariff_name,
traffic_used_gb=traffic_used_gb,
traffic_limit_gb=traffic_limit_gb,
device_limit=device_limit,
days_remaining=days_remaining,
subscriptions=sub_list,
promo_group_id=user.promo_group_id,
promo_group_name=user.promo_group.name if user.promo_group else None,
total_spent_kopeks=user_stats.get('total_spent', 0),
@@ -347,7 +393,10 @@ async def _sync_subscription_to_panel(
changes['action'] = 'updated'
logger.info('Updated user in Remnawave panel', user_id=user.id)
except Exception as update_error:
if hasattr(update_error, 'status_code') and update_error.status_code == 404:
error_code = (getattr(update_error, 'response_data', None) or {}).get('errorCode', '')
if (
hasattr(update_error, 'status_code') and update_error.status_code == 404
) or error_code == 'A018':
panel_uuid = None # Will create new
else:
raise
@@ -417,6 +466,11 @@ async def list_users(
search: str | None = Query(None, max_length=255),
email: str | None = Query(None, max_length=255),
status: UserStatusEnum | None = Query(None),
subscription_status: str | None = Query(None, max_length=20),
tariff_id: str | None = Query(None, max_length=255),
promo_group_id: int | None = Query(None),
campaign_id: int | None = Query(None),
partner_id: int | None = Query(None),
sort_by: SortByEnum = Query(SortByEnum.CREATED_AT),
admin: User = Depends(require_permission('users:read')),
db: AsyncSession = Depends(get_cabinet_db),
@@ -443,6 +497,14 @@ async def list_users(
order_by_total_spent = sort_by == SortByEnum.TOTAL_SPENT
order_by_purchase_count = sort_by == SortByEnum.PURCHASE_COUNT
# Parse comma-separated tariff_ids
tariff_ids: list[int] | None = None
if tariff_id:
try:
tariff_ids = [int(x.strip()) for x in tariff_id.split(',') if x.strip()]
except ValueError:
tariff_ids = None
users = await get_users_list(
db=db,
offset=offset,
@@ -450,6 +512,11 @@ async def list_users(
search=search,
email=email,
status=user_status,
subscription_status=subscription_status,
tariff_ids=tariff_ids,
promo_group_id=promo_group_id,
campaign_id=campaign_id,
partner_id=partner_id,
order_by_balance=order_by_balance,
order_by_traffic=order_by_traffic,
order_by_last_activity=order_by_last_activity,
@@ -457,7 +524,17 @@ async def list_users(
order_by_purchase_count=order_by_purchase_count,
)
total = await get_users_count(db=db, status=user_status, search=search, email=email)
total = await get_users_count(
db=db,
status=user_status,
search=search,
email=email,
subscription_status=subscription_status,
tariff_ids=tariff_ids,
promo_group_id=promo_group_id,
campaign_id=campaign_id,
partner_id=partner_id,
)
# Get spending stats for all users
user_ids = [u.id for u in users]
@@ -823,6 +900,50 @@ async def get_user_panel_info(
return UserPanelInfoResponse(found=False)
@router.get('/{user_id}/subscription-request-history')
async def get_subscription_request_history(
user_id: int,
admin: User = Depends(require_permission('users:read')),
db: AsyncSession = Depends(get_cabinet_db),
subscription_id: int | None = Query(None, description='Subscription ID for multi-tariff'),
offset: int = Query(0, ge=0),
limit: int = Query(20, ge=1, le=100),
):
"""Get subscription request history from RemnaWave panel."""
from app.database.crud.user import get_user_by_id
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')
panel_uuid = None
if settings.is_multi_tariff_enabled() and subscription_id:
from app.database.crud.subscription import get_subscription_by_id_for_user
sub = await get_subscription_by_id_for_user(db, subscription_id, user_id)
if sub:
panel_uuid = sub.remnawave_uuid
else:
panel_uuid = getattr(user, 'remnawave_uuid', None)
if not panel_uuid:
return {'total': 0, 'records': []}
try:
from app.services.remnawave_service import RemnaWaveService
service = RemnaWaveService()
if not service.is_configured:
return {'total': 0, 'records': []}
async with service.get_api_client() as api:
result = await api.get_subscription_request_history(panel_uuid, offset=offset, limit=limit)
return result
except Exception as e:
logger.error('Error getting subscription request history', user_id=user_id, error=e)
return {'total': 0, 'records': []}
@router.get('/{user_id}/node-usage', response_model=UserNodeUsageResponse)
async def get_user_node_usage(
user_id: int,
@@ -1050,6 +1171,17 @@ async def update_user_subscription(
detail='User already has a subscription. Enable multi-tariff mode to add more.',
)
# Проверка: нельзя создать вторую активную подписку с тем же тарифом
if is_multi_tariff and request.tariff_id:
from app.database.crud.subscription import get_subscription_by_user_and_tariff
existing = await get_subscription_by_user_and_tariff(db, user.id, request.tariff_id)
if existing:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='User already has an active subscription for this tariff. Extend it instead.',
)
from app.database.crud.subscription import create_paid_subscription
days = request.days or 30
@@ -1069,16 +1201,25 @@ async def update_user_subscription(
if tariff.allowed_squads:
connected_squads = tariff.allowed_squads
new_sub = await create_paid_subscription(
db=db,
user_id=user.id,
duration_days=days,
traffic_limit_gb=traffic_limit,
device_limit=device_limit,
is_trial=is_trial,
tariff_id=request.tariff_id,
connected_squads=connected_squads,
)
from sqlalchemy.exc import IntegrityError
try:
new_sub = await create_paid_subscription(
db=db,
user_id=user.id,
duration_days=days,
traffic_limit_gb=traffic_limit,
device_limit=device_limit,
is_trial=is_trial,
tariff_id=request.tariff_id,
connected_squads=connected_squads,
)
except IntegrityError:
await db.rollback()
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='User already has an active subscription for this tariff. Extend it instead.',
)
# Sync to Remnawave panel
await _sync_subscription_to_panel(db, user, new_sub)
@@ -1191,6 +1332,18 @@ async def update_user_subscription(
detail='Tariff not found',
)
# Проверка: нельзя сменить тариф, если у пользователя уже есть
# другая активная подписка с целевым тарифом
if is_multi_tariff and request.tariff_id != subscription.tariff_id:
from app.database.crud.subscription import get_subscription_by_user_and_tariff
existing = await get_subscription_by_user_and_tariff(db, user.id, request.tariff_id)
if existing and existing.id != subscription.id:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='User already has an active subscription for the target tariff',
)
# Preserve extra purchased devices above the old tariff's base limit
from app.database.crud.subscription import calc_device_limit_on_tariff_switch
@@ -1322,6 +1475,18 @@ async def update_user_subscription(
)
if request.action == 'activate':
# Проверка: нельзя активировать, если у пользователя уже есть
# другая активная подписка с тем же тарифом
if is_multi_tariff and subscription.tariff_id:
from app.database.crud.subscription import get_subscription_by_user_and_tariff
existing = await get_subscription_by_user_and_tariff(db, user.id, subscription.tariff_id)
if existing and existing.id != subscription.id:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail='Cannot activate: user already has an active subscription for this tariff',
)
subscription.status = SubscriptionStatus.ACTIVE.value
if subscription.end_date and subscription.end_date <= datetime.now(UTC):
# Extend by 30 days if expired
@@ -1627,9 +1792,25 @@ async def block_user(
admin: User = Depends(require_permission('users:block')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Block a user (shortcut for status update)."""
request = UpdateUserStatusRequest(status=UserStatusEnum.BLOCKED, reason=reason)
return await update_user_status(user_id, request, admin, db)
"""Block a user — sets DB status AND disables panel user in RemnaWave."""
from app.services.user_service import UserService
user_service = UserService()
success = await user_service.block_user(
db,
user_id,
admin.id,
reason=reason or 'Заблокирован администратором',
)
if not success:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='User not found or block failed')
return UpdateUserStatusResponse(
success=True,
old_status='active',
new_status='blocked',
message='User blocked',
)
@router.post('/{user_id}/unblock', response_model=UpdateUserStatusResponse)
@@ -1638,9 +1819,20 @@ async def unblock_user(
admin: User = Depends(require_permission('users:block')),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Unblock a user (shortcut for status update)."""
request = UpdateUserStatusRequest(status=UserStatusEnum.ACTIVE)
return await update_user_status(user_id, request, admin, db)
"""Unblock a user — sets DB status AND re-enables panel user in RemnaWave."""
from app.services.user_service import UserService
user_service = UserService()
success = await user_service.unblock_user(db, user_id, admin.id)
if not success:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail='User not found or unblock failed')
return UpdateUserStatusResponse(
success=True,
old_status='blocked',
new_status='active',
message='User unblocked',
)
# === Restrictions Management ===
@@ -3023,6 +3215,11 @@ async def sync_user_from_panel(
changes['remnawave_short_uuid'] = {'old': sub.remnawave_short_uuid, 'new': panel_user.short_uuid}
sub.remnawave_short_uuid = panel_user.short_uuid
# Update crypto link
if panel_user.happ_crypto_link and sub.subscription_crypto_link != panel_user.happ_crypto_link:
changes['subscription_crypto_link'] = {'old': sub.subscription_crypto_link, 'new': '***'}
sub.subscription_crypto_link = panel_user.happ_crypto_link
# Update traffic usage if requested
if request.update_traffic and sync_sub:
panel_traffic_used = panel_user.used_traffic_bytes / (1024**3) if panel_user.used_traffic_bytes else 0
@@ -3038,7 +3235,7 @@ async def sync_user_from_panel(
int(panel_user.traffic_limit_bytes / (1024**3)) if panel_user.traffic_limit_bytes else 100
)
panel_expire_utc = panel_datetime_to_utc(panel_user.expire_at)
days_remaining = max(1, (panel_expire_utc - datetime.now(UTC)).days)
days_remaining = max(1, math.ceil((panel_expire_utc - datetime.now(UTC)).total_seconds() / 86400))
new_sub = await create_paid_subscription(
db=db,
@@ -3241,7 +3438,10 @@ async def sync_user_to_panel(
await api.update_user(**update_kwargs)
action = 'updated'
except Exception as update_error:
if hasattr(update_error, 'status_code') and update_error.status_code == 404:
error_code = (getattr(update_error, 'response_data', None) or {}).get('errorCode', '')
if (
hasattr(update_error, 'status_code') and update_error.status_code == 404
) or error_code == 'A018':
# User not found in panel, create new
panel_uuid = None
else:
+3 -4
View File
@@ -815,10 +815,9 @@ async def auth_telegram_oidc(
# Update user info from OIDC claims
if username and username != user.username:
user.username = username
if first_name and first_name != user.first_name:
user.first_name = first_name
if last_name is not None and last_name != user.last_name:
user.last_name = last_name
# NOTE: не обновляем first_name/last_name из OIDC
# Telegram OIDC возвращает только поле name как полное имя без разделения на first/last
# Имя правильно заполняется через middleware при обычном использовании бота
user.cabinet_last_login = datetime.now(UTC)
await db.commit()
+130
View File
@@ -794,6 +794,126 @@ async def create_topup(
detail='Failed to create SeverPay payment',
)
elif request.payment_method == 'paypear':
if not settings.is_paypear_enabled():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='PayPear payment method is unavailable',
)
payment_service = PaymentService()
result = await payment_service.create_paypear_payment(
db=db,
user_id=user.id,
amount_kopeks=request.amount_kopeks,
description=settings.get_balance_payment_description(
request.amount_kopeks, telegram_user_id=user.telegram_id, user_db_id=user.id
),
email=getattr(user, 'email', None),
language=getattr(user, 'language', None) or settings.DEFAULT_LANGUAGE,
return_url=cabinet_success_url,
)
if result and result.get('payment_url'):
payment_url = result.get('payment_url')
payment_id = str(result.get('local_payment_id') or result.get('order_id') or 'pending')
else:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to create PayPear payment',
)
elif request.payment_method == 'rollypay':
if not settings.is_rollypay_enabled():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='RollyPay payment method is unavailable',
)
payment_service = PaymentService()
payment_method_type = request.payment_option or None
result = await payment_service.create_rollypay_payment(
db=db,
user_id=user.id,
amount_kopeks=request.amount_kopeks,
description=settings.get_balance_payment_description(
request.amount_kopeks, telegram_user_id=user.telegram_id, user_db_id=user.id
),
email=getattr(user, 'email', None),
language=getattr(user, 'language', None) or settings.DEFAULT_LANGUAGE,
payment_method_type=payment_method_type,
return_url=cabinet_success_url,
)
if result and result.get('payment_url'):
payment_url = result.get('payment_url')
payment_id = str(result.get('local_payment_id') or result.get('order_id') or 'pending')
else:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to create RollyPay payment',
)
elif request.payment_method == 'overpay':
if not settings.is_overpay_enabled():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Overpay payment method is unavailable',
)
payment_service = PaymentService()
result = await payment_service.create_overpay_payment(
db=db,
user_id=user.id,
amount_kopeks=request.amount_kopeks,
description=settings.get_balance_payment_description(
request.amount_kopeks, telegram_user_id=user.telegram_id, user_db_id=user.id
),
email=getattr(user, 'email', None),
language=getattr(user, 'language', None) or settings.DEFAULT_LANGUAGE,
return_url=cabinet_success_url,
)
if result and result.get('payment_url'):
payment_url = result.get('payment_url')
payment_id = str(result.get('local_payment_id') or result.get('order_id') or 'pending')
else:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to create Overpay payment',
)
elif request.payment_method == 'aurapay':
if not settings.is_aurapay_enabled():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='AuraPay payment method is unavailable',
)
payment_service = PaymentService()
payment_method_type = request.payment_option or None
result = await payment_service.create_aurapay_payment(
db=db,
user_id=user.id,
amount_kopeks=request.amount_kopeks,
description=settings.get_balance_payment_description(
request.amount_kopeks, telegram_user_id=user.telegram_id, user_db_id=user.id
),
email=getattr(user, 'email', None),
language=getattr(user, 'language', None) or settings.DEFAULT_LANGUAGE,
payment_method_type=payment_method_type,
return_url=cabinet_success_url,
)
if result and result.get('payment_url'):
payment_url = result.get('payment_url')
payment_id = str(result.get('local_payment_id') or result.get('order_id') or 'pending')
else:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to create AuraPay payment',
)
else:
# For other payment methods, redirect to bot
raise HTTPException(
@@ -1086,15 +1206,20 @@ async def get_latest_payment_by_method(
from sqlalchemy.orm import selectinload
from app.database.models import (
AuraPayPayment,
CloudPaymentsPayment,
CryptoBotPayment,
FreekassaPayment,
HeleketPayment,
KassaAiPayment,
MulenPayPayment,
OverpayPayment,
Pal24Payment,
PayPearPayment,
PlategaPayment,
RioPayPayment,
RollyPayPayment,
SeverPayPayment,
WataPayment,
YooKassaPayment,
)
@@ -1111,6 +1236,11 @@ async def get_latest_payment_by_method(
PaymentMethod.FREEKASSA: FreekassaPayment,
PaymentMethod.KASSA_AI: KassaAiPayment,
PaymentMethod.RIOPAY: RioPayPayment,
PaymentMethod.SEVERPAY: SeverPayPayment,
PaymentMethod.ROLLYPAY: RollyPayPayment,
PaymentMethod.PAYPEAR: PayPearPayment,
PaymentMethod.OVERPAY: OverpayPayment,
PaymentMethod.AURAPAY: AuraPayPayment,
}
model = model_map.get(payment_method)
+73 -1
View File
@@ -17,7 +17,7 @@ from app.config import settings
from app.database.crud.system_setting import get_setting_value
from app.database.models import SystemSetting, User
from ..dependencies import get_cabinet_db, require_permission
from ..dependencies import get_cabinet_db, get_current_cabinet_user, require_permission
logger = structlog.get_logger(__name__)
@@ -291,12 +291,24 @@ class GiftEnabledUpdate(BaseModel):
enabled: bool
class OfflineConvGoal(BaseModel):
"""Yandex Metrika offline conversion goal descriptor."""
name: str
event_id: str
dedup: str
class AnalyticsCountersResponse(BaseModel):
"""Analytics counter settings."""
yandex_metrika_id: str = ''
google_ads_id: str = ''
google_ads_label: str = ''
offline_conv_enabled: bool = False
offline_conv_counter_id: str = ''
offline_conv_measurement_secret_masked: str = ''
offline_conv_goals: list[OfflineConvGoal] = []
class AnalyticsCountersUpdate(BaseModel):
@@ -924,10 +936,27 @@ async def get_analytics_counters(
google_id = await get_setting_value(db, GOOGLE_ADS_ID_KEY) or ''
google_label = await get_setting_value(db, GOOGLE_ADS_LABEL_KEY) or ''
# Yandex Metrika offline conversions snapshot from Settings
oc_enabled = bool(getattr(settings, 'YANDEX_OFFLINE_CONV_ENABLED', False))
oc_counter = str(getattr(settings, 'YANDEX_OFFLINE_CONV_COUNTER_ID', '') or '')
oc_secret = str(getattr(settings, 'YANDEX_OFFLINE_CONV_MEASUREMENT_SECRET', '') or '')
oc_secret_masked = ('*' * 8 + oc_secret[-4:]) if len(oc_secret) > 4 else ('***' if oc_secret else '')
oc_goals: list[OfflineConvGoal] = []
if oc_enabled:
oc_goals = [
OfflineConvGoal(name='Registration', event_id='registration', dedup='user_id'),
OfflineConvGoal(name='Trial', event_id='trial-add', dedup='user_id'),
OfflineConvGoal(name='Purchase', event_id='purchase', dedup='order_id'),
]
return AnalyticsCountersResponse(
yandex_metrika_id=yandex_id,
google_ads_id=google_id,
google_ads_label=google_label,
offline_conv_enabled=oc_enabled,
offline_conv_counter_id=oc_counter,
offline_conv_measurement_secret_masked=oc_secret_masked,
offline_conv_goals=oc_goals,
)
@@ -966,13 +995,56 @@ async def update_analytics_counters(
google_id = await get_setting_value(db, GOOGLE_ADS_ID_KEY) or ''
google_label = await get_setting_value(db, GOOGLE_ADS_LABEL_KEY) or ''
oc_enabled = bool(getattr(settings, 'YANDEX_OFFLINE_CONV_ENABLED', False))
oc_counter = str(getattr(settings, 'YANDEX_OFFLINE_CONV_COUNTER_ID', '') or '')
oc_secret = str(getattr(settings, 'YANDEX_OFFLINE_CONV_MEASUREMENT_SECRET', '') or '')
oc_secret_masked = ('*' * 8 + oc_secret[-4:]) if len(oc_secret) > 4 else ('***' if oc_secret else '')
oc_goals: list[OfflineConvGoal] = []
if oc_enabled:
oc_goals = [
OfflineConvGoal(name='Registration', event_id='registration', dedup='user_id'),
OfflineConvGoal(name='Trial', event_id='trial-add', dedup='user_id'),
OfflineConvGoal(name='Purchase', event_id='purchase', dedup='order_id'),
]
return AnalyticsCountersResponse(
yandex_metrika_id=yandex_id,
google_ads_id=google_id,
google_ads_label=google_label,
offline_conv_enabled=oc_enabled,
offline_conv_counter_id=oc_counter,
offline_conv_measurement_secret_masked=oc_secret_masked,
offline_conv_goals=oc_goals,
)
# ============ Yandex CID Sync ============
class YandexCidRequest(BaseModel):
cid: str = Field(max_length=128, pattern=r'^[A-Za-z0-9._:-]{4,128}$')
@router.post('/analytics/yandex-cid', status_code=204)
async def store_yandex_cid(
body: YandexCidRequest,
user: User = Depends(get_current_cabinet_user),
db: AsyncSession = Depends(get_cabinet_db),
):
"""Store Yandex Metrika ClientID for the authenticated cabinet user."""
try:
from app.services import yandex_offline_conv_service as yandex_conv
await yandex_conv.store_cid(db, user.id, body.cid, source='cabinet')
await db.commit()
except Exception as exc:
logger.warning('Failed to store yandex_cid', user_id=user.id, exc=str(exc))
try:
await db.rollback()
except Exception:
pass
# ============ Lite Mode Routes ============
+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)
+36 -1
View File
@@ -23,7 +23,7 @@ from app.services.guest_purchase_service import (
)
from app.services.payment_method_config_service import _get_method_defaults
from app.services.payment_service import PaymentService
from app.utils.cache import RateLimitCache
from app.utils.cache import RateLimitCache, cache
logger = structlog.get_logger(__name__)
@@ -99,6 +99,11 @@ class LandingConfigResponse(BaseModel):
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,}$')
@@ -123,6 +128,9 @@ class PurchaseRequest(BaseModel):
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':
@@ -535,6 +543,11 @@ async def get_landing_config(
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,
)
@@ -644,9 +657,17 @@ async def create_landing_purchase(
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}'
@@ -690,6 +711,20 @@ async def create_landing_purchase(
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,
+10
View File
@@ -99,25 +99,35 @@ async def upload_media(
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(
+2 -2
View File
@@ -28,7 +28,7 @@ class NotificationSettingsResponse(BaseModel):
subscription_expiry_days: int = 3
traffic_warning_enabled: bool = True
traffic_warning_percent: int = 80
balance_low_enabled: bool = True
balance_low_enabled: bool = False
balance_low_threshold: int = 100 # kopeks
news_enabled: bool = True
promo_offers_enabled: bool = True
@@ -60,7 +60,7 @@ def _get_notification_settings(user: User) -> dict[str, Any]:
'subscription_expiry_days': settings_data.get('subscription_expiry_days', 3),
'traffic_warning_enabled': settings_data.get('traffic_warning_enabled', True),
'traffic_warning_percent': settings_data.get('traffic_warning_percent', 80),
'balance_low_enabled': settings_data.get('balance_low_enabled', True),
'balance_low_enabled': settings_data.get('balance_low_enabled', False),
'balance_low_threshold': settings_data.get('balance_low_threshold', 100),
'news_enabled': settings_data.get('news_enabled', True),
'promo_offers_enabled': settings_data.get('promo_offers_enabled', True),
+1 -1
View File
@@ -144,7 +144,7 @@ async def get_available_polls(
selectinload(PollResponse.poll).selectinload(Poll.questions),
selectinload(PollResponse.answers),
)
.order_by(PollResponse.created_at.desc())
.order_by(PollResponse.sent_at.desc())
)
responses = result.scalars().all()
+24
View File
@@ -5,6 +5,7 @@ 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
@@ -67,6 +68,29 @@ async def activate_promocode(
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',
@@ -49,7 +49,8 @@ async def update_autopay(
)
# Триальные подписки — пробник, автопродление не имеет смысла
if subscription.is_trial:
# 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',
@@ -13,6 +13,7 @@ POST /subscription/devices/save-cart
from __future__ import annotations
import math
from datetime import UTC, datetime
from typing import Any
@@ -108,7 +109,24 @@ async def purchase_devices_legacy(
detail='Докупка устройств недоступна',
)
base_total_price = device_price * request.devices
# Устройства в пределах тарифного лимита — бесплатные
current_devices = subscription.device_limit or 1
if tariff:
tariff_included = tariff.device_limit or 0
if current_devices < tariff_included:
free_devices = tariff_included - current_devices
chargeable_devices = max(0, request.devices - free_devices)
else:
chargeable_devices = request.devices
else:
free_baseline = settings.DEFAULT_DEVICE_LIMIT
if current_devices < free_baseline:
free_devices = free_baseline - current_devices
chargeable_devices = max(0, request.devices - free_devices)
else:
chargeable_devices = request.devices
base_total_price = device_price * chargeable_devices
# Lock user row to prevent TOCTOU on promo-offer state
from app.database.crud.user import lock_user_for_pricing
@@ -228,10 +246,15 @@ async def purchase_devices_legacy(
# Sync with RemnaWave
try:
service = SubscriptionService()
if _resolve_panel_uuid(subscription, user):
await service.update_remnawave_user(db, subscription)
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(user, 'remnawave_uuid', None)
if _should_create:
await service.create_remnawave_user(db, subscription)
else:
await service.update_remnawave_user(db, subscription)
except Exception as e:
logger.error('Failed to sync devices with RemnaWave (legacy endpoint)', error=e)
from app.services.remnawave_retry_queue import remnawave_retry_queue
@@ -239,7 +262,7 @@ async def purchase_devices_legacy(
remnawave_retry_queue.enqueue(
subscription_id=subscription.id,
user_id=user.id,
action='update' if _resolve_panel_uuid(subscription, user) else 'create',
action='create' if _should_create else 'update',
)
# Отправляем уведомление админам
@@ -358,13 +381,30 @@ async def purchase_devices(
if end_date.tzinfo is None:
end_date = end_date.replace(tzinfo=UTC)
days_left = max(1, (end_date - now).days)
days_left = max(1, math.ceil((end_date - now).total_seconds() / 86400))
total_days = 30 # Base period for device price calculation
# Устройства в пределах тарифного лимита — бесплатные
if tariff:
tariff_included = tariff.device_limit or 0
if current_devices < tariff_included:
free_devices = tariff_included - current_devices
chargeable_devices = max(0, request.devices - free_devices)
else:
chargeable_devices = request.devices
else:
free_baseline = settings.DEFAULT_DEVICE_LIMIT
if current_devices < free_baseline:
free_devices = free_baseline - current_devices
chargeable_devices = max(0, request.devices - free_devices)
else:
chargeable_devices = request.devices
# Calculate base price before discount
base_price_per_month = device_price * request.devices
base_price_per_month = device_price * chargeable_devices
base_price_prorated = int(base_price_per_month * days_left / total_days)
base_price_prorated = max(100, base_price_prorated) # Minimum 1 ruble
if chargeable_devices > 0:
base_price_prorated = max(100, base_price_prorated) # Minimum 1 ruble
# Lock user BEFORE discount computation to prevent TOCTOU on promo group
from app.database.crud.user import lock_user_for_pricing
@@ -476,10 +516,15 @@ async def purchase_devices(
# Sync with RemnaWave
service = SubscriptionService()
try:
if _resolve_panel_uuid(subscription, user):
await service.update_remnawave_user(db, subscription)
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(user, 'remnawave_uuid', None)
if _should_create:
await service.create_remnawave_user(db, subscription)
else:
await service.update_remnawave_user(db, subscription)
except Exception as e:
logger.error('Failed to sync devices with RemnaWave', error=e)
from app.services.remnawave_retry_queue import remnawave_retry_queue
@@ -487,7 +532,7 @@ async def purchase_devices(
remnawave_retry_queue.enqueue(
subscription_id=subscription.id,
user_id=user.id,
action='update' if _resolve_panel_uuid(subscription, user) else 'create',
action='create' if _should_create else 'update',
)
await db.refresh(user)
@@ -614,11 +659,28 @@ async def save_devices_cart(
if end_date.tzinfo is None:
end_date = end_date.replace(tzinfo=UTC)
days_left = max(1, (end_date - now).days)
days_left = max(1, math.ceil((end_date - now).total_seconds() / 86400))
total_days = 30
base_total_price = int(device_price * request.devices * days_left / total_days)
base_total_price = max(100, base_total_price) # Minimum 1 ruble
# Устройства в пределах тарифного лимита — бесплатные
if tariff:
tariff_included = tariff.device_limit or 0
if current_devices < tariff_included:
free_devices = tariff_included - current_devices
chargeable_devices = max(0, request.devices - free_devices)
else:
chargeable_devices = request.devices
else:
free_baseline = settings.DEFAULT_DEVICE_LIMIT
if current_devices < free_baseline:
free_devices = free_baseline - current_devices
chargeable_devices = max(0, request.devices - free_devices)
else:
chargeable_devices = request.devices
base_total_price = int(device_price * chargeable_devices * days_left / total_days)
if chargeable_devices > 0:
base_total_price = max(100, base_total_price) # Minimum 1 ruble
# Apply discount from promo group
period_hint_days = days_left
@@ -711,12 +773,29 @@ async def get_device_price(
if end_date.tzinfo is None:
end_date = end_date.replace(tzinfo=UTC)
days_left = max(1, (end_date - now).days)
days_left = max(1, math.ceil((end_date - now).total_seconds() / 86400))
total_days = 30
# Устройства в пределах тарифного лимита — бесплатные
if tariff:
tariff_included = tariff.device_limit or 0
if current_devices < tariff_included:
free_devices = tariff_included - current_devices
chargeable_devices = max(0, devices - free_devices)
else:
chargeable_devices = devices
else:
free_baseline = settings.DEFAULT_DEVICE_LIMIT
if current_devices < free_baseline:
free_devices = free_baseline - current_devices
chargeable_devices = max(0, devices - free_devices)
else:
chargeable_devices = devices
# Calculate base price before discount (total first, then floor)
base_total_price = int(device_price * devices * days_left / total_days)
base_total_price = max(100, base_total_price)
base_total_price = int(device_price * chargeable_devices * days_left / total_days)
if chargeable_devices > 0:
base_total_price = max(100, base_total_price)
# Apply discount from promo group
period_hint_days = days_left
@@ -353,6 +353,9 @@ async def get_purchase_options(
'all_tariffs_purchased': len(purchased_tariff_ids) >= len(tariffs)
if settings.is_multi_tariff_enabled()
else False,
# Направления смены тарифа
'tariff_switch_upgrade_enabled': settings.TARIFF_SWITCH_UPGRADE_ENABLED,
'tariff_switch_downgrade_enabled': settings.TARIFF_SWITCH_DOWNGRADE_ENABLED,
}
# Classic mode - return periods
@@ -892,8 +895,14 @@ async def purchase_tariff(
except Exception as trial_err:
logger.warning('Failed to disable trial on RemnaWave', error=trial_err, trial_id=trial_sub.id)
try:
if subscription.remnawave_uuid:
# Existing subscription with Remnawave user — update it
# Mirror the bot handler logic: in single-tariff mode, check user.remnawave_uuid
# (webhook clears it on panel deletion), not subscription.remnawave_uuid
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(user, 'remnawave_uuid', None)
if not _should_create:
await service.update_remnawave_user(
db,
subscription,
@@ -902,7 +911,6 @@ async def purchase_tariff(
sync_squads=True,
)
else:
# New subscription — create new Remnawave user
await service.create_remnawave_user(
db,
subscription,
@@ -916,7 +924,7 @@ async def purchase_tariff(
remnawave_retry_queue.enqueue(
subscription_id=subscription.id,
user_id=user.id,
action='create' if not subscription.remnawave_uuid else 'update',
action='create' if _should_create else 'update',
)
# Save cart for auto-renewal (not for daily tariffs - they have their own charging)
@@ -1219,9 +1227,11 @@ async def activate_trial(
trial_tariff = None
if trial_tariff:
from app.database.crud.server_squad import get_effective_tariff_squad_uuids
trial_traffic_limit = trial_tariff.traffic_limit_gb
trial_device_limit = trial_tariff.device_limit
trial_squads = trial_tariff.allowed_squads or []
trial_squads = await get_effective_tariff_squad_uuids(db, trial_tariff.allowed_squads)
tariff_id_for_trial = trial_tariff.id
tariff_trial_days = getattr(trial_tariff, 'trial_duration_days', None)
if tariff_trial_days:
@@ -1235,7 +1245,7 @@ async def activate_trial(
except Exception as e:
logger.error('Error getting trial tariff', error=e)
# BUG-12 fix: If no squads from tariff, fallback to trial-eligible servers
# No trial tariff configured, use the legacy random trial squad fallback.
if not trial_squads:
from app.database.crud.server_squad import get_random_trial_squad_uuid
@@ -57,7 +57,14 @@ async def get_renewal_options(
return []
# Determine available periods
if subscription.tariff_id and subscription.tariff and subscription.tariff.period_prices:
# Скрытый/неактивный тариф (например, триальный после промокода) —
# не показываем его периоды, используем стандартные
if (
subscription.tariff_id
and subscription.tariff
and subscription.tariff.is_active
and subscription.tariff.period_prices
):
periods = sorted(int(k) for k in subscription.tariff.period_prices.keys())
else:
periods = settings.get_available_renewal_periods()
@@ -128,7 +135,12 @@ async def renew_subscription(
detail=f'Cannot renew subscription with status: {_actual_status}',
)
if subscription.tariff_id and subscription.tariff and subscription.tariff.period_prices:
if (
subscription.tariff_id
and subscription.tariff
and subscription.tariff.is_active
and subscription.tariff.period_prices
):
available_periods = [int(p) for p in subscription.tariff.period_prices.keys()]
else:
available_periods = settings.get_available_renewal_periods()
@@ -119,6 +119,18 @@ async def preview_tariff_switch(
)
upgrade_cost = switch_result.upgrade_cost
is_upgrade = switch_result.is_upgrade
# Проверяем разрешение на смену в данном направлении
if is_upgrade and not settings.TARIFF_SWITCH_UPGRADE_ENABLED:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Повышение тарифа недоступно',
)
if not is_upgrade and not settings.TARIFF_SWITCH_DOWNGRADE_ENABLED:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Понижение тарифа недоступно',
)
base_upgrade_cost = switch_result.raw_cost
discount_value = switch_result.discount_value
period_discount_percent = switch_result.effective_discount_pct
@@ -263,11 +275,24 @@ async def switch_tariff(
user=user,
)
upgrade_cost = switch_result.upgrade_cost
is_upgrade = switch_result.is_upgrade
base_upgrade_cost = switch_result.raw_cost
discount_value = switch_result.discount_value
period_discount_percent = switch_result.effective_discount_pct
new_period_days = switch_result.new_period_days
# Проверяем разрешение на смену в данном направлении
if is_upgrade and not settings.TARIFF_SWITCH_UPGRADE_ENABLED:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Повышение тарифа недоступно',
)
if not is_upgrade and not settings.TARIFF_SWITCH_DOWNGRADE_ENABLED:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail='Понижение тарифа недоступно',
)
# Validate daily price for switching TO daily
new_is_daily = getattr(new_tariff, 'is_daily', False)
current_is_daily = getattr(current_tariff, 'is_daily', False) if current_tariff else False
@@ -9,6 +9,7 @@ POST /subscription/traffic/save-cart
from __future__ import annotations
import math
from datetime import UTC, datetime
from typing import Any
@@ -316,17 +317,23 @@ async def purchase_traffic(
# Синхронизируем с RemnaWave
try:
subscription_service = SubscriptionService()
_panel_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else getattr(user, 'remnawave_uuid', None)
)
if _panel_uuid:
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(user, 'remnawave_uuid', None)
if _should_create:
await subscription_service.create_remnawave_user(db, subscription)
else:
await subscription_service.update_remnawave_user(db, subscription)
if subscription.status == 'active':
await subscription_service.enable_remnawave_user(_panel_uuid)
else:
await subscription_service.create_remnawave_user(db, subscription)
_enable_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled()
else getattr(user, 'remnawave_uuid', None)
)
if _enable_uuid:
await subscription_service.enable_remnawave_user(_enable_uuid)
except Exception as e:
logger.error('Failed to sync traffic with RemnaWave', error=e)
from app.services.remnawave_retry_queue import remnawave_retry_queue
@@ -334,7 +341,7 @@ async def purchase_traffic(
remnawave_retry_queue.enqueue(
subscription_id=subscription.id,
user_id=user.id,
action='update' if _panel_uuid else 'create',
action='create' if _should_create else 'update',
)
# Создаём транзакцию
@@ -472,7 +479,7 @@ async def save_traffic_cart(
from app.utils.pricing_utils import calculate_prorated_price as _calc_prorated
now = datetime.now(UTC)
days_left = max(1, (subscription.end_date - now).days)
days_left = max(1, math.ceil((subscription.end_date - now).total_seconds() / 86400))
prorated_price, _ = _calc_prorated(
base_price_kopeks,
subscription.end_date,
@@ -611,15 +618,15 @@ async def switch_traffic_package(
# Sync with RemnaWave
try:
subscription_service = SubscriptionService()
_panel_uuid2 = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else getattr(user, 'remnawave_uuid', None)
)
if _panel_uuid2:
await subscription_service.update_remnawave_user(db, subscription)
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(user, 'remnawave_uuid', None)
if _should_create:
await subscription_service.create_remnawave_user(db, subscription)
else:
await subscription_service.update_remnawave_user(db, subscription)
except Exception as e:
logger.error('Failed to sync traffic switch with RemnaWave', error=e)
from app.services.remnawave_retry_queue import remnawave_retry_queue
@@ -628,7 +635,7 @@ async def switch_traffic_package(
remnawave_retry_queue.enqueue(
subscription_id=subscription.id,
user_id=subscription.user_id,
action='update' if _panel_uuid2 else 'create',
action='create' if _should_create else 'update',
)
await db.refresh(user)
+49 -9
View File
@@ -20,6 +20,7 @@ from ..schemas.tickets import (
TicketCreateRequest,
TicketDetailResponse,
TicketListResponse,
TicketMediaItem,
TicketMessageCreateRequest,
TicketMessageResponse,
TicketResponse,
@@ -33,14 +34,23 @@ router = APIRouter(prefix='/tickets', tags=['Cabinet Tickets'])
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),
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,
)
@@ -143,15 +153,30 @@ async def create_ticket(
db.add(ticket)
await db.flush()
# Resolve media payload
items_payload = None
primary_type = request.media_type
primary_file_id = request.media_file_id
primary_caption = request.media_caption
if getattr(request, 'media_items', None):
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
# Create initial message with optional media
has_media = bool(primary_file_id)
message = TicketMessage(
ticket_id=ticket.id,
user_id=user.id,
message_text=request.message,
is_from_admin=False,
media_type=request.media_type,
media_file_id=request.media_file_id,
media_caption=request.media_caption,
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)
@@ -259,15 +284,30 @@ async def add_ticket_message(
detail='Replies to this ticket are blocked',
)
# Resolve media payload
items_payload = None
primary_type = request.media_type
primary_file_id = request.media_file_id
primary_caption = request.media_caption
if getattr(request, 'media_items', None):
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
# Create message with optional media
has_media = bool(primary_file_id)
message = TicketMessage(
ticket_id=ticket.id,
user_id=user.id,
message_text=request.message,
is_from_admin=False,
media_type=request.media_type,
media_file_id=request.media_file_id,
media_caption=request.media_caption,
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)
@@ -286,8 +326,8 @@ async def add_ticket_message(
ticket,
request.message,
db,
media_file_id=request.media_file_id,
media_type=request.media_type,
media_file_id=primary_file_id,
media_type=primary_type,
)
except Exception as e:
logger.error('Error notifying admins about ticket reply from cabinet', error=e)
+78
View File
@@ -0,0 +1,78 @@
"""Schemas for admin bulk actions."""
from enum import StrEnum
from pydantic import BaseModel, Field, model_validator
class BulkActionType(StrEnum):
EXTEND_SUBSCRIPTION = 'extend_subscription'
CANCEL_SUBSCRIPTION = 'cancel_subscription'
ACTIVATE_SUBSCRIPTION = 'activate_subscription'
CHANGE_TARIFF = 'change_tariff'
ADD_DAYS = 'add_days'
ADD_TRAFFIC = 'add_traffic'
ADD_BALANCE = 'add_balance'
ASSIGN_PROMO_GROUP = 'assign_promo_group'
GRANT_SUBSCRIPTION = 'grant_subscription'
SET_DEVICES = 'set_devices'
DELETE_SUBSCRIPTION = 'delete_subscription'
DELETE_USER = 'delete_user'
class BulkActionParams(BaseModel):
days: int | None = Field(None, ge=1, le=3650)
tariff_id: int | None = Field(None, gt=0)
traffic_gb: int | None = Field(None, ge=1, le=10000)
amount_kopeks: int | None = Field(None, ge=1, le=2_000_000_000)
balance_description: str = Field(default='Массовое начисление баланса', max_length=500)
promo_group_id: int | None = None
device_limit: int | None = Field(None, ge=1, le=50)
delete_from_panel: bool = Field(default=True)
force_delete_active_paid: bool = Field(default=False)
class BulkSubscriptionInfo(BaseModel):
id: int
tariff_id: int | None = None
tariff_name: str | None = None
status: str
days_remaining: int
traffic_used_gb: float = 0
traffic_limit_gb: int = 0
device_limit: int = 0
class BulkExecuteRequest(BaseModel):
action: BulkActionType
user_ids: list[int] | None = Field(None, min_length=1, max_length=500)
subscription_ids: list[int] | None = Field(None, min_length=1, max_length=2000)
params: BulkActionParams = Field(default_factory=BulkActionParams)
dry_run: bool = Field(default=False, description='Preview only, no mutations')
@model_validator(mode='after')
def _exactly_one_target(self):
has_users = self.user_ids is not None
has_subs = self.subscription_ids is not None
if has_users == has_subs:
raise ValueError('Exactly one of user_ids or subscription_ids must be provided')
return self
class BulkUserResult(BaseModel):
user_id: int
subscription_id: int | None = None
success: bool
message: str
username: str | None = None
subscriptions: list[BulkSubscriptionInfo] | None = None
class BulkExecuteResponse(BaseModel):
action: str
total: int
success_count: int
error_count: int
skipped_count: int
dry_run: bool
results: list[BulkUserResult]
+78
View File
@@ -0,0 +1,78 @@
"""Schemas for info pages in cabinet."""
from datetime import datetime
from pydantic import BaseModel, ConfigDict, Field
class InfoPageResponse(BaseModel):
"""Full info page response."""
id: int
slug: str
title: dict[str, str]
content: dict[str, str]
page_type: str = 'page'
is_active: bool
sort_order: int
icon: str | None = None
replaces_tab: str | None = None
created_at: datetime
updated_at: datetime | None = None
model_config = ConfigDict(from_attributes=True)
class InfoPageListItem(BaseModel):
"""Compact info page for list views."""
id: int
slug: str
title: dict[str, str]
page_type: str = 'page'
is_active: bool
sort_order: int
icon: str | None = None
replaces_tab: str | None = None
updated_at: datetime | None = None
model_config = ConfigDict(from_attributes=True)
class InfoPageCreateRequest(BaseModel):
"""Request to create an info page."""
slug: str = Field(min_length=1, max_length=200, pattern=r'^[a-z0-9\-]+$')
title: dict[str, str] = Field(default_factory=dict)
content: dict[str, str] = Field(default_factory=dict)
page_type: str = Field(default='page', pattern=r'^(page|faq)$')
is_active: bool = True
sort_order: int = 0
icon: str | None = Field(None, max_length=50)
replaces_tab: str | None = Field(None, pattern=r'^(faq|rules|privacy|offer)$')
class InfoPageUpdateRequest(BaseModel):
"""Request to update an info page."""
slug: str | None = Field(None, min_length=1, max_length=200, pattern=r'^[a-z0-9\-]+$')
title: dict[str, str] | None = None
content: dict[str, str] | None = None
page_type: str | None = Field(None, pattern=r'^(page|faq)$')
is_active: bool | None = None
sort_order: int | None = None
icon: str | None = Field(None, max_length=50)
replaces_tab: str | None = Field(None, pattern=r'^(faq|rules|privacy|offer)$')
class ReorderItem(BaseModel):
"""Single item in a reorder request."""
id: int
sort_order: int = Field(ge=0)
class ReorderRequest(BaseModel):
"""Request to bulk-reorder info pages."""
items: list[ReorderItem] = Field(..., min_length=1)
+67 -3
View File
@@ -2,7 +2,50 @@
from datetime import datetime
from pydantic import BaseModel, Field
from pydantic import BaseModel, Field, model_validator
ALLOWED_MEDIA_TYPES = {'photo', 'video', 'document'}
MAX_MEDIA_ITEMS = 10
class TicketMediaItem(BaseModel):
"""Single media attachment in a ticket message."""
type: str = Field(..., description='Media type: photo, video, or document')
file_id: str = Field(..., max_length=255, description='Telegram file_id')
caption: str | None = Field(None, max_length=1000, description='Optional caption')
@model_validator(mode='after')
def validate_type(self) -> 'TicketMediaItem':
if self.type not in ALLOWED_MEDIA_TYPES:
raise ValueError(f'type must be one of: {sorted(ALLOWED_MEDIA_TYPES)}')
return self
def _validate_media_bundle(
media_type: str | None,
media_file_id: str | None,
media_items: list[TicketMediaItem] | None,
) -> None:
"""Shared validator for media-attached request bodies."""
if media_items is not None:
if len(media_items) == 0:
raise ValueError('media_items must not be empty (send null instead)')
if len(media_items) > MAX_MEDIA_ITEMS:
raise ValueError(f'media_items cannot exceed {MAX_MEDIA_ITEMS} entries')
if media_file_id and media_file_id != media_items[0].file_id:
raise ValueError('legacy media_file_id must match media_items[0].file_id')
if media_type and media_type != media_items[0].type:
raise ValueError('legacy media_type must match media_items[0].type')
return
if media_file_id and not media_type:
raise ValueError('media_type is required when media_file_id is provided')
if media_type and not media_file_id:
raise ValueError('media_file_id is required when media_type is provided')
if media_type and media_type not in ALLOWED_MEDIA_TYPES:
raise ValueError(f'media_type must be one of: {sorted(ALLOWED_MEDIA_TYPES)}')
class TicketMessageResponse(BaseModel):
@@ -15,6 +58,7 @@ class TicketMessageResponse(BaseModel):
media_type: str | None = None
media_file_id: str | None = None
media_caption: str | None = None
media_items: list[TicketMediaItem] | None = None
created_at: datetime
class Config:
@@ -69,16 +113,36 @@ class TicketCreateRequest(BaseModel):
"""Request to create a new ticket."""
title: str = Field(..., min_length=3, max_length=255, description='Ticket title')
message: str = Field(..., min_length=10, max_length=4000, description='Initial message')
message: str = Field(default='', max_length=4000, description='Initial message')
media_type: str | None = Field(None, description='Media type: photo, video, document')
media_file_id: str | None = Field(None, description='Telegram file_id of uploaded media')
media_caption: str | None = Field(None, max_length=1000, description='Media caption')
media_items: list[TicketMediaItem] | None = Field(None, description='Multi-media attachments')
@model_validator(mode='after')
def validate_has_content(self) -> 'TicketCreateRequest':
_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 TicketMessageCreateRequest(BaseModel):
"""Request to add message to ticket."""
message: str = Field(..., min_length=1, max_length=4000, description='Message text')
message: str = Field(default='', max_length=4000, description='Message text')
media_type: str | None = Field(None, description='Media type: photo, video, document')
media_file_id: str | None = Field(None, description='Telegram file_id of uploaded media')
media_caption: str | None = Field(None, max_length=1000, description='Media caption')
media_items: list[TicketMediaItem] | None = Field(None, description='Multi-media attachments')
@model_validator(mode='after')
def validate_has_content(self) -> 'TicketMessageCreateRequest':
_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
+24
View File
@@ -82,6 +82,21 @@ class UserPromoGroupInfo(BaseModel):
# === User List ===
class SubscriptionListItem(BaseModel):
"""Compact subscription info for user list (multi-tariff mode)."""
id: int
tariff_id: int | None = None
tariff_name: str | None = None
status: str
is_trial: bool = False
end_date: datetime | None = None
days_remaining: int = 0
traffic_used_gb: float = 0
traffic_limit_gb: int = 0
device_limit: int = 0
class UserListItem(BaseModel):
"""User item in list."""
@@ -102,6 +117,15 @@ class UserListItem(BaseModel):
subscription_status: str | None = None
subscription_is_trial: bool = False
subscription_end_date: datetime | None = None
tariff_id: int | None = None
tariff_name: str | None = None
traffic_used_gb: float = 0
traffic_limit_gb: int = 0
device_limit: int = 0
days_remaining: int = 0
# All subscriptions (multi-tariff)
subscriptions: list[SubscriptionListItem] = []
# Promo group
promo_group_id: int | None = None
+10 -1
View File
@@ -12,7 +12,16 @@ def get_campaign_deep_link(start_parameter: str) -> str:
def get_campaign_web_link(start_parameter: str) -> str | None:
"""Generate a web app link for a campaign."""
"""Generate a web app link for a campaign.
Prefers CABINET_URL (where the auth flow captures ?campaign= param),
falls back to MINIAPP_CUSTOM_URL for backwards compatibility.
"""
cabinet_url = settings._normalized_cabinet_url()
if cabinet_url:
sep = '&' if '?' in cabinet_url else '?'
return f'{cabinet_url}{sep}campaign={start_parameter}'
base_url = (settings.MINIAPP_CUSTOM_URL or '').rstrip('/')
if base_url:
return f'{base_url}/?campaign={start_parameter}'
+153 -39
View File
@@ -1,5 +1,3 @@
import hashlib
import hmac
import html
import os
import re
@@ -67,10 +65,22 @@ class Settings(BaseSettings):
ADMIN_NOTIFICATIONS_PROMO_TOPIC_ID: int | None = None # Промокоды, кампании, промогруппы
ADMIN_NOTIFICATIONS_PARTNERS_TOPIC_ID: int | None = None # Партнёрки, выводы, админ-действия
# Per-category enable/disable (default True for backwards compatibility)
ADMIN_NOTIFICATIONS_PURCHASES_ENABLED: bool = True
ADMIN_NOTIFICATIONS_RENEWALS_ENABLED: bool = True
ADMIN_NOTIFICATIONS_TRIALS_ENABLED: bool = True
ADMIN_NOTIFICATIONS_BALANCE_ENABLED: bool = True
ADMIN_NOTIFICATIONS_ADDONS_ENABLED: bool = True
ADMIN_NOTIFICATIONS_INFRASTRUCTURE_ENABLED: bool = True
ADMIN_NOTIFICATIONS_ERRORS_ENABLED: bool = True
ADMIN_NOTIFICATIONS_PROMO_ENABLED: bool = True
ADMIN_NOTIFICATIONS_PARTNERS_ENABLED: bool = True
ADMIN_NOTIFICATIONS_TICKETS_ENABLED: bool = True
# Настройки очереди чеков NaloGO
NALOGO_QUEUE_CHECK_INTERVAL: int = 300 # Интервал проверки очереди (секунды)
NALOGO_QUEUE_CHECK_INTERVAL: int = 600 # Интервал проверки очереди (секунды, 10 мин)
NALOGO_QUEUE_RECEIPT_DELAY: int = 3 # Задержка между отправкой чеков (секунды)
NALOGO_QUEUE_MAX_ATTEMPTS: int = 10 # Максимум попыток отправки чека
NALOGO_QUEUE_MAX_ATTEMPTS: int = 72 # Максимум попыток отправки чека (72 × 10мин = 12 часов)
ADMIN_REPORTS_ENABLED: bool = False
ADMIN_REPORTS_CHAT_ID: str | None = None
@@ -148,6 +158,9 @@ class Settings(BaseSettings):
DEFAULT_TRAFFIC_RESET_STRATEGY: str = 'MONTH'
RESET_TRAFFIC_ON_PAYMENT: bool = False
RESET_TRAFFIC_ON_TARIFF_SWITCH: bool = True
RESET_DEVICES_ON_RENEWAL: bool = False
TARIFF_SWITCH_UPGRADE_ENABLED: bool = True
TARIFF_SWITCH_DOWNGRADE_ENABLED: bool = True
MAX_DEVICES_LIMIT: int = 20
TRIAL_WARNING_HOURS: int = 2
@@ -324,6 +337,7 @@ class Settings(BaseSettings):
SUBSCRIPTION_RENEWAL_BALANCE_THRESHOLD_KOPEKS: int = 20000
MONITORING_INTERVAL: int = 60
LOW_BALANCE_ALERT_EXPIRY_DAYS: int = 3 # Only alert when subscription expires within N days
INACTIVE_USER_DELETE_MONTHS: int = 3
MAINTENANCE_MODE: bool = False
@@ -436,6 +450,7 @@ class Settings(BaseSettings):
MULENPAY_LANGUAGE: str = 'ru'
MULENPAY_VAT_CODE: int = 0
DISPLAY_NAME_RESTRICTION_ENABLED: bool = True
DISPLAY_NAME_BANNED_KEYWORDS: str = '\n'.join(DEFAULT_DISPLAY_NAME_BANNED_KEYWORDS)
MULENPAY_PAYMENT_SUBJECT: int = 4
MULENPAY_PAYMENT_MODE: int = 4
@@ -562,6 +577,21 @@ class Settings(BaseSettings):
KASSA_AI_SBERPAY_ENABLED: bool = False # SberPay — payment_system_id=43
KASSA_AI_SBERPAY_DISPLAY_NAME: str = 'SberPay (KassaAI)'
# ── Yandex Metrika offline conversions (server → mc.yandex.ru/collect) ──
YANDEX_OFFLINE_CONV_ENABLED: bool = False
YANDEX_OFFLINE_CONV_COUNTER_ID: str = ''
YANDEX_OFFLINE_CONV_MEASUREMENT_SECRET: str = ''
YANDEX_OFFLINE_CONV_START_PREFIX: str = 'utm_ya_'
YANDEX_OFFLINE_CONV_DL: str = ''
YANDEX_OFFLINE_CONV_DT: str = ''
YANDEX_OFFLINE_CONV_CURRENCY: str = 'RUB'
# ── S2S Postback (server-to-server affiliate notifications) ──
S2S_POSTBACK_ENABLED: bool = False
S2S_POSTBACK_REGISTRATION_URL: str = ''
S2S_POSTBACK_TRIAL_URL: str = ''
S2S_POSTBACK_PURCHASE_URL: str = ''
# RioPay (api.riopay.online) v2.0.1
RIOPAY_ENABLED: bool = False
RIOPAY_API_TOKEN: str | None = None # x-api-token header
@@ -586,6 +616,59 @@ class Settings(BaseSettings):
SEVERPAY_RETURN_URL: str | None = None
SEVERPAY_LIFETIME: int = 1440 # minutes, 30-4320
# PayPear (paypear.ru)
PAYPEAR_ENABLED: bool = False
PAYPEAR_SHOP_ID: str | None = None
PAYPEAR_SECRET_KEY: str | None = None
PAYPEAR_DISPLAY_NAME: str = 'PayPear'
PAYPEAR_CURRENCY: str = 'RUB'
PAYPEAR_MIN_AMOUNT_KOPEKS: int = 10000 # 100₽
PAYPEAR_MAX_AMOUNT_KOPEKS: int = 10000000 # 100 000₽
PAYPEAR_WEBHOOK_PATH: str = '/paypear-webhook'
PAYPEAR_RETURN_URL: str | None = None
PAYPEAR_PAYMENT_METHOD: str = 'sbp' # bank_card, sbp, sberpay, tpay
# RollyPay (rollypay.io)
ROLLYPAY_ENABLED: bool = False
ROLLYPAY_API_KEY: str | None = None # X-API-Key header
ROLLYPAY_SIGNING_SECRET: str | None = None # HMAC webhook verification
ROLLYPAY_DISPLAY_NAME: str = 'RollyPay'
ROLLYPAY_CURRENCY: str = 'RUB'
ROLLYPAY_MIN_AMOUNT_KOPEKS: int = 10000 # 100₽
ROLLYPAY_MAX_AMOUNT_KOPEKS: int = 10000000 # 100 000₽
ROLLYPAY_WEBHOOK_PATH: str = '/rollypay-webhook'
ROLLYPAY_RETURN_URL: str | None = None
# Overpay (pay.overpay.io)
OVERPAY_ENABLED: bool = False
OVERPAY_API_URL: str = 'https://api.overpay.io'
OVERPAY_USERNAME: str | None = None
OVERPAY_PASSWORD: str | None = None
OVERPAY_PROJECT_ID: str | None = None
OVERPAY_P12_PATH: str | None = None
OVERPAY_P12_PASSPHRASE: str | None = None
OVERPAY_DISPLAY_NAME: str = 'Overpay'
OVERPAY_CURRENCY: str = 'RUB'
OVERPAY_MIN_AMOUNT_KOPEKS: int = 10000
OVERPAY_MAX_AMOUNT_KOPEKS: int = 10000000
OVERPAY_WEBHOOK_PATH: str = '/overpay-webhook'
OVERPAY_RETURN_URL: str | None = None
OVERPAY_LIFETIME_MINUTES: int = 1440
OVERPAY_PAYMENT_METHODS: str = 'card,fps'
# AuraPay (aurapay.tech)
AURAPAY_ENABLED: bool = False
AURAPAY_API_KEY: str | None = None # X-ApiKey header
AURAPAY_SHOP_ID: str | None = None # X-ShopId header (UUID)
AURAPAY_SECRET_KEY: str | None = None # Secret key #2 for webhook HMAC
AURAPAY_DISPLAY_NAME: str = 'AuraPay'
AURAPAY_CURRENCY: str = 'RUB'
AURAPAY_MIN_AMOUNT_KOPEKS: int = 10000 # 100₽
AURAPAY_MAX_AMOUNT_KOPEKS: int = 10000000 # 100 000₽
AURAPAY_WEBHOOK_PATH: str = '/aurapay-webhook'
AURAPAY_RETURN_URL: str | None = None
AURAPAY_PAYMENT_LIFETIME_MINUTES: int = 60
MAIN_MENU_MODE: str = 'default' # 'default' | 'cabinet'
# Стиль кнопок Cabinet: primary (синий), success (зелёный), danger (красный), '' (по умолчанию для каждой секции)
CABINET_BUTTON_STYLE: str = ''
@@ -730,6 +813,7 @@ class Settings(BaseSettings):
WEBHOOK_URL: str | None = None
WEBHOOK_PATH: str = '/webhook'
WEBHOOK_SECRET_TOKEN: str | None = None
WEBHOOK_IP: str | None = None # IP адрес для setWebhook, чтобы Telegram не резолвил домен
WEBHOOK_DROP_PENDING_UPDATES: bool = True
WEBHOOK_MAX_QUEUE_SIZE: int = 1024
WEBHOOK_WORKERS: int = 4
@@ -770,9 +854,6 @@ class Settings(BaseSettings):
BACKUP_SEND_TOPIC_ID: int | None = None
BACKUP_ARCHIVE_PASSWORD: str | None = None
EXTERNAL_ADMIN_TOKEN: str | None = None
EXTERNAL_ADMIN_TOKEN_BOT_ID: int | None = None
# Cabinet (Personal Account) settings
CABINET_ENABLED: bool = False
CABINET_JWT_SECRET: str | None = None
@@ -825,6 +906,10 @@ class Settings(BaseSettings):
# Format: socks5://user:password@host:port or socks5://host:port
PROXY_URL: str | None = None
# Custom Telegram Bot API server URL (for regions where api.telegram.org is blocked)
# Examples: Cloudflare Worker proxy, self-hosted telegram-bot-api (tdlib), nginx reverse proxy
TELEGRAM_API_URL: str | None = None
@field_validator('PROXY_URL', 'NALOGO_PROXY_URL', mode='before')
@classmethod
def validate_proxy_url(cls, value: str | None) -> str | None:
@@ -972,6 +1057,10 @@ class Settings(BaseSettings):
"""Return SOCKS5 proxy URL or None."""
return self.PROXY_URL if self.PROXY_URL else None
def get_telegram_api_url(self) -> str | None:
"""Return custom Telegram Bot API server URL or None."""
return self.TELEGRAM_API_URL if self.TELEGRAM_API_URL else None
def get_nalogo_proxy_url(self) -> str | None:
"""Return SOCKS proxy URL for nalogo or None.
@@ -1185,7 +1274,13 @@ class Settings(BaseSettings):
if not sanitized_username:
sanitized_username = _sanitize(f'user_{identifier}')
return sanitized_username[:36].strip('_-') or 'user'
result = sanitized_username[:36].strip('_-') or 'user'
# RemnaWave требует username минимум 3 символа
if len(result) < 3:
result = f'{result}_{identifier}'[:36].strip('_-')
return result or 'user'
@staticmethod
def parse_daily_time_list(raw_value: str | None) -> list[time]:
@@ -1565,37 +1660,6 @@ class Settings(BaseSettings):
def get_app_config_cache_ttl(self) -> int:
return self.APP_CONFIG_CACHE_TTL
def build_external_admin_token(self, bot_username: str) -> str:
"""Генерирует детерминированный и криптографически стойкий токен внешней админки."""
normalized = (bot_username or '').strip().lstrip('@').lower()
if not normalized:
raise ValueError('Bot username is required to build external admin token')
secret = (self.BOT_TOKEN or '').strip()
if not secret:
raise ValueError('Bot token is required to build external admin token')
digest = hmac.new(
key=secret.encode('utf-8'),
msg=f'remnawave.external_admin::{normalized}'.encode(),
digestmod=hashlib.sha256,
).hexdigest()
return digest[:48]
def get_external_admin_token(self) -> str | None:
token = (self.EXTERNAL_ADMIN_TOKEN or '').strip()
return token or None
def get_external_admin_bot_id(self) -> int | None:
try:
return int(self.EXTERNAL_ADMIN_TOKEN_BOT_ID) if self.EXTERNAL_ADMIN_TOKEN_BOT_ID else None
except (TypeError, ValueError): # pragma: no cover - защитная ветка для некорректных значений
logger.warning(
'Некорректный идентификатор бота для внешней админки',
EXTERNAL_ADMIN_TOKEN_BOT_ID=self.EXTERNAL_ADMIN_TOKEN_BOT_ID,
)
return None
def is_traffic_selectable(self) -> bool:
return self.TRAFFIC_SELECTION_MODE.lower() == 'selectable'
@@ -1963,6 +2027,56 @@ class Settings(BaseSettings):
def get_severpay_display_name_html(self) -> str:
return html.escape(self.get_severpay_display_name())
def is_paypear_enabled(self) -> bool:
return self.PAYPEAR_ENABLED and self.PAYPEAR_SHOP_ID is not None and self.PAYPEAR_SECRET_KEY is not None
def get_paypear_display_name(self) -> str:
name = (self.PAYPEAR_DISPLAY_NAME or '').strip()
return name if name else 'PayPear'
def get_paypear_display_name_html(self) -> str:
return html.escape(self.get_paypear_display_name())
def is_rollypay_enabled(self) -> bool:
return self.ROLLYPAY_ENABLED and self.ROLLYPAY_API_KEY is not None and self.ROLLYPAY_SIGNING_SECRET is not None
def get_rollypay_display_name(self) -> str:
name = (self.ROLLYPAY_DISPLAY_NAME or '').strip()
return name if name else 'RollyPay'
def get_rollypay_display_name_html(self) -> str:
return html.escape(self.get_rollypay_display_name())
def is_overpay_enabled(self) -> bool:
return (
self.OVERPAY_ENABLED
and self.OVERPAY_USERNAME is not None
and self.OVERPAY_PASSWORD is not None
and self.OVERPAY_PROJECT_ID is not None
)
def get_overpay_display_name(self) -> str:
name = (self.OVERPAY_DISPLAY_NAME or '').strip()
return name if name else 'Overpay'
def get_overpay_display_name_html(self) -> str:
return html.escape(self.get_overpay_display_name())
def is_aurapay_enabled(self) -> bool:
return (
self.AURAPAY_ENABLED
and self.AURAPAY_API_KEY is not None
and self.AURAPAY_SHOP_ID is not None
and self.AURAPAY_SECRET_KEY is not None
)
def get_aurapay_display_name(self) -> str:
name = (self.AURAPAY_DISPLAY_NAME or '').strip()
return name if name else 'AuraPay'
def get_aurapay_display_name_html(self) -> str:
return html.escape(self.get_aurapay_display_name())
def is_kassa_ai_sbp_enabled(self) -> bool:
return self.KASSA_AI_SBP_ENABLED and self.is_kassa_ai_enabled()
+157
View File
@@ -0,0 +1,157 @@
"""CRUD операции для платежей AuraPay."""
from datetime import UTC, datetime
import structlog
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import AuraPayPayment
logger = structlog.get_logger(__name__)
async def create_aurapay_payment(
db: AsyncSession,
*,
user_id: int | None,
order_id: str,
amount_kopeks: int,
currency: str = 'RUB',
description: str | None = None,
payment_url: str | None = None,
payment_method: str | None = None,
aurapay_invoice_id: str | None = None,
expires_at: datetime | None = None,
metadata_json: dict | None = None,
) -> AuraPayPayment:
"""Создает запись о платеже AuraPay."""
payment = AuraPayPayment(
user_id=user_id,
order_id=order_id,
amount_kopeks=amount_kopeks,
currency=currency,
description=description,
payment_url=payment_url,
payment_method=payment_method,
aurapay_invoice_id=aurapay_invoice_id,
expires_at=expires_at,
metadata_json=metadata_json,
status='pending',
is_paid=False,
)
db.add(payment)
await db.commit()
await db.refresh(payment)
logger.info('Создан платеж AuraPay', order_id=order_id, user_id=user_id)
return payment
async def get_aurapay_payment_by_order_id(db: AsyncSession, order_id: str) -> AuraPayPayment | None:
"""Получает платеж по order_id (internal)."""
result = await db.execute(select(AuraPayPayment).where(AuraPayPayment.order_id == order_id))
return result.scalar_one_or_none()
async def get_aurapay_payment_by_invoice_id(db: AsyncSession, aurapay_invoice_id: str) -> AuraPayPayment | None:
"""Получает платеж по UUID от AuraPay."""
result = await db.execute(select(AuraPayPayment).where(AuraPayPayment.aurapay_invoice_id == aurapay_invoice_id))
return result.scalar_one_or_none()
async def get_aurapay_payment_by_id(db: AsyncSession, payment_id: int) -> AuraPayPayment | None:
"""Получает платеж по ID."""
result = await db.execute(select(AuraPayPayment).where(AuraPayPayment.id == payment_id))
return result.scalar_one_or_none()
async def get_aurapay_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> AuraPayPayment | None:
"""Получает платеж по ID с блокировкой FOR UPDATE."""
result = await db.execute(
select(AuraPayPayment)
.where(AuraPayPayment.id == payment_id)
.with_for_update()
.execution_options(populate_existing=True)
)
return result.scalar_one_or_none()
async def update_aurapay_payment_status(
db: AsyncSession,
payment: AuraPayPayment,
*,
status: str,
is_paid: bool | None = None,
aurapay_invoice_id: str | None = None,
payment_method: str | None = None,
callback_payload: dict | None = None,
transaction_id: int | None = None,
) -> AuraPayPayment:
"""Обновляет статус платежа."""
payment.status = status
payment.updated_at = datetime.now(UTC)
if is_paid is not None:
payment.is_paid = is_paid
if is_paid:
payment.paid_at = datetime.now(UTC)
if aurapay_invoice_id is not None:
payment.aurapay_invoice_id = aurapay_invoice_id
if payment_method is not None:
payment.payment_method = payment_method
if callback_payload is not None:
payment.callback_payload = callback_payload
if transaction_id is not None:
payment.transaction_id = transaction_id
await db.commit()
await db.refresh(payment)
logger.info(
'Обновлен статус платежа AuraPay',
order_id=payment.order_id,
status=status,
is_paid=payment.is_paid,
)
return payment
async def get_pending_aurapay_payments(db: AsyncSession, user_id: int) -> list[AuraPayPayment]:
"""Получает незавершенные платежи пользователя."""
result = await db.execute(
select(AuraPayPayment).where(
AuraPayPayment.user_id == user_id,
AuraPayPayment.status == 'pending',
AuraPayPayment.is_paid == False,
)
)
return list(result.scalars().all())
async def get_expired_pending_aurapay_payments(
db: AsyncSession,
) -> list[AuraPayPayment]:
"""Получает просроченные платежи в статусе pending."""
now = datetime.now(UTC)
result = await db.execute(
select(AuraPayPayment).where(
AuraPayPayment.status == 'pending',
AuraPayPayment.is_paid == False,
AuraPayPayment.expires_at < now,
)
)
return list(result.scalars().all())
async def link_aurapay_payment_to_transaction(
db: AsyncSession,
*,
payment: AuraPayPayment,
transaction_id: int,
) -> AuraPayPayment:
"""Связывает платеж с транзакцией."""
payment.transaction_id = transaction_id
payment.updated_at = datetime.now(UTC)
await db.flush()
await db.refresh(payment)
return payment
+214
View File
@@ -0,0 +1,214 @@
"""CRUD operations for info pages."""
from datetime import UTC, datetime
from typing import Any
import structlog
from sqlalchemy import delete, select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import InfoPage
logger = structlog.get_logger(__name__)
# Fields that can be set via update_info_page
_ALLOWED_UPDATE_FIELDS: frozenset[str] = frozenset(
{
'slug',
'title',
'content',
'page_type',
'is_active',
'sort_order',
'icon',
'replaces_tab',
}
)
# Fields that can be explicitly set to None
_NULLABLE_UPDATE_FIELDS: frozenset[str] = frozenset(
{
'icon',
'replaces_tab',
}
)
async def create_info_page(
db: AsyncSession,
*,
slug: str,
title: dict[str, str],
content: dict[str, str],
page_type: str = 'page',
is_active: bool = True,
sort_order: int = 0,
icon: str | None = None,
replaces_tab: str | None = None,
) -> InfoPage:
"""Create a new info page.
Raises:
IntegrityError: if slug is not unique (caller must handle).
"""
page = InfoPage(
slug=slug,
title=title,
content=content,
page_type=page_type,
is_active=is_active,
sort_order=sort_order,
icon=icon,
replaces_tab=replaces_tab,
)
db.add(page)
try:
await db.commit()
except IntegrityError:
await db.rollback()
raise
await db.refresh(page)
logger.info('Created info page', page_id=page.id, slug=page.slug)
return page
async def get_info_page_by_id(db: AsyncSession, page_id: int) -> InfoPage | None:
"""Get an info page by ID."""
result = await db.execute(select(InfoPage).where(InfoPage.id == page_id))
return result.scalar_one_or_none()
async def get_info_page_by_slug(db: AsyncSession, slug: str) -> InfoPage | None:
"""Get an info page by slug."""
result = await db.execute(select(InfoPage).where(InfoPage.slug == slug))
return result.scalar_one_or_none()
async def get_all_info_pages(
db: AsyncSession,
*,
include_inactive: bool = False,
page_type: str | None = None,
) -> list[InfoPage]:
"""Get all info pages, ordered by sort_order ascending."""
stmt = select(InfoPage)
if not include_inactive:
stmt = stmt.where(InfoPage.is_active.is_(True))
if page_type is not None:
stmt = stmt.where(InfoPage.page_type == page_type)
stmt = stmt.order_by(InfoPage.sort_order.asc(), InfoPage.id.asc())
result = await db.execute(stmt)
return list(result.scalars().all())
async def update_info_page(
db: AsyncSession,
page_id: int,
**kwargs: Any,
) -> InfoPage | None:
"""Update an info page. Only whitelisted fields are applied.
Raises:
IntegrityError: if slug conflicts with another page (caller must handle).
"""
update_data: dict[str, Any] = {}
for key, value in kwargs.items():
if key not in _ALLOWED_UPDATE_FIELDS:
continue
if value is None and key not in _NULLABLE_UPDATE_FIELDS:
continue
update_data[key] = value
if not update_data:
return await get_info_page_by_id(db, page_id)
update_data['updated_at'] = datetime.now(UTC)
await db.execute(update(InfoPage).where(InfoPage.id == page_id).values(**update_data))
try:
await db.commit()
except IntegrityError:
await db.rollback()
raise
page = await get_info_page_by_id(db, page_id)
if page:
logger.info(
'Updated info page',
page_id=page_id,
updated_fields=list(update_data.keys()),
)
return page
async def delete_info_page(db: AsyncSession, page_id: int) -> None:
"""Delete an info page."""
await db.execute(delete(InfoPage).where(InfoPage.id == page_id))
await db.commit()
logger.info('Deleted info page', page_id=page_id)
async def get_tab_replacements(db: AsyncSession) -> dict[str, str | None]:
"""Return a mapping of tab name to info page slug for active pages with replaces_tab set.
Returns dict like ``{'faq': 'my-custom-faq', 'rules': None, 'privacy': None, 'offer': None}``.
"""
result_map: dict[str, str | None] = {
'faq': None,
'rules': None,
'privacy': None,
'offer': None,
}
stmt = select(InfoPage).where(
InfoPage.is_active.is_(True),
InfoPage.replaces_tab.isnot(None),
)
result = await db.execute(stmt)
for page in result.scalars().all():
if page.replaces_tab in result_map:
result_map[page.replaces_tab] = page.slug
return result_map
async def clear_replaces_tab(db: AsyncSession, tab: str, *, exclude_page_id: int | None = None) -> None:
"""Clear replaces_tab for all pages that currently replace the given tab.
Optionally exclude a specific page (the one being saved).
"""
stmt = (
update(InfoPage)
.where(
InfoPage.replaces_tab == tab,
)
.values(replaces_tab=None, updated_at=datetime.now(UTC))
)
if exclude_page_id is not None:
stmt = stmt.where(InfoPage.id != exclude_page_id)
await db.execute(stmt)
async def reorder_info_pages(db: AsyncSession, items: list[dict]) -> None:
"""Bulk update sort_order for info pages.
Each item must have ``id`` and ``sort_order`` attributes.
"""
for item in items:
page_id = item.id if hasattr(item, 'id') else item.get('id')
sort_order = item.sort_order if hasattr(item, 'sort_order') else item.get('sort_order')
if page_id is None or sort_order is None:
continue
await db.execute(
update(InfoPage).where(InfoPage.id == page_id).values(sort_order=sort_order, updated_at=datetime.now(UTC))
)
await db.commit()
logger.info('Reordered info pages', count=len(items))
+5
View File
@@ -76,6 +76,11 @@ _LANDING_UPDATABLE_FIELDS = frozenset(
'discount_ends_at',
'discount_badge_text',
'background_config',
'sticky_pay_button',
'analytics_view_enabled',
'analytics_view_goal',
'analytics_click_enabled',
'analytics_click_goal',
}
)
+157
View File
@@ -0,0 +1,157 @@
"""CRUD операции для платежей Overpay."""
from datetime import UTC, datetime
import structlog
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import OverpayPayment
logger = structlog.get_logger(__name__)
async def create_overpay_payment(
db: AsyncSession,
*,
user_id: int | None,
order_id: str,
amount_kopeks: int,
currency: str = 'RUB',
description: str | None = None,
payment_url: str | None = None,
payment_method: str | None = None,
overpay_payment_id: str | None = None,
expires_at: datetime | None = None,
metadata_json: dict | None = None,
) -> OverpayPayment:
"""Создает запись о платеже Overpay."""
payment = OverpayPayment(
user_id=user_id,
order_id=order_id,
amount_kopeks=amount_kopeks,
currency=currency,
description=description,
payment_url=payment_url,
payment_method=payment_method,
overpay_payment_id=overpay_payment_id,
expires_at=expires_at,
metadata_json=metadata_json,
status='pending',
is_paid=False,
)
db.add(payment)
await db.commit()
await db.refresh(payment)
logger.info('Создан платеж Overpay', order_id=order_id, user_id=user_id)
return payment
async def get_overpay_payment_by_order_id(db: AsyncSession, order_id: str) -> OverpayPayment | None:
"""Получает платеж по order_id (internal)."""
result = await db.execute(select(OverpayPayment).where(OverpayPayment.order_id == order_id))
return result.scalar_one_or_none()
async def get_overpay_payment_by_overpay_id(db: AsyncSession, overpay_payment_id: str) -> OverpayPayment | None:
"""Получает платеж по ID от Overpay."""
result = await db.execute(select(OverpayPayment).where(OverpayPayment.overpay_payment_id == overpay_payment_id))
return result.scalar_one_or_none()
async def get_overpay_payment_by_id(db: AsyncSession, payment_id: int) -> OverpayPayment | None:
"""Получает платеж по ID."""
result = await db.execute(select(OverpayPayment).where(OverpayPayment.id == payment_id))
return result.scalar_one_or_none()
async def get_overpay_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> OverpayPayment | None:
"""Получает платеж по ID с блокировкой FOR UPDATE."""
result = await db.execute(
select(OverpayPayment)
.where(OverpayPayment.id == payment_id)
.with_for_update()
.execution_options(populate_existing=True)
)
return result.scalar_one_or_none()
async def update_overpay_payment_status(
db: AsyncSession,
payment: OverpayPayment,
*,
status: str,
is_paid: bool | None = None,
overpay_payment_id: str | None = None,
payment_method: str | None = None,
callback_payload: dict | None = None,
transaction_id: int | None = None,
) -> OverpayPayment:
"""Обновляет статус платежа."""
payment.status = status
payment.updated_at = datetime.now(UTC)
if is_paid is not None:
payment.is_paid = is_paid
if is_paid:
payment.paid_at = datetime.now(UTC)
if overpay_payment_id is not None:
payment.overpay_payment_id = overpay_payment_id
if payment_method is not None:
payment.payment_method = payment_method
if callback_payload is not None:
payment.callback_payload = callback_payload
if transaction_id is not None:
payment.transaction_id = transaction_id
await db.commit()
await db.refresh(payment)
logger.info(
'Обновлен статус платежа Overpay',
order_id=payment.order_id,
status=status,
is_paid=payment.is_paid,
)
return payment
async def get_pending_overpay_payments(db: AsyncSession, user_id: int) -> list[OverpayPayment]:
"""Получает незавершенные платежи пользователя."""
result = await db.execute(
select(OverpayPayment).where(
OverpayPayment.user_id == user_id,
OverpayPayment.status == 'pending',
OverpayPayment.is_paid == False,
)
)
return list(result.scalars().all())
async def get_expired_pending_overpay_payments(
db: AsyncSession,
) -> list[OverpayPayment]:
"""Получает просроченные платежи в статусе pending."""
now = datetime.now(UTC)
result = await db.execute(
select(OverpayPayment).where(
OverpayPayment.status == 'pending',
OverpayPayment.is_paid == False,
OverpayPayment.expires_at < now,
)
)
return list(result.scalars().all())
async def link_overpay_payment_to_transaction(
db: AsyncSession,
*,
payment: OverpayPayment,
transaction_id: int,
) -> OverpayPayment:
"""Связывает платеж с транзакцией."""
payment.transaction_id = transaction_id
payment.updated_at = datetime.now(UTC)
await db.flush()
await db.refresh(payment)
return payment
+157
View File
@@ -0,0 +1,157 @@
"""CRUD операции для платежей PayPear."""
from datetime import UTC, datetime
import structlog
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import PayPearPayment
logger = structlog.get_logger(__name__)
async def create_paypear_payment(
db: AsyncSession,
*,
user_id: int | None,
order_id: str,
amount_kopeks: int,
currency: str = 'RUB',
description: str | None = None,
payment_url: str | None = None,
payment_method: str | None = None,
paypear_id: str | None = None,
expires_at: datetime | None = None,
metadata_json: dict | None = None,
) -> PayPearPayment:
"""Создает запись о платеже PayPear."""
payment = PayPearPayment(
user_id=user_id,
order_id=order_id,
amount_kopeks=amount_kopeks,
currency=currency,
description=description,
payment_url=payment_url,
payment_method=payment_method,
paypear_id=paypear_id,
expires_at=expires_at,
metadata_json=metadata_json,
status='pending',
is_paid=False,
)
db.add(payment)
await db.commit()
await db.refresh(payment)
logger.info('Создан платеж PayPear', order_id=order_id, user_id=user_id)
return payment
async def get_paypear_payment_by_order_id(db: AsyncSession, order_id: str) -> PayPearPayment | None:
"""Получает платеж по order_id (internal)."""
result = await db.execute(select(PayPearPayment).where(PayPearPayment.order_id == order_id))
return result.scalar_one_or_none()
async def get_paypear_payment_by_paypear_id(db: AsyncSession, paypear_id: str) -> PayPearPayment | None:
"""Получает платеж по ID от PayPear."""
result = await db.execute(select(PayPearPayment).where(PayPearPayment.paypear_id == paypear_id))
return result.scalar_one_or_none()
async def get_paypear_payment_by_id(db: AsyncSession, payment_id: int) -> PayPearPayment | None:
"""Получает платеж по ID."""
result = await db.execute(select(PayPearPayment).where(PayPearPayment.id == payment_id))
return result.scalar_one_or_none()
async def get_paypear_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> PayPearPayment | None:
"""Получает платеж по ID с блокировкой FOR UPDATE."""
result = await db.execute(
select(PayPearPayment)
.where(PayPearPayment.id == payment_id)
.with_for_update()
.execution_options(populate_existing=True)
)
return result.scalar_one_or_none()
async def update_paypear_payment_status(
db: AsyncSession,
payment: PayPearPayment,
*,
status: str,
is_paid: bool | None = None,
paypear_id: str | None = None,
payment_method: str | None = None,
callback_payload: dict | None = None,
transaction_id: int | None = None,
) -> PayPearPayment:
"""Обновляет статус платежа."""
payment.status = status
payment.updated_at = datetime.now(UTC)
if is_paid is not None:
payment.is_paid = is_paid
if is_paid:
payment.paid_at = datetime.now(UTC)
if paypear_id is not None:
payment.paypear_id = paypear_id
if payment_method is not None:
payment.payment_method = payment_method
if callback_payload is not None:
payment.callback_payload = callback_payload
if transaction_id is not None:
payment.transaction_id = transaction_id
await db.commit()
await db.refresh(payment)
logger.info(
'Обновлен статус платежа PayPear',
order_id=payment.order_id,
status=status,
is_paid=payment.is_paid,
)
return payment
async def get_pending_paypear_payments(db: AsyncSession, user_id: int) -> list[PayPearPayment]:
"""Получает незавершенные платежи пользователя."""
result = await db.execute(
select(PayPearPayment).where(
PayPearPayment.user_id == user_id,
PayPearPayment.status == 'pending',
PayPearPayment.is_paid == False,
)
)
return list(result.scalars().all())
async def get_expired_pending_paypear_payments(
db: AsyncSession,
) -> list[PayPearPayment]:
"""Получает просроченные платежи в статусе pending."""
now = datetime.now(UTC)
result = await db.execute(
select(PayPearPayment).where(
PayPearPayment.status == 'pending',
PayPearPayment.is_paid == False,
PayPearPayment.expires_at < now,
)
)
return list(result.scalars().all())
async def link_paypear_payment_to_transaction(
db: AsyncSession,
*,
payment: PayPearPayment,
transaction_id: int,
) -> PayPearPayment:
"""Связывает платеж с транзакцией."""
payment.transaction_id = transaction_id
payment.updated_at = datetime.now(UTC)
await db.flush()
await db.refresh(payment)
return payment
+1 -1
View File
@@ -166,7 +166,7 @@ async def update_promo_group(
group.device_discount_percent = max(0, min(100, device_discount_percent))
if period_discounts is not None:
normalized_period_discounts = _normalize_period_discounts(period_discounts)
group.period_discounts = normalized_period_discounts or None
group.period_discounts = normalized_period_discounts if normalized_period_discounts else None
if auto_assign_total_spent_kopeks is not None:
value = max(0, auto_assign_total_spent_kopeks)
group.auto_assign_total_spent_kopeks = value if value > 0 else None
+157
View File
@@ -0,0 +1,157 @@
"""CRUD операции для платежей RollyPay."""
from datetime import UTC, datetime
import structlog
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import RollyPayPayment
logger = structlog.get_logger(__name__)
async def create_rollypay_payment(
db: AsyncSession,
*,
user_id: int | None,
order_id: str,
amount_kopeks: int,
currency: str = 'RUB',
description: str | None = None,
payment_url: str | None = None,
payment_method: str | None = None,
rollypay_payment_id: str | None = None,
expires_at: datetime | None = None,
metadata_json: dict | None = None,
) -> RollyPayPayment:
"""Создает запись о платеже RollyPay."""
payment = RollyPayPayment(
user_id=user_id,
order_id=order_id,
amount_kopeks=amount_kopeks,
currency=currency,
description=description,
payment_url=payment_url,
payment_method=payment_method,
rollypay_payment_id=rollypay_payment_id,
expires_at=expires_at,
metadata_json=metadata_json,
status='pending',
is_paid=False,
)
db.add(payment)
await db.commit()
await db.refresh(payment)
logger.info('Создан платеж RollyPay', order_id=order_id, user_id=user_id)
return payment
async def get_rollypay_payment_by_order_id(db: AsyncSession, order_id: str) -> RollyPayPayment | None:
"""Получает платеж по order_id (internal)."""
result = await db.execute(select(RollyPayPayment).where(RollyPayPayment.order_id == order_id))
return result.scalar_one_or_none()
async def get_rollypay_payment_by_rollypay_id(db: AsyncSession, rollypay_payment_id: str) -> RollyPayPayment | None:
"""Получает платеж по ID от RollyPay."""
result = await db.execute(select(RollyPayPayment).where(RollyPayPayment.rollypay_payment_id == rollypay_payment_id))
return result.scalar_one_or_none()
async def get_rollypay_payment_by_id(db: AsyncSession, payment_id: int) -> RollyPayPayment | None:
"""Получает платеж по ID."""
result = await db.execute(select(RollyPayPayment).where(RollyPayPayment.id == payment_id))
return result.scalar_one_or_none()
async def get_rollypay_payment_by_id_for_update(db: AsyncSession, payment_id: int) -> RollyPayPayment | None:
"""Получает платеж по ID с блокировкой FOR UPDATE."""
result = await db.execute(
select(RollyPayPayment)
.where(RollyPayPayment.id == payment_id)
.with_for_update()
.execution_options(populate_existing=True)
)
return result.scalar_one_or_none()
async def update_rollypay_payment_status(
db: AsyncSession,
payment: RollyPayPayment,
*,
status: str,
is_paid: bool | None = None,
rollypay_payment_id: str | None = None,
payment_method: str | None = None,
callback_payload: dict | None = None,
transaction_id: int | None = None,
) -> RollyPayPayment:
"""Обновляет статус платежа."""
payment.status = status
payment.updated_at = datetime.now(UTC)
if is_paid is not None:
payment.is_paid = is_paid
if is_paid:
payment.paid_at = datetime.now(UTC)
if rollypay_payment_id is not None:
payment.rollypay_payment_id = rollypay_payment_id
if payment_method is not None:
payment.payment_method = payment_method
if callback_payload is not None:
payment.callback_payload = callback_payload
if transaction_id is not None:
payment.transaction_id = transaction_id
await db.commit()
await db.refresh(payment)
logger.info(
'Обновлен статус платежа RollyPay',
order_id=payment.order_id,
status=status,
is_paid=payment.is_paid,
)
return payment
async def get_pending_rollypay_payments(db: AsyncSession, user_id: int) -> list[RollyPayPayment]:
"""Получает незавершенные платежи пользователя."""
result = await db.execute(
select(RollyPayPayment).where(
RollyPayPayment.user_id == user_id,
RollyPayPayment.status == 'pending',
RollyPayPayment.is_paid == False,
)
)
return list(result.scalars().all())
async def get_expired_pending_rollypay_payments(
db: AsyncSession,
) -> list[RollyPayPayment]:
"""Получает просроченные платежи в статусе pending."""
now = datetime.now(UTC)
result = await db.execute(
select(RollyPayPayment).where(
RollyPayPayment.status == 'pending',
RollyPayPayment.is_paid == False,
RollyPayPayment.expires_at < now,
)
)
return list(result.scalars().all())
async def link_rollypay_payment_to_transaction(
db: AsyncSession,
*,
payment: RollyPayPayment,
transaction_id: int,
) -> RollyPayPayment:
"""Связывает платеж с транзакцией."""
payment.transaction_id = transaction_id
payment.updated_at = datetime.now(UTC)
await db.flush()
await db.refresh(payment)
return payment
+23 -1
View File
@@ -33,7 +33,15 @@ logger = structlog.get_logger(__name__)
async def _get_default_promo_group_id(db: AsyncSession) -> int | None:
result = await db.execute(select(PromoGroup.id).where(PromoGroup.is_default.is_(True)).limit(1))
return result.scalar_one_or_none()
default_id = result.scalar_one_or_none()
if default_id is not None:
return default_id
# На пустой БД дефолтной промогруппы нет — создаём автоматически
from app.database.crud.user import _get_or_create_default_promo_group
default_group = await _get_or_create_default_promo_group(db)
return default_group.id
async def create_server_squad(
@@ -155,6 +163,20 @@ async def get_available_server_squads(
return result.scalars().unique().all()
async def get_effective_tariff_squad_uuids(
db: AsyncSession,
allowed_squads: Sequence[str] | None,
) -> list[str]:
"""Resolve tariff squads, treating an empty list as "all available squads"."""
normalized = [str(squad_uuid) for squad_uuid in (allowed_squads or []) if squad_uuid]
if normalized:
return list(dict.fromkeys(normalized))
available = await get_available_server_squads(db)
return [squad.squad_uuid for squad in available if squad.squad_uuid]
async def get_active_server_squads(db: AsyncSession) -> list[ServerSquad]:
"""Возвращает список активных серверов, доступных для подключения."""
+10 -8
View File
@@ -1,3 +1,4 @@
import math
import secrets
from collections.abc import Iterable
from datetime import UTC, datetime, timedelta
@@ -142,8 +143,8 @@ async def create_trial_subscription(
if device_limit is None:
device_limit = settings.TRIAL_DEVICE_LIMIT
# Если переданы connected_squads, используем их
# Иначе используем squad_uuid или получаем случайный
# Если переданы connected_squads, используем их.
# Иначе используем squad_uuid или все доступные сквады по умолчанию.
final_squads = []
if connected_squads:
final_squads = connected_squads
@@ -151,13 +152,14 @@ async def create_trial_subscription(
final_squads = [squad_uuid]
else:
try:
from app.database.crud.server_squad import get_random_trial_squad_uuid
from app.database.crud.server_squad import get_effective_tariff_squad_uuids
random_squad = await get_random_trial_squad_uuid(db)
if random_squad:
final_squads = [random_squad]
final_squads = await get_effective_tariff_squad_uuids(db, None)
if final_squads:
logger.debug(
'Выбран сквад для триальной подписки пользователя', random_squad=random_squad, user_id=user_id
'Выбраны дефолтные сквады для триальной подписки пользователя',
final_squads=final_squads,
user_id=user_id,
)
except Exception as error:
logger.error('Не удалось получить сквад для триальной подписки пользователя', user_id=user_id, error=error)
@@ -1295,7 +1297,7 @@ async def add_subscription_servers(
if paid_prices is None:
now = datetime.now(UTC)
days_remaining = max(1, (subscription.end_date - now).days)
days_remaining = max(1, math.ceil((subscription.end_date - now).total_seconds() / 86400))
paid_prices = []
from app.database.models import ServerSquad
+6 -2
View File
@@ -25,6 +25,7 @@ class TicketCRUD:
media_type: str | None = None,
media_file_id: str | None = None,
media_caption: str | None = None,
media_items: list[dict] | None = None,
) -> Ticket:
"""Создать новый тикет с первым сообщением"""
ticket = Ticket(user_id=user_id, title=title, status=TicketStatus.OPEN.value, priority=priority)
@@ -37,10 +38,11 @@ class TicketCRUD:
user_id=user_id,
message_text=message_text,
is_from_admin=False,
has_media=bool(media_type and media_file_id),
has_media=bool(media_type and media_file_id) or bool(media_items),
media_type=media_type,
media_file_id=media_file_id,
media_caption=media_caption,
media_items=media_items,
)
db.add(message)
@@ -381,6 +383,7 @@ class TicketMessageCRUD:
media_type: str | None = None,
media_file_id: str | None = None,
media_caption: str | None = None,
media_items: list[dict] | None = None,
) -> TicketMessage:
"""Добавить сообщение в тикет"""
message = TicketMessage(
@@ -388,10 +391,11 @@ class TicketMessageCRUD:
user_id=user_id,
message_text=message_text,
is_from_admin=is_from_admin,
has_media=bool(media_type and media_file_id),
has_media=bool(media_type and media_file_id) or bool(media_items),
media_type=media_type,
media_file_id=media_file_id,
media_caption=media_caption,
media_items=media_items,
)
db.add(message)
+10 -6
View File
@@ -27,6 +27,10 @@ REAL_PAYMENT_METHODS = [
PaymentMethod.KASSA_AI.value,
PaymentMethod.RIOPAY.value,
PaymentMethod.SEVERPAY.value,
PaymentMethod.ROLLYPAY.value,
PaymentMethod.PAYPEAR.value,
PaymentMethod.OVERPAY.value,
PaymentMethod.AURAPAY.value,
]
@@ -230,17 +234,17 @@ async def get_user_transactions_count(
async def get_user_total_spent_kopeks(db: AsyncSession, user_id: int) -> int:
"""Sum of personal spending for promo group auto-assignment.
Only counts SUBSCRIPTION_PAYMENT (user's own subscriptions).
GIFT_PAYMENT is excluded buying a gift for someone else is not personal spending.
"""
result = await db.execute(
select(func.coalesce(func.sum(func.abs(Transaction.amount_kopeks)), 0)).where(
and_(
Transaction.user_id == user_id,
Transaction.is_completed.is_(True),
Transaction.type.in_(
[
TransactionType.SUBSCRIPTION_PAYMENT.value,
TransactionType.GIFT_PAYMENT.value,
]
),
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
)
)
)
+144 -26
View File
@@ -3,7 +3,7 @@ import string
from datetime import UTC, datetime, timedelta
import structlog
from sqlalchemy import and_, case, func, nullslast, or_, select, text
from sqlalchemy import and_, case, exists, func, nullslast, or_, select, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
@@ -13,6 +13,8 @@ from app.database.crud.discount_offer import get_latest_claimed_offer_for_user
from app.database.crud.promo_group import get_default_promo_group
from app.database.crud.promo_offer_log import log_promo_offer_action
from app.database.models import (
AdvertisingCampaign,
AdvertisingCampaignRegistration,
PaymentMethod,
PromoGroup,
Subscription,
@@ -710,30 +712,52 @@ async def subtract_user_balance(
await db.refresh(user)
if consume_promo_offer and log_context:
try:
await log_promo_offer_action(
db,
user_id=user.id,
offer_id=log_context.get('offer_id'),
action='consumed',
source=log_context.get('source'),
percent=log_context.get('percent'),
effect_type=log_context.get('effect_type'),
details=log_context.get('details'),
commit=commit,
)
except Exception as log_error: # pragma: no cover - defensive logging
logger.warning(
'Failed to record promo offer consumption log for user', user_id=user.id, log_error=log_error
)
if commit:
try:
await db.rollback()
except Exception as rollback_error: # pragma: no cover - defensive logging
logger.warning(
'Failed to rollback session after promo offer consumption log failure',
rollback_error=rollback_error,
# Пишем лог в ОТДЕЛЬНОЙ сессии, чтобы его commit/rollback не касался
# основной сессии caller'а. Иначе rollback в случае фейла логирования
# экспайрит объекты сессии и следующее обращение к subscription/user
# attrs у caller'а падает с MissingGreenlet.
if commit:
try:
from app.database.database import AsyncSessionLocal
async with AsyncSessionLocal() as log_db:
await log_promo_offer_action(
log_db,
user_id=user.id,
offer_id=log_context.get('offer_id'),
action='consumed',
source=log_context.get('source'),
percent=log_context.get('percent'),
effect_type=log_context.get('effect_type'),
details=log_context.get('details'),
commit=True,
)
except Exception as log_error: # pragma: no cover - defensive logging
logger.warning(
'Failed to record promo offer consumption log for user',
user_id=user.id,
log_error=log_error,
)
else:
# Caller управляет транзакцией — пишем в его сессию без commit.
try:
await log_promo_offer_action(
db,
user_id=user.id,
offer_id=log_context.get('offer_id'),
action='consumed',
source=log_context.get('source'),
percent=log_context.get('percent'),
effect_type=log_context.get('effect_type'),
details=log_context.get('details'),
commit=False,
)
except Exception as log_error: # pragma: no cover - defensive logging
logger.warning(
'Failed to record promo offer consumption log for user',
user_id=user.id,
log_error=log_error,
)
logger.info('✅ Средства списаны: →', old_balance=old_balance, balance_kopeks=user.balance_kopeks)
return True
@@ -839,6 +863,11 @@ async def get_users_list(
search: str | None = None,
email: str | None = None,
status: UserStatus | None = None,
subscription_status: str | None = None,
tariff_ids: list[int] | None = None,
promo_group_id: int | None = None,
campaign_id: int | None = None,
partner_id: int | None = None,
order_by_balance: bool = False,
order_by_traffic: bool = False,
order_by_last_activity: bool = False,
@@ -854,6 +883,41 @@ async def get_users_list(
if status:
query = query.where(User.status == status.value)
# Subscription-level filters via subquery
if subscription_status or tariff_ids:
sub_conditions = []
if subscription_status:
sub_conditions.append(Subscription.status == subscription_status)
if tariff_ids:
sub_conditions.append(Subscription.tariff_id.in_(tariff_ids))
sub_query = select(Subscription.user_id).where(and_(*sub_conditions)).distinct().scalar_subquery()
query = query.where(User.id.in_(sub_query))
if promo_group_id:
query = query.where(User.promo_group_id == promo_group_id)
if campaign_id:
query = query.where(
exists(
select(AdvertisingCampaignRegistration.id).where(
AdvertisingCampaignRegistration.user_id == User.id,
AdvertisingCampaignRegistration.campaign_id == campaign_id,
)
)
)
if partner_id:
query = query.where(
exists(
select(AdvertisingCampaignRegistration.id)
.join(AdvertisingCampaign, AdvertisingCampaign.id == AdvertisingCampaignRegistration.campaign_id)
.where(
AdvertisingCampaignRegistration.user_id == User.id,
AdvertisingCampaign.partner_user_id == partner_id,
)
)
)
if search:
search_term = f'%{search}%'
conditions = [
@@ -933,13 +997,55 @@ async def get_users_list(
async def get_users_count(
db: AsyncSession, status: UserStatus | None = None, search: str | None = None, email: str | None = None
db: AsyncSession,
status: UserStatus | None = None,
search: str | None = None,
email: str | None = None,
subscription_status: str | None = None,
tariff_ids: list[int] | None = None,
promo_group_id: int | None = None,
campaign_id: int | None = None,
partner_id: int | None = None,
) -> int:
query = select(func.count(User.id))
if status:
query = query.where(User.status == status.value)
if subscription_status or tariff_ids:
sub_conditions = []
if subscription_status:
sub_conditions.append(Subscription.status == subscription_status)
if tariff_ids:
sub_conditions.append(Subscription.tariff_id.in_(tariff_ids))
sub_query = select(Subscription.user_id).where(and_(*sub_conditions)).distinct().scalar_subquery()
query = query.where(User.id.in_(sub_query))
if promo_group_id:
query = query.where(User.promo_group_id == promo_group_id)
if campaign_id:
query = query.where(
exists(
select(AdvertisingCampaignRegistration.id).where(
AdvertisingCampaignRegistration.user_id == User.id,
AdvertisingCampaignRegistration.campaign_id == campaign_id,
)
)
)
if partner_id:
query = query.where(
exists(
select(AdvertisingCampaignRegistration.id)
.join(AdvertisingCampaign, AdvertisingCampaign.id == AdvertisingCampaignRegistration.campaign_id)
.where(
AdvertisingCampaignRegistration.user_id == User.id,
AdvertisingCampaign.partner_user_id == partner_id,
)
)
)
if search:
search_term = f'%{search}%'
conditions = [
@@ -1090,6 +1196,12 @@ async def get_users_for_promo_segment(db: AsyncSession, segment: str) -> list[Us
async def get_inactive_users(db: AsyncSession, months: int = 3) -> list[User]:
threshold_date = datetime.now(UTC) - timedelta(days=months * 30)
# Подзапрос: пользователи, у которых есть подписка с end_date >= threshold
# (активная или недавно истёкшая) — таких удалять нельзя
users_with_recent_subs = (
select(Subscription.user_id).where(Subscription.end_date >= threshold_date).distinct().scalar_subquery()
)
result = await db.execute(
select(User)
.options(
@@ -1098,7 +1210,13 @@ async def get_inactive_users(db: AsyncSession, months: int = 3) -> list[User]:
selectinload(User.referrer),
selectinload(User.promo_group),
)
.where(and_(User.last_activity < threshold_date, User.status == UserStatus.ACTIVE.value))
.where(
and_(
User.last_activity < threshold_date,
User.status == UserStatus.ACTIVE.value,
User.id.not_in(users_with_recent_subs),
)
)
)
users = result.scalars().all()
+108
View File
@@ -0,0 +1,108 @@
"""CRUD operations for yandex_client_id_map table."""
from __future__ import annotations
from datetime import UTC, datetime
import structlog
from sqlalchemy import select, update
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.models import YandexClientIdMap
logger = structlog.get_logger(__name__)
async def upsert_cid(
db: AsyncSession,
user_id: int,
cid: str,
source: str = 'web',
counter_id: str | None = None,
subid: str | None = None,
) -> YandexClientIdMap:
"""Insert or update Yandex ClientID for a user (race-safe via ON CONFLICT)."""
now = datetime.now(UTC)
values = {
'yandex_cid': cid,
'source': source,
'updated_at': now,
}
if counter_id:
values['counter_id'] = counter_id
if subid:
values['subid'] = subid
stmt = (
pg_insert(YandexClientIdMap)
.values(user_id=user_id, yandex_cid=cid, source=source, counter_id=counter_id, subid=subid)
.on_conflict_do_update(index_elements=['user_id'], set_=values)
.returning(YandexClientIdMap)
)
result = await db.execute(stmt)
await db.flush()
return result.scalar_one()
async def get_cid(db: AsyncSession, user_id: int) -> YandexClientIdMap | None:
"""Get Yandex ClientID mapping for a user."""
result = await db.execute(select(YandexClientIdMap).where(YandexClientIdMap.user_id == user_id))
return result.scalar_one_or_none()
async def mark_registration_sent(db: AsyncSession, user_id: int) -> None:
"""Mark registration event as sent for a user."""
await db.execute(
update(YandexClientIdMap)
.where(YandexClientIdMap.user_id == user_id)
.values(registration_sent=True, updated_at=datetime.now(UTC))
)
await db.flush()
async def mark_trial_sent(db: AsyncSession, user_id: int) -> None:
"""Mark trial event as sent for a user."""
await db.execute(
update(YandexClientIdMap)
.where(YandexClientIdMap.user_id == user_id)
.values(trial_sent=True, updated_at=datetime.now(UTC))
)
await db.flush()
async def upsert_subid(
db: AsyncSession,
user_id: int,
subid: str,
source: str = 'web',
) -> None:
"""Save subid for a user. Updates existing record or creates with placeholder CID."""
if not subid or len(subid) > 255:
return
now = datetime.now(UTC)
# Try update first (don't create empty CID records)
result = await db.execute(
update(YandexClientIdMap).where(YandexClientIdMap.user_id == user_id).values(subid=subid, updated_at=now)
)
if result.rowcount == 0:
# No existing record — create with placeholder
stmt = (
pg_insert(YandexClientIdMap)
.values(user_id=user_id, yandex_cid='_subid_only', source=source, subid=subid)
.on_conflict_do_update(
index_elements=['user_id'],
set_={'subid': subid, 'updated_at': now},
)
)
await db.execute(stmt)
await db.flush()
logger.info('Subid saved', user_id=user_id, subid=subid, source=source)
async def get_subid(db: AsyncSession, user_id: int) -> str | None:
"""Get subid for a user."""
result = await db.execute(select(YandexClientIdMap.subid).where(YandexClientIdMap.user_id == user_id))
return result.scalar_one_or_none()
+305 -7
View File
@@ -162,6 +162,10 @@ class PaymentMethod(Enum):
KASSA_AI = 'kassa_ai'
RIOPAY = 'riopay'
SEVERPAY = 'severpay'
PAYPEAR = 'paypear'
ROLLYPAY = 'rollypay'
OVERPAY = 'overpay'
AURAPAY = 'aurapay'
MANUAL = 'manual'
BALANCE = 'balance'
@@ -878,6 +882,254 @@ class SeverPayPayment(Base):
return f'<SeverPayPayment(id={self.id}, order_id={self.order_id}, amount={self.amount_rubles}₽, status={self.status})>'
class PayPearPayment(Base):
"""Платежи через PayPear (paypear.ru)."""
__tablename__ = 'paypear_payments'
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True, index=True)
# Идентификаторы
order_id = Column(String(64), unique=True, nullable=False, index=True) # Наш internal ID
paypear_id = Column(String(64), unique=True, nullable=True, index=True) # ID от PayPear
# Суммы
amount_kopeks = Column(Integer, nullable=False)
currency = Column(String(10), nullable=False, default='RUB')
description = Column(Text, nullable=True)
# Статусы
status = Column(String(32), nullable=False, default='pending')
is_paid = Column(Boolean, default=False)
# Данные платежа
payment_url = Column(Text, nullable=True)
payment_method = Column(String(32), nullable=True)
# Метаданные
metadata_json = Column(JSON, nullable=True)
callback_payload = Column(JSON, nullable=True)
# Временные метки
paid_at = Column(AwareDateTime(), nullable=True)
expires_at = Column(AwareDateTime(), nullable=True)
created_at = Column(AwareDateTime(), default=func.now())
updated_at = Column(AwareDateTime(), default=func.now(), onupdate=func.now())
# Связь с транзакцией
transaction_id = Column(Integer, ForeignKey('transactions.id'), nullable=True)
# Relationships
user = relationship('User', backref='paypear_payments')
transaction = relationship('Transaction', backref='paypear_payment')
@property
def amount_rubles(self) -> float:
return self.amount_kopeks / 100
@property
def is_pending(self) -> bool:
return self.status == 'pending'
@property
def is_success(self) -> bool:
return self.status == 'success' and self.is_paid
@property
def is_failed(self) -> bool:
return self.status in ['failed', 'expired', 'canceled', 'amount_mismatch']
def __repr__(self) -> str: # pragma: no cover - debug helper
return f'<PayPearPayment(id={self.id}, order_id={self.order_id}, amount={self.amount_rubles}₽, status={self.status})>'
class RollyPayPayment(Base):
"""Платежи через RollyPay (rollypay.io)."""
__tablename__ = 'rollypay_payments'
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True, index=True)
# Идентификаторы
order_id = Column(String(64), unique=True, nullable=False, index=True) # Наш internal ID
rollypay_payment_id = Column(String(128), unique=True, nullable=True, index=True) # pay_uuid от RollyPay
# Суммы
amount_kopeks = Column(Integer, nullable=False)
currency = Column(String(10), nullable=False, default='RUB')
description = Column(Text, nullable=True)
# Статусы
status = Column(String(32), nullable=False, default='pending')
is_paid = Column(Boolean, default=False)
# Данные платежа
payment_url = Column(Text, nullable=True)
payment_method = Column(String(32), nullable=True)
# Метаданные
metadata_json = Column(JSON, nullable=True)
callback_payload = Column(JSON, nullable=True)
# Временные метки
paid_at = Column(AwareDateTime(), nullable=True)
expires_at = Column(AwareDateTime(), nullable=True)
created_at = Column(AwareDateTime(), default=func.now())
updated_at = Column(AwareDateTime(), default=func.now(), onupdate=func.now())
# Связь с транзакцией
transaction_id = Column(Integer, ForeignKey('transactions.id'), nullable=True)
# Relationships
user = relationship('User', backref='rollypay_payments')
transaction = relationship('Transaction', backref='rollypay_payment')
@property
def amount_rubles(self) -> float:
return self.amount_kopeks / 100
@property
def is_pending(self) -> bool:
return self.status == 'pending'
@property
def is_success(self) -> bool:
return self.status == 'success' and self.is_paid
@property
def is_failed(self) -> bool:
return self.status in ['failed', 'expired', 'canceled', 'chargeback', 'amount_mismatch']
def __repr__(self) -> str: # pragma: no cover - debug helper
return f'<RollyPayPayment(id={self.id}, order_id={self.order_id}, amount={self.amount_rubles}₽, status={self.status})>'
class OverpayPayment(Base):
"""Платежи через Overpay (pay.overpay.io)."""
__tablename__ = 'overpay_payments'
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True, index=True)
# Идентификаторы
order_id = Column(String(64), unique=True, nullable=False, index=True) # Наш internal ID
overpay_payment_id = Column(String(128), unique=True, nullable=True, index=True) # ID от Overpay
# Суммы
amount_kopeks = Column(Integer, nullable=False)
currency = Column(String(10), nullable=False, default='RUB')
description = Column(Text, nullable=True)
# Статусы
status = Column(String(32), nullable=False, default='pending')
is_paid = Column(Boolean, default=False)
# Данные платежа
payment_url = Column(Text, nullable=True)
payment_method = Column(String(32), nullable=True)
# Метаданные
metadata_json = Column(JSON, nullable=True)
callback_payload = Column(JSON, nullable=True)
# Временные метки
paid_at = Column(AwareDateTime(), nullable=True)
expires_at = Column(AwareDateTime(), nullable=True)
created_at = Column(AwareDateTime(), default=func.now())
updated_at = Column(AwareDateTime(), default=func.now(), onupdate=func.now())
# Связь с транзакцией
transaction_id = Column(Integer, ForeignKey('transactions.id'), nullable=True)
# Relationships
user = relationship('User', backref='overpay_payments')
transaction = relationship('Transaction', backref='overpay_payment')
@property
def amount_rubles(self) -> float:
return self.amount_kopeks / 100
@property
def is_pending(self) -> bool:
return self.status == 'pending'
@property
def is_success(self) -> bool:
return self.status == 'success' and self.is_paid
@property
def is_failed(self) -> bool:
return self.status in ['failed', 'expired', 'canceled', 'chargeback', 'amount_mismatch']
def __repr__(self) -> str: # pragma: no cover - debug helper
return f'<OverpayPayment(id={self.id}, order_id={self.order_id}, amount={self.amount_rubles}₽, status={self.status})>'
class AuraPayPayment(Base):
"""Платежи через AuraPay (aurapay.tech)."""
__tablename__ = 'aurapay_payments'
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey('users.id', ondelete='SET NULL'), nullable=True, index=True)
# Идентификаторы
order_id = Column(String(64), unique=True, nullable=False, index=True) # Наш internal ID
aurapay_invoice_id = Column(String(128), unique=True, nullable=True, index=True) # UUID от AuraPay
# Суммы
amount_kopeks = Column(Integer, nullable=False)
currency = Column(String(10), nullable=False, default='RUB')
description = Column(Text, nullable=True)
# Статусы
status = Column(String(32), nullable=False, default='pending')
is_paid = Column(Boolean, default=False)
# Данные платежа
payment_url = Column(Text, nullable=True)
payment_method = Column(String(32), nullable=True)
# Метаданные
metadata_json = Column(JSON, nullable=True)
callback_payload = Column(JSON, nullable=True)
# Временные метки
paid_at = Column(AwareDateTime(), nullable=True)
expires_at = Column(AwareDateTime(), nullable=True)
created_at = Column(AwareDateTime(), default=func.now())
updated_at = Column(AwareDateTime(), default=func.now(), onupdate=func.now())
# Связь с транзакцией
transaction_id = Column(Integer, ForeignKey('transactions.id'), nullable=True)
# Relationships
user = relationship('User', backref='aurapay_payments')
transaction = relationship('Transaction', backref='aurapay_payment')
@property
def amount_rubles(self) -> float:
return self.amount_kopeks / 100
@property
def is_pending(self) -> bool:
return self.status == 'pending'
@property
def is_success(self) -> bool:
return self.status == 'success' and self.is_paid
@property
def is_failed(self) -> bool:
return self.status in ['failed', 'expired', 'canceled', 'amount_mismatch']
def __repr__(self) -> str: # pragma: no cover - debug helper
return f'<AuraPayPayment(id={self.id}, order_id={self.order_id}, amount={self.amount_rubles}₽, status={self.status})>'
class PromoGroup(Base):
__tablename__ = 'promo_groups'
@@ -933,13 +1185,6 @@ class PromoGroup(Base):
if period_days in discounts:
return discounts[period_days]
# For daily tariffs (period_days=1): fallback to the smallest configured period discount.
# Admins configure discounts for standard periods (30, 90, 180, 360) but not for daily.
# If all periods have 100% discount, daily should too.
if period_days <= 1 and discounts:
smallest_period = min(discounts)
return discounts[smallest_period]
if self.is_default:
try:
from app.config import settings
@@ -2654,6 +2899,8 @@ class TicketMessage(Base):
media_type = Column(String(20), nullable=True) # photo, video, document, voice, etc.
media_file_id = Column(String(255), nullable=True)
media_caption = Column(Text, nullable=True)
# Multi-media gallery (photos/videos/documents bundled in one bubble)
media_items = Column(JSONB, nullable=True)
created_at = Column(AwareDateTime(), default=func.now())
@@ -3275,6 +3522,13 @@ class LandingPage(Base):
background_config = Column(
JSON, nullable=True
) # AnimationConfig: {enabled, type, settings, opacity, blur, reducedOnMobile}
# Sticky pay button on mobile (full-width fixed bottom)
sticky_pay_button = Column(Boolean, nullable=False, default=False, server_default=text('false'))
# Yandex Metrika landing-level conversion goals
analytics_view_enabled = Column(Boolean, nullable=False, default=False, server_default=text('false'))
analytics_view_goal = Column(String(64), nullable=True)
analytics_click_enabled = Column(Boolean, nullable=False, default=False, server_default=text('false'))
analytics_click_goal = Column(String(64), nullable=True)
created_at = Column(AwareDateTime(), server_default=func.now())
updated_at = Column(AwareDateTime(), server_default=func.now(), onupdate=func.now())
@@ -3337,6 +3591,10 @@ class GuestPurchase(Base):
retry_count = Column(Integer, nullable=False, default=0, server_default='0')
receipt_uuid = Column(String(255), nullable=True, index=True)
receipt_created_at = Column(AwareDateTime(), nullable=True)
# Yandex Metrika offline conversions: client identifier + traffic source tags
yandex_cid = Column(String(128), nullable=True)
subid = Column(String(255), nullable=True)
referrer = Column(String(500), nullable=True)
landing = relationship('LandingPage', back_populates='guest_purchases', lazy='selectin')
tariff = relationship('Tariff', lazy='selectin')
@@ -3418,3 +3676,43 @@ class NewsTag(Base):
def __repr__(self) -> str:
return f"<NewsTag id={self.id} name='{self.name}'>"
class YandexClientIdMap(Base):
"""Yandex Metrika client identifier captured per user.
Stores the mapping user_id -> yandex_cid so we can fire offline
conversion events to mc.yandex.ru with the right CID even after
the user leaves the landing/web flow. The ``subid`` column carries
a pass-through traffic-source identifier for S2S postbacks.
"""
__tablename__ = 'yandex_client_id_map'
id = Column(Integer, primary_key=True, autoincrement=True)
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'), unique=True, nullable=False)
yandex_cid = Column(String(128), nullable=False)
source = Column(String(20), nullable=False, default='web', server_default='web')
counter_id = Column(String(32), nullable=True)
registration_sent = Column(Boolean, default=False, server_default=text('false'), nullable=False)
trial_sent = Column(Boolean, default=False, server_default=text('false'), nullable=False)
subid = Column(String(255), nullable=True)
created_at = Column(AwareDateTime(), server_default=func.now())
updated_at = Column(AwareDateTime(), server_default=func.now(), onupdate=func.now())
class InfoPage(Base):
"""Static informational page with multilingual title/content (JSONB)."""
__tablename__ = 'info_pages'
id = Column(Integer, primary_key=True, index=True)
slug = Column(String(200), unique=True, nullable=False)
title = Column(JSONB, nullable=False, server_default='{}')
content = Column(JSONB, nullable=False, server_default='{}')
page_type = Column(String(20), nullable=False, default='page', server_default='page')
is_active = Column(Boolean, nullable=False, default=True, server_default='true')
sort_order = Column(Integer, nullable=False, default=0, server_default='0')
icon = Column(String(50), nullable=True)
replaces_tab = Column(String(20), nullable=True) # 'faq', 'rules', 'privacy', 'offer', or null
created_at = Column(AwareDateTime(), server_default=func.now())
updated_at = Column(AwareDateTime(), server_default=func.now(), onupdate=func.now())
+21
View File
@@ -541,6 +541,27 @@ class RemnaWaveAPI:
return []
raise
async def get_subscription_request_history(
self,
uuid: str,
offset: int = 0,
limit: int = 20,
) -> dict:
"""Get subscription request history for a panel user.
Returns dict with 'total' and 'records' list.
Each record has: id, userUuid, requestAt, requestIp, userAgent.
"""
try:
response = await self._make_request(
'GET',
f'/api/users/{uuid}/subscription-request-history',
params={'offset': offset, 'limit': limit},
)
return response.get('response', {'total': 0, 'records': []})
except RemnaWaveAPIError:
return {'total': 0, 'records': []}
async def update_user(
self,
uuid: str,
+5 -4
View File
@@ -313,7 +313,7 @@ async def restore_backup_start(callback: types.CallbackQuery, db_user: User, db:
else:
text = """📥 <b>Восстановление из бекапа</b>
📎 Отправьте файл бекапа (.json или .json.gz)
📎 Отправьте файл бекапа (.json, .json.gz или .tar.gz)
<b>ВАЖНО:</b>
Файл должен быть создан этой системой бекапов
@@ -383,7 +383,7 @@ async def restore_backup_execute(callback: types.CallbackQuery, db_user: User, d
async def handle_backup_file_upload(message: types.Message, db_user: User, db: AsyncSession, state: FSMContext):
if not message.document:
await message.answer(
'❌ Пожалуйста, отправьте файл бекапа (.json или .json.gz)',
'❌ Пожалуйста, отправьте файл бекапа (.json, .json.gz или .tar.gz)',
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text='◀️ Отмена', callback_data='backup_panel')]]
),
@@ -391,10 +391,11 @@ async def handle_backup_file_upload(message: types.Message, db_user: User, db: A
return
document = message.document
allowed_extensions = ('.json', '.json.gz', '.tar.gz', '.tar')
if not (document.file_name.endswith('.json') or document.file_name.endswith('.json.gz')):
if not document.file_name or not any(document.file_name.endswith(ext) for ext in allowed_extensions):
await message.answer(
'❌ Неподдерживаемый формат файла. Загрузите .json или .json.gz файл',
'❌ Неподдерживаемый формат файла. Загрузите .json, .json.gz или .tar.gz файл',
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text='◀️ Отмена', callback_data='backup_panel')]]
),
+17 -2
View File
@@ -63,7 +63,7 @@ CATEGORY_GROUP_METADATA: dict[str, dict[str, object]] = {
},
'payments': {
'title': '💳 Платежные системы',
'description': 'YooKassa, CryptoBot, Heleket, CloudPayments, Freekassa, MulenPay, PAL24, Wata, Platega, Tribute, Kassa AI, RioPay, SeverPay и Telegram Stars.',
'description': 'YooKassa, CryptoBot, Heleket, CloudPayments, Freekassa, MulenPay, PAL24, Wata, Platega, Tribute, Kassa AI, RioPay, SeverPay, PayPear, RollyPay и Telegram Stars.',
'icon': '💳',
'categories': (
'PAYMENT',
@@ -76,6 +76,10 @@ CATEGORY_GROUP_METADATA: dict[str, dict[str, object]] = {
'KASSA_AI',
'RIOPAY',
'SEVERPAY',
'PAYPEAR',
'ROLLYPAY',
'OVERPAY',
'AURAPAY',
'MULENPAY',
'PAL24',
'WATA',
@@ -154,7 +158,6 @@ CATEGORY_GROUP_METADATA: dict[str, dict[str, object]] = {
'LOG',
'MODERATION',
'DEBUG',
'EXTERNAL_ADMIN',
),
},
}
@@ -1260,6 +1263,18 @@ def _build_settings_keyboard(
elif category_key == 'SEVERPAY':
label = texts.t('PAYMENT_SEVERPAY', f'💳 {settings.get_severpay_display_name()}')
test_payment_buttons.append([_test_button(f'{label} · тест', 'severpay')])
elif category_key == 'PAYPEAR':
label = texts.t('PAYMENT_PAYPEAR', f'💳 {settings.get_paypear_display_name()}')
test_payment_buttons.append([_test_button(f'{label} · тест', 'paypear')])
elif category_key == 'ROLLYPAY':
label = texts.t('PAYMENT_ROLLYPAY', f'💳 {settings.get_rollypay_display_name()}')
test_payment_buttons.append([_test_button(f'{label} · тест', 'rollypay')])
elif category_key == 'OVERPAY':
label = texts.t('PAYMENT_OVERPAY', f'💳 {settings.get_overpay_display_name()}')
test_payment_buttons.append([_test_button(f'{label} · тест', 'overpay')])
elif category_key == 'AURAPAY':
label = texts.t('PAYMENT_AURAPAY', f'💳 {settings.get_aurapay_display_name()}')
test_payment_buttons.append([_test_button(f'{label} · тест', 'aurapay')])
if test_payment_buttons:
rows.extend(test_payment_buttons)
+2
View File
@@ -1559,6 +1559,7 @@ async def get_target_users_count(db: AsyncSession, target: str) -> int:
Subscription.user_id == User.id,
Subscription.status == SubscriptionStatus.ACTIVE.value,
)
.correlate(User)
.exists()
)
query = select(sql_func.count(User.id)).where(base_filter, ~subquery)
@@ -1613,6 +1614,7 @@ async def get_target_users_count(db: AsyncSession, target: str) -> int:
Subscription.user_id == User.id,
Subscription.status == SubscriptionStatus.ACTIVE.value,
)
.correlate(User)
.exists()
)
query = (
+2 -4
View File
@@ -4518,11 +4518,9 @@ async def _grant_paid_subscription(
trial_squads: list[str] = []
try:
from app.database.crud.server_squad import get_random_trial_squad_uuid
from app.database.crud.server_squad import get_effective_tariff_squad_uuids
trial_uuid = await get_random_trial_squad_uuid(db)
if trial_uuid:
trial_squads = [trial_uuid]
trial_squads = await get_effective_tariff_squad_uuids(db, None)
except Exception as error:
logger.error('Не удалось подобрать сквад при выдаче подписки админом', admin_id=admin_id, error=error)
+247
View File
@@ -0,0 +1,247 @@
"""Handler for AuraPay balance top-up."""
import html
import structlog
from aiogram import types
from aiogram.fsm.context import FSMContext
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import User
from app.keyboards.inline import get_back_keyboard
from app.localization.texts import get_texts
from app.services.payment_service import PaymentService
from app.states import BalanceStates
from app.utils.decorators import error_handler
logger = structlog.get_logger(__name__)
def _check_topup_restriction(db_user: User, texts) -> InlineKeyboardMarkup | None:
"""Проверяет ограничение на пополнение. Возвращает клавиатуру если ограничен, иначе None."""
if not getattr(db_user, 'restriction_topup', False):
return None
keyboard = []
support_url = settings.get_support_contact_url()
if support_url:
keyboard.append([InlineKeyboardButton(text='\U0001f198 Обжаловать', url=support_url)])
keyboard.append([InlineKeyboardButton(text=texts.BACK, callback_data='menu_balance')])
return InlineKeyboardMarkup(inline_keyboard=keyboard)
async def _create_aurapay_payment_and_respond(
message_or_callback,
db_user: User,
db: AsyncSession,
amount_kopeks: int,
edit_message: bool = False,
):
"""
Common logic for creating AuraPay payment and sending response.
"""
texts = get_texts(db_user.language)
amount_rub = amount_kopeks / 100
# Create payment
payment_service = PaymentService()
description = settings.PAYMENT_BALANCE_TEMPLATE.format(
service_name=settings.PAYMENT_SERVICE_NAME,
description='Пополнение баланса',
)
result = await payment_service.create_aurapay_payment(
db=db,
user_id=db_user.id,
amount_kopeks=amount_kopeks,
description=description,
email=getattr(db_user, 'email', None),
language=db_user.language,
)
if not result:
error_text = texts.t(
'PAYMENT_CREATE_ERROR',
'Не удалось создать платёж. Попробуйте позже.',
)
if edit_message:
await message_or_callback.edit_text(
error_text,
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
else:
await message_or_callback.answer(
error_text,
parse_mode='HTML',
)
return
payment_url = result.get('payment_url')
display_name = settings.get_aurapay_display_name()
# Create keyboard with payment button
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=texts.t(
'PAY_BUTTON',
'\U0001f4b3 Оплатить {amount}\u20bd',
).format(amount=f'{amount_rub:.0f}'),
url=payment_url,
)
],
[
InlineKeyboardButton(
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
callback_data='menu_balance',
)
],
]
)
response_text = texts.t(
'AURAPAY_PAYMENT_CREATED',
'\U0001f4b3 <b>Оплата через {name}</b>\n\n'
'Сумма: <b>{amount}\u20bd</b>\n\n'
'Нажмите кнопку ниже для оплаты.\n'
'После успешной оплаты баланс будет пополнен автоматически.',
).format(name=display_name, amount=f'{amount_rub:.2f}')
if edit_message:
await message_or_callback.edit_text(
response_text,
reply_markup=keyboard,
parse_mode='HTML',
)
else:
await message_or_callback.answer(
response_text,
reply_markup=keyboard,
parse_mode='HTML',
)
logger.info('AuraPay payment created', telegram_id=db_user.telegram_id, amount_rub=amount_rub)
@error_handler
async def process_aurapay_payment_amount(
message: types.Message,
db_user: User,
db: AsyncSession,
amount_kopeks: int,
state: FSMContext,
):
"""
Process payment amount directly.
"""
texts = get_texts(db_user.language)
restriction_kb = _check_topup_restriction(db_user, texts)
if restriction_kb:
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
await message.answer(
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=restriction_kb,
)
await state.clear()
return
# Validate amount
min_amount = settings.AURAPAY_MIN_AMOUNT_KOPEKS
max_amount = settings.AURAPAY_MAX_AMOUNT_KOPEKS
if amount_kopeks < min_amount:
await message.answer(
texts.t(
'PAYMENT_AMOUNT_TOO_LOW',
'Минимальная сумма пополнения: {min_amount}\u20bd',
).format(min_amount=min_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
if amount_kopeks > max_amount:
await message.answer(
texts.t(
'PAYMENT_AMOUNT_TOO_HIGH',
'Максимальная сумма пополнения: {max_amount}\u20bd',
).format(max_amount=max_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
await state.clear()
await _create_aurapay_payment_and_respond(
message_or_callback=message,
db_user=db_user,
db=db,
amount_kopeks=amount_kopeks,
edit_message=False,
)
@error_handler
async def start_aurapay_topup(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
):
"""
Start AuraPay top-up process - ask for amount.
"""
texts = get_texts(db_user.language)
restriction_kb = _check_topup_restriction(db_user, texts)
if restriction_kb:
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
await callback.message.edit_text(
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=restriction_kb,
)
return
await state.set_state(BalanceStates.waiting_for_amount)
await state.update_data(payment_method='aurapay')
min_amount = settings.AURAPAY_MIN_AMOUNT_KOPEKS // 100
max_amount = settings.AURAPAY_MAX_AMOUNT_KOPEKS // 100
display_name = settings.get_aurapay_display_name()
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
callback_data='menu_balance',
)
]
]
)
await callback.message.edit_text(
texts.t(
'AURAPAY_ENTER_AMOUNT',
'\U0001f4b3 <b>Пополнение через {name}</b>\n\n'
'Введите сумму пополнения в рублях.\n\n'
'Минимум: {min_amount}\u20bd\n'
'Максимум: {max_amount}\u20bd',
).format(
name=display_name,
min_amount=min_amount,
max_amount=f'{max_amount:,}'.replace(',', ' '),
),
parse_mode='HTML',
reply_markup=keyboard,
)
+60 -7
View File
@@ -149,6 +149,34 @@ async def route_payment_by_method(
await process_severpay_payment_amount(message, db_user, db, amount_kopeks, state)
return True
if payment_method == 'paypear':
from .paypear import process_paypear_payment_amount
async with AsyncSessionLocal() as db:
await process_paypear_payment_amount(message, db_user, db, amount_kopeks, state)
return True
if payment_method == 'rollypay':
from .rollypay import process_rollypay_payment_amount
async with AsyncSessionLocal() as db:
await process_rollypay_payment_amount(message, db_user, db, amount_kopeks, state)
return True
if payment_method == 'overpay':
from .overpay import process_overpay_payment_amount
async with AsyncSessionLocal() as db:
await process_overpay_payment_amount(message, db_user, db, amount_kopeks, state)
return True
if payment_method == 'aurapay':
from .aurapay import process_aurapay_payment_amount
async with AsyncSessionLocal() as db:
await process_aurapay_payment_amount(message, db_user, db, amount_kopeks, state)
return True
if payment_method == 'riopay':
from .riopay import process_riopay_payment_amount
@@ -470,12 +498,16 @@ async def process_topup_amount(message: types.Message, db_user: User, state: FSM
amount_rubles = float(amount_text.replace(',', '.'))
if amount_rubles < 1:
await message.answer('Минимальная сумма пополнения: 1 ₽', reply_markup=get_back_keyboard(db_user.language))
await message.answer(
'Минимальная сумма пополнения: 1 ₽',
reply_markup=get_back_keyboard(db_user.language, callback_data='balance_topup'),
)
return
if amount_rubles > 50000:
await message.answer(
'Максимальная сумма пополнения: 50,000 ₽', reply_markup=get_back_keyboard(db_user.language)
'Максимальная сумма пополнения: 50,000 ₽',
reply_markup=get_back_keyboard(db_user.language, callback_data='balance_topup'),
)
return
@@ -488,7 +520,7 @@ async def process_topup_amount(message: types.Message, db_user: User, state: FSM
min_rubles = settings.YOOKASSA_MIN_AMOUNT_KOPEKS / 100
await message.answer(
f'❌ Минимальная сумма для оплаты через YooKassa: {min_rubles:.0f}',
reply_markup=get_back_keyboard(db_user.language),
reply_markup=get_back_keyboard(db_user.language, callback_data='balance_topup'),
)
return
@@ -496,7 +528,7 @@ async def process_topup_amount(message: types.Message, db_user: User, state: FSM
max_rubles = settings.YOOKASSA_MAX_AMOUNT_KOPEKS / 100
await message.answer(
f'❌ Максимальная сумма для оплаты через YooKassa: {max_rubles:,.0f}'.replace(',', ' '),
reply_markup=get_back_keyboard(db_user.language),
reply_markup=get_back_keyboard(db_user.language, callback_data='balance_topup'),
)
return
@@ -572,6 +604,7 @@ async def handle_topup_amount_callback(
platega_method_code = int(method[len('platega_m') :])
await state.update_data(payment_method='platega', platega_method=platega_method_code)
await state.set_state(BalanceStates.waiting_for_amount)
async with AsyncSessionLocal() as db:
await process_platega_payment_amount(callback.message, db_user, db, amount_kopeks, state)
elif method == 'platega':
@@ -583,6 +616,7 @@ async def handle_topup_amount_callback(
method_code = int(data.get('platega_method', 0)) if data else 0
if method_code > 0:
await state.set_state(BalanceStates.waiting_for_amount)
async with AsyncSessionLocal() as db:
await process_platega_payment_amount(callback.message, db_user, db, amount_kopeks, state)
else:
@@ -594,9 +628,12 @@ async def handle_topup_amount_callback(
await start_tribute_payment(callback, db_user)
return
# Стандартные методы через роутер
elif not await route_payment_by_method(callback.message, db_user, amount_kopeks, state, method):
await callback.answer('❌ Неизвестный способ оплаты', show_alert=True)
return
else:
await state.update_data(payment_method=method)
await state.set_state(BalanceStates.waiting_for_amount)
if not await route_payment_by_method(callback.message, db_user, amount_kopeks, state, method):
await callback.answer('❌ Неизвестный способ оплаты', show_alert=True)
return
await callback.answer()
@@ -719,6 +756,22 @@ def register_balance_handlers(dp: Dispatcher):
dp.callback_query.register(start_severpay_topup, F.data == 'topup_severpay')
from .paypear import start_paypear_topup
dp.callback_query.register(start_paypear_topup, F.data == 'topup_paypear')
from .rollypay import start_rollypay_topup
dp.callback_query.register(start_rollypay_topup, F.data == 'topup_rollypay')
from .overpay import start_overpay_topup
dp.callback_query.register(start_overpay_topup, F.data == 'topup_overpay')
from .aurapay import start_aurapay_topup
dp.callback_query.register(start_aurapay_topup, F.data == 'topup_aurapay')
from .mulenpay import check_mulenpay_payment_status
dp.callback_query.register(check_mulenpay_payment_status, F.data.startswith('check_mulenpay_'))
+247
View File
@@ -0,0 +1,247 @@
"""Handler for Overpay balance top-up."""
import html
import structlog
from aiogram import types
from aiogram.fsm.context import FSMContext
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import User
from app.keyboards.inline import get_back_keyboard
from app.localization.texts import get_texts
from app.services.payment_service import PaymentService
from app.states import BalanceStates
from app.utils.decorators import error_handler
logger = structlog.get_logger(__name__)
def _check_topup_restriction(db_user: User, texts) -> InlineKeyboardMarkup | None:
"""Проверяет ограничение на пополнение. Возвращает клавиатуру если ограничен, иначе None."""
if not getattr(db_user, 'restriction_topup', False):
return None
keyboard = []
support_url = settings.get_support_contact_url()
if support_url:
keyboard.append([InlineKeyboardButton(text='\U0001f198 Обжаловать', url=support_url)])
keyboard.append([InlineKeyboardButton(text=texts.BACK, callback_data='menu_balance')])
return InlineKeyboardMarkup(inline_keyboard=keyboard)
async def _create_overpay_payment_and_respond(
message_or_callback,
db_user: User,
db: AsyncSession,
amount_kopeks: int,
edit_message: bool = False,
):
"""
Common logic for creating Overpay payment and sending response.
"""
texts = get_texts(db_user.language)
amount_rub = amount_kopeks / 100
# Create payment
payment_service = PaymentService()
description = settings.PAYMENT_BALANCE_TEMPLATE.format(
service_name=settings.PAYMENT_SERVICE_NAME,
description='Пополнение баланса',
)
result = await payment_service.create_overpay_payment(
db=db,
user_id=db_user.id,
amount_kopeks=amount_kopeks,
description=description,
email=getattr(db_user, 'email', None),
language=db_user.language,
)
if not result:
error_text = texts.t(
'PAYMENT_CREATE_ERROR',
'Не удалось создать платёж. Попробуйте позже.',
)
if edit_message:
await message_or_callback.edit_text(
error_text,
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
else:
await message_or_callback.answer(
error_text,
parse_mode='HTML',
)
return
payment_url = result.get('payment_url')
display_name = settings.get_overpay_display_name()
# Create keyboard with payment button
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=texts.t(
'PAY_BUTTON',
'\U0001f4b3 Оплатить {amount}\u20bd',
).format(amount=f'{amount_rub:.0f}'),
url=payment_url,
)
],
[
InlineKeyboardButton(
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
callback_data='menu_balance',
)
],
]
)
response_text = texts.t(
'OVERPAY_PAYMENT_CREATED',
'\U0001f4b3 <b>Оплата через {name}</b>\n\n'
'Сумма: <b>{amount}\u20bd</b>\n\n'
'Нажмите кнопку ниже для оплаты.\n'
'После успешной оплаты баланс будет пополнен автоматически.',
).format(name=display_name, amount=f'{amount_rub:.2f}')
if edit_message:
await message_or_callback.edit_text(
response_text,
reply_markup=keyboard,
parse_mode='HTML',
)
else:
await message_or_callback.answer(
response_text,
reply_markup=keyboard,
parse_mode='HTML',
)
logger.info('Overpay payment created', telegram_id=db_user.telegram_id, amount_rub=amount_rub)
@error_handler
async def process_overpay_payment_amount(
message: types.Message,
db_user: User,
db: AsyncSession,
amount_kopeks: int,
state: FSMContext,
):
"""
Process payment amount directly.
"""
texts = get_texts(db_user.language)
restriction_kb = _check_topup_restriction(db_user, texts)
if restriction_kb:
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
await message.answer(
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=restriction_kb,
)
await state.clear()
return
# Validate amount
min_amount = settings.OVERPAY_MIN_AMOUNT_KOPEKS
max_amount = settings.OVERPAY_MAX_AMOUNT_KOPEKS
if amount_kopeks < min_amount:
await message.answer(
texts.t(
'PAYMENT_AMOUNT_TOO_LOW',
'Минимальная сумма пополнения: {min_amount}\u20bd',
).format(min_amount=min_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
if amount_kopeks > max_amount:
await message.answer(
texts.t(
'PAYMENT_AMOUNT_TOO_HIGH',
'Максимальная сумма пополнения: {max_amount}\u20bd',
).format(max_amount=max_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
await state.clear()
await _create_overpay_payment_and_respond(
message_or_callback=message,
db_user=db_user,
db=db,
amount_kopeks=amount_kopeks,
edit_message=False,
)
@error_handler
async def start_overpay_topup(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
):
"""
Start Overpay top-up process - ask for amount.
"""
texts = get_texts(db_user.language)
restriction_kb = _check_topup_restriction(db_user, texts)
if restriction_kb:
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
await callback.message.edit_text(
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=restriction_kb,
)
return
await state.set_state(BalanceStates.waiting_for_amount)
await state.update_data(payment_method='overpay')
min_amount = settings.OVERPAY_MIN_AMOUNT_KOPEKS // 100
max_amount = settings.OVERPAY_MAX_AMOUNT_KOPEKS // 100
display_name = settings.get_overpay_display_name()
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
callback_data='menu_balance',
)
]
]
)
await callback.message.edit_text(
texts.t(
'OVERPAY_ENTER_AMOUNT',
'\U0001f4b3 <b>Пополнение через {name}</b>\n\n'
'Введите сумму пополнения в рублях.\n\n'
'Минимум: {min_amount}\u20bd\n'
'Максимум: {max_amount}\u20bd',
).format(
name=display_name,
min_amount=min_amount,
max_amount=f'{max_amount:,}'.replace(',', ' '),
),
parse_mode='HTML',
reply_markup=keyboard,
)
+247
View File
@@ -0,0 +1,247 @@
"""Handler for PayPear balance top-up."""
import html
import structlog
from aiogram import types
from aiogram.fsm.context import FSMContext
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import User
from app.keyboards.inline import get_back_keyboard
from app.localization.texts import get_texts
from app.services.payment_service import PaymentService
from app.states import BalanceStates
from app.utils.decorators import error_handler
logger = structlog.get_logger(__name__)
def _check_topup_restriction(db_user: User, texts) -> InlineKeyboardMarkup | None:
"""Проверяет ограничение на пополнение. Возвращает клавиатуру если ограничен, иначе None."""
if not getattr(db_user, 'restriction_topup', False):
return None
keyboard = []
support_url = settings.get_support_contact_url()
if support_url:
keyboard.append([InlineKeyboardButton(text='\U0001f198 Обжаловать', url=support_url)])
keyboard.append([InlineKeyboardButton(text=texts.BACK, callback_data='menu_balance')])
return InlineKeyboardMarkup(inline_keyboard=keyboard)
async def _create_paypear_payment_and_respond(
message_or_callback,
db_user: User,
db: AsyncSession,
amount_kopeks: int,
edit_message: bool = False,
):
"""
Common logic for creating PayPear payment and sending response.
"""
texts = get_texts(db_user.language)
amount_rub = amount_kopeks / 100
# Create payment
payment_service = PaymentService()
description = settings.PAYMENT_BALANCE_TEMPLATE.format(
service_name=settings.PAYMENT_SERVICE_NAME,
description='Пополнение баланса',
)
result = await payment_service.create_paypear_payment(
db=db,
user_id=db_user.id,
amount_kopeks=amount_kopeks,
description=description,
email=getattr(db_user, 'email', None),
language=db_user.language,
)
if not result:
error_text = texts.t(
'PAYMENT_CREATE_ERROR',
'Не удалось создать платёж. Попробуйте позже.',
)
if edit_message:
await message_or_callback.edit_text(
error_text,
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
else:
await message_or_callback.answer(
error_text,
parse_mode='HTML',
)
return
payment_url = result.get('payment_url')
display_name = settings.get_paypear_display_name()
# Create keyboard with payment button
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=texts.t(
'PAY_BUTTON',
'\U0001f4b3 Оплатить {amount}\u20bd',
).format(amount=f'{amount_rub:.0f}'),
url=payment_url,
)
],
[
InlineKeyboardButton(
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
callback_data='menu_balance',
)
],
]
)
response_text = texts.t(
'PAYPEAR_PAYMENT_CREATED',
'\U0001f4b3 <b>Оплата через {name}</b>\n\n'
'Сумма: <b>{amount}\u20bd</b>\n\n'
'Нажмите кнопку ниже для оплаты.\n'
'После успешной оплаты баланс будет пополнен автоматически.',
).format(name=display_name, amount=f'{amount_rub:.2f}')
if edit_message:
await message_or_callback.edit_text(
response_text,
reply_markup=keyboard,
parse_mode='HTML',
)
else:
await message_or_callback.answer(
response_text,
reply_markup=keyboard,
parse_mode='HTML',
)
logger.info('PayPear payment created', telegram_id=db_user.telegram_id, amount_rub=amount_rub)
@error_handler
async def process_paypear_payment_amount(
message: types.Message,
db_user: User,
db: AsyncSession,
amount_kopeks: int,
state: FSMContext,
):
"""
Process payment amount directly.
"""
texts = get_texts(db_user.language)
restriction_kb = _check_topup_restriction(db_user, texts)
if restriction_kb:
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
await message.answer(
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=restriction_kb,
)
await state.clear()
return
# Validate amount
min_amount = settings.PAYPEAR_MIN_AMOUNT_KOPEKS
max_amount = settings.PAYPEAR_MAX_AMOUNT_KOPEKS
if amount_kopeks < min_amount:
await message.answer(
texts.t(
'PAYMENT_AMOUNT_TOO_LOW',
'Минимальная сумма пополнения: {min_amount}\u20bd',
).format(min_amount=min_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
if amount_kopeks > max_amount:
await message.answer(
texts.t(
'PAYMENT_AMOUNT_TOO_HIGH',
'Максимальная сумма пополнения: {max_amount}\u20bd',
).format(max_amount=max_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
await state.clear()
await _create_paypear_payment_and_respond(
message_or_callback=message,
db_user=db_user,
db=db,
amount_kopeks=amount_kopeks,
edit_message=False,
)
@error_handler
async def start_paypear_topup(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
):
"""
Start PayPear top-up process - ask for amount.
"""
texts = get_texts(db_user.language)
restriction_kb = _check_topup_restriction(db_user, texts)
if restriction_kb:
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
await callback.message.edit_text(
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=restriction_kb,
)
return
await state.set_state(BalanceStates.waiting_for_amount)
await state.update_data(payment_method='paypear')
min_amount = settings.PAYPEAR_MIN_AMOUNT_KOPEKS // 100
max_amount = settings.PAYPEAR_MAX_AMOUNT_KOPEKS // 100
display_name = settings.get_paypear_display_name()
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
callback_data='menu_balance',
)
]
]
)
await callback.message.edit_text(
texts.t(
'PAYPEAR_ENTER_AMOUNT',
'\U0001f4b3 <b>Пополнение через {name}</b>\n\n'
'Введите сумму пополнения в рублях.\n\n'
'Минимум: {min_amount}\u20bd\n'
'Максимум: {max_amount}\u20bd',
).format(
name=display_name,
min_amount=min_amount,
max_amount=f'{max_amount:,}'.replace(',', ' '),
),
parse_mode='HTML',
reply_markup=keyboard,
)
+5 -2
View File
@@ -42,6 +42,7 @@ async def _prompt_amount(
# Если сумма уже известна (например, после быстрого выбора),
# сразу создаём платеж и сбрасываем временное значение.
await state.update_data(platega_pending_amount=None)
await state.set_state(BalanceStates.waiting_for_amount)
from app.database.database import AsyncSessionLocal
@@ -294,8 +295,9 @@ async def process_platega_payment_amount(
'PLATEGA_AMOUNT_TOO_LOW',
'Минимальная сумма для оплаты через Platega: {amount}',
).format(amount=settings.format_price(settings.PLATEGA_MIN_AMOUNT_KOPEKS)),
reply_markup=get_back_keyboard(db_user.language),
reply_markup=get_back_keyboard(db_user.language, callback_data='balance_topup'),
)
await state.set_state(BalanceStates.waiting_for_amount)
return
if amount_kopeks > settings.PLATEGA_MAX_AMOUNT_KOPEKS:
@@ -304,8 +306,9 @@ async def process_platega_payment_amount(
'PLATEGA_AMOUNT_TOO_HIGH',
'Максимальная сумма для оплаты через Platega: {amount}',
).format(amount=settings.format_price(settings.PLATEGA_MAX_AMOUNT_KOPEKS)),
reply_markup=get_back_keyboard(db_user.language),
reply_markup=get_back_keyboard(db_user.language, callback_data='balance_topup'),
)
await state.set_state(BalanceStates.waiting_for_amount)
return
try:
+247
View File
@@ -0,0 +1,247 @@
"""Handler for RollyPay balance top-up."""
import html
import structlog
from aiogram import types
from aiogram.fsm.context import FSMContext
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import User
from app.keyboards.inline import get_back_keyboard
from app.localization.texts import get_texts
from app.services.payment_service import PaymentService
from app.states import BalanceStates
from app.utils.decorators import error_handler
logger = structlog.get_logger(__name__)
def _check_topup_restriction(db_user: User, texts) -> InlineKeyboardMarkup | None:
"""Проверяет ограничение на пополнение. Возвращает клавиатуру если ограничен, иначе None."""
if not getattr(db_user, 'restriction_topup', False):
return None
keyboard = []
support_url = settings.get_support_contact_url()
if support_url:
keyboard.append([InlineKeyboardButton(text='\U0001f198 Обжаловать', url=support_url)])
keyboard.append([InlineKeyboardButton(text=texts.BACK, callback_data='menu_balance')])
return InlineKeyboardMarkup(inline_keyboard=keyboard)
async def _create_rollypay_payment_and_respond(
message_or_callback,
db_user: User,
db: AsyncSession,
amount_kopeks: int,
edit_message: bool = False,
):
"""
Common logic for creating RollyPay payment and sending response.
"""
texts = get_texts(db_user.language)
amount_rub = amount_kopeks / 100
# Create payment
payment_service = PaymentService()
description = settings.PAYMENT_BALANCE_TEMPLATE.format(
service_name=settings.PAYMENT_SERVICE_NAME,
description='Пополнение баланса',
)
result = await payment_service.create_rollypay_payment(
db=db,
user_id=db_user.id,
amount_kopeks=amount_kopeks,
description=description,
email=getattr(db_user, 'email', None),
language=db_user.language,
)
if not result:
error_text = texts.t(
'PAYMENT_CREATE_ERROR',
'Не удалось создать платёж. Попробуйте позже.',
)
if edit_message:
await message_or_callback.edit_text(
error_text,
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
else:
await message_or_callback.answer(
error_text,
parse_mode='HTML',
)
return
payment_url = result.get('payment_url')
display_name = settings.get_rollypay_display_name()
# Create keyboard with payment button
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=texts.t(
'PAY_BUTTON',
'\U0001f4b3 Оплатить {amount}\u20bd',
).format(amount=f'{amount_rub:.0f}'),
url=payment_url,
)
],
[
InlineKeyboardButton(
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
callback_data='menu_balance',
)
],
]
)
response_text = texts.t(
'ROLLYPAY_PAYMENT_CREATED',
'\U0001f4b3 <b>Оплата через {name}</b>\n\n'
'Сумма: <b>{amount}\u20bd</b>\n\n'
'Нажмите кнопку ниже для оплаты.\n'
'После успешной оплаты баланс будет пополнен автоматически.',
).format(name=display_name, amount=f'{amount_rub:.2f}')
if edit_message:
await message_or_callback.edit_text(
response_text,
reply_markup=keyboard,
parse_mode='HTML',
)
else:
await message_or_callback.answer(
response_text,
reply_markup=keyboard,
parse_mode='HTML',
)
logger.info('RollyPay payment created', telegram_id=db_user.telegram_id, amount_rub=amount_rub)
@error_handler
async def process_rollypay_payment_amount(
message: types.Message,
db_user: User,
db: AsyncSession,
amount_kopeks: int,
state: FSMContext,
):
"""
Process payment amount directly.
"""
texts = get_texts(db_user.language)
restriction_kb = _check_topup_restriction(db_user, texts)
if restriction_kb:
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
await message.answer(
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=restriction_kb,
)
await state.clear()
return
# Validate amount
min_amount = settings.ROLLYPAY_MIN_AMOUNT_KOPEKS
max_amount = settings.ROLLYPAY_MAX_AMOUNT_KOPEKS
if amount_kopeks < min_amount:
await message.answer(
texts.t(
'PAYMENT_AMOUNT_TOO_LOW',
'Минимальная сумма пополнения: {min_amount}\u20bd',
).format(min_amount=min_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
if amount_kopeks > max_amount:
await message.answer(
texts.t(
'PAYMENT_AMOUNT_TOO_HIGH',
'Максимальная сумма пополнения: {max_amount}\u20bd',
).format(max_amount=max_amount // 100),
reply_markup=get_back_keyboard(db_user.language),
parse_mode='HTML',
)
return
await state.clear()
await _create_rollypay_payment_and_respond(
message_or_callback=message,
db_user=db_user,
db=db,
amount_kopeks=amount_kopeks,
edit_message=False,
)
@error_handler
async def start_rollypay_topup(
callback: types.CallbackQuery,
db_user: User,
db: AsyncSession,
state: FSMContext,
):
"""
Start RollyPay top-up process - ask for amount.
"""
texts = get_texts(db_user.language)
restriction_kb = _check_topup_restriction(db_user, texts)
if restriction_kb:
reason = html.escape(getattr(db_user, 'restriction_reason', None) or 'Действие ограничено администратором')
await callback.message.edit_text(
f'\U0001f6ab <b>Пополнение ограничено</b>\n\n{reason}',
parse_mode='HTML',
reply_markup=restriction_kb,
)
return
await state.set_state(BalanceStates.waiting_for_amount)
await state.update_data(payment_method='rollypay')
min_amount = settings.ROLLYPAY_MIN_AMOUNT_KOPEKS // 100
max_amount = settings.ROLLYPAY_MAX_AMOUNT_KOPEKS // 100
display_name = settings.get_rollypay_display_name()
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=texts.t('BACK_BUTTON', '\u25c0\ufe0f Назад'),
callback_data='menu_balance',
)
]
]
)
await callback.message.edit_text(
texts.t(
'ROLLYPAY_ENTER_AMOUNT',
'\U0001f4b3 <b>Пополнение через {name}</b>\n\n'
'Введите сумму пополнения в рублях.\n\n'
'Минимум: {min_amount}\u20bd\n'
'Максимум: {max_amount}\u20bd',
).format(
name=display_name,
min_amount=min_amount,
max_amount=f'{max_amount:,}'.replace(',', ' '),
),
parse_mode='HTML',
reply_markup=keyboard,
)
+13 -2
View File
@@ -118,12 +118,23 @@ def register_handlers(dp: Dispatcher):
dp.callback_query.register(handle_cancel, F.data.in_(['cancel', 'subscription_cancel']))
# Самый последний: ловим любые неизвестные текстовые сообщения
# Исключаем специальные сервисные события (например, успешные платежи),
# чтобы их обработка не прерывалась общим хендлером неизвестных сообщений
# Исключаем специальные сервисные события (например, успешные платежи)
# и сообщения от самого бота (например, фото главного меню)
dp.message.register(
handle_unknown_message,
StateFilter(None),
F.from_user.is_bot.is_(False),
F.successful_payment.is_(None),
F.text.is_not(None),
~F.text.startswith('/'),
)
# Ловим медиа-сообщения (фото, видео, документы, стикеры и т.д.)
# без активного состояния — чтобы пользователь знал, что бот не принял медиа
dp.message.register(
handle_unknown_message,
StateFilter(None),
F.from_user.is_bot.is_(False),
F.successful_payment.is_(None),
F.text.is_(None),
)
+6 -2
View File
@@ -169,7 +169,9 @@ async def show_main_menu(
await db.commit()
# Multi-tariff aware: check if user has ANY active subscription
has_active_subscription = any(sub.is_active for sub in (getattr(db_user, 'subscriptions', None) or []))
# 'limited' (traffic exhausted) subscriptions are still active for UI purposes
_subs = getattr(db_user, 'subscriptions', None) or []
has_active_subscription = any(sub.is_active or getattr(sub, 'actual_status', None) == 'limited' for sub in _subs)
subscription_is_active = has_active_subscription
menu_text = await get_main_menu_text(db_user, texts, db)
@@ -1013,7 +1015,9 @@ async def handle_back_to_menu(callback: types.CallbackQuery, state: FSMContext,
texts = get_texts(db_user.language)
# Multi-tariff aware: check if user has ANY active subscription
has_active_subscription = any(sub.is_active for sub in (getattr(db_user, 'subscriptions', None) or []))
# 'limited' (traffic exhausted) subscriptions are still active for UI purposes
_subs = getattr(db_user, 'subscriptions', None) or []
has_active_subscription = any(sub.is_active or getattr(sub, 'actual_status', None) == 'limited' for sub in _subs)
subscription_is_active = has_active_subscription
menu_text = await get_main_menu_text(db_user, texts, db)
+3 -4
View File
@@ -120,8 +120,7 @@ async def show_referral_info(callback: types.CallbackQuery, db_user: User, db: A
# Show bot link
referral_text += (
texts.t('REFERRAL_BOT_LINK_TITLE', '🤖 <b>Ссылка на бота:</b>')
+ f'\n<code>{html_escape(bot_referral_link)}</code>\n'
texts.t('REFERRAL_BOT_LINK_TITLE', '🤖 <b>Ссылка на бота:</b>') + f'\n{html_escape(bot_referral_link)}\n'
)
# Show cabinet link if configured
@@ -129,7 +128,7 @@ async def show_referral_info(callback: types.CallbackQuery, db_user: User, db: A
referral_text += (
'\n'
+ texts.t('REFERRAL_CABINET_LINK_TITLE', '🌐 <b>Ссылка на кабинет:</b>')
+ f'\n<code>{html_escape(cabinet_referral_link)}</code>\n'
+ f'\n{html_escape(cabinet_referral_link)}\n'
)
referral_text += (
@@ -551,7 +550,7 @@ async def create_invite_message(callback: types.CallbackQuery, db_user: User):
'Нажмите на текст ниже, чтобы скопировать:',
)
+ '\n\n'
f'<blockquote><code>{html_escape(invite_text)}</code></blockquote>'
f'<blockquote>{html_escape(invite_text)}</blockquote>'
),
keyboard,
)
+11 -4
View File
@@ -344,8 +344,9 @@ def _calculate_subscription_flags(subscription):
return False, False
actual_status = getattr(subscription, 'actual_status', None)
has_active_subscription = actual_status in {'active', 'trial'}
subscription_is_active = bool(getattr(subscription, 'is_active', False))
# 'limited' subscriptions are still active (traffic exhausted, but subscription not expired)
has_active_subscription = actual_status in {'active', 'trial', 'limited'}
subscription_is_active = bool(getattr(subscription, 'is_active', False)) or actual_status == 'limited'
return has_active_subscription, subscription_is_active
@@ -1147,14 +1148,18 @@ async def _show_privacy_policy_after_rules(
logger.info('🔒 Используется политика конфиденциальности из БД для языка', language=language)
try:
await callback.message.edit_text(privacy_policy_text, reply_markup=get_privacy_policy_keyboard(language))
await callback.message.edit_text(
privacy_policy_text, reply_markup=get_privacy_policy_keyboard(language), parse_mode='HTML'
)
await state.set_state(RegistrationStates.waiting_for_privacy_policy_accept)
logger.info('🔒 Политика конфиденциальности отправлена пользователю', from_user_id=callback.from_user.id)
return True
except Exception as e:
logger.error('Ошибка при показе политики конфиденциальности', error=e, exc_info=True)
try:
await callback.message.answer(privacy_policy_text, reply_markup=get_privacy_policy_keyboard(language))
await callback.message.answer(
privacy_policy_text, reply_markup=get_privacy_policy_keyboard(language), parse_mode='HTML'
)
await state.set_state(RegistrationStates.waiting_for_privacy_policy_accept)
logger.info(
'🔒 Политика конфиденциальности отправлена новым сообщением пользователю',
@@ -1724,6 +1729,7 @@ async def complete_registration_from_callback(callback: types.CallbackQuery, sta
await callback.message.answer(
offer_text,
reply_markup=get_post_registration_keyboard(user.language),
parse_mode='HTML',
)
logger.info('✅ Приветственное сообщение отправлено пользователю', telegram_id=user.telegram_id)
if pinned_message and not pinned_message.send_before_menu:
@@ -2078,6 +2084,7 @@ async def complete_registration(message: types.Message, state: FSMContext, db: A
await message.answer(
offer_text,
reply_markup=keyboard,
parse_mode='HTML',
)
logger.info('✅ Приветственное сообщение отправлено пользователю', telegram_id=user.telegram_id)
if pinned_message and not pinned_message.send_before_menu:
+12
View File
@@ -101,6 +101,18 @@ async def toggle_autopay(callback: types.CallbackQuery, db_user: User, db: Async
enable = callback.data.startswith('autopay_enable')
if enable:
# Trial subscriptions cannot use autopay
if subscription.is_trial or subscription.is_trial is None:
texts = get_texts(db_user.language)
await callback.answer(
texts.t(
'AUTOPAY_NOT_AVAILABLE_TRIAL',
'Автоплатеж недоступен для пробных подписок.',
),
show_alert=True,
)
return
# Classic subscriptions cannot use autopay when tariff mode is enabled
if settings.is_tariffs_mode() and not subscription.tariff_id:
texts = get_texts(db_user.language)
+2 -1
View File
@@ -1,6 +1,7 @@
import asyncio
import base64
import html as html_mod
import math
import re
import time
from datetime import UTC, datetime
@@ -545,7 +546,7 @@ def get_traffic_switch_keyboard(
# Считаем по дням (как в кабинете и подтверждении)
if subscription_end_date:
now = datetime.now(UTC)
days_left = max(1, (subscription_end_date - now).days)
days_left = max(1, math.ceil((subscription_end_date - now).total_seconds() / 86400))
price_multiplier = days_left / 30
period_text = f' (за {days_left} дн.)' if days_left > 1 else ' (за 1 день)'
else:
+2 -1
View File
@@ -1,4 +1,5 @@
import html
import math
from datetime import UTC, datetime
from aiogram import types
@@ -266,7 +267,7 @@ async def apply_countries_changes(callback: types.CallbackQuery, db_user: User,
logger.info('🔧 Добавлено: Удалено', added=added, removed=removed)
now = datetime.now(UTC)
days_to_pay = max(1, (subscription.end_date - now).days)
days_to_pay = max(1, math.ceil((subscription.end_date - now).total_seconds() / 86400))
period_hint_days = days_to_pay if days_to_pay > 0 else None
+43 -13
View File
@@ -1,4 +1,5 @@
import html as html_mod
import math
from datetime import UTC, datetime
from aiogram import types
@@ -325,9 +326,14 @@ async def confirm_change_devices(
if devices_difference > 0:
additional_devices = devices_difference
# Для тарифов - все устройства платные (нет бесплатного лимита)
# Устройства в пределах тарифного лимита — бесплатные
if tariff:
chargeable_devices = additional_devices
tariff_included = tariff.device_limit or 0
if current_devices < tariff_included:
free_devices = tariff_included - current_devices
chargeable_devices = max(0, additional_devices - free_devices)
else:
chargeable_devices = additional_devices
elif current_devices < settings.DEFAULT_DEVICE_LIMIT:
free_devices = settings.DEFAULT_DEVICE_LIMIT - current_devices
chargeable_devices = max(0, additional_devices - free_devices)
@@ -338,7 +344,7 @@ async def confirm_change_devices(
# Считаем стоимость по оставшимся дням подписки
now = datetime.now(UTC)
days_left = max(1, (subscription.end_date - now).days)
days_left = max(1, math.ceil((subscription.end_date - now).total_seconds() / 86400))
period_hint_days = days_left
devices_discount_percent = PricingEngine.get_addon_discount_percent(
@@ -352,7 +358,8 @@ async def confirm_change_devices(
)
# Цена = месячная_цена * days_left / 30
price = int(discounted_per_month * days_left / 30)
price = max(100, price) # Минимум 1 рубль
if chargeable_devices > 0:
price = max(100, price) # Минимум 1 рубль (только для платных устройств)
total_discount = int(discount_per_month * days_left / 30)
period_label = f'{days_left} дн.' if days_left > 1 else '1 день'
@@ -553,7 +560,12 @@ async def execute_change_devices(
devices_difference = new_devices_count - current_devices
if devices_difference > 0:
if tariff:
chargeable_devices = devices_difference
tariff_included = tariff.device_limit or 0
if current_devices < tariff_included:
free_devices = tariff_included - current_devices
chargeable_devices = max(0, devices_difference - free_devices)
else:
chargeable_devices = devices_difference
elif current_devices < settings.DEFAULT_DEVICE_LIMIT:
free_devices = settings.DEFAULT_DEVICE_LIMIT - current_devices
chargeable_devices = max(0, devices_difference - free_devices)
@@ -561,7 +573,7 @@ async def execute_change_devices(
chargeable_devices = devices_difference
devices_price_per_month = chargeable_devices * price_per_device
days_left = max(1, (subscription.end_date - datetime.now(UTC)).days)
days_left = max(1, math.ceil((subscription.end_date - datetime.now(UTC)).total_seconds() / 86400))
devices_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'devices',
@@ -572,7 +584,8 @@ async def execute_change_devices(
devices_discount_percent,
)
price = int(discounted_per_month * days_left / 30)
price = max(100, price)
if chargeable_devices > 0:
price = max(100, price)
else:
price = 0
@@ -589,7 +602,7 @@ async def execute_change_devices(
)
return
charged_days = max(1, (subscription.end_date - datetime.now(UTC)).days)
charged_days = max(1, math.ceil((subscription.end_date - datetime.now(UTC)).total_seconds() / 86400))
await create_transaction(
db=db,
user_id=db_user.id,
@@ -1215,7 +1228,22 @@ async def confirm_add_devices(callback: types.CallbackQuery, db_user: User, db:
)
return
devices_price_per_month = devices_count * price_per_device
# Устройства в пределах тарифного лимита — бесплатные
current_devices = subscription.device_limit or 1
if tariff:
tariff_included = tariff.device_limit or 0
if current_devices < tariff_included:
free_devices = tariff_included - current_devices
chargeable_devices = max(0, devices_count - free_devices)
else:
chargeable_devices = devices_count
elif current_devices < settings.DEFAULT_DEVICE_LIMIT:
free_devices = settings.DEFAULT_DEVICE_LIMIT - current_devices
chargeable_devices = max(0, devices_count - free_devices)
else:
chargeable_devices = devices_count
devices_price_per_month = chargeable_devices * price_per_device
# TOCTOU: lock user row before reading promo/discount state
db_user = await lock_user_for_pricing(db, db_user.id)
@@ -1226,7 +1254,7 @@ async def confirm_add_devices(callback: types.CallbackQuery, db_user: User, db:
if is_daily_tariff:
# Для суточных тарифов считаем по дням (как в кабинете)
now = datetime.now(UTC)
days_left = max(1, (subscription.end_date - now).days)
days_left = max(1, math.ceil((subscription.end_date - now).total_seconds() / 86400))
period_hint_days = days_left
devices_discount_percent = PricingEngine.get_addon_discount_percent(
@@ -1240,13 +1268,14 @@ async def confirm_add_devices(callback: types.CallbackQuery, db_user: User, db:
)
# Цена = месячная_цена * days_left / 30
price = int(discounted_per_month * days_left / 30)
price = max(100, price) # Минимум 1 рубль
if chargeable_devices > 0:
price = max(100, price) # Минимум 1 рубль (только для платных устройств)
total_discount = int(discount_per_month * days_left / 30)
period_label = f'{days_left} дн.' if days_left > 1 else '1 день'
else:
# Для обычных тарифов - по дням (как в кабинете)
now = datetime.now(UTC)
days_left = max(1, (subscription.end_date - now).days)
days_left = max(1, math.ceil((subscription.end_date - now).total_seconds() / 86400))
period_hint_days = days_left
devices_discount_percent = PricingEngine.get_addon_discount_percent(
@@ -1260,7 +1289,8 @@ async def confirm_add_devices(callback: types.CallbackQuery, db_user: User, db:
)
# Цена = месячная_цена * days_left / 30
price = int(discounted_per_month * days_left / 30)
price = max(100, price) # Минимум 1 рубль
if chargeable_devices > 0:
price = max(100, price) # Минимум 1 рубль (только для платных устройств)
total_discount = int(discount_per_month * days_left / 30)
period_label = f'{days_left} дн.' if days_left > 1 else '1 день'
+45 -27
View File
@@ -922,9 +922,11 @@ async def activate_trial(callback: types.CallbackQuery, db_user: User, db: Async
trial_tariff = await get_tariff_by_id(db, trial_tariff_id)
if trial_tariff:
from app.database.crud.server_squad import get_effective_tariff_squad_uuids
trial_traffic_limit = trial_tariff.traffic_limit_gb
trial_device_limit = trial_tariff.device_limit
trial_squads = trial_tariff.allowed_squads or []
trial_squads = await get_effective_tariff_squad_uuids(db, trial_tariff.allowed_squads)
tariff_id_for_trial = trial_tariff.id
tariff_trial_days = getattr(trial_tariff, 'trial_duration_days', None)
if tariff_trial_days:
@@ -937,7 +939,7 @@ async def activate_trial(callback: types.CallbackQuery, db_user: User, db: Async
except Exception as e:
logger.error('Ошибка получения триального тарифа', error=e)
# BUG-12 fix: If no squads from tariff, fallback to trial-eligible servers
# No trial tariff configured, use the legacy random trial squad fallback.
if not trial_squads:
from app.database.crud.server_squad import get_random_trial_squad_uuid
@@ -1579,11 +1581,15 @@ async def return_to_saved_cart(callback: types.CallbackQuery, state: FSMContext,
if settings.is_traffic_fixed():
traffic_value = prepared_cart_data.get('traffic_gb')
if traffic_value is None:
traffic_value = prepared_cart_data.get('traffic_limit_gb')
if traffic_value is None:
traffic_value = settings.get_fixed_traffic_limit()
traffic_display = 'Безлимитный' if traffic_value == 0 else f'{traffic_value} ГБ'
else:
traffic_value = prepared_cart_data.get('traffic_gb', 0) or 0
traffic_value = prepared_cart_data.get('traffic_gb')
if traffic_value is None:
traffic_value = prepared_cart_data.get('traffic_limit_gb', 0)
traffic_display = 'Безлимитный' if traffic_value == 0 else f'{traffic_value} ГБ'
summary_lines = [
@@ -1596,6 +1602,8 @@ async def return_to_saved_cart(callback: types.CallbackQuery, state: FSMContext,
if settings.is_devices_selection_enabled():
devices_value = prepared_cart_data.get('devices')
if devices_value is None:
devices_value = prepared_cart_data.get('device_limit')
if devices_value is not None:
summary_lines.append(f'📱 Устройства: {devices_value}')
@@ -1970,7 +1978,10 @@ async def confirm_extend_subscription(
'description': f'Продление подписки на {days} дней',
'consume_promo_offer': bool(promo_offer_discount > 0),
'device_limit': device_limit,
'devices': device_limit,
'traffic_limit_gb': renewal_traffic_gb,
'traffic_gb': renewal_traffic_gb,
'countries': list(subscription.connected_squads or []),
}
await user_cart_service.save_user_cart(db_user.id, cart_data)
@@ -2225,7 +2236,12 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
devices_selection_enabled = settings.is_devices_selection_enabled()
forced_disabled_limit: int | None = None
if devices_selection_enabled:
devices_selected = data.get('devices', settings.DEFAULT_DEVICE_LIMIT)
# Для extend-корзины ключ может быть 'device_limit' вместо 'devices'
devices_selected = data.get('devices')
if devices_selected is None:
devices_selected = data.get('device_limit')
if devices_selected is None:
devices_selected = settings.DEFAULT_DEVICE_LIMIT
else:
forced_disabled_limit = settings.get_disabled_mode_device_limit()
if forced_disabled_limit is None:
@@ -2586,17 +2602,19 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
subscription_service = SubscriptionService()
# При покупке подписки ВСЕГДА сбрасываем трафик в панели
_purchase_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else db_user.remnawave_uuid
)
if settings.is_multi_tariff_enabled() and not getattr(subscription, 'remnawave_uuid', None):
logger.warning(
'Multi-tariff: subscription missing remnawave_uuid, using user fallback',
subscription_id=getattr(subscription, 'id', None),
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(db_user, 'remnawave_uuid', None)
if _should_create:
remnawave_user = await subscription_service.create_remnawave_user(
db,
subscription,
reset_traffic=True,
reset_reason='покупка подписки',
)
if _purchase_uuid:
else:
remnawave_user = await subscription_service.update_remnawave_user(
db,
subscription,
@@ -2604,16 +2622,9 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
reset_reason='покупка подписки',
sync_squads=True,
)
else:
remnawave_user = await subscription_service.create_remnawave_user(
db,
subscription,
reset_traffic=True,
reset_reason='покупка подписки',
)
if not remnawave_user:
logger.error('Не удалось создать/обновить RemnaWave пользователя для', telegram_id=db_user.telegram_id)
logger.error('Не удалось создать/обновить RemnaWave пользователя', telegram_id=db_user.telegram_id)
try:
remnawave_user = await subscription_service.create_remnawave_user(
db,
@@ -2622,7 +2633,7 @@ async def confirm_purchase(callback: types.CallbackQuery, state: FSMContext, db_
reset_reason='покупка подписки (повторная попытка)',
)
except Exception as retry_error:
logger.error('Повторная попытка создания RemnaWave пользователя также не удалась', error=retry_error)
logger.error('Повторная попытка создания RemnaWave пользователя не удалась', error=retry_error)
from app.services.remnawave_retry_queue import remnawave_retry_queue
remnawave_retry_queue.enqueue(
@@ -3312,9 +3323,11 @@ async def handle_trial_pay_with_balance(callback: types.CallbackQuery, db_user:
if trial_tariff_id > 0:
trial_tariff = await _get_tariff(db, trial_tariff_id)
if trial_tariff:
from app.database.crud.server_squad import get_effective_tariff_squad_uuids
trial_traffic_limit = trial_tariff.traffic_limit_gb
trial_device_limit = trial_tariff.device_limit
trial_squads = trial_tariff.allowed_squads or []
trial_squads = await get_effective_tariff_squad_uuids(db, trial_tariff.allowed_squads)
tariff_id_for_trial = trial_tariff.id
tariff_trial_days = getattr(trial_tariff, 'trial_duration_days', None)
if tariff_trial_days:
@@ -3327,7 +3340,7 @@ async def handle_trial_pay_with_balance(callback: types.CallbackQuery, db_user:
except Exception as e:
logger.error('Ошибка получения триального тарифа для платного триала', error=e)
# BUG-12 fix: If no squads from tariff, fallback to trial-eligible servers
# No trial tariff configured, use the legacy random trial squad fallback.
if not trial_squads:
from app.database.crud.server_squad import get_random_trial_squad_uuid
@@ -3678,9 +3691,11 @@ async def handle_trial_payment_method(callback: types.CallbackQuery, db_user: Us
if trial_tariff_id > 0:
trial_tariff = await _get_tariff(db, trial_tariff_id)
if trial_tariff:
from app.database.crud.server_squad import get_effective_tariff_squad_uuids
trial_traffic = trial_tariff.traffic_limit_gb
trial_devices = trial_tariff.device_limit
trial_squads_list = trial_tariff.allowed_squads or []
trial_squads_list = await get_effective_tariff_squad_uuids(db, trial_tariff.allowed_squads)
tariff_id_for_trial = trial_tariff.id
tariff_trial_days = getattr(trial_tariff, 'trial_duration_days', None)
if tariff_trial_days:
@@ -3693,7 +3708,7 @@ async def handle_trial_payment_method(callback: types.CallbackQuery, db_user: Us
except Exception as e:
logger.error('Ошибка получения триального тарифа для платного триала', error=e)
# Если тариф не задал серверы, получаем случайный сквад
# Если триальный тариф не найден, используем legacy fallback со случайным сквадом.
if not trial_squads_list:
from app.database.crud.server_squad import get_random_trial_squad_uuid
@@ -4511,8 +4526,11 @@ async def _extend_existing_subscription(
'return_to_cart': True,
'description': f'Продление подписки на {period_days} дней',
'device_limit': device_limit,
'devices': device_limit,
'traffic_limit_gb': traffic_limit_gb,
'traffic_gb': traffic_limit_gb,
'squad_uuid': squad_uuid,
'countries': [squad_uuid] if squad_uuid else [],
'consume_promo_offer': consume_promo,
}
+376 -94
View File
@@ -939,6 +939,13 @@ async def handle_custom_confirm(
await callback.answer('Недостаточно средств на балансе', show_alert=True)
return
# Отвечаем на callback СРАЗУ — до тяжёлых операций (панель, транзакции),
# иначе Telegram инвалидирует query через 30 сек → TelegramBadRequest
try:
await callback.answer()
except Exception:
pass
texts = get_texts(db_user.language)
# Save promo offer state before deduction (for restore on failure)
@@ -958,11 +965,17 @@ async def handle_custom_confirm(
mark_as_paid_subscription=True,
)
if not success:
await callback.answer('Ошибка списания баланса', show_alert=True)
try:
await callback.message.edit_text('❌ Ошибка списания баланса')
except Exception:
pass
return
except Exception as e:
logger.error('Ошибка списания баланса при покупке кастомного тарифа', error=e, exc_info=True)
await callback.answer('Ошибка списания баланса', show_alert=True)
try:
await callback.message.edit_text('❌ Ошибка списания баланса')
except Exception:
pass
return
# Получаем список серверов из тарифа
@@ -1049,7 +1062,10 @@ async def handle_custom_confirm(
price_kopeks=total_price,
refund_error=refund_error,
)
await callback.answer('Произошла ошибка при оформлении подписки', show_alert=True)
try:
await callback.message.edit_text('❌ Произошла ошибка при оформлении подписки')
except Exception:
pass
return
try:
@@ -1057,20 +1073,20 @@ async def handle_custom_confirm(
# При покупке тарифа ВСЕГДА сбрасываем трафик в панели
try:
subscription_service = SubscriptionService()
_panel_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else getattr(db_user, 'remnawave_uuid', None)
)
if _panel_uuid:
await subscription_service.update_remnawave_user(
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(db_user, 'remnawave_uuid', None)
if _should_create:
await subscription_service.create_remnawave_user(
db,
subscription,
reset_traffic=True,
reset_reason='покупка тарифа',
)
else:
await subscription_service.create_remnawave_user(
await subscription_service.update_remnawave_user(
db,
subscription,
reset_traffic=True,
@@ -1148,11 +1164,12 @@ async def handle_custom_confirm(
),
parse_mode='HTML',
)
await callback.answer('Подписка оформлена!', show_alert=True)
except Exception as e:
logger.error('Ошибка при покупке тарифа с кастомными параметрами', error=e, exc_info=True)
await callback.answer('Произошла ошибка при оформлении подписки', show_alert=True)
try:
await callback.message.edit_text('❌ Произошла ошибка при оформлении подписки')
except Exception:
pass
@error_handler
@@ -1377,6 +1394,13 @@ async def confirm_tariff_purchase(
await callback.answer('Недостаточно средств на балансе', show_alert=True)
return
# Отвечаем на callback СРАЗУ — до тяжёлых операций (панель, транзакции),
# иначе Telegram инвалидирует query через 30 сек → TelegramBadRequest
try:
await callback.answer()
except Exception:
pass
texts = get_texts(db_user.language)
# Списываем баланс
@@ -1395,11 +1419,17 @@ async def confirm_tariff_purchase(
mark_as_paid_subscription=True,
)
if not success:
await callback.answer('Ошибка списания баланса', show_alert=True)
try:
await callback.message.edit_text('❌ Ошибка списания баланса')
except Exception:
pass
return
except Exception as e:
logger.error('Ошибка списания баланса при покупке тарифа', error=e, exc_info=True)
await callback.answer('Ошибка списания баланса', show_alert=True)
try:
await callback.message.edit_text('❌ Ошибка списания баланса')
except Exception:
pass
return
# Получаем список серверов из тарифа
@@ -1457,10 +1487,12 @@ async def confirm_tariff_purchase(
db_user.promo_offer_discount_source = saved_promo_source
db_user.promo_offer_discount_expires_at = saved_promo_expires
await db.commit()
await callback.answer(
f'Максимум подписок: {settings.get_max_active_subscriptions()}',
show_alert=True,
)
try:
await callback.message.edit_text(
f'❌ Максимум подписок: {settings.get_max_active_subscriptions()}'
)
except Exception:
pass
return
# Create NEW subscription for this tariff (multi-tariff: new Remnawave user)
@@ -1537,7 +1569,10 @@ async def confirm_tariff_purchase(
reason='Возврат: тариф уже активен',
error=refund_error,
)
await callback.answer('У вас уже есть активная подписка на этот тариф', show_alert=True)
try:
await callback.message.edit_text('❌ У вас уже есть активная подписка на этот тариф')
except Exception:
pass
return
except Exception as e:
logger.error('Ошибка создания/продления подписки при покупке тарифа', error=e, exc_info=True)
@@ -1581,27 +1616,33 @@ async def confirm_tariff_purchase(
reason='Возврат: ошибка покупки тарифа',
error=refund_error,
)
await callback.answer('Произошла ошибка при оформлении подписки', show_alert=True)
try:
await callback.message.edit_text('❌ Произошла ошибка при оформлении подписки')
except Exception:
pass
return
# Обновляем пользователя в Remnawave
# При покупке тарифа ВСЕГДА сбрасываем трафик в панели
try:
subscription_service = SubscriptionService()
_panel_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else getattr(db_user, 'remnawave_uuid', None)
)
if _panel_uuid:
await subscription_service.update_remnawave_user(
# In multi-tariff mode, each subscription has its own panel user.
# A new subscription has no remnawave_uuid yet, so always CREATE.
# In single-tariff mode, reuse the user-level UUID if available.
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(db_user, 'remnawave_uuid', None)
if _should_create:
await subscription_service.create_remnawave_user(
db,
subscription,
reset_traffic=True,
reset_reason='покупка тарифа',
)
else:
await subscription_service.create_remnawave_user(
await subscription_service.update_remnawave_user(
db,
subscription,
reset_traffic=True,
@@ -1683,7 +1724,6 @@ async def confirm_tariff_purchase(
),
parse_mode='HTML',
)
await callback.answer('Подписка оформлена!', show_alert=True)
# ==================== Покупка суточного тарифа ====================
@@ -1738,6 +1778,13 @@ async def confirm_daily_tariff_purchase(
await callback.answer('Недостаточно средств на балансе', show_alert=True)
return
# Отвечаем на callback СРАЗУ — до тяжёлых операций (панель, транзакции),
# иначе Telegram инвалидирует query через 30 сек → TelegramBadRequest
try:
await callback.answer()
except Exception:
pass
texts = get_texts(db_user.language)
try:
@@ -1751,11 +1798,17 @@ async def confirm_daily_tariff_purchase(
mark_as_paid_subscription=True,
)
if not success:
await callback.answer('Ошибка списания баланса', show_alert=True)
try:
await callback.message.edit_text('❌ Ошибка списания баланса')
except Exception:
pass
return
except Exception as e:
logger.error('Ошибка списания баланса при покупке суточного тарифа', error=e, exc_info=True)
await callback.answer('Ошибка списания баланса', show_alert=True)
try:
await callback.message.edit_text('❌ Ошибка списания баланса')
except Exception:
pass
return
# Получаем список серверов из тарифа
@@ -1861,27 +1914,30 @@ async def confirm_daily_tariff_purchase(
price_kopeks=final_daily_price,
refund_error=refund_error,
)
await callback.answer('Произошла ошибка при оформлении подписки', show_alert=True)
try:
await callback.message.edit_text('❌ Произошла ошибка при оформлении подписки')
except Exception:
pass
return
# Обновляем пользователя в Remnawave
# При покупке тарифа ВСЕГДА сбрасываем трафик в панели
try:
subscription_service = SubscriptionService()
_panel_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else getattr(db_user, 'remnawave_uuid', None)
)
if _panel_uuid:
await subscription_service.update_remnawave_user(
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(db_user, 'remnawave_uuid', None)
if _should_create:
await subscription_service.create_remnawave_user(
db,
subscription,
reset_traffic=True,
reset_reason='покупка суточного тарифа',
)
else:
await subscription_service.create_remnawave_user(
await subscription_service.update_remnawave_user(
db,
subscription,
reset_traffic=True,
@@ -1961,7 +2017,6 @@ async def confirm_daily_tariff_purchase(
),
parse_mode='HTML',
)
await callback.answer('Подписка оформлена!', show_alert=True)
# ==================== Продление по тарифу ====================
@@ -2102,8 +2157,36 @@ async def show_tariff_extend(
subscription = None
else:
subscription = await get_subscription_by_user_id(db, db_user.id)
if not subscription or not subscription.tariff_id:
await callback.answer('Тариф не найден', show_alert=True)
if not subscription:
await callback.answer('Подписка не найдена', show_alert=True)
return
if not subscription.tariff_id:
# Legacy user without tariff — show tariff selection for upgrade
promo_group_id = getattr(db_user, 'promo_group_id', None)
tariffs = await get_tariffs_for_user(db, promo_group_id)
if not tariffs:
await callback.answer('Нет доступных тарифов', show_alert=True)
return
keyboard = []
for t in tariffs:
if t.is_daily:
continue
keyboard.append([InlineKeyboardButton(text=f'📦 {t.name}', callback_data=f'tariff_select:{t.id}')])
if not keyboard:
await callback.answer('Нет доступных тарифов для продления', show_alert=True)
return
keyboard.append([InlineKeyboardButton(text='◀️ Назад', callback_data='back_to_menu')])
await callback.message.edit_text(
'🔄 <b>Выберите тариф для продления</b>\n\n'
'Для продления подписки необходимо выбрать тариф.\n'
'Подписка будет обновлена с параметрами выбранного тарифа.',
reply_markup=InlineKeyboardMarkup(inline_keyboard=keyboard),
parse_mode='HTML',
)
await callback.answer()
return
tariff = await get_tariff_by_id(db, subscription.tariff_id)
@@ -2111,6 +2194,31 @@ async def show_tariff_extend(
await callback.answer('Тариф не найден', show_alert=True)
return
# Скрытый/неактивный тариф (например, триальный после промокода) —
# показываем список доступных тарифов вместо продления скрытого
if not tariff.is_active:
promo_group_id = getattr(db_user, 'promo_group_id', None)
tariffs = await get_tariffs_for_user(db, promo_group_id)
active_tariffs = [t for t in tariffs if not t.is_daily]
if not active_tariffs:
await callback.answer('Нет доступных тарифов для продления', show_alert=True)
return
keyboard = []
for t in active_tariffs:
keyboard.append([InlineKeyboardButton(text=f'📦 {t.name}', callback_data=f'tariff_select:{t.id}')])
keyboard.append([InlineKeyboardButton(text='◀️ Назад', callback_data='back_to_menu')])
await callback.message.edit_text(
'🔄 <b>Выберите тариф для продления</b>\n\n'
'Для продления подписки необходимо выбрать тариф.\n'
'Подписка будет обновлена с параметрами выбранного тарифа.',
reply_markup=InlineKeyboardMarkup(inline_keyboard=keyboard),
parse_mode='HTML',
)
await callback.answer()
return
traffic = format_traffic(tariff.traffic_limit_gb)
# Проверяем есть ли у пользователя скидки по периодам
@@ -2308,6 +2416,13 @@ async def confirm_tariff_extend(
await callback.answer('Недостаточно средств на балансе', show_alert=True)
return
# Отвечаем на callback СРАЗУ — до тяжёлых операций (панель, транзакции),
# иначе Telegram инвалидирует query через 30 сек → TelegramBadRequest
try:
await callback.answer()
except Exception:
pass
texts = get_texts(db_user.language)
try:
@@ -2321,7 +2436,10 @@ async def confirm_tariff_extend(
mark_as_paid_subscription=True,
)
if not success:
await callback.answer('Ошибка списания баланса', show_alert=True)
try:
await callback.message.edit_text('❌ Ошибка списания баланса')
except Exception:
pass
return
# Запоминаем, был ли триал ДО продления
@@ -2340,20 +2458,20 @@ async def confirm_tariff_extend(
# Обновляем пользователя в Remnawave
try:
subscription_service = SubscriptionService()
_panel_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else getattr(db_user, 'remnawave_uuid', None)
)
if _panel_uuid:
await subscription_service.update_remnawave_user(
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(db_user, 'remnawave_uuid', None)
if _should_create:
await subscription_service.create_remnawave_user(
db,
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_PAYMENT or was_trial,
reset_reason='конвертация триала' if was_trial else 'продление тарифа',
)
else:
await subscription_service.create_remnawave_user(
await subscription_service.update_remnawave_user(
db,
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_PAYMENT or was_trial,
@@ -2431,11 +2549,12 @@ async def confirm_tariff_extend(
),
parse_mode='HTML',
)
await callback.answer('Подписка продлена!', show_alert=True)
except Exception as e:
logger.error('Ошибка при продлении тарифа', error=e, exc_info=True)
await callback.answer('Произошла ошибка при продлении подписки', show_alert=True)
try:
await callback.message.edit_text('❌ Произошла ошибка при продлении подписки')
except Exception:
pass
# ==================== Переключение тарифов ====================
@@ -2610,6 +2729,18 @@ async def show_tariff_switch_list(
current_tariff_id = subscription.tariff_id
# Проверяем, разрешена ли смена тарифа хотя бы в одном направлении
if not settings.TARIFF_SWITCH_UPGRADE_ENABLED and not settings.TARIFF_SWITCH_DOWNGRADE_ENABLED:
await callback.message.edit_text(
'🚫 <b>Смена тарифа недоступна</b>\n\nАдминистратор отключил возможность смены тарифа.',
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text=texts.BACK, callback_data='menu_subscription')]]
),
parse_mode='HTML',
)
await callback.answer()
return
# Получаем доступные тарифы
promo_group_id = getattr(db_user, 'promo_group_id', None)
tariffs = await get_tariffs_for_user(db, promo_group_id)
@@ -2622,6 +2753,14 @@ async def show_tariff_switch_list(
else:
available_tariffs = [t for t in tariffs if t.id != current_tariff_id]
# Фильтруем по разрешённым направлениям (upgrade/downgrade)
current_tariff = await get_tariff_by_id(db, current_tariff_id) if current_tariff_id else None
if current_tariff:
remaining_days = max(0, (subscription.end_date - datetime.now(UTC)).days) if subscription.end_date else 0
available_tariffs = _filter_tariffs_by_switch_direction(
available_tariffs, current_tariff, remaining_days, db_user
)
if not available_tariffs:
await callback.message.edit_text(
'😔 <b>Нет доступных тарифов для переключения</b>\n\nВы уже используете единственный доступный тариф.',
@@ -2683,6 +2822,24 @@ async def select_tariff_switch(
await callback.answer('Тариф недоступен', show_alert=True)
return
# Проверяем разрешение на смену в данном направлении
current_subscription_sw, _sw_sub_id_check = await _resolve_subscription(callback, db_user, db, state)
if current_subscription_sw and current_subscription_sw.tariff_id:
cur_tariff_sw = await get_tariff_by_id(db, current_subscription_sw.tariff_id)
if cur_tariff_sw:
rem_days = (
max(0, (current_subscription_sw.end_date - datetime.now(UTC)).days)
if current_subscription_sw.end_date
else 0
)
_, is_up = _calculate_instant_switch_cost(cur_tariff_sw, tariff, rem_days, db_user)
if is_up and not settings.TARIFF_SWITCH_UPGRADE_ENABLED:
await callback.answer('Повышение тарифа недоступно', show_alert=True)
return
if not is_up and not settings.TARIFF_SWITCH_DOWNGRADE_ENABLED:
await callback.answer('Понижение тарифа недоступно', show_alert=True)
return
traffic = format_traffic(tariff.traffic_limit_gb)
# Проверяем, суточный ли это тариф
@@ -2904,6 +3061,19 @@ async def confirm_tariff_switch(
await callback.answer('У вас нет активной подписки', show_alert=True)
return
# Проверяем разрешение на смену в данном направлении
if subscription.tariff_id and subscription.tariff_id != tariff_id:
cur_tariff_obj = await get_tariff_by_id(db, subscription.tariff_id)
if cur_tariff_obj:
rem_days = max(0, (subscription.end_date - datetime.now(UTC)).days) if subscription.end_date else 0
_, is_up = _calculate_instant_switch_cost(cur_tariff_obj, tariff, rem_days, db_user)
if is_up and not settings.TARIFF_SWITCH_UPGRADE_ENABLED:
await callback.answer('Повышение тарифа недоступно', show_alert=True)
return
if not is_up and not settings.TARIFF_SWITCH_DOWNGRADE_ENABLED:
await callback.answer('Понижение тарифа недоступно', show_alert=True)
return
# Calculate price via PricingEngine (handles per-category discounts + extra devices)
from app.services.pricing_engine import pricing_engine
@@ -2924,6 +3094,13 @@ async def confirm_tariff_switch(
await callback.answer('Недостаточно средств на балансе', show_alert=True)
return
# Отвечаем на callback СРАЗУ — до тяжёлых операций (панель, транзакции),
# иначе Telegram инвалидирует query через 30 сек → TelegramBadRequest
try:
await callback.answer()
except Exception:
pass
texts = get_texts(db_user.language)
try:
@@ -2937,7 +3114,10 @@ async def confirm_tariff_switch(
mark_as_paid_subscription=True,
)
if not success:
await callback.answer('Ошибка списания баланса', show_alert=True)
try:
await callback.message.edit_text('❌ Ошибка списания баланса')
except Exception:
pass
return
# Получаем список серверов из тарифа
@@ -2973,20 +3153,20 @@ async def confirm_tariff_switch(
# Обновляем пользователя в Remnawave
try:
subscription_service = SubscriptionService()
_panel_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else getattr(db_user, 'remnawave_uuid', None)
)
if _panel_uuid:
await subscription_service.update_remnawave_user(
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(db_user, 'remnawave_uuid', None)
if _should_create:
await subscription_service.create_remnawave_user(
db,
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
reset_reason='переключение тарифа',
)
else:
await subscription_service.create_remnawave_user(
await subscription_service.update_remnawave_user(
db,
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
@@ -3091,11 +3271,13 @@ async def confirm_tariff_switch(
),
parse_mode='HTML',
)
await callback.answer('Тариф изменён!', show_alert=True)
except Exception as e:
logger.error('Ошибка при переключении тарифа', error=e, exc_info=True)
await callback.answer('Произошла ошибка при переключении тарифа', show_alert=True)
try:
await callback.message.edit_text('❌ Произошла ошибка при переключении тарифа')
except Exception:
pass
# ==================== Смена на суточный тариф ====================
@@ -3156,6 +3338,26 @@ async def confirm_daily_tariff_switch(
await callback.answer('У вас нет активной подписки', show_alert=True)
return
# Проверяем разрешение на смену в данном направлении
if subscription.tariff_id and subscription.tariff_id != tariff_id:
cur_tariff_daily = await get_tariff_by_id(db, subscription.tariff_id)
if cur_tariff_daily:
rem_days = max(0, (subscription.end_date - datetime.now(UTC)).days) if subscription.end_date else 0
_, is_up = _calculate_instant_switch_cost(cur_tariff_daily, tariff, rem_days, db_user)
if is_up and not settings.TARIFF_SWITCH_UPGRADE_ENABLED:
await callback.answer('Повышение тарифа недоступно', show_alert=True)
return
if not is_up and not settings.TARIFF_SWITCH_DOWNGRADE_ENABLED:
await callback.answer('Понижение тарифа недоступно', show_alert=True)
return
# Отвечаем на callback СРАЗУ — до тяжёлых операций (панель, транзакции),
# иначе Telegram инвалидирует query через 30 сек → TelegramBadRequest
try:
await callback.answer()
except Exception:
pass
texts = get_texts(db_user.language)
try:
@@ -3169,7 +3371,10 @@ async def confirm_daily_tariff_switch(
mark_as_paid_subscription=True,
)
if not success:
await callback.answer('Ошибка списания баланса', show_alert=True)
try:
await callback.message.edit_text('❌ Ошибка списания баланса')
except Exception:
pass
return
# Получаем список серверов из тарифа
@@ -3221,20 +3426,20 @@ async def confirm_daily_tariff_switch(
# Обновляем пользователя в Remnawave (сброс трафика по админ-настройке)
try:
subscription_service = SubscriptionService()
_panel_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else getattr(db_user, 'remnawave_uuid', None)
)
if _panel_uuid:
await subscription_service.update_remnawave_user(
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(db_user, 'remnawave_uuid', None)
if _should_create:
await subscription_service.create_remnawave_user(
db,
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
reset_reason='смена на суточный тариф',
)
else:
await subscription_service.create_remnawave_user(
await subscription_service.update_remnawave_user(
db,
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
@@ -3325,7 +3530,6 @@ async def confirm_daily_tariff_switch(
),
parse_mode='HTML',
)
await callback.answer('Тариф изменён!', show_alert=True)
except Exception as e:
logger.error('Ошибка при смене на суточный тариф', error=e, exc_info=True)
@@ -3358,7 +3562,10 @@ async def confirm_daily_tariff_switch(
price_kopeks=final_daily_price,
refund_error=refund_error,
)
await callback.answer('Произошла ошибка при смене тарифа', show_alert=True)
try:
await callback.message.edit_text('❌ Произошла ошибка при смене тарифа')
except Exception:
pass
# ==================== Мгновенное переключение тарифов (без выбора периода) ====================
@@ -3387,6 +3594,30 @@ def _calculate_instant_switch_cost(
return result.upgrade_cost, result.is_upgrade
def _filter_tariffs_by_switch_direction(
tariffs: list[Tariff],
current_tariff: Tariff,
remaining_days: int,
db_user: User | None = None,
) -> list[Tariff]:
"""Фильтрует тарифы по разрешённым направлениям смены (upgrade/downgrade)."""
upgrade_ok = settings.TARIFF_SWITCH_UPGRADE_ENABLED
downgrade_ok = settings.TARIFF_SWITCH_DOWNGRADE_ENABLED
if upgrade_ok and downgrade_ok:
return tariffs
filtered = []
for tariff in tariffs:
if tariff.id == current_tariff.id:
filtered.append(tariff)
continue
_, is_upgrade = _calculate_instant_switch_cost(current_tariff, tariff, remaining_days, db_user)
if (is_upgrade and upgrade_ok) or (not is_upgrade and downgrade_ok):
filtered.append(tariff)
return filtered
def format_instant_switch_list_text(
tariffs: list[Tariff],
current_tariff: Tariff,
@@ -3394,16 +3625,21 @@ def format_instant_switch_list_text(
db_user: User | None = None,
) -> str:
"""Форматирует текст со списком тарифов для мгновенного переключения."""
upgrade_ok = settings.TARIFF_SWITCH_UPGRADE_ENABLED
downgrade_ok = settings.TARIFF_SWITCH_DOWNGRADE_ENABLED
lines = [
'📦 <b>Мгновенная смена тарифа</b>',
f'📌 Текущий: <b>{html.escape(current_tariff.name)}</b>',
f'⏰ Осталось: <b>{remaining_days} дн.</b>',
'',
'💡 При переключении остаток дней сохраняется.',
'⬆️ Повышение тарифа = доплата за разницу',
'⬇️ Понижение = бесплатно',
'',
]
if upgrade_ok:
lines.append('⬆️ Повышение тарифа = доплата за разницу')
if downgrade_ok:
lines.append('⬇️ Понижение = бесплатно')
lines.append('')
for tariff in tariffs:
if tariff.id == current_tariff.id:
@@ -3535,6 +3771,18 @@ async def show_instant_switch_list(
await callback.answer()
return
# Проверяем, разрешена ли смена тарифа хотя бы в одном направлении
if not settings.TARIFF_SWITCH_UPGRADE_ENABLED and not settings.TARIFF_SWITCH_DOWNGRADE_ENABLED:
await callback.message.edit_text(
'🚫 <b>Смена тарифа недоступна</b>\n\nАдминистратор отключил возможность смены тарифа.',
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text=texts.BACK, callback_data='menu_subscription')]]
),
parse_mode='HTML',
)
await callback.answer()
return
# Получаем доступные тарифы
promo_group_id = getattr(db_user, 'promo_group_id', None)
tariffs = await get_tariffs_for_user(db, promo_group_id)
@@ -3547,6 +3795,9 @@ async def show_instant_switch_list(
else:
available_tariffs = [t for t in tariffs if t.id != current_tariff.id]
# Фильтруем по разрешённым направлениям (upgrade/downgrade)
available_tariffs = _filter_tariffs_by_switch_direction(available_tariffs, current_tariff, remaining_days, db_user)
if not available_tariffs:
await callback.message.edit_text(
'😔 <b>Нет доступных тарифов для переключения</b>\n\nВы уже используете единственный доступный тариф.',
@@ -3616,6 +3867,14 @@ async def preview_instant_switch(
# Рассчитываем стоимость переключения
upgrade_cost, is_upgrade = _calculate_instant_switch_cost(current_tariff, new_tariff, remaining_days, db_user)
# Проверяем разрешение на смену в данном направлении
if is_upgrade and not settings.TARIFF_SWITCH_UPGRADE_ENABLED:
await callback.answer('Повышение тарифа недоступно', show_alert=True)
return
if not is_upgrade and not settings.TARIFF_SWITCH_DOWNGRADE_ENABLED:
await callback.answer('Понижение тарифа недоступно', show_alert=True)
return
# Проверяем баланс
user_balance = db_user.balance_kopeks or 0
@@ -3790,12 +4049,27 @@ async def confirm_instant_switch(
is_upgrade = switch_result.is_upgrade
consume_promo = switch_result.offer_discount_pct > 0
# Проверяем разрешение на смену в данном направлении
if is_upgrade and not settings.TARIFF_SWITCH_UPGRADE_ENABLED:
await callback.answer('Повышение тарифа недоступно', show_alert=True)
return
if not is_upgrade and not settings.TARIFF_SWITCH_DOWNGRADE_ENABLED:
await callback.answer('Понижение тарифа недоступно', show_alert=True)
return
# Проверяем баланс если это upgrade (use locked user's fresh balance)
user_balance = db_user.balance_kopeks or 0
if is_upgrade and user_balance < upgrade_cost:
await callback.answer('Недостаточно средств на балансе', show_alert=True)
return
# Отвечаем на callback СРАЗУ — до тяжёлых операций (панель, транзакции),
# иначе Telegram инвалидирует query через 30 сек → TelegramBadRequest
try:
await callback.answer()
except Exception:
pass
texts = get_texts(db_user.language)
try:
@@ -3811,7 +4085,10 @@ async def confirm_instant_switch(
mark_as_paid_subscription=True,
)
if not success:
await callback.answer('Ошибка списания баланса', show_alert=True)
try:
await callback.message.edit_text('❌ Ошибка списания баланса')
except Exception:
pass
return
# Получаем список серверов из нового тарифа
@@ -3878,7 +4155,10 @@ async def confirm_instant_switch(
mark_as_paid_subscription=True,
)
if not success:
await callback.answer('❌ Недостаточно средств', show_alert=True)
try:
await callback.message.edit_text('❌ Недостаточно средств')
except Exception:
pass
return
await create_transaction(
db,
@@ -3915,20 +4195,20 @@ async def confirm_instant_switch(
# Обновляем пользователя в Remnawave (сброс трафика по админ-настройке)
try:
subscription_service = SubscriptionService()
_panel_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else getattr(db_user, 'remnawave_uuid', None)
)
if _panel_uuid:
await subscription_service.update_remnawave_user(
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(db_user, 'remnawave_uuid', None)
if _should_create:
await subscription_service.create_remnawave_user(
db,
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
reset_reason='мгновенное переключение тарифа',
)
else:
await subscription_service.create_remnawave_user(
await subscription_service.update_remnawave_user(
db,
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_TARIFF_SWITCH,
@@ -4052,11 +4332,13 @@ async def confirm_instant_switch(
),
parse_mode='HTML',
)
await callback.answer('Тариф изменён!', show_alert=True)
except Exception as e:
logger.error('Ошибка при мгновенном переключении тарифа', error=e, exc_info=True)
await callback.answer('Произошла ошибка при переключении тарифа', show_alert=True)
try:
await callback.message.edit_text('❌ Произошла ошибка при переключении тарифа')
except Exception:
pass
async def return_to_saved_tariff_cart(
+4 -3
View File
@@ -1,3 +1,4 @@
import math
from datetime import UTC, datetime
from aiogram import types
@@ -807,7 +808,7 @@ async def confirm_switch_traffic(
new_price_per_month = settings.get_traffic_price(new_traffic_gb)
now = datetime.now(UTC)
days_remaining = max(1, (subscription.end_date - now).days)
days_remaining = max(1, math.ceil((subscription.end_date - now).total_seconds() / 86400))
period_hint_days = days_remaining if days_remaining > 0 else None
traffic_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
@@ -911,7 +912,7 @@ async def execute_switch_traffic(
base_traffic = current_traffic - purchased_traffic
old_price_per_month = settings.get_traffic_price(base_traffic)
new_price_per_month = settings.get_traffic_price(new_traffic_gb)
days_remaining = max(1, (subscription.end_date - datetime.now(UTC)).days)
days_remaining = max(1, math.ceil((subscription.end_date - datetime.now(UTC)).total_seconds() / 86400))
traffic_discount_percent = PricingEngine.get_addon_discount_percent(
db_user,
'traffic',
@@ -936,7 +937,7 @@ async def execute_switch_traffic(
await callback.answer('⚠️ Ошибка списания средств', show_alert=True)
return
days_remaining = max(1, (subscription.end_date - datetime.now(UTC)).days)
days_remaining = max(1, math.ceil((subscription.end_date - datetime.now(UTC)).total_seconds() / 86400))
await create_transaction(
db=db,
user_id=db_user.id,
+54 -5
View File
@@ -1,3 +1,4 @@
import math
from datetime import UTC, datetime
import structlog
@@ -1807,6 +1808,54 @@ def get_payment_methods_keyboard(amount_kopeks: int, language: str = DEFAULT_LAN
)
has_direct_payment_methods = True
if settings.is_paypear_enabled():
paypear_name = settings.get_paypear_display_name()
keyboard.append(
[
InlineKeyboardButton(
text=texts.t('PAYMENT_PAYPEAR', f'💳 Оплата ({paypear_name})'),
callback_data=_build_callback('paypear'),
)
]
)
has_direct_payment_methods = True
if settings.is_rollypay_enabled():
rollypay_name = settings.get_rollypay_display_name()
keyboard.append(
[
InlineKeyboardButton(
text=texts.t('PAYMENT_ROLLYPAY', f'💳 {rollypay_name}'),
callback_data=_build_callback('rollypay'),
)
]
)
has_direct_payment_methods = True
if settings.is_overpay_enabled():
overpay_name = settings.get_overpay_display_name()
keyboard.append(
[
InlineKeyboardButton(
text=texts.t('PAYMENT_OVERPAY', f'💳 {overpay_name}'),
callback_data=_build_callback('overpay'),
)
]
)
has_direct_payment_methods = True
if settings.is_aurapay_enabled():
aurapay_name = settings.get_aurapay_display_name()
keyboard.append(
[
InlineKeyboardButton(
text=texts.t('PAYMENT_AURAPAY', f'💳 {aurapay_name}'),
callback_data=_build_callback('aurapay'),
)
]
)
has_direct_payment_methods = True
if settings.is_support_topup_enabled():
keyboard.append(
[
@@ -2121,7 +2170,7 @@ def get_add_traffic_keyboard(
# Считаем по дням (как в кабинете и подтверждении)
if subscription_end_date:
now = datetime.now(UTC)
days_left = max(1, (subscription_end_date - now).days)
days_left = max(1, math.ceil((subscription_end_date - now).total_seconds() / 86400))
price_multiplier = days_left / 30
period_text = f' (за {days_left} дн.)' if days_left > 1 else ' (за 1 день)'
else:
@@ -2263,7 +2312,7 @@ def get_change_devices_keyboard(
# Считаем по дням (как в кабинете и подтверждении)
if subscription_end_date:
now = datetime.now(UTC)
days_left = max(1, (subscription_end_date - now).days)
days_left = max(1, math.ceil((subscription_end_date - now).total_seconds() / 86400))
price_multiplier = days_left / 30
period_text = f' (за {days_left} дн.)' if days_left > 1 else ' (за 1 день)'
else:
@@ -2274,8 +2323,8 @@ def get_change_devices_keyboard(
tariff_device_price = getattr(tariff, 'device_price_kopeks', None) if tariff else None
if tariff and tariff_device_price:
device_price_per_month = tariff_device_price
# Для тарифов все устройства платные (нет бесплатного лимита)
default_device_limit = 0
# Устройства в пределах тарифного лимита — бесплатные
default_device_limit = tariff.device_limit if tariff else 0
else:
device_price_per_month = settings.PRICE_PER_DEVICE
default_device_limit = settings.DEFAULT_DEVICE_LIMIT
@@ -2425,7 +2474,7 @@ def get_manage_countries_keyboard(
# Считаем по дням (как в кабинете и подтверждении)
if subscription_end_date:
now = datetime.now(UTC)
days_left = max(1, (subscription_end_date - now).days)
days_left = max(1, math.ceil((subscription_end_date - now).total_seconds() / 86400))
price_multiplier = days_left / 30
logger.info(
'🔍 Расчет для управления странами: осталось дней до',
+46
View File
@@ -15,6 +15,7 @@ Usage::
from __future__ import annotations
import logging
import sys
from typing import Any
import structlog
@@ -56,6 +57,46 @@ def _prefix_logger_name(logger: Any, method_name: str, event_dict: dict[str, Any
return event_dict
def _auto_capture_exc_info(logger: Any, method_name: str, event_dict: dict[str, Any]) -> dict[str, Any]:
"""Auto-populate event_dict['exc_info'] so tracebacks render in files/console.
Without this, callers must pass ``exc_info=True`` at every ``logger.error``
site. Instead, we try:
1. exc_info=True replace with sys.exc_info() (standard structlog behaviour)
2. no exc_info but we're inside an active except block → use sys.exc_info()
3. error/exc/exception/e/err kwarg is a BaseException with __traceback__
synthesize an exc_info tuple from it
Result: ``logger.error('msg', error=e)`` inside any ``except`` block now
renders the full traceback to files, console, and Telegram automatically.
"""
exc_info = event_dict.get('exc_info')
if exc_info is True:
current = sys.exc_info()
if current[1] is not None:
event_dict['exc_info'] = current
return event_dict
if exc_info:
return event_dict
# Only auto-capture from sys.exc_info() for error/critical levels.
# For warning/info inside except blocks, callers must pass exc_info=True explicitly.
if method_name in ('error', 'critical', 'exception'):
current = sys.exc_info()
if current[1] is not None:
event_dict['exc_info'] = current
return event_dict
for key in ('error', 'exc', 'exception', 'e', 'err'):
candidate = event_dict.get(key)
if isinstance(candidate, BaseException) and candidate.__traceback__ is not None:
event_dict['exc_info'] = (type(candidate), candidate, candidate.__traceback__)
return event_dict
return event_dict
def setup_logging() -> tuple[logging.Formatter, logging.Formatter, Any]:
"""Configure structlog and return formatters + notifier.
@@ -82,6 +123,11 @@ def setup_logging() -> tuple[logging.Formatter, logging.Formatter, Any]:
structlog.stdlib.PositionalArgumentsFormatter(),
timestamper,
structlog.processors.StackInfoRenderer(),
# Auto-capture traceback from sys.exc_info()/error-kwarg BEFORE any
# consumer looks at event_dict. Runs for ALL log levels so files,
# console, and Telegram all see the same traceback without requiring
# every caller to pass exc_info=True.
_auto_capture_exc_info,
# TelegramNotifierProcessor MUST run while exc_info is still a raw
# tuple so it can extract the traceback for Telegram notifications.
# ConsoleRenderer handles exc_info formatting downstream (with Rich
+16 -1
View File
@@ -129,13 +129,28 @@ class TelegramNotifierProcessor:
if any(logger_name.startswith(prefix) for prefix in IGNORED_LOGGER_PREFIXES):
return event_dict
# 4. Resolve exc_info=True to actual tuple while still in except block.
# 4. Resolve exc_info into actual tuple while still in except block.
# logger.exception() sets exc_info=True (bool); we need the tuple for
# traceback extraction. sys.exc_info() works because the processor runs
# synchronously inside the except clause.
#
# If exc_info is not passed at all, auto-capture traceback from:
# (a) sys.exc_info() — works when logger.error is called inside except
# (b) error/exc/exception kwargs if they carry __traceback__
# This avoids having to pass exc_info=True at every logger.error site.
exc_info = event_dict.get('exc_info')
if exc_info is True:
event_dict['exc_info'] = sys.exc_info()
elif not exc_info:
current = sys.exc_info()
if current[1] is not None:
event_dict['exc_info'] = current
else:
for key in ('error', 'exc', 'exception', 'e', 'err'):
candidate = event_dict.get(key)
if isinstance(candidate, BaseException) and candidate.__traceback__ is not None:
event_dict['exc_info'] = (type(candidate), candidate, candidate.__traceback__)
break
# 5. Bot not initialized yet — skip
bot = self._bot
@@ -85,6 +85,9 @@ class DisplayNameRestrictionMiddleware(BaseMiddleware):
if not user or user.is_bot:
return await handler(event, data)
if not settings.DISPLAY_NAME_RESTRICTION_ENABLED:
return await handler(event, data)
display_name = self._build_display_name(user)
username = user.username or ''
@@ -67,6 +67,12 @@ class AdminNotificationService:
NotificationCategory.TICKETS: self.ticket_topic_id,
}
# Per-category enabled flags (default True — backwards compatible)
self.category_enabled: dict[NotificationCategory, bool] = {}
for cat in NotificationCategory:
key = f'ADMIN_NOTIFICATIONS_{cat.value.upper()}_ENABLED'
self.category_enabled[cat] = getattr(settings, key, True)
async def _get_referrer_info(self, db: AsyncSession, referred_by_id: int | None) -> str:
if not referred_by_id:
return 'Нет'
@@ -1266,6 +1272,11 @@ class AdminNotificationService:
logger.warning('ADMIN_NOTIFICATIONS_CHAT_ID не настроен')
return False
# Per-category suppression
if category and not self.category_enabled.get(category, True):
logger.debug('Уведомление подавлено (категория отключена)', category=category.value)
return False
try:
message_kwargs = {
'chat_id': self.chat_id,
+216
View File
@@ -0,0 +1,216 @@
"""Сервис для работы с API AuraPay (aurapay.tech)."""
import hashlib
import hmac
from typing import Any
import aiohttp
import structlog
from app.config import settings
logger = structlog.get_logger(__name__)
API_BASE_URL = 'https://app.aurapay.tech'
class AuraPayAPIError(Exception):
"""Ошибка API AuraPay."""
def __init__(self, status_code: int, message: str):
self.status_code = status_code
self.message = message
super().__init__(f'AuraPay API error ({status_code}): {message}')
class AuraPayService:
"""Сервис для работы с API AuraPay."""
def __init__(self):
self._session: aiohttp.ClientSession | None = None
@property
def api_key(self) -> str:
return settings.AURAPAY_API_KEY or ''
@property
def shop_id(self) -> str:
return settings.AURAPAY_SHOP_ID or ''
@property
def secret_key(self) -> str:
return settings.AURAPAY_SECRET_KEY or ''
async def _get_session(self) -> aiohttp.ClientSession:
"""Возвращает переиспользуемую HTTP-сессию."""
if self._session is None or self._session.closed:
self._session = aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=30),
)
return self._session
async def close(self) -> None:
"""Закрывает HTTP-сессию."""
if self._session and not self._session.closed:
await self._session.close()
self._session = None
def _build_headers(self) -> dict[str, str]:
"""Строит заголовки запроса с X-ApiKey и X-ShopId."""
return {
'Content-Type': 'application/json',
'X-ApiKey': self.api_key,
'X-ShopId': self.shop_id,
}
async def create_invoice(
self,
*,
amount: float,
order_id: str,
comment: str = '',
service: str | None = None,
success_url: str | None = None,
fail_url: str | None = None,
callback_url: str | None = None,
custom_fields: str | None = None,
lifetime: int | None = None,
) -> dict[str, Any]:
"""
Создает инвойс через API AuraPay.
POST /invoice/create
"""
payload: dict[str, Any] = {
'amount': amount,
'order_id': order_id,
}
if comment:
payload['comment'] = comment
if service:
payload['service'] = service
if success_url:
payload['success_url'] = success_url
if fail_url:
payload['fail_url'] = fail_url
if callback_url:
payload['callback_url'] = callback_url
if custom_fields:
payload['custom_fields'] = custom_fields
if lifetime is not None:
payload['lifetime'] = lifetime
logger.info(
'AuraPay API create_invoice',
order_id=order_id,
amount=amount,
service=service,
)
try:
session = await self._get_session()
async with session.post(
f'{API_BASE_URL}/invoice/create',
json=payload,
headers=self._build_headers(),
) as response:
data = await response.json(content_type=None)
if response.status == 200:
logger.info(
'AuraPay API invoice created',
order_id=order_id,
invoice_id=data.get('id'),
status=data.get('status'),
)
return data
error_msg = data.get('message') or data.get('error') or str(data)
logger.error(
'AuraPay create_invoice error',
status_code=response.status,
error_msg=error_msg,
response_data=data,
)
raise AuraPayAPIError(response.status, error_msg)
except aiohttp.ClientError as e:
logger.exception('AuraPay API connection error', error=e)
raise
async def get_invoice_status(
self,
*,
order_id: str | None = None,
invoice_id: str | None = None,
) -> dict[str, Any]:
"""
Получает статус инвойса.
POST /invoice/status
"""
if not order_id and not invoice_id:
raise ValueError('Either order_id or invoice_id must be provided')
payload: dict[str, str] = {}
if order_id:
payload['order_id'] = order_id
if invoice_id:
payload['id'] = invoice_id
logger.info('AuraPay get_invoice_status', order_id=order_id, invoice_id=invoice_id)
try:
session = await self._get_session()
async with session.post(
f'{API_BASE_URL}/invoice/status',
json=payload,
headers=self._build_headers(),
) as response:
data = await response.json(content_type=None)
if response.status == 200:
return data
error_msg = data.get('message') or data.get('error') or str(data)
logger.error(
'AuraPay get_invoice_status error',
status_code=response.status,
error_msg=error_msg,
)
raise AuraPayAPIError(response.status, error_msg)
except aiohttp.ClientError as e:
logger.exception('AuraPay API connection error', error=e)
raise
def verify_webhook_signature(self, payload: dict[str, Any], received_signature: str) -> bool:
"""Верификация подписи webhook AuraPay через HMAC-SHA256.
Algorithm: sort JSON keys alphabetically, concatenate all VALUES
(converted to str) into one string, HMAC-SHA256 with secret key #2.
Header: X-SIGNATURE
"""
try:
if not received_signature:
logger.warning('AuraPay webhook: отсутствует X-SIGNATURE')
return False
# Сортируем ключи по алфавиту и конкатенируем значения
sorted_keys = sorted(payload.keys())
concatenated_values = ''.join(str(payload[key]) for key in sorted_keys)
expected = hmac.new(
self.secret_key.encode('utf-8'),
concatenated_values.encode('utf-8'),
hashlib.sha256,
).hexdigest()
return hmac.compare_digest(expected, received_signature)
except Exception as e:
logger.error('AuraPay webhook verify error', error=e)
return False
# Singleton instance
aurapay_service = AuraPayService()
+51
View File
@@ -31,6 +31,7 @@ from app.database.models import (
AdminRole,
AdvertisingCampaign,
AdvertisingCampaignRegistration,
AuraPayPayment,
BroadcastHistory,
ButtonClickLog,
CabinetRefreshToken,
@@ -40,18 +41,27 @@ from app.database.models import (
ContestTemplate,
CryptoBotPayment,
DiscountOffer,
EmailTemplate,
FaqPage,
FaqSetting,
FreekassaPayment,
GuestPurchase,
HeleketPayment,
InfoPage,
KassaAiPayment,
LandingPage,
MainMenuButton,
MenuLayoutHistory,
MonitoringLog,
MulenPayPayment,
NewsArticle,
NewsCategory,
NewsTag,
OverpayPayment,
Pal24Payment,
PartnerApplication,
PaymentMethodConfig,
PayPearPayment,
PinnedMessage,
PlategaPayment,
Poll,
@@ -71,9 +81,13 @@ from app.database.models import (
ReferralContestVirtualParticipant,
ReferralEarning,
RequiredChannel,
RioPayPayment,
RollyPayPayment,
SavedPaymentMethod,
SentNotification,
ServerSquad,
ServiceRule,
SeverPayPayment,
Squad,
Subscription,
SubscriptionConversion,
@@ -102,6 +116,7 @@ from app.database.models import (
WheelPrize,
WheelSpin,
WithdrawalRequest,
YandexClientIdMap,
YooKassaPayment,
payment_method_promo_groups,
server_squad_promo_groups,
@@ -183,6 +198,13 @@ class BackupService:
CloudPaymentsPayment,
FreekassaPayment,
KassaAiPayment,
RioPayPayment,
SeverPayPayment,
PayPearPayment,
RollyPayPayment,
OverpayPayment,
AuraPayPayment,
SavedPaymentMethod,
# --- Settings/content ---
PaymentMethodConfig,
PrivacyPolicy,
@@ -192,6 +214,17 @@ class BackupService:
PinnedMessage,
MainMenuButton,
MenuLayoutHistory,
EmailTemplate,
InfoPage,
# --- News (FK: none / self-contained) ---
NewsCategory,
NewsTag,
NewsArticle,
# --- Landing / Guest purchases (FK: users, tariffs, landings) ---
LandingPage,
GuestPurchase,
# --- Yandex analytics (FK: users) ---
YandexClientIdMap,
# --- User data (FK: users, promo_groups, subscriptions) ---
UserPromoGroup,
TrafficPurchase,
@@ -1476,6 +1509,13 @@ class BackupService:
'cloudpayments_payments',
'freekassa_payments',
'kassa_ai_payments',
'riopay_payments',
'severpay_payments',
'paypear_payments',
'rollypay_payments',
'overpay_payments',
'aurapay_payments',
'saved_payment_methods',
# --- Content/config ---
'pinned_messages',
'main_menu_buttons',
@@ -1485,6 +1525,17 @@ class BackupService:
'privacy_policies',
'public_offers',
'payment_method_configs',
'email_templates',
'info_pages',
# --- News ---
'news_articles',
'news_categories',
'news_tags',
# --- Landing / Guest purchases ---
'guest_purchases',
'landing_pages',
# --- Yandex analytics ---
'yandex_client_id_map',
# --- Support ---
'support_audit_logs',
'ticket_messages',
+12 -20
View File
@@ -159,17 +159,13 @@ class AdvertisingCampaignService:
device_limit = campaign.subscription_device_limit
if device_limit is None:
device_limit = settings.DEFAULT_DEVICE_LIMIT
squads = list(campaign.subscription_squads or [])
try:
from app.database.crud.server_squad import get_effective_tariff_squad_uuids
if not squads:
try:
from app.database.crud.server_squad import get_random_trial_squad_uuid
trial_uuid = await get_random_trial_squad_uuid(db)
if trial_uuid:
squads = [trial_uuid]
except Exception as error:
logger.error('Не удалось подобрать сквад для кампании', campaign_id=campaign.id, error=error)
squads = await get_effective_tariff_squad_uuids(db, campaign.subscription_squads)
except Exception as error:
logger.error('Не удалось подобрать сквады для кампании', campaign_id=campaign.id, error=error)
squads = list(campaign.subscription_squads or [])
if existing_subscription:
# Multi-tariff: extend the best existing subscription
@@ -305,17 +301,13 @@ class AdvertisingCampaignService:
traffic_limit = tariff.traffic_limit_gb
device_limit = tariff.device_limit
squads = list(tariff.allowed_squads or [])
try:
from app.database.crud.server_squad import get_effective_tariff_squad_uuids
if not squads:
try:
from app.database.crud.server_squad import get_random_trial_squad_uuid
trial_uuid = await get_random_trial_squad_uuid(db)
if trial_uuid:
squads = [trial_uuid]
except Exception as error:
logger.error('Не удалось подобрать сквад для тарифа кампании', campaign_id=campaign.id, error=error)
squads = await get_effective_tariff_squad_uuids(db, tariff.allowed_squads)
except Exception as error:
logger.error('Не удалось подобрать сквады для тарифа кампании', campaign_id=campaign.id, error=error)
squads = list(tariff.allowed_squads or [])
if existing_subscription:
# Multi-tariff: extend the existing subscription for this tariff
+15 -2
View File
@@ -146,9 +146,22 @@ class DailySubscriptionService:
# Недостаточно средств - приостанавливаем подписку
await suspend_daily_subscription_insufficient_balance(db, subscription)
# Уведомляем пользователя
# Уведомляем пользователя (rate-limit: 1 раз в 6 часов)
if self._bot:
await self._notify_insufficient_balance(user, subscription, daily_price)
from app.utils.cache import cache
cache_key = f'daily_insuf_notify:{subscription.id}'
try:
already_notified = await cache.get(cache_key)
except Exception:
already_notified = None
if not already_notified:
await self._notify_insufficient_balance(user, subscription, daily_price)
try:
await cache.set(cache_key, '1', expire=21600) # 6 hours
except Exception:
pass
logger.info(
'Подписка приостановлена: недостаточно средств (баланс: требуется: )',
-146
View File
@@ -1,146 +0,0 @@
"""Утилиты для синхронизации токена внешней админки."""
from __future__ import annotations
import structlog
from sqlalchemy import select
from sqlalchemy.exc import SQLAlchemyError
from app.config import settings
from app.database.database import AsyncSessionLocal
from app.database.models import SystemSetting
from app.services.system_settings_service import (
ReadOnlySettingError,
bot_configuration_service,
)
logger = structlog.get_logger(__name__)
async def ensure_external_admin_token(
bot_username: str | None,
bot_id: int | None,
) -> str | None:
"""Генерирует и сохраняет токен внешней админки, если требуется."""
username_raw = (bot_username or '').strip()
if not username_raw:
logger.warning(
'⚠️ Не удалось обеспечить токен внешней админки: username бота отсутствует',
)
return None
normalized_username = username_raw.lstrip('@').lower()
if not normalized_username:
logger.warning(
'⚠️ Не удалось обеспечить токен внешней админки: username пустой после нормализации',
)
return None
try:
token = settings.build_external_admin_token(normalized_username)
except Exception as error: # pragma: no cover - защитный блок
logger.error('❌ Ошибка генерации токена внешней админки', error=error)
return None
try:
async with AsyncSessionLocal() as session:
result = await session.execute(
select(SystemSetting.key, SystemSetting.value).where(
SystemSetting.key.in_(['EXTERNAL_ADMIN_TOKEN', 'EXTERNAL_ADMIN_TOKEN_BOT_ID'])
)
)
rows = dict(result.all())
existing_token = rows.get('EXTERNAL_ADMIN_TOKEN')
existing_bot_id_raw = rows.get('EXTERNAL_ADMIN_TOKEN_BOT_ID')
existing_bot_id: int | None = None
if existing_bot_id_raw is not None:
try:
existing_bot_id = int(existing_bot_id_raw)
except (TypeError, ValueError): # pragma: no cover - защита от мусорных значений
logger.warning(
'⚠️ Не удалось разобрать сохраненный идентификатор бота внешней админки',
existing_bot_id_raw=existing_bot_id_raw,
)
if existing_token == token and existing_bot_id == bot_id:
if settings.get_external_admin_token() != token:
settings.EXTERNAL_ADMIN_TOKEN = token
if existing_bot_id != settings.EXTERNAL_ADMIN_TOKEN_BOT_ID:
settings.EXTERNAL_ADMIN_TOKEN_BOT_ID = existing_bot_id
return token
if existing_bot_id is not None and bot_id is not None and existing_bot_id != bot_id:
logger.error(
'❌ Обнаружено несовпадение ID бота для токена внешней админки: сохранен , текущий',
existing_bot_id=existing_bot_id,
bot_id=bot_id,
)
try:
await bot_configuration_service.reset_value(
session,
'EXTERNAL_ADMIN_TOKEN',
force=True,
)
await bot_configuration_service.reset_value(
session,
'EXTERNAL_ADMIN_TOKEN_BOT_ID',
force=True,
)
await session.commit()
logger.warning(
'⚠️ Токен внешней админки очищен из-за несовпадения идентификаторов бота',
)
except Exception as cleanup_error: # pragma: no cover - защитный блок
await session.rollback()
logger.error(
'❌ Не удалось очистить токен внешней админки после обнаружения подмены',
cleanup_error=cleanup_error,
)
finally:
settings.EXTERNAL_ADMIN_TOKEN = None
settings.EXTERNAL_ADMIN_TOKEN_BOT_ID = None
return None
updates: list[tuple[str, object]] = []
if existing_token != token:
updates.append(('EXTERNAL_ADMIN_TOKEN', token))
if bot_id is not None and existing_bot_id != bot_id:
updates.append(('EXTERNAL_ADMIN_TOKEN_BOT_ID', bot_id))
if not updates:
# Токен совпал, но могли отсутствовать значения в настройках приложения
if settings.get_external_admin_token() != (existing_token or token):
settings.EXTERNAL_ADMIN_TOKEN = existing_token or token
if existing_bot_id is not None and (existing_bot_id != settings.EXTERNAL_ADMIN_TOKEN_BOT_ID):
settings.EXTERNAL_ADMIN_TOKEN_BOT_ID = existing_bot_id
elif bot_id is not None and bot_id != settings.EXTERNAL_ADMIN_TOKEN_BOT_ID and existing_bot_id is None:
settings.EXTERNAL_ADMIN_TOKEN_BOT_ID = bot_id
return existing_token or token
try:
for key, value in updates:
await bot_configuration_service.set_value(
session,
key,
value,
force=True,
)
await session.commit()
logger.info('✅ Токен внешней админки синхронизирован для @', normalized_username=normalized_username)
except ReadOnlySettingError: # pragma: no cover - force=True предотвращает исключение
await session.rollback()
logger.warning(
'⚠️ Не удалось сохранить токен внешней админки из-за ограничения доступа',
)
return None
return token
except SQLAlchemyError as error:
logger.error('❌ Ошибка сохранения токена внешней админки', error=error)
return None
+99 -28
View File
@@ -145,6 +145,8 @@ async def create_purchase(
gift_recipient_value: str | None = None,
gift_message: str | None = None,
source: str = 'landing',
subid: str | None = None,
referrer: str | None = None,
buyer_user_id: int | None = None,
commit: bool = True,
) -> GuestPurchase:
@@ -152,6 +154,8 @@ async def create_purchase(
purchase = await create_guest_purchase(
db,
commit=commit,
subid=subid,
referrer=referrer,
landing_id=landing.id if landing else None,
tariff_id=tariff.id,
period_days=period_days,
@@ -438,28 +442,93 @@ async def fulfill_purchase(
purchase.status = GuestPurchaseStatus.DELIVERED.value
purchase.user_id = user.id
purchase.delivered_at = datetime.now(UTC)
# Extract subid from Redis cache (saved at purchase creation)
try:
from app.utils.cache import cache
_cached_subid = await cache.get(f'subid:purchase:{purchase.token}')
if _cached_subid:
purchase.subid = _cached_subid if isinstance(_cached_subid, str) else _cached_subid.decode()
from app.database.crud.yandex_client_id import upsert_subid
await upsert_subid(db, user.id, purchase.subid, source='landing')
except Exception:
pass
if recipient_type == 'email' and not purchase.is_gift and is_new_account:
purchase.auto_login_token = create_auto_login_token(user.id)
await db.commit()
await db.refresh(purchase, attribute_names=['landing', 'user', 'buyer'])
# Create transaction so promo group auto-assignment and contest tracking work
# Create transaction so promo group auto-assignment and contest tracking work.
# Skip for gift recipients — they didn't pay, so their spending shouldn't be inflated.
transaction = None
if not purchase.is_gift:
try:
payment_method_enum = _resolve_payment_method(purchase.payment_method)
transaction = await create_transaction(
db=db,
user_id=user.id,
type=TransactionType.SUBSCRIPTION_PAYMENT,
amount_kopeks=purchase.amount_kopeks,
description=f'Покупка подписки через лендинг ({notification_tariff_name}, {purchase.period_days} дн.)',
payment_method=payment_method_enum,
external_id=purchase.payment_id,
is_completed=True,
)
except Exception:
logger.exception('Failed to create transaction for guest purchase', purchase_id=purchase.id)
# Save Yandex CID from Redis → DB (enables on_registration/on_purchase to use it)
try:
payment_method_enum = _resolve_payment_method(purchase.payment_method)
transaction = await create_transaction(
db=db,
user_id=user.id,
type=TransactionType.SUBSCRIPTION_PAYMENT,
amount_kopeks=purchase.amount_kopeks,
description=f'Покупка подписки через лендинг ({notification_tariff_name}, {purchase.period_days} дн.)',
payment_method=payment_method_enum,
external_id=purchase.payment_id,
is_completed=True,
)
from app.services import yandex_offline_conv_service as yandex_conv
from app.utils.cache import cache
_cached_cid = await cache.get(f'yacid:purchase:{purchase.token}')
if _cached_cid:
await yandex_conv.store_cid(db, user.id, _cached_cid, source='landing')
await db.commit()
except Exception:
logger.exception('Failed to create transaction for guest purchase', purchase_id=purchase.id)
logger.debug('Failed to save CID from Redis')
# Registration event (new accounts only) + S2S postback
if is_new_account:
try:
from app.services import yandex_offline_conv_service as yandex_conv
await yandex_conv.on_registration(db, user.id)
except Exception:
logger.debug('Yandex on_registration hook error')
try:
from app.database.crud.yandex_client_id import get_subid
from app.services.s2s_postback_service import send_postback
_subid = purchase.subid or await get_subid(db, user.id)
if _subid:
await send_postback('registration', _subid, user_id=user.id)
except Exception:
logger.debug('S2S postback registration hook error')
# Purchase event + S2S postback (always for paid purchases)
try:
from app.services import yandex_offline_conv_service as yandex_conv
await yandex_conv.on_purchase(db, user.id, purchase.amount_kopeks)
except Exception:
logger.debug('Yandex on_purchase hook error')
try:
from app.database.crud.yandex_client_id import get_subid
from app.services.s2s_postback_service import send_postback
_subid = purchase.subid or await get_subid(db, user.id)
if _subid:
await send_postback('purchase', _subid, amount=purchase.amount_kopeks / 100, user_id=user.id)
except Exception:
logger.debug('S2S postback purchase hook error')
try:
await send_guest_notification(
@@ -1147,21 +1216,23 @@ async def activate_purchase(db: AsyncSession, purchase_token: str, *, skip_notif
await db.commit()
await db.refresh(purchase, attribute_names=['landing', 'user', 'buyer'])
# Create transaction so promo group auto-assignment and contest tracking work
try:
payment_method_enum = _resolve_payment_method(purchase.payment_method)
await create_transaction(
db=db,
user_id=user.id,
type=TransactionType.SUBSCRIPTION_PAYMENT,
amount_kopeks=purchase.amount_kopeks,
description=f'Покупка подписки через лендинг ({notification_tariff_name}, {purchase.period_days} дн.)',
payment_method=payment_method_enum,
external_id=purchase.payment_id,
is_completed=True,
)
except Exception:
logger.exception('Failed to create transaction for activated purchase', purchase_id=purchase.id)
# Create transaction so promo group auto-assignment and contest tracking work.
# Skip for gift recipients — they didn't pay, so their spending shouldn't be inflated.
if not purchase.is_gift:
try:
payment_method_enum = _resolve_payment_method(purchase.payment_method)
await create_transaction(
db=db,
user_id=user.id,
type=TransactionType.SUBSCRIPTION_PAYMENT,
amount_kopeks=purchase.amount_kopeks,
description=f'Покупка подписки через лендинг ({notification_tariff_name}, {purchase.period_days} дн.)',
payment_method=payment_method_enum,
external_id=purchase.payment_id,
is_completed=True,
)
except Exception:
logger.exception('Failed to create transaction for activated purchase', purchase_id=purchase.id)
if not skip_notification:
try:
+323 -166
View File
@@ -373,7 +373,22 @@ class MonitoringService:
user = await get_user_by_id(db, subscription.user_id)
if user and self.bot:
await self._send_subscription_expired_notification(user, subscription, tariff_name=_tariff_name)
# Skip notification if user has another ACTIVE subscription (multi-tariff)
skip_notify = False
if settings.is_multi_tariff_enabled():
other_active = await db.execute(
select(Subscription.id)
.where(
Subscription.user_id == user.id,
Subscription.id != subscription.id,
Subscription.status == SubscriptionStatus.ACTIVE.value,
Subscription.end_date > datetime.now(UTC),
)
.limit(1)
)
skip_notify = other_active.scalar_one_or_none() is not None
if not skip_notify:
await self._send_subscription_expired_notification(user, subscription, tariff_name=_tariff_name)
logger.info(
"🔴 Подписка пользователя истекла и статус изменен на 'expired'", user_id=subscription.user_id
@@ -901,18 +916,24 @@ class MonitoringService:
)
try:
panel_uuid_restore = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled() and subscription.remnawave_uuid
else user.remnawave_uuid
)
if panel_uuid_restore:
await self.subscription_service.enable_remnawave_user(panel_uuid_restore)
if settings.is_multi_tariff_enabled():
_should_create = not subscription.remnawave_uuid
else:
_should_create = not getattr(user, 'remnawave_uuid', None)
if _should_create:
# create_remnawave_user calls db.commit() internally --
# flush accumulated batch state first to preserve atomicity.
await batch_db.commit()
await self.subscription_service.create_remnawave_user(batch_db, subscription)
else:
_enable_uuid = (
subscription.remnawave_uuid
if settings.is_multi_tariff_enabled()
else user.remnawave_uuid
)
if _enable_uuid:
await self.subscription_service.enable_remnawave_user(_enable_uuid)
except Exception as api_error:
logger.error(
'Failed to update RemnaWave user',
@@ -959,8 +980,12 @@ class MonitoringService:
try:
now = datetime.now(UTC)
# Lookback window — don't re-check subscriptions expired more than 30 days ago
lookback = now - timedelta(days=30)
result = await db.execute(
select(Subscription)
.join(User, Subscription.user_id == User.id)
.options(
selectinload(Subscription.user),
selectinload(Subscription.tariff),
@@ -968,7 +993,10 @@ class MonitoringService:
.where(
and_(
Subscription.is_trial == False,
Subscription.status == SubscriptionStatus.EXPIRED.value,
Subscription.end_date <= now,
Subscription.end_date >= lookback,
User.status == UserStatus.ACTIVE.value,
)
)
)
@@ -992,6 +1020,21 @@ class MonitoringService:
if subscription.end_date is None:
continue
# Skip if user has another ACTIVE subscription — they still have service
if settings.is_multi_tariff_enabled():
other_active = await db.execute(
select(Subscription.id)
.where(
Subscription.user_id == user.id,
Subscription.id != subscription.id,
Subscription.status == SubscriptionStatus.ACTIVE.value,
Subscription.end_date > now,
)
.limit(1)
)
if other_active.scalar_one_or_none() is not None:
continue
time_since_end = now - subscription.end_date
if time_since_end.total_seconds() < 0:
continue
@@ -1084,6 +1127,7 @@ class MonitoringService:
result = await db.execute(
select(Subscription)
.join(User, Subscription.user_id == User.id)
.options(
selectinload(Subscription.user),
selectinload(Subscription.tariff),
@@ -1094,6 +1138,7 @@ class MonitoringService:
Subscription.is_trial == False,
Subscription.end_date > current_time,
Subscription.end_date <= threshold_date,
User.status == UserStatus.ACTIVE.value,
)
)
)
@@ -1196,160 +1241,229 @@ class MonitoringService:
processed_count = 0
failed_count = 0
for subscription in autopay_subscriptions:
from app.database.crud.subscription import is_recently_updated_by_webhook
if is_recently_updated_by_webhook(subscription):
logger.debug(
'Пропуск автоплатежа подписки : обновлена вебхуком недавно', subscription_id=subscription.id
)
continue
user = subscription.user
if not user:
continue
user_identifier = user.telegram_id or f'email:{user.id}'
# Определяем период продления: из тарифа (минимальный) или 30 дней по умолчанию
tariff = getattr(subscription, 'tariff', None)
if tariff:
autopay_period = tariff.get_shortest_period() or 30
else:
autopay_period = 30
# Захватываем (sub_id, user_id) ДО цикла, пока сессия ещё свежая.
# В цикле каждую итерацию делаем refetch subscription+user через
# async-запрос: это единственный безопасный способ избежать
# MissingGreenlet при sync-lazy-load, который SQLAlchemy 2.0 async
# session не поддерживает (напр. lock_user_for_pricing c
# populate_existing=True разгружает Subscription.user backref).
autopay_pairs: list[tuple[int, int]] = [(s.id, s.user_id) for s in autopay_subscriptions]
for sub_id_local, sub_user_id_local in autopay_pairs:
try:
from app.database.crud.user import lock_user_for_pricing
from app.services.pricing_engine import pricing_engine
user = await lock_user_for_pricing(db, user.id)
pricing = await pricing_engine.calculate_renewal_price(
db,
subscription,
autopay_period,
user=user,
# Refetch subscription с eager load user/tariff —
# никаких lazy access по ходу итерации.
refetch_result = await db.execute(
select(Subscription)
.options(
selectinload(Subscription.user).options(
selectinload(User.promo_group),
selectinload(User.user_promo_groups).selectinload(UserPromoGroup.promo_group),
),
selectinload(Subscription.tariff),
)
.where(Subscription.id == sub_id_local)
)
renewal_cost = pricing.final_total
except Exception as e:
logger.error(
'Ошибка расчёта стоимости автопродления, пропускаем',
subscription_id=subscription.id,
user_id=user.id,
error=str(e),
)
failed_count += 1
continue
subscription = refetch_result.scalar_one_or_none()
if subscription is None:
continue
if renewal_cost <= 0:
logger.warning(
'Нулевая стоимость автопродления, пропускаем',
subscription_id=subscription.id,
user_id=user.id,
renewal_cost=renewal_cost,
)
failed_count += 1
continue
from app.database.crud.subscription import is_recently_updated_by_webhook
# calculate_renewal_price уже включает promo_group + promo_offer скидки.
# Не применяем promo_offer повторно — только consume-им при успешной оплате.
charge_amount = renewal_cost
promo_discount_percent = get_user_active_promo_discount_percent(user)
if is_recently_updated_by_webhook(subscription):
logger.debug(
'Пропуск автоплатежа подписки : обновлена вебхуком недавно',
subscription_id=subscription.id,
)
continue
autopay_key = f'autopay_{user.id}_{subscription.id}'
if autopay_key in self._notified_users:
continue
user = subscription.user
if not user:
continue
if user.balance_kopeks >= charge_amount:
success = await subtract_user_balance(
db,
user,
charge_amount,
'Автопродление подписки',
consume_promo_offer=promo_discount_percent > 0,
mark_as_paid_subscription=True,
)
user_identifier = user.telegram_id or f'email:{user.id}'
if success:
# extend_subscription сам обработает EXPIRED→ACTIVE переход
# (проверяет status + end_date для определения was_expired)
if subscription.status == SubscriptionStatus.EXPIRED.value:
logger.info(
'🔄 Autopay: продление EXPIRED подписки (восстановление)',
subscription_id=subscription.id,
user_id=user.id,
)
old_end_date = subscription.end_date
await extend_subscription(db, subscription, autopay_period)
await self.subscription_service.update_remnawave_user(
# Определяем период продления: из тарифа (минимальный) или 30 дней по умолчанию
tariff = getattr(subscription, 'tariff', None)
if tariff:
autopay_period = tariff.get_shortest_period() or 30
else:
autopay_period = 30
try:
from app.database.crud.user import lock_user_for_pricing
from app.services.pricing_engine import pricing_engine
user = await lock_user_for_pricing(db, user.id)
pricing = await pricing_engine.calculate_renewal_price(
db,
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_PAYMENT,
reset_reason='автопродление подписки',
autopay_period,
user=user,
)
renewal_cost = pricing.final_total
except Exception as e:
logger.error(
'Ошибка расчёта стоимости автопродления, пропускаем',
subscription_id=subscription.id,
user_id=user.id,
error=str(e),
)
failed_count += 1
continue
if renewal_cost <= 0:
logger.warning(
'Нулевая стоимость автопродления, пропускаем',
subscription_id=subscription.id,
user_id=user.id,
renewal_cost=renewal_cost,
)
failed_count += 1
continue
# calculate_renewal_price уже включает promo_group + promo_offer скидки.
# Не применяем promo_offer повторно — только consume-им при успешной оплате.
charge_amount = renewal_cost
promo_discount_percent = get_user_active_promo_discount_percent(user)
autopay_key = f'autopay_{user.id}_{subscription.id}'
if autopay_key in self._notified_users:
continue
if user.balance_kopeks >= charge_amount:
success = await subtract_user_balance(
db,
user,
charge_amount,
'Автопродление подписки',
consume_promo_offer=promo_discount_percent > 0,
mark_as_paid_subscription=True,
)
# Создаём транзакцию, чтобы автопродление было видно в статистике и карточке пользователя
try:
from app.database.crud.transaction import create_transaction
from app.database.models import PaymentMethod, TransactionType
transaction = await create_transaction(
db=db,
user_id=user.id,
type=TransactionType.SUBSCRIPTION_PAYMENT,
amount_kopeks=charge_amount,
description=f'Автопродление подписки на {autopay_period} дней',
payment_method=PaymentMethod.BALANCE,
)
except Exception as exc:
logger.warning('Не удалось создать транзакцию автопродления', user_id=user.id, exc=exc)
transaction = None
# Отправляем уведомление администраторам
try:
from app.services.subscription_renewal_service import with_admin_notification_service
if transaction:
await with_admin_notification_service(
lambda svc: svc.send_subscription_extension_notification(
db,
user,
subscription,
transaction,
autopay_period,
old_end_date,
new_end_date=subscription.end_date,
balance_after=user.balance_kopeks,
)
if success:
# subtract_user_balance мог оставить сессию в expired state
# (напр. rollback внутри log_promo_offer_action при consume_promo_offer).
# Перезагружаем subscription с eager-загрузкой user/tariff, чтобы
# избежать MissingGreenlet на последующих обращениях к subscription.*
refetch_result = await db.execute(
select(Subscription)
.options(
selectinload(Subscription.user),
selectinload(Subscription.tariff),
)
except Exception as exc:
.where(Subscription.id == subscription.id)
)
refreshed_subscription = refetch_result.scalar_one_or_none()
if refreshed_subscription is None:
logger.warning(
'Подписка пропала после списания — пропускаем шаги продления',
subscription_id=subscription.id,
user_id=user.id,
)
processed_count += 1
self._notified_users.add(autopay_key)
continue
subscription = refreshed_subscription
# extend_subscription сам обработает EXPIRED→ACTIVE переход
# (проверяет status + end_date для определения was_expired)
if subscription.status == SubscriptionStatus.EXPIRED.value:
logger.info(
'🔄 Autopay: продление EXPIRED подписки (восстановление)',
subscription_id=subscription.id,
user_id=user.id,
)
old_end_date = subscription.end_date
await extend_subscription(db, subscription, autopay_period)
await self.subscription_service.update_remnawave_user(
db,
subscription,
reset_traffic=settings.RESET_TRAFFIC_ON_PAYMENT,
reset_reason='автопродление подписки',
)
# Создаём транзакцию, чтобы автопродление было видно в статистике и карточке пользователя
try:
from app.database.crud.transaction import create_transaction
from app.database.models import PaymentMethod, TransactionType
transaction = await create_transaction(
db=db,
user_id=user.id,
type=TransactionType.SUBSCRIPTION_PAYMENT,
amount_kopeks=charge_amount,
description=f'Автопродление подписки на {autopay_period} дней',
payment_method=PaymentMethod.BALANCE,
)
except Exception as exc:
logger.warning('Не удалось создать транзакцию автопродления', user_id=user.id, exc=exc)
transaction = None
# Отправляем уведомление администраторам
try:
from app.services.subscription_renewal_service import with_admin_notification_service
if transaction:
await with_admin_notification_service(
lambda svc: svc.send_subscription_extension_notification(
db,
user,
subscription,
transaction,
autopay_period,
old_end_date,
new_end_date=subscription.end_date,
balance_after=user.balance_kopeks,
)
)
except Exception as exc:
logger.warning(
'Не удалось отправить админ-уведомление об автопродлении', user_id=user.id, exc=exc
)
# Send notification via appropriate channel
if user.telegram_id and self.bot:
await self._send_autopay_success_notification(
user, charge_amount, autopay_period, subscription=subscription
)
elif not user.telegram_id:
# Email-only user - use notification delivery service
await notification_delivery_service.notify_autopay_success(
user=user,
amount_kopeks=charge_amount,
new_expires_at=subscription.end_date,
)
processed_count += 1
self._notified_users.add(autopay_key)
logger.info(
'💳 Автопродление подписки пользователя успешно (списано , скидка %)',
user_identifier=user_identifier,
charge_amount=charge_amount,
promo_discount_percent=promo_discount_percent,
)
else:
failed_count += 1
if await self._check_autopay_fail_cooldown(user.id, user_identifier):
if user.telegram_id and self.bot:
await self._send_autopay_failed_notification(
user, user.balance_kopeks, charge_amount, subscription=subscription
)
elif not user.telegram_id:
await notification_delivery_service.notify_autopay_failed(
user=user,
reason='Ошибка списания средств',
)
await self._set_autopay_fail_cooldown(user.id, user_identifier)
logger.warning(
'Не удалось отправить админ-уведомление об автопродлении', user_id=user.id, exc=exc
'💳 Ошибка списания средств для автопродления пользователя',
user_identifier=user_identifier,
)
# Send notification via appropriate channel
if user.telegram_id and self.bot:
await self._send_autopay_success_notification(
user, charge_amount, autopay_period, subscription=subscription
)
elif not user.telegram_id:
# Email-only user - use notification delivery service
await notification_delivery_service.notify_autopay_success(
user=user,
amount_kopeks=charge_amount,
new_expires_at=subscription.end_date,
)
processed_count += 1
self._notified_users.add(autopay_key)
logger.info(
'💳 Автопродление подписки пользователя успешно (списано , скидка %)',
user_identifier=user_identifier,
charge_amount=charge_amount,
promo_discount_percent=promo_discount_percent,
)
else:
failed_count += 1
if await self._check_autopay_fail_cooldown(user.id, user_identifier):
if user.telegram_id and self.bot:
await self._send_autopay_failed_notification(
@@ -1358,30 +1472,35 @@ class MonitoringService:
elif not user.telegram_id:
await notification_delivery_service.notify_autopay_failed(
user=user,
reason='Ошибка списания средств',
reason='Недостаточно средств на балансе',
)
await self._set_autopay_fail_cooldown(user.id, user_identifier)
logger.warning(
'💳 Ошибка списания средств для автопродления пользователя', user_identifier=user_identifier
'💳 Недостаточно средств для автопродления у пользователя',
user_identifier=user_identifier,
)
else:
except Exception as sub_error:
failed_count += 1
if await self._check_autopay_fail_cooldown(user.id, user_identifier):
if user.telegram_id and self.bot:
await self._send_autopay_failed_notification(
user, user.balance_kopeks, charge_amount, subscription=subscription
)
elif not user.telegram_id:
await notification_delivery_service.notify_autopay_failed(
user=user,
reason='Недостаточно средств на балансе',
)
await self._set_autopay_fail_cooldown(user.id, user_identifier)
logger.warning(
'💳 Недостаточно средств для автопродления у пользователя', user_identifier=user_identifier
# Используем локально захваченные id — subscription-объект
# может быть expired после чужого rollback'а.
logger.error(
'Ошибка автопродления отдельной подписки',
subscription_id=sub_id_local,
user_id=sub_user_id_local,
error=sub_error,
exc_info=True,
)
# Сессия могла остаться с aborted-транзакцией — откатываем,
# чтобы следующая итерация начала refetch на чистой сессии.
try:
await db.rollback()
except Exception as rollback_error:
logger.warning(
'Не удалось сделать rollback сессии после ошибки автопродления',
rollback_error=rollback_error,
)
continue
if processed_count > 0 or failed_count > 0:
await self._log_monitoring_event(
@@ -1392,7 +1511,7 @@ class MonitoringService:
)
except Exception as e:
logger.error('Ошибка обработки автоплатежей', error=e)
logger.error('Ошибка обработки автоплатежей', error=e, exc_info=True)
async def _send_subscription_expired_notification(
self, user: User, subscription: Subscription, *, tariff_name: str | None = None
@@ -2069,23 +2188,43 @@ class MonitoringService:
logger.error('Error checking traffic warnings', error=error)
async def _check_low_balance_alerts(self, db: AsyncSession):
"""Check users with autopay enabled who have low balance and notify them."""
"""Check users with autopay enabled who have low balance and notify them.
Guards:
- Disabled by default; users opt-in via cabinet notification settings
- Only alerts when subscription expires within LOW_BALANCE_ALERT_EXPIRY_DAYS (default 3)
- Quiet hours: skips sending between 22:00 and 09:00 server time
- Rate-limited: max 1 alert per 24 hours per user
"""
if not self.bot:
return
try:
from datetime import UTC, datetime, timedelta
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
from sqlalchemy import select
from app.database.models import Subscription, User
from app.utils.notification_prefs import get_balance_low_threshold, is_balance_low_enabled
# Only check users with active autopay subscriptions — low balance matters for them
# Quiet hours: don't disturb users at night (22:00-09:00 UTC)
current_hour = datetime.now(UTC).hour
if current_hour >= 22 or current_hour < 9:
return
# Only alert for subscriptions expiring soon (default 3 days)
expiry_days = getattr(settings, 'LOW_BALANCE_ALERT_EXPIRY_DAYS', 3)
expiry_threshold = datetime.now(UTC) + timedelta(days=expiry_days)
result = await db.execute(
select(User)
.join(Subscription, Subscription.user_id == User.id)
.where(
Subscription.status.in_(['active', 'trial']),
Subscription.autopay_enabled.is_(True),
Subscription.end_date.isnot(None),
Subscription.end_date <= expiry_threshold,
User.telegram_id.isnot(None),
)
.distinct()
@@ -2128,10 +2267,28 @@ class MonitoringService:
balance=f'{balance_rub:.0f}',
threshold=f'{threshold_rub:.0f}',
)
# Build inline keyboard with cabinet top-up button
keyboard = None
miniapp_url = settings.get_main_menu_miniapp_url()
if miniapp_url:
topup_label = texts.get('LOW_BALANCE_TOPUP_BUTTON', '💳 Пополнить баланс')
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=topup_label,
web_app=WebAppInfo(url=miniapp_url),
)
]
]
)
await self.bot.send_message(
user.telegram_id,
message,
parse_mode='HTML',
reply_markup=keyboard,
)
# Mark as sent for 24 hours
try:
+291
View File
@@ -0,0 +1,291 @@
"""Сервис для работы с API Overpay (pay.overpay.io)."""
import ssl
import tempfile
from typing import Any
import httpx
import structlog
from cryptography.hazmat.primitives.serialization import (
BestAvailableEncryption,
Encoding,
NoEncryption,
PrivateFormat,
pkcs12,
)
from app.config import settings
logger = structlog.get_logger(__name__)
class OverpayAPIError(Exception):
"""Ошибка API Overpay."""
def __init__(self, status_code: int, message: str):
self.status_code = status_code
self.message = message
super().__init__(f'Overpay API error ({status_code}): {message}')
class OverpayService:
"""Сервис для работы с API Overpay.
Overpay использует HTTP Basic Auth + mTLS (P12 сертификат).
"""
def __init__(self):
self._client: httpx.AsyncClient | None = None
self._ssl_context: ssl.SSLContext | None = None
self._temp_cert_file: str | None = None
self._temp_key_file: str | None = None
@property
def api_url(self) -> str:
return (settings.OVERPAY_API_URL or 'https://api.overpay.io').rstrip('/')
@property
def username(self) -> str:
return settings.OVERPAY_USERNAME or ''
@property
def password(self) -> str:
return settings.OVERPAY_PASSWORD or ''
@property
def project_id(self) -> str:
return settings.OVERPAY_PROJECT_ID or ''
def _build_ssl_context(self) -> ssl.SSLContext | None:
"""Создает SSL контекст с P12 сертификатом для mTLS."""
p12_path = settings.OVERPAY_P12_PATH
if not p12_path:
return None
if self._ssl_context is not None:
return self._ssl_context
try:
passphrase = settings.OVERPAY_P12_PASSPHRASE
passphrase_bytes = passphrase.encode('utf-8') if passphrase else None
with open(p12_path, 'rb') as f:
p12_data = f.read()
private_key, certificate, additional_certs = pkcs12.load_key_and_certificates(p12_data, passphrase_bytes)
# Write PEM files to temp files for ssl.SSLContext
cert_pem = certificate.public_bytes(Encoding.PEM)
if additional_certs:
for cert in additional_certs:
cert_pem += cert.public_bytes(Encoding.PEM)
if passphrase_bytes:
key_pem = private_key.private_bytes(
Encoding.PEM,
PrivateFormat.TraditionalOpenSSL,
BestAvailableEncryption(passphrase_bytes),
)
else:
key_pem = private_key.private_bytes(
Encoding.PEM,
PrivateFormat.TraditionalOpenSSL,
NoEncryption(),
)
# Write to temp files
with tempfile.NamedTemporaryFile(delete=False, suffix='.pem') as cert_file:
cert_file.write(cert_pem)
cert_file.flush()
self._temp_cert_file = cert_file.name
with tempfile.NamedTemporaryFile(delete=False, suffix='.pem') as key_file:
key_file.write(key_pem)
key_file.flush()
self._temp_key_file = key_file.name
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_cert_chain(
certfile=self._temp_cert_file,
keyfile=self._temp_key_file,
password=passphrase,
)
ctx.load_default_certs()
self._ssl_context = ctx
logger.info('Overpay: SSL контекст с P12 сертификатом создан')
return ctx
except Exception as e:
logger.exception('Overpay: ошибка загрузки P12 сертификата', error=e)
return None
async def _get_client(self) -> httpx.AsyncClient:
"""Возвращает переиспользуемый HTTP-клиент с mTLS."""
if self._client is not None and not self._client.is_closed:
return self._client
ssl_context = self._build_ssl_context()
self._client = httpx.AsyncClient(
timeout=httpx.Timeout(30.0),
auth=httpx.BasicAuth(self.username, self.password),
verify=ssl_context if ssl_context else True,
)
return self._client
async def close(self) -> None:
"""Закрывает HTTP-клиент."""
if self._client and not self._client.is_closed:
await self._client.aclose()
self._client = None
# Clean up temp files
from pathlib import Path
for path in (self._temp_cert_file, self._temp_key_file):
if path:
try:
Path(path).unlink()
except OSError:
pass
self._temp_cert_file = None
self._temp_key_file = None
self._ssl_context = None
async def create_payment(
self,
*,
amount: str,
currency: str = 'RUB',
lifetime_minutes: int = 1440,
merchant_transaction_id: str,
description: str = '',
return_url: str | None = None,
payment_methods: list[str] | None = None,
) -> dict[str, Any]:
"""
Создает платеж через API Overpay.
POST {API_URL}/orders/
"""
payload: dict[str, Any] = {
'amount': amount,
'currency': currency,
'livetimeMinutes': lifetime_minutes,
'projectId': self.project_id,
'merchantTransactionId': merchant_transaction_id,
}
if description:
payload['description'] = description
if return_url:
payload['returnUrl'] = return_url
if payment_methods:
payload['paymentMethods'] = payment_methods
logger.info(
'Overpay API create_payment',
merchant_transaction_id=merchant_transaction_id,
amount=amount,
currency=currency,
)
try:
client = await self._get_client()
response = await client.post(
f'{self.api_url}/orders/',
json=payload,
headers={'Content-Type': 'application/json'},
)
data = response.json()
if response.status_code == 200 or response.status_code == 201:
logger.info(
'Overpay API payment created',
merchant_transaction_id=merchant_transaction_id,
overpay_id=data.get('id'),
result_url=data.get('resultUrl'),
)
return data
error_msg = data.get('message') or data.get('error') or str(data)
logger.error(
'Overpay create_payment error',
status_code=response.status_code,
error_msg=error_msg,
response_data=data,
)
raise OverpayAPIError(response.status_code, error_msg)
except httpx.HTTPError as e:
logger.exception('Overpay API connection error', error=e)
raise
async def get_payment(self, order_id: str) -> dict[str, Any]:
"""
Получает информацию о платеже по ID.
GET {API_URL}/orders/{id}
"""
logger.info('Overpay get_payment', order_id=order_id)
try:
client = await self._get_client()
response = await client.get(
f'{self.api_url}/orders/{order_id}',
headers={'Content-Type': 'application/json'},
)
data = response.json()
if response.status_code == 200:
return data
error_msg = data.get('message') or data.get('error') or str(data)
logger.error(
'Overpay get_payment error',
status_code=response.status_code,
error_msg=error_msg,
)
raise OverpayAPIError(response.status_code, error_msg)
except httpx.HTTPError as e:
logger.exception('Overpay API connection error', error=e)
raise
async def refund_payment(self, order_id: str, amount: str) -> dict[str, Any]:
"""
Возврат платежа.
PUT {API_URL}/orders/{id}/refund
"""
logger.info('Overpay refund_payment', order_id=order_id, amount=amount)
try:
client = await self._get_client()
response = await client.put(
f'{self.api_url}/orders/{order_id}/refund',
json={'amount': amount},
headers={'Content-Type': 'application/json'},
)
data = response.json()
if response.status_code == 200:
logger.info('Overpay refund successful', order_id=order_id, amount=amount)
return data
error_msg = data.get('message') or data.get('error') or str(data)
logger.error(
'Overpay refund error',
status_code=response.status_code,
error_msg=error_msg,
)
raise OverpayAPIError(response.status_code, error_msg)
except httpx.HTTPError as e:
logger.exception('Overpay API connection error', error=e)
raise
# Singleton instance
overpay_service = OverpayService()
+2 -14
View File
@@ -1121,10 +1121,6 @@ class PartnerStatsService:
),
Transaction.amount_kopeks,
),
(
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
func.abs(Transaction.amount_kopeks),
),
else_=0,
)
),
@@ -1137,12 +1133,8 @@ class PartnerStatsService:
and_(
Transaction.user_id == User.id,
Transaction.is_completed.is_(True),
Transaction.type.in_(
[
TransactionType.DEPOSIT.value,
TransactionType.SUBSCRIPTION_PAYMENT.value,
]
),
Transaction.type == TransactionType.DEPOSIT.value,
Transaction.payment_method.in_(REAL_PAYMENT_METHODS),
),
)
.where(AdvertisingCampaignRegistration.campaign_id == campaign_id)
@@ -1159,10 +1151,6 @@ class PartnerStatsService:
),
Transaction.amount_kopeks,
),
(
Transaction.type == TransactionType.SUBSCRIPTION_PAYMENT.value,
func.abs(Transaction.amount_kopeks),
),
else_=0,
)
),
+8
View File
@@ -4,6 +4,7 @@
оставался компактным и импортировал только нужные компоненты.
"""
from .aurapay import AuraPayPaymentMixin
from .cloudpayments import CloudPaymentsPaymentMixin
from .common import PaymentCommonMixin
from .cryptobot import CryptoBotPaymentMixin
@@ -11,9 +12,12 @@ from .freekassa import FreekassaPaymentMixin
from .heleket import HeleketPaymentMixin
from .kassa_ai import KassaAiPaymentMixin
from .mulenpay import MulenPayPaymentMixin
from .overpay import OverpayPaymentMixin
from .pal24 import Pal24PaymentMixin
from .paypear import PayPearPaymentMixin
from .platega import PlategaPaymentMixin
from .riopay import RioPayPaymentMixin
from .rollypay import RollyPayPaymentMixin
from .severpay import SeverPayPaymentMixin
from .stars import TelegramStarsMixin
from .tribute import TributePaymentMixin
@@ -22,16 +26,20 @@ from .yookassa import YooKassaPaymentMixin
__all__ = [
'AuraPayPaymentMixin',
'CloudPaymentsPaymentMixin',
'CryptoBotPaymentMixin',
'FreekassaPaymentMixin',
'HeleketPaymentMixin',
'KassaAiPaymentMixin',
'MulenPayPaymentMixin',
'OverpayPaymentMixin',
'Pal24PaymentMixin',
'PayPearPaymentMixin',
'PaymentCommonMixin',
'PlategaPaymentMixin',
'RioPayPaymentMixin',
'RollyPayPaymentMixin',
'SeverPayPaymentMixin',
'TelegramStarsMixin',
'TributePaymentMixin',
+636
View File
@@ -0,0 +1,636 @@
"""Mixin для интеграции с AuraPay (aurapay.tech)."""
from __future__ import annotations
import uuid
from datetime import UTC, datetime, timedelta
from importlib import import_module
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import PaymentMethod, TransactionType
from app.services.aurapay_service import aurapay_service
from app.utils.payment_logger import payment_logger as logger
from app.utils.user_utils import format_referrer_info
# Маппинг статусов AuraPay -> internal
AURAPAY_STATUS_MAP: dict[str, tuple[str, bool]] = {
'PENDING': ('pending', False),
'PAID': ('success', True),
'EXPIRED': ('expired', False),
}
class AuraPayPaymentMixin:
"""Mixin для работы с платежами AuraPay."""
async def create_aurapay_payment(
self,
db: AsyncSession,
*,
user_id: int | None,
amount_kopeks: int,
description: str = 'Пополнение баланса',
email: str | None = None,
language: str = 'ru',
payment_method_type: str | None = None,
return_url: str | None = None,
) -> dict[str, Any] | None:
"""
Создает платеж AuraPay.
Returns:
Словарь с данными платежа или None при ошибке
"""
if not settings.is_aurapay_enabled():
logger.error('AuraPay не настроен')
return None
# Валидация лимитов
if amount_kopeks < settings.AURAPAY_MIN_AMOUNT_KOPEKS:
logger.warning(
'AuraPay: сумма меньше минимальной',
amount_kopeks=amount_kopeks,
AURAPAY_MIN_AMOUNT_KOPEKS=settings.AURAPAY_MIN_AMOUNT_KOPEKS,
)
return None
if amount_kopeks > settings.AURAPAY_MAX_AMOUNT_KOPEKS:
logger.warning(
'AuraPay: сумма больше максимальной',
amount_kopeks=amount_kopeks,
AURAPAY_MAX_AMOUNT_KOPEKS=settings.AURAPAY_MAX_AMOUNT_KOPEKS,
)
return None
# Получаем telegram_id пользователя для order_id
payment_module = import_module('app.services.payment_service')
if user_id is not None:
user = await payment_module.get_user_by_id(db, user_id)
tg_id = user.telegram_id if user else user_id
else:
user = None
tg_id = 'guest'
# Генерируем уникальный order_id с telegram_id для удобного поиска
order_id = f'ap{tg_id}_{uuid.uuid4().hex[:6]}'
amount_rubles = amount_kopeks / 100
currency = settings.AURAPAY_CURRENCY
# Метаданные
metadata = {
'user_id': user_id,
'amount_kopeks': amount_kopeks,
'description': description,
'language': language,
'type': 'balance_topup',
}
try:
# Формируем webhook URL
webhook_url = None
if settings.WEBHOOK_URL:
webhook_url = f'{settings.WEBHOOK_URL.rstrip("/")}{settings.AURAPAY_WEBHOOK_PATH}'
lifetime = settings.AURAPAY_PAYMENT_LIFETIME_MINUTES
# Используем API для создания инвойса
result = await aurapay_service.create_invoice(
amount=amount_rubles,
order_id=order_id,
comment=description,
service=payment_method_type,
success_url=return_url or settings.AURAPAY_RETURN_URL,
fail_url=return_url or settings.AURAPAY_RETURN_URL,
callback_url=webhook_url,
custom_fields=f'user_id={user_id}' if user_id else None,
lifetime=lifetime,
)
payment_data = result.get('payment_data', {})
payment_url = payment_data.get('url') if isinstance(payment_data, dict) else None
aurapay_invoice_id = result.get('id')
if not payment_url:
logger.error('AuraPay API не вернул URL платежа', result=result)
return None
logger.info(
'AuraPay API: создан инвойс',
order_id=order_id,
aurapay_invoice_id=aurapay_invoice_id,
payment_url=payment_url,
)
# Срок действия из expires_at ответа или lifetime минут по умолчанию
expires_at_str = result.get('expires_at')
if expires_at_str:
try:
expires_at = datetime.fromisoformat(expires_at_str)
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=UTC)
except (ValueError, TypeError):
expires_at = datetime.now(UTC) + timedelta(minutes=lifetime)
else:
expires_at = datetime.now(UTC) + timedelta(minutes=lifetime)
# Сохраняем в БД
aurapay_crud = import_module('app.database.crud.aurapay')
local_payment = await aurapay_crud.create_aurapay_payment(
db=db,
user_id=user_id,
order_id=order_id,
amount_kopeks=amount_kopeks,
currency=currency,
description=description,
payment_url=payment_url,
payment_method=payment_method_type,
aurapay_invoice_id=aurapay_invoice_id,
expires_at=expires_at,
metadata_json=metadata,
)
logger.info(
'AuraPay: создан платеж',
order_id=order_id,
user_id=user_id,
amount_rubles=amount_rubles,
currency=currency,
)
return {
'order_id': order_id,
'aurapay_invoice_id': aurapay_invoice_id,
'amount_kopeks': amount_kopeks,
'amount_rubles': amount_rubles,
'currency': currency,
'payment_url': payment_url,
'expires_at': expires_at.isoformat(),
'local_payment_id': local_payment.id,
}
except Exception as e:
logger.exception('AuraPay: ошибка создания платежа', error=e)
return None
async def process_aurapay_webhook(
self,
db: AsyncSession,
payload: dict[str, Any],
) -> bool:
"""
Обрабатывает webhook от AuraPay.
Подпись проверяется в webserver/payments.py до вызова этого метода.
Args:
db: Сессия БД
payload: JSON тело webhook (signature проверена в webserver)
Returns:
True если платеж успешно обработан
"""
try:
aurapay_invoice_id = payload.get('id')
order_id = payload.get('order_id')
aurapay_status = payload.get('status')
if not aurapay_invoice_id or not aurapay_status:
logger.warning('AuraPay webhook: отсутствуют обязательные поля', payload=payload)
return False
# Определяем is_paid по статусу
is_confirmed = aurapay_status == 'PAID'
# Ищем платеж по order_id (наш) или aurapay_invoice_id
aurapay_crud = import_module('app.database.crud.aurapay')
payment = None
if order_id:
payment = await aurapay_crud.get_aurapay_payment_by_order_id(db, str(order_id))
if not payment and aurapay_invoice_id:
payment = await aurapay_crud.get_aurapay_payment_by_invoice_id(db, aurapay_invoice_id)
if not payment:
logger.warning(
'AuraPay webhook: платеж не найден',
order_id=order_id,
aurapay_invoice_id=aurapay_invoice_id,
)
return False
# Lock payment row immediately to prevent concurrent webhook processing (TOCTOU race)
locked = await aurapay_crud.get_aurapay_payment_by_id_for_update(db, payment.id)
if not locked:
logger.error('AuraPay: не удалось заблокировать платёж', payment_id=payment.id)
return False
payment = locked
# Проверка дублирования (re-check from locked row)
if payment.is_paid:
logger.info('AuraPay webhook: платеж уже обработан', order_id=payment.order_id)
return True
# Маппинг статуса
status_info = AURAPAY_STATUS_MAP.get(aurapay_status, ('pending', False))
internal_status, is_paid = status_info
# Если статус PAID, принудительно считаем оплаченным
if is_confirmed:
is_paid = True
internal_status = 'success'
callback_payload = {
'aurapay_invoice_id': aurapay_invoice_id,
'order_id': order_id,
'status': aurapay_status,
'amount': payload.get('amount'),
'service': payload.get('service'),
'payer_details': payload.get('payer_details'),
}
# Проверка суммы ДО обновления статуса
# AuraPay отправляет amount как строку "1250.00"
if is_paid:
amount_value = payload.get('amount')
if amount_value is not None:
received_kopeks = round(float(amount_value) * 100)
if abs(received_kopeks - payment.amount_kopeks) > 1:
logger.error(
'AuraPay amount mismatch',
expected_kopeks=payment.amount_kopeks,
received_kopeks=received_kopeks,
order_id=payment.order_id,
)
await aurapay_crud.update_aurapay_payment_status(
db=db,
payment=payment,
status='amount_mismatch',
is_paid=False,
aurapay_invoice_id=aurapay_invoice_id,
callback_payload=callback_payload,
)
return False
# Финализируем платеж если оплачен — без промежуточного commit
if is_paid:
# Inline field assignments to keep FOR UPDATE lock intact
payment.status = internal_status
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.aurapay_invoice_id = aurapay_invoice_id or payment.aurapay_invoice_id
payment.callback_payload = callback_payload
payment.updated_at = datetime.now(UTC)
await db.flush()
return await self._finalize_aurapay_payment(
db, payment, aurapay_invoice_id=aurapay_invoice_id, trigger='webhook'
)
# Для не-success статусов можно безопасно коммитить
payment = await aurapay_crud.update_aurapay_payment_status(
db=db,
payment=payment,
status=internal_status,
is_paid=False,
aurapay_invoice_id=aurapay_invoice_id,
callback_payload=callback_payload,
)
return True
except Exception as e:
logger.exception('AuraPay webhook: ошибка обработки', error=e)
return False
async def _finalize_aurapay_payment(
self,
db: AsyncSession,
payment: Any,
*,
aurapay_invoice_id: str | None,
trigger: str,
) -> bool:
"""Создаёт транзакцию, начисляет баланс и отправляет уведомления.
FOR UPDATE lock must be acquired by the caller before invoking this method.
"""
payment_module = import_module('app.services.payment_service')
aurapay_crud = import_module('app.database.crud.aurapay')
# FOR UPDATE lock already acquired by caller — just check idempotency
if payment.transaction_id:
logger.info(
'AuraPay платеж уже связан с транзакцией',
order_id=payment.order_id,
transaction_id=payment.transaction_id,
trigger=trigger,
)
return True
# Read fresh metadata AFTER lock to avoid stale data
metadata = dict(getattr(payment, 'metadata_json', {}) or {})
# --- Guest purchase flow ---
from app.services.payment.common import try_fulfill_guest_purchase
guest_result = await try_fulfill_guest_purchase(
db,
metadata=metadata,
payment_amount_kopeks=payment.amount_kopeks,
provider_payment_id=str(aurapay_invoice_id) if aurapay_invoice_id else payment.order_id,
provider_name='aurapay',
)
if guest_result is not None:
return True
# Ensure paid fields are set (idempotent — caller may have already set them)
if not payment.is_paid:
payment.status = 'success'
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.updated_at = datetime.now(UTC)
balance_already_credited = bool(metadata.get('balance_credited'))
user = await payment_module.get_user_by_id(db, payment.user_id)
if not user:
logger.error('Пользователь не найден для AuraPay', user_id=payment.user_id)
return False
# Загружаем промогруппы в асинхронном контексте
await db.refresh(user, attribute_names=['promo_group', 'user_promo_groups'])
for user_promo_group in getattr(user, 'user_promo_groups', []):
await db.refresh(user_promo_group, attribute_names=['promo_group'])
promo_group = user.get_primary_promo_group()
subscription = getattr(user, 'subscription', None)
referrer_info = format_referrer_info(user)
transaction_external_id = str(aurapay_invoice_id) if aurapay_invoice_id else payment.order_id
# Проверяем дупликат транзакции
existing_transaction = None
if transaction_external_id:
existing_transaction = await payment_module.get_transaction_by_external_id(
db,
transaction_external_id,
PaymentMethod.AURAPAY,
)
display_name = settings.get_aurapay_display_name()
description = f'Пополнение через {display_name}'
transaction = existing_transaction
created_transaction = False
if not transaction:
transaction = await payment_module.create_transaction(
db,
user_id=payment.user_id,
type=TransactionType.DEPOSIT,
amount_kopeks=payment.amount_kopeks,
description=description,
payment_method=PaymentMethod.AURAPAY,
external_id=transaction_external_id,
is_completed=True,
created_at=getattr(payment, 'created_at', None),
commit=False,
)
created_transaction = True
await aurapay_crud.link_aurapay_payment_to_transaction(db, payment=payment, transaction_id=transaction.id)
should_credit_balance = created_transaction or not balance_already_credited
if not should_credit_balance:
logger.info('AuraPay платеж уже зачислил баланс ранее', order_id=payment.order_id)
return True
# Lock user row to prevent concurrent balance race conditions
from app.database.crud.user import lock_user_for_update
user = await lock_user_for_update(db, user)
old_balance = user.balance_kopeks
was_first_topup = not user.has_made_first_topup
user.balance_kopeks += payment.amount_kopeks
user.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(user)
# Emit deferred side-effects after atomic commit
from app.database.crud.transaction import emit_transaction_side_effects
await emit_transaction_side_effects(
db,
transaction,
amount_kopeks=payment.amount_kopeks,
user_id=payment.user_id,
type=TransactionType.DEPOSIT,
payment_method=PaymentMethod.AURAPAY,
external_id=transaction_external_id,
)
topup_status = '\U0001f195 Первое пополнение' if was_first_topup else '\U0001f504 Пополнение'
try:
from app.services.referral_service import process_referral_topup
await process_referral_topup(
db,
user.id,
payment.amount_kopeks,
getattr(self, 'bot', None),
)
except Exception as error:
logger.error('Ошибка обработки реферального пополнения AuraPay', error=error)
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
await db.refresh(user)
if getattr(self, 'bot', None):
try:
from app.services.admin_notification_service import AdminNotificationService
notification_service = AdminNotificationService(self.bot)
await notification_service.send_balance_topup_notification(
user,
transaction,
old_balance,
topup_status=topup_status,
referrer_info=referrer_info,
subscription=subscription,
promo_group=promo_group,
db=db,
)
except Exception as error:
logger.error('Ошибка отправки админ уведомления AuraPay', error=error)
if getattr(self, 'bot', None) and user.telegram_id:
try:
keyboard = await self.build_topup_success_keyboard(user)
await self.bot.send_message(
user.telegram_id,
(
'\u2705 <b>Пополнение успешно!</b>\n\n'
f'\U0001f4b0 Сумма: {settings.format_price(payment.amount_kopeks)}\n'
f'\U0001f4b3 Способ: {display_name}\n'
f'\U0001f194 Транзакция: {transaction.id}\n\n'
'Баланс пополнен автоматически!'
),
parse_mode='HTML',
reply_markup=keyboard,
)
except Exception as error:
logger.error('Ошибка отправки уведомления пользователю AuraPay', error=error)
try:
from app.services.payment.common import send_cart_notification_after_topup
await send_cart_notification_after_topup(user, payment.amount_kopeks, db, getattr(self, 'bot', None))
except Exception as error:
logger.error(
'Ошибка при работе с сохраненной корзиной для пользователя',
user_id=payment.user_id,
error=error,
exc_info=True,
)
metadata['balance_change'] = {
'old_balance': old_balance,
'new_balance': user.balance_kopeks,
'credited_at': datetime.now(UTC).isoformat(),
}
metadata['balance_credited'] = True
payment.metadata_json = metadata
await db.commit()
logger.info(
'Обработан AuraPay платеж',
order_id=payment.order_id,
user_id=payment.user_id,
trigger=trigger,
)
return True
async def check_aurapay_payment_status(
self,
db: AsyncSession,
order_id: str,
) -> dict[str, Any] | None:
"""Проверяет статус платежа через API."""
try:
aurapay_crud = import_module('app.database.crud.aurapay')
payment = await aurapay_crud.get_aurapay_payment_by_order_id(db, order_id)
if not payment:
logger.warning('AuraPay payment not found', order_id=order_id)
return None
if payment.is_paid:
return {
'payment': payment,
'status': 'success',
'is_paid': True,
}
# Проверяем через API по aurapay_invoice_id или order_id
try:
order_data = await aurapay_service.get_invoice_status(
order_id=payment.order_id,
invoice_id=payment.aurapay_invoice_id,
)
aurapay_status = order_data.get('status')
if aurapay_status:
status_info = AURAPAY_STATUS_MAP.get(aurapay_status, ('pending', False))
internal_status, is_paid = status_info
if is_paid:
# Проверка суммы — AuraPay возвращает amount как число
api_amount = order_data.get('amount')
if api_amount is not None:
received_kopeks = round(float(api_amount) * 100)
if abs(received_kopeks - payment.amount_kopeks) > 1:
logger.error(
'AuraPay amount mismatch (API check)',
expected_kopeks=payment.amount_kopeks,
received_kopeks=received_kopeks,
order_id=payment.order_id,
)
await aurapay_crud.update_aurapay_payment_status(
db=db,
payment=payment,
status='amount_mismatch',
is_paid=False,
aurapay_invoice_id=payment.aurapay_invoice_id,
callback_payload={
'check_source': 'api',
'aurapay_order_data': order_data,
},
)
return {
'payment': payment,
'status': 'amount_mismatch',
'is_paid': False,
}
# Acquire FOR UPDATE lock before finalization
locked = await aurapay_crud.get_aurapay_payment_by_id_for_update(db, payment.id)
if not locked:
logger.error('AuraPay: не удалось заблокировать платёж', payment_id=payment.id)
return None
payment = locked
if payment.is_paid:
logger.info('AuraPay платеж уже обработан (api_check)', order_id=payment.order_id)
return {
'payment': payment,
'status': 'success',
'is_paid': True,
}
logger.info('AuraPay payment confirmed via API', order_id=payment.order_id)
# Inline field updates — NO intermediate commit that would release FOR UPDATE lock
payment.status = 'success'
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.callback_payload = {
'check_source': 'api',
'aurapay_order_data': order_data,
}
payment.updated_at = datetime.now(UTC)
await db.flush()
await self._finalize_aurapay_payment(
db,
payment,
aurapay_invoice_id=payment.aurapay_invoice_id,
trigger='api_check',
)
elif internal_status != payment.status:
# Обновляем статус если изменился
payment = await aurapay_crud.update_aurapay_payment_status(
db=db,
payment=payment,
status=internal_status,
)
except Exception as e:
logger.error('Error checking AuraPay payment status via API', error=e)
return {
'payment': payment,
'status': payment.status or 'pending',
'is_paid': payment.is_paid,
}
except Exception as e:
logger.exception('AuraPay: ошибка проверки статуса', error=e)
return None
+567
View File
@@ -0,0 +1,567 @@
"""Mixin для интеграции с Overpay (pay.overpay.io)."""
from __future__ import annotations
import uuid
from datetime import UTC, datetime, timedelta
from importlib import import_module
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import PaymentMethod, TransactionType
from app.services.overpay_service import overpay_service
from app.utils.payment_logger import payment_logger as logger
from app.utils.user_utils import format_referrer_info
# Маппинг статусов Overpay -> internal
OVERPAY_STATUS_MAP: dict[str, tuple[str, bool]] = {
'charged': ('success', True),
'authorized': ('authorized', False),
'preflight': ('pending', False),
'new': ('pending', False),
'processing': ('processing', False),
'prepared': ('processing', False),
'rejected': ('rejected', False),
'declined': ('declined', False),
'reversed': ('reversed', False),
'refunded': ('refunded', False),
'chargeback': ('chargeback', False),
'error': ('error', False),
}
class OverpayPaymentMixin:
"""Mixin для работы с платежами Overpay."""
async def create_overpay_payment(
self,
db: AsyncSession,
*,
user_id: int | None,
amount_kopeks: int,
description: str = 'Пополнение баланса',
email: str | None = None,
language: str = 'ru',
return_url: str | None = None,
) -> dict[str, Any] | None:
"""
Создает платеж Overpay.
Returns:
Словарь с данными платежа или None при ошибке
"""
if not settings.is_overpay_enabled():
logger.error('Overpay не настроен')
return None
# Валидация лимитов
if amount_kopeks < settings.OVERPAY_MIN_AMOUNT_KOPEKS:
logger.warning(
'Overpay: сумма меньше минимальной',
amount_kopeks=amount_kopeks,
OVERPAY_MIN_AMOUNT_KOPEKS=settings.OVERPAY_MIN_AMOUNT_KOPEKS,
)
return None
if amount_kopeks > settings.OVERPAY_MAX_AMOUNT_KOPEKS:
logger.warning(
'Overpay: сумма больше максимальной',
amount_kopeks=amount_kopeks,
OVERPAY_MAX_AMOUNT_KOPEKS=settings.OVERPAY_MAX_AMOUNT_KOPEKS,
)
return None
# Получаем telegram_id пользователя для order_id
payment_module = import_module('app.services.payment_service')
if user_id is not None:
user = await payment_module.get_user_by_id(db, user_id)
tg_id = user.telegram_id if user else user_id
else:
user = None
tg_id = 'guest'
# Генерируем уникальный order_id с telegram_id для удобного поиска
order_id = f'op{tg_id}_{uuid.uuid4().hex[:6]}'
amount_rubles = amount_kopeks / 100
amount_value = f'{amount_rubles:.2f}'
currency = settings.OVERPAY_CURRENCY
# Метаданные
metadata = {
'user_id': user_id,
'amount_kopeks': amount_kopeks,
'description': description,
'language': language,
'type': 'balance_topup',
}
# Методы оплаты из настроек
payment_methods_str = settings.OVERPAY_PAYMENT_METHODS
payment_methods = (
[m.strip() for m in payment_methods_str.split(',') if m.strip()] if payment_methods_str else None
)
try:
# Используем API для создания платежа
result = await overpay_service.create_payment(
amount=amount_value,
currency=currency,
lifetime_minutes=settings.OVERPAY_LIFETIME_MINUTES,
merchant_transaction_id=order_id,
description=description,
return_url=return_url or settings.OVERPAY_RETURN_URL,
payment_methods=payment_methods,
)
payment_url = result.get('resultUrl')
overpay_payment_id = str(result.get('id', '')) if result.get('id') else None
if not payment_url:
logger.error('Overpay API не вернул URL платежа', result=result)
return None
logger.info(
'Overpay API: создан платеж',
order_id=order_id,
overpay_payment_id=overpay_payment_id,
payment_url=payment_url,
)
# Срок действия
expires_at = datetime.now(UTC) + timedelta(minutes=settings.OVERPAY_LIFETIME_MINUTES)
# Сохраняем в БД
overpay_crud = import_module('app.database.crud.overpay')
local_payment = await overpay_crud.create_overpay_payment(
db=db,
user_id=user_id,
order_id=order_id,
amount_kopeks=amount_kopeks,
currency=currency,
description=description,
payment_url=payment_url,
overpay_payment_id=overpay_payment_id,
expires_at=expires_at,
metadata_json=metadata,
)
logger.info(
'Overpay: создан платеж',
order_id=order_id,
user_id=user_id,
amount_rubles=amount_rubles,
currency=currency,
)
return {
'order_id': order_id,
'overpay_payment_id': overpay_payment_id,
'amount_kopeks': amount_kopeks,
'amount_rubles': amount_rubles,
'currency': currency,
'payment_url': payment_url,
'expires_at': expires_at.isoformat(),
'local_payment_id': local_payment.id,
}
except Exception as e:
logger.exception('Overpay: ошибка создания платежа', error=e)
return None
async def process_overpay_webhook(
self,
db: AsyncSession,
payload: dict[str, Any],
) -> bool:
"""
Обрабатывает webhook от Overpay.
mTLS обеспечивает аутентификацию; дополнительно проверяем наличие платежа в БД.
Args:
db: Сессия БД
payload: JSON тело webhook
Returns:
True если платеж успешно обработан
"""
try:
overpay_payment_id = str(payload.get('id', '')) if payload.get('id') else None
merchant_transaction_id = payload.get('merchantTransactionId')
overpay_status = payload.get('status')
if not overpay_payment_id or not overpay_status:
logger.warning('Overpay webhook: отсутствуют обязательные поля', payload=payload)
return False
# Ищем платеж по order_id (наш merchantTransactionId) или overpay_payment_id
overpay_crud = import_module('app.database.crud.overpay')
payment = None
if merchant_transaction_id:
payment = await overpay_crud.get_overpay_payment_by_order_id(db, merchant_transaction_id)
if not payment and overpay_payment_id:
payment = await overpay_crud.get_overpay_payment_by_overpay_id(db, overpay_payment_id)
if not payment:
logger.warning(
'Overpay webhook: платеж не найден',
merchant_transaction_id=merchant_transaction_id,
overpay_payment_id=overpay_payment_id,
)
return False
# Lock payment row immediately to prevent concurrent webhook processing (TOCTOU race)
locked = await overpay_crud.get_overpay_payment_by_id_for_update(db, payment.id)
if not locked:
logger.error('Overpay: не удалось заблокировать платёж', payment_id=payment.id)
return False
payment = locked
# Проверка дублирования (re-check from locked row)
if payment.is_paid:
logger.info('Overpay webhook: платеж уже обработан', order_id=payment.order_id)
return True
# Маппинг статуса
status_info = OVERPAY_STATUS_MAP.get(overpay_status, ('pending', False))
internal_status, is_paid = status_info
callback_payload = {
'overpay_payment_id': overpay_payment_id,
'merchant_transaction_id': merchant_transaction_id,
'status': overpay_status,
}
# Финализируем платеж если оплачен — без промежуточного commit
if is_paid:
# Inline field assignments to keep FOR UPDATE lock intact
payment.status = internal_status
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.overpay_payment_id = overpay_payment_id or payment.overpay_payment_id
payment.callback_payload = callback_payload
payment.updated_at = datetime.now(UTC)
await db.flush()
return await self._finalize_overpay_payment(
db, payment, overpay_payment_id=overpay_payment_id, trigger='webhook'
)
# Для не-success статусов можно безопасно коммитить
payment = await overpay_crud.update_overpay_payment_status(
db=db,
payment=payment,
status=internal_status,
is_paid=False,
overpay_payment_id=overpay_payment_id,
callback_payload=callback_payload,
)
return True
except Exception as e:
logger.exception('Overpay webhook: ошибка обработки', error=e)
return False
async def _finalize_overpay_payment(
self,
db: AsyncSession,
payment: Any,
*,
overpay_payment_id: str | None,
trigger: str,
) -> bool:
"""Создаёт транзакцию, начисляет баланс и отправляет уведомления.
FOR UPDATE lock must be acquired by the caller before invoking this method.
"""
payment_module = import_module('app.services.payment_service')
overpay_crud = import_module('app.database.crud.overpay')
# FOR UPDATE lock already acquired by caller — just check idempotency
if payment.transaction_id:
logger.info(
'Overpay платеж уже связан с транзакцией',
order_id=payment.order_id,
transaction_id=payment.transaction_id,
trigger=trigger,
)
return True
# Read fresh metadata AFTER lock to avoid stale data
metadata = dict(getattr(payment, 'metadata_json', {}) or {})
# --- Guest purchase flow ---
from app.services.payment.common import try_fulfill_guest_purchase
guest_result = await try_fulfill_guest_purchase(
db,
metadata=metadata,
payment_amount_kopeks=payment.amount_kopeks,
provider_payment_id=str(overpay_payment_id) if overpay_payment_id else payment.order_id,
provider_name='overpay',
)
if guest_result is not None:
return True
# Ensure paid fields are set (idempotent — caller may have already set them)
if not payment.is_paid:
payment.status = 'success'
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.updated_at = datetime.now(UTC)
balance_already_credited = bool(metadata.get('balance_credited'))
user = await payment_module.get_user_by_id(db, payment.user_id)
if not user:
logger.error('Пользователь не найден для Overpay', user_id=payment.user_id)
return False
# Загружаем промогруппы в асинхронном контексте
await db.refresh(user, attribute_names=['promo_group', 'user_promo_groups'])
for user_promo_group in getattr(user, 'user_promo_groups', []):
await db.refresh(user_promo_group, attribute_names=['promo_group'])
promo_group = user.get_primary_promo_group()
subscription = getattr(user, 'subscription', None)
referrer_info = format_referrer_info(user)
transaction_external_id = str(overpay_payment_id) if overpay_payment_id else payment.order_id
# Проверяем дупликат транзакции
existing_transaction = None
if transaction_external_id:
existing_transaction = await payment_module.get_transaction_by_external_id(
db,
transaction_external_id,
PaymentMethod.OVERPAY,
)
display_name = settings.get_overpay_display_name()
description = f'Пополнение через {display_name}'
transaction = existing_transaction
created_transaction = False
if not transaction:
transaction = await payment_module.create_transaction(
db,
user_id=payment.user_id,
type=TransactionType.DEPOSIT,
amount_kopeks=payment.amount_kopeks,
description=description,
payment_method=PaymentMethod.OVERPAY,
external_id=transaction_external_id,
is_completed=True,
created_at=getattr(payment, 'created_at', None),
commit=False,
)
created_transaction = True
await overpay_crud.link_overpay_payment_to_transaction(db, payment=payment, transaction_id=transaction.id)
should_credit_balance = created_transaction or not balance_already_credited
if not should_credit_balance:
logger.info('Overpay платеж уже зачислил баланс ранее', order_id=payment.order_id)
return True
# Lock user row to prevent concurrent balance race conditions
from app.database.crud.user import lock_user_for_update
user = await lock_user_for_update(db, user)
old_balance = user.balance_kopeks
was_first_topup = not user.has_made_first_topup
user.balance_kopeks += payment.amount_kopeks
user.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(user)
# Emit deferred side-effects after atomic commit
from app.database.crud.transaction import emit_transaction_side_effects
await emit_transaction_side_effects(
db,
transaction,
amount_kopeks=payment.amount_kopeks,
user_id=payment.user_id,
type=TransactionType.DEPOSIT,
payment_method=PaymentMethod.OVERPAY,
external_id=transaction_external_id,
)
topup_status = '\U0001f195 Первое пополнение' if was_first_topup else '\U0001f504 Пополнение'
try:
from app.services.referral_service import process_referral_topup
await process_referral_topup(
db,
user.id,
payment.amount_kopeks,
getattr(self, 'bot', None),
)
except Exception as error:
logger.error('Ошибка обработки реферального пополнения Overpay', error=error)
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
await db.refresh(user)
if getattr(self, 'bot', None):
try:
from app.services.admin_notification_service import AdminNotificationService
notification_service = AdminNotificationService(self.bot)
await notification_service.send_balance_topup_notification(
user,
transaction,
old_balance,
topup_status=topup_status,
referrer_info=referrer_info,
subscription=subscription,
promo_group=promo_group,
db=db,
)
except Exception as error:
logger.error('Ошибка отправки админ уведомления Overpay', error=error)
if getattr(self, 'bot', None) and user.telegram_id:
try:
keyboard = await self.build_topup_success_keyboard(user)
await self.bot.send_message(
user.telegram_id,
(
'\u2705 <b>Пополнение успешно!</b>\n\n'
f'\U0001f4b0 Сумма: {settings.format_price(payment.amount_kopeks)}\n'
f'\U0001f4b3 Способ: {display_name}\n'
f'\U0001f194 Транзакция: {transaction.id}\n\n'
'Баланс пополнен автоматически!'
),
parse_mode='HTML',
reply_markup=keyboard,
)
except Exception as error:
logger.error('Ошибка отправки уведомления пользователю Overpay', error=error)
try:
from app.services.payment.common import send_cart_notification_after_topup
await send_cart_notification_after_topup(user, payment.amount_kopeks, db, getattr(self, 'bot', None))
except Exception as error:
logger.error(
'Ошибка при работе с сохраненной корзиной для пользователя',
user_id=payment.user_id,
error=error,
exc_info=True,
)
metadata['balance_change'] = {
'old_balance': old_balance,
'new_balance': user.balance_kopeks,
'credited_at': datetime.now(UTC).isoformat(),
}
metadata['balance_credited'] = True
payment.metadata_json = metadata
await db.commit()
logger.info(
'Обработан Overpay платеж',
order_id=payment.order_id,
user_id=payment.user_id,
trigger=trigger,
)
return True
async def check_overpay_payment_status(
self,
db: AsyncSession,
order_id: str,
) -> dict[str, Any] | None:
"""Проверяет статус платежа через API."""
try:
overpay_crud = import_module('app.database.crud.overpay')
payment = await overpay_crud.get_overpay_payment_by_order_id(db, order_id)
if not payment:
logger.warning('Overpay payment not found', order_id=order_id)
return None
if payment.is_paid:
return {
'payment': payment,
'status': 'success',
'is_paid': True,
}
# Проверяем через API по overpay_payment_id
if payment.overpay_payment_id:
try:
order_data = await overpay_service.get_payment(payment.overpay_payment_id)
overpay_status = order_data.get('status')
if overpay_status:
status_info = OVERPAY_STATUS_MAP.get(overpay_status, ('pending', False))
internal_status, is_paid = status_info
if is_paid:
# Acquire FOR UPDATE lock before finalization
locked = await overpay_crud.get_overpay_payment_by_id_for_update(db, payment.id)
if not locked:
logger.error('Overpay: не удалось заблокировать платёж', payment_id=payment.id)
return None
payment = locked
if payment.is_paid:
logger.info('Overpay платеж уже обработан (api_check)', order_id=payment.order_id)
return {
'payment': payment,
'status': 'success',
'is_paid': True,
}
logger.info('Overpay payment confirmed via API', order_id=payment.order_id)
# Inline field updates — NO intermediate commit that would release FOR UPDATE lock
payment.status = 'success'
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.callback_payload = {
'check_source': 'api',
'overpay_order_data': order_data,
}
payment.updated_at = datetime.now(UTC)
await db.flush()
await self._finalize_overpay_payment(
db,
payment,
overpay_payment_id=payment.overpay_payment_id,
trigger='api_check',
)
elif internal_status != payment.status:
# Обновляем статус если изменился
payment = await overpay_crud.update_overpay_payment_status(
db=db,
payment=payment,
status=internal_status,
)
except Exception as e:
logger.error('Error checking Overpay payment status via API', error=e)
return {
'payment': payment,
'status': payment.status or 'pending',
'is_paid': payment.is_paid,
}
except Exception as e:
logger.exception('Overpay: ошибка проверки статуса', error=e)
return None
+4 -4
View File
@@ -558,8 +558,8 @@ class Pal24PaymentMixin:
payment_id_str = str(payment.payment_id)
try:
payment_response = await service.get_payment_status(payment_id_str)
except Pal24APIError as error:
logger.error('Ошибка Pal24 API при получении статуса платежа', error=error)
except Pal24APIError:
logger.debug('Pal24 payment_id не найден или невалиден', payment_id=payment_id_str)
else:
if payment_response:
remote_payloads['payment_status'] = payment_response
@@ -569,8 +569,8 @@ class Pal24PaymentMixin:
try:
payments_response = await service.get_bill_payments(bill_id_str)
except Pal24APIError as error:
logger.error('Ошибка Pal24 API при получении списка платежей', error=error)
except Pal24APIError:
logger.debug('Pal24 bill payments не найдены', bill_id=bill_id_str)
else:
if payments_response:
remote_payloads['bill_payments'] = payments_response
+645
View File
@@ -0,0 +1,645 @@
"""Mixin для интеграции с PayPear (paypear.ru)."""
from __future__ import annotations
import uuid
from datetime import UTC, datetime, timedelta
from importlib import import_module
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import PaymentMethod, TransactionType
from app.services.paypear_service import paypear_service
from app.utils.payment_logger import payment_logger as logger
from app.utils.user_utils import format_referrer_info
# Маппинг статусов PayPear -> internal
PAYPEAR_STATUS_MAP: dict[str, tuple[str, bool]] = {
'NEW': ('pending', False),
'PROCESS': ('processing', False),
'CONFIRMED': ('success', True),
'CANCELED': ('canceled', False),
'REFUNDED': ('refunded', False),
'EXPIRED': ('expired', False),
}
class PayPearPaymentMixin:
"""Mixin для работы с платежами PayPear."""
async def create_paypear_payment(
self,
db: AsyncSession,
*,
user_id: int | None,
amount_kopeks: int,
description: str = 'Пополнение баланса',
email: str | None = None,
language: str = 'ru',
return_url: str | None = None,
) -> dict[str, Any] | None:
"""
Создает платеж PayPear.
Returns:
Словарь с данными платежа или None при ошибке
"""
if not settings.is_paypear_enabled():
logger.error('PayPear не настроен')
return None
# Валидация лимитов
if amount_kopeks < settings.PAYPEAR_MIN_AMOUNT_KOPEKS:
logger.warning(
'PayPear: сумма меньше минимальной',
amount_kopeks=amount_kopeks,
PAYPEAR_MIN_AMOUNT_KOPEKS=settings.PAYPEAR_MIN_AMOUNT_KOPEKS,
)
return None
if amount_kopeks > settings.PAYPEAR_MAX_AMOUNT_KOPEKS:
logger.warning(
'PayPear: сумма больше максимальной',
amount_kopeks=amount_kopeks,
PAYPEAR_MAX_AMOUNT_KOPEKS=settings.PAYPEAR_MAX_AMOUNT_KOPEKS,
)
return None
# Получаем telegram_id пользователя для order_id
payment_module = import_module('app.services.payment_service')
if user_id is not None:
user = await payment_module.get_user_by_id(db, user_id)
tg_id = user.telegram_id if user else user_id
else:
user = None
tg_id = 'guest'
# Генерируем уникальный order_id с telegram_id для удобного поиска
order_id = f'pp{tg_id}_{uuid.uuid4().hex[:6]}'
amount_rubles = amount_kopeks / 100
currency = settings.PAYPEAR_CURRENCY
# Метаданные
metadata = {
'user_id': user_id,
'amount_kopeks': amount_kopeks,
'description': description,
'language': language,
'type': 'balance_topup',
}
try:
payment_method_type = settings.PAYPEAR_PAYMENT_METHOD
# Используем API для создания платежа
result = await paypear_service.create_payment(
order_id=order_id,
amount_rubles=amount_rubles,
currency=currency,
payment_method_type=payment_method_type,
description=description,
return_url=return_url or settings.PAYPEAR_RETURN_URL,
metadata=metadata,
)
confirmation = result.get('confirmation', {})
payment_url = (
(confirmation.get('confirmation_url') or confirmation.get('url'))
if isinstance(confirmation, dict)
else None
)
paypear_id = result.get('id')
if not payment_url:
logger.error('PayPear API не вернул confirmation_url', result=result)
return None
# PayPear может добавить комиссию к сумме — сохраняем фактическую сумму
# для корректной проверки в webhook (amount включает комиссию)
api_amount = result.get('amount', {})
if isinstance(api_amount, dict) and api_amount.get('value') is not None:
charged_kopeks = round(float(api_amount['value']) * 100)
metadata['paypear_charged_kopeks'] = charged_kopeks
logger.info(
'PayPear API: создан платеж',
order_id=order_id,
paypear_id=paypear_id,
payment_url=payment_url,
charged_kopeks=metadata.get('paypear_charged_kopeks'),
)
# Срок действия — 30 минут по умолчанию
expires_at = datetime.now(UTC) + timedelta(minutes=30)
# Сохраняем в БД
paypear_crud = import_module('app.database.crud.paypear')
local_payment = await paypear_crud.create_paypear_payment(
db=db,
user_id=user_id,
order_id=order_id,
amount_kopeks=amount_kopeks,
currency=currency,
description=description,
payment_url=payment_url,
payment_method=payment_method_type,
paypear_id=paypear_id,
expires_at=expires_at,
metadata_json=metadata,
)
logger.info(
'PayPear: создан платеж',
order_id=order_id,
user_id=user_id,
amount_rubles=amount_rubles,
currency=currency,
)
return {
'order_id': order_id,
'paypear_id': paypear_id,
'amount_kopeks': amount_kopeks,
'amount_rubles': amount_rubles,
'currency': currency,
'payment_url': payment_url,
'expires_at': expires_at.isoformat(),
'local_payment_id': local_payment.id,
}
except Exception as e:
logger.exception('PayPear: ошибка создания платежа', error=e)
return None
async def process_paypear_webhook(
self,
db: AsyncSession,
payload: dict[str, Any],
) -> bool:
"""
Обрабатывает webhook от PayPear.
Подпись проверяется в webserver/payments.py до вызова этого метода.
Args:
db: Сессия БД
payload: JSON тело webhook (signature проверена в webserver)
Returns:
True если платеж успешно обработан
"""
try:
event = payload.get('event')
obj = payload.get('object', {})
paypear_id = obj.get('id')
order_id = obj.get('order_id')
paypear_status = obj.get('status')
if not paypear_id or not paypear_status:
logger.warning('PayPear webhook: отсутствуют обязательные поля', payload=payload)
return False
# Определяем is_paid по event
is_confirmed = event == 'payment.confirmed'
# Ищем платеж по order_id (наш) или paypear_id
paypear_crud = import_module('app.database.crud.paypear')
payment = None
if order_id:
payment = await paypear_crud.get_paypear_payment_by_order_id(db, order_id)
if not payment and paypear_id:
payment = await paypear_crud.get_paypear_payment_by_paypear_id(db, paypear_id)
if not payment:
logger.warning(
'PayPear webhook: платеж не найден',
order_id=order_id,
paypear_id=paypear_id,
)
return False
# Lock payment row immediately to prevent concurrent webhook processing (TOCTOU race)
locked = await paypear_crud.get_paypear_payment_by_id_for_update(db, payment.id)
if not locked:
logger.error('PayPear: не удалось заблокировать платёж', payment_id=payment.id)
return False
payment = locked
# Проверка дублирования (re-check from locked row)
if payment.is_paid:
logger.info('PayPear webhook: платеж уже обработан', order_id=payment.order_id)
return True
# Маппинг статуса
status_info = PAYPEAR_STATUS_MAP.get(paypear_status, ('pending', False))
internal_status, is_paid = status_info
# Если event = payment.confirmed, принудительно считаем оплаченным
if is_confirmed:
is_paid = True
internal_status = 'success'
callback_payload = {
'paypear_id': paypear_id,
'order_id': order_id,
'status': paypear_status,
'event': event,
'amount': obj.get('amount'),
}
# Проверка суммы ДО обновления статуса
# PayPear добавляет комиссию к amount — сравниваем с сохранённой суммой
# (paypear_charged_kopeks), а не с исходной суммой пополнения
if is_paid:
amount_info = obj.get('amount', {})
if isinstance(amount_info, dict):
amount_value = amount_info.get('value')
else:
amount_value = amount_info
if amount_value is not None:
received_kopeks = round(float(amount_value) * 100)
payment_metadata = dict(getattr(payment, 'metadata_json', {}) or {})
expected_kopeks = payment_metadata.get('paypear_charged_kopeks', payment.amount_kopeks)
if abs(received_kopeks - expected_kopeks) > 1:
logger.error(
'PayPear amount mismatch',
expected_kopeks=expected_kopeks,
received_kopeks=received_kopeks,
original_amount_kopeks=payment.amount_kopeks,
order_id=payment.order_id,
)
await paypear_crud.update_paypear_payment_status(
db=db,
payment=payment,
status='amount_mismatch',
is_paid=False,
paypear_id=paypear_id,
callback_payload=callback_payload,
)
return False
# Финализируем платеж если оплачен — без промежуточного commit
if is_paid:
# Inline field assignments to keep FOR UPDATE lock intact
payment.status = internal_status
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.paypear_id = paypear_id or payment.paypear_id
payment.callback_payload = callback_payload
payment.updated_at = datetime.now(UTC)
await db.flush()
return await self._finalize_paypear_payment(db, payment, paypear_id=paypear_id, trigger='webhook')
# Для не-success статусов можно безопасно коммитить
payment = await paypear_crud.update_paypear_payment_status(
db=db,
payment=payment,
status=internal_status,
is_paid=False,
paypear_id=paypear_id,
callback_payload=callback_payload,
)
return True
except Exception as e:
logger.exception('PayPear webhook: ошибка обработки', error=e)
return False
async def _finalize_paypear_payment(
self,
db: AsyncSession,
payment: Any,
*,
paypear_id: str | None,
trigger: str,
) -> bool:
"""Создаёт транзакцию, начисляет баланс и отправляет уведомления.
FOR UPDATE lock must be acquired by the caller before invoking this method.
"""
payment_module = import_module('app.services.payment_service')
paypear_crud = import_module('app.database.crud.paypear')
# FOR UPDATE lock already acquired by caller — just check idempotency
if payment.transaction_id:
logger.info(
'PayPear платеж уже связан с транзакцией',
order_id=payment.order_id,
transaction_id=payment.transaction_id,
trigger=trigger,
)
return True
# Read fresh metadata AFTER lock to avoid stale data
metadata = dict(getattr(payment, 'metadata_json', {}) or {})
# --- Guest purchase flow ---
from app.services.payment.common import try_fulfill_guest_purchase
guest_result = await try_fulfill_guest_purchase(
db,
metadata=metadata,
payment_amount_kopeks=payment.amount_kopeks,
provider_payment_id=str(paypear_id) if paypear_id else payment.order_id,
provider_name='paypear',
)
if guest_result is not None:
return True
# Ensure paid fields are set (idempotent — caller may have already set them)
if not payment.is_paid:
payment.status = 'success'
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.updated_at = datetime.now(UTC)
balance_already_credited = bool(metadata.get('balance_credited'))
user = await payment_module.get_user_by_id(db, payment.user_id)
if not user:
logger.error('Пользователь не найден для PayPear', user_id=payment.user_id)
return False
# Загружаем промогруппы в асинхронном контексте
await db.refresh(user, attribute_names=['promo_group', 'user_promo_groups'])
for user_promo_group in getattr(user, 'user_promo_groups', []):
await db.refresh(user_promo_group, attribute_names=['promo_group'])
promo_group = user.get_primary_promo_group()
subscription = getattr(user, 'subscription', None)
referrer_info = format_referrer_info(user)
transaction_external_id = str(paypear_id) if paypear_id else payment.order_id
# Проверяем дупликат транзакции
existing_transaction = None
if transaction_external_id:
existing_transaction = await payment_module.get_transaction_by_external_id(
db,
transaction_external_id,
PaymentMethod.PAYPEAR,
)
display_name = settings.get_paypear_display_name()
description = f'Пополнение через {display_name}'
transaction = existing_transaction
created_transaction = False
if not transaction:
transaction = await payment_module.create_transaction(
db,
user_id=payment.user_id,
type=TransactionType.DEPOSIT,
amount_kopeks=payment.amount_kopeks,
description=description,
payment_method=PaymentMethod.PAYPEAR,
external_id=transaction_external_id,
is_completed=True,
created_at=getattr(payment, 'created_at', None),
commit=False,
)
created_transaction = True
await paypear_crud.link_paypear_payment_to_transaction(db, payment=payment, transaction_id=transaction.id)
should_credit_balance = created_transaction or not balance_already_credited
if not should_credit_balance:
logger.info('PayPear платеж уже зачислил баланс ранее', order_id=payment.order_id)
return True
# Lock user row to prevent concurrent balance race conditions
from app.database.crud.user import lock_user_for_update
user = await lock_user_for_update(db, user)
old_balance = user.balance_kopeks
was_first_topup = not user.has_made_first_topup
user.balance_kopeks += payment.amount_kopeks
user.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(user)
# Emit deferred side-effects after atomic commit
from app.database.crud.transaction import emit_transaction_side_effects
await emit_transaction_side_effects(
db,
transaction,
amount_kopeks=payment.amount_kopeks,
user_id=payment.user_id,
type=TransactionType.DEPOSIT,
payment_method=PaymentMethod.PAYPEAR,
external_id=transaction_external_id,
)
topup_status = '\U0001f195 Первое пополнение' if was_first_topup else '\U0001f504 Пополнение'
try:
from app.services.referral_service import process_referral_topup
await process_referral_topup(
db,
user.id,
payment.amount_kopeks,
getattr(self, 'bot', None),
)
except Exception as error:
logger.error('Ошибка обработки реферального пополнения PayPear', error=error)
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
await db.refresh(user)
if getattr(self, 'bot', None):
try:
from app.services.admin_notification_service import AdminNotificationService
notification_service = AdminNotificationService(self.bot)
await notification_service.send_balance_topup_notification(
user,
transaction,
old_balance,
topup_status=topup_status,
referrer_info=referrer_info,
subscription=subscription,
promo_group=promo_group,
db=db,
)
except Exception as error:
logger.error('Ошибка отправки админ уведомления PayPear', error=error)
if getattr(self, 'bot', None) and user.telegram_id:
try:
keyboard = await self.build_topup_success_keyboard(user)
await self.bot.send_message(
user.telegram_id,
(
'\u2705 <b>Пополнение успешно!</b>\n\n'
f'\U0001f4b0 Сумма: {settings.format_price(payment.amount_kopeks)}\n'
f'\U0001f4b3 Способ: {display_name}\n'
f'\U0001f194 Транзакция: {transaction.id}\n\n'
'Баланс пополнен автоматически!'
),
parse_mode='HTML',
reply_markup=keyboard,
)
except Exception as error:
logger.error('Ошибка отправки уведомления пользователю PayPear', error=error)
try:
from app.services.payment.common import send_cart_notification_after_topup
await send_cart_notification_after_topup(user, payment.amount_kopeks, db, getattr(self, 'bot', None))
except Exception as error:
logger.error(
'Ошибка при работе с сохраненной корзиной для пользователя',
user_id=payment.user_id,
error=error,
exc_info=True,
)
metadata['balance_change'] = {
'old_balance': old_balance,
'new_balance': user.balance_kopeks,
'credited_at': datetime.now(UTC).isoformat(),
}
metadata['balance_credited'] = True
payment.metadata_json = metadata
await db.commit()
logger.info(
'Обработан PayPear платеж',
order_id=payment.order_id,
user_id=payment.user_id,
trigger=trigger,
)
return True
async def check_paypear_payment_status(
self,
db: AsyncSession,
order_id: str,
) -> dict[str, Any] | None:
"""Проверяет статус платежа через API."""
try:
paypear_crud = import_module('app.database.crud.paypear')
payment = await paypear_crud.get_paypear_payment_by_order_id(db, order_id)
if not payment:
logger.warning('PayPear payment not found', order_id=order_id)
return None
if payment.is_paid:
return {
'payment': payment,
'status': 'success',
'is_paid': True,
}
# Проверяем через API по paypear_id
if payment.paypear_id:
try:
order_data = await paypear_service.get_payment(payment.paypear_id)
paypear_status = order_data.get('status')
if paypear_status:
status_info = PAYPEAR_STATUS_MAP.get(paypear_status, ('pending', False))
internal_status, is_paid = status_info
if is_paid:
# Проверка суммы — сравниваем с paypear_charged_kopeks
# (amount включает комиссию PayPear)
amount_info = order_data.get('amount', {})
api_amount = amount_info.get('value') if isinstance(amount_info, dict) else amount_info
if api_amount is not None:
received_kopeks = round(float(api_amount) * 100)
payment_metadata = dict(getattr(payment, 'metadata_json', {}) or {})
expected_kopeks = payment_metadata.get('paypear_charged_kopeks', payment.amount_kopeks)
if abs(received_kopeks - expected_kopeks) > 1:
logger.error(
'PayPear amount mismatch (API check)',
expected_kopeks=expected_kopeks,
received_kopeks=received_kopeks,
original_amount_kopeks=payment.amount_kopeks,
order_id=payment.order_id,
)
await paypear_crud.update_paypear_payment_status(
db=db,
payment=payment,
status='amount_mismatch',
is_paid=False,
paypear_id=payment.paypear_id,
callback_payload={
'check_source': 'api',
'paypear_order_data': order_data,
},
)
return {
'payment': payment,
'status': 'amount_mismatch',
'is_paid': False,
}
# Acquire FOR UPDATE lock before finalization
locked = await paypear_crud.get_paypear_payment_by_id_for_update(db, payment.id)
if not locked:
logger.error('PayPear: не удалось заблокировать платёж', payment_id=payment.id)
return None
payment = locked
if payment.is_paid:
logger.info('PayPear платеж уже обработан (api_check)', order_id=payment.order_id)
return {
'payment': payment,
'status': 'success',
'is_paid': True,
}
logger.info('PayPear payment confirmed via API', order_id=payment.order_id)
# Inline field updates — NO intermediate commit that would release FOR UPDATE lock
payment.status = 'success'
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.callback_payload = {
'check_source': 'api',
'paypear_order_data': order_data,
}
payment.updated_at = datetime.now(UTC)
await db.flush()
await self._finalize_paypear_payment(
db,
payment,
paypear_id=payment.paypear_id,
trigger='api_check',
)
elif internal_status != payment.status:
# Обновляем статус если изменился
payment = await paypear_crud.update_paypear_payment_status(
db=db,
payment=payment,
status=internal_status,
)
except Exception as e:
logger.error('Error checking PayPear payment status via API', error=e)
return {
'payment': payment,
'status': payment.status or 'pending',
'is_paid': payment.is_paid,
}
except Exception as e:
logger.exception('PayPear: ошибка проверки статуса', error=e)
return None
+629
View File
@@ -0,0 +1,629 @@
"""Mixin для интеграции с RollyPay (rollypay.io)."""
from __future__ import annotations
import uuid
from datetime import UTC, datetime, timedelta
from importlib import import_module
from typing import Any
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.database.models import PaymentMethod, TransactionType
from app.services.rollypay_service import rollypay_service
from app.utils.payment_logger import payment_logger as logger
from app.utils.user_utils import format_referrer_info
# Маппинг статусов RollyPay -> internal
ROLLYPAY_STATUS_MAP: dict[str, tuple[str, bool]] = {
'created': ('pending', False),
'processing': ('processing', False),
'paid': ('success', True),
'expired': ('expired', False),
'canceled': ('canceled', False),
'chargeback': ('chargeback', False),
}
class RollyPayPaymentMixin:
"""Mixin для работы с платежами RollyPay."""
async def create_rollypay_payment(
self,
db: AsyncSession,
*,
user_id: int | None,
amount_kopeks: int,
description: str = 'Пополнение баланса',
email: str | None = None,
language: str = 'ru',
payment_method_type: str | None = None,
return_url: str | None = None,
) -> dict[str, Any] | None:
"""
Создает платеж RollyPay.
Returns:
Словарь с данными платежа или None при ошибке
"""
if not settings.is_rollypay_enabled():
logger.error('RollyPay не настроен')
return None
# Валидация лимитов
if amount_kopeks < settings.ROLLYPAY_MIN_AMOUNT_KOPEKS:
logger.warning(
'RollyPay: сумма меньше минимальной',
amount_kopeks=amount_kopeks,
ROLLYPAY_MIN_AMOUNT_KOPEKS=settings.ROLLYPAY_MIN_AMOUNT_KOPEKS,
)
return None
if amount_kopeks > settings.ROLLYPAY_MAX_AMOUNT_KOPEKS:
logger.warning(
'RollyPay: сумма больше максимальной',
amount_kopeks=amount_kopeks,
ROLLYPAY_MAX_AMOUNT_KOPEKS=settings.ROLLYPAY_MAX_AMOUNT_KOPEKS,
)
return None
# Получаем telegram_id пользователя для order_id
payment_module = import_module('app.services.payment_service')
if user_id is not None:
user = await payment_module.get_user_by_id(db, user_id)
tg_id = user.telegram_id if user else user_id
else:
user = None
tg_id = 'guest'
# Генерируем уникальный order_id с telegram_id для удобного поиска
order_id = f'rp{tg_id}_{uuid.uuid4().hex[:6]}'
amount_rubles = amount_kopeks / 100
amount_value = f'{amount_rubles:.2f}'
currency = settings.ROLLYPAY_CURRENCY
# Метаданные
metadata = {
'user_id': user_id,
'amount_kopeks': amount_kopeks,
'description': description,
'language': language,
'type': 'balance_topup',
}
try:
# Используем API для создания платежа
result = await rollypay_service.create_payment(
amount_value=amount_value,
currency=currency,
order_id=order_id,
payment_method=payment_method_type,
description=description,
redirect_url=return_url or settings.ROLLYPAY_RETURN_URL,
customer_id=str(tg_id),
metadata=metadata,
)
payment_url = result.get('pay_url')
rollypay_payment_id = result.get('payment_id')
if not payment_url:
logger.error('RollyPay API не вернул URL платежа', result=result)
return None
logger.info(
'RollyPay API: создан платеж',
order_id=order_id,
rollypay_payment_id=rollypay_payment_id,
payment_url=payment_url,
)
# Срок действия из expires_at ответа или 30 минут по умолчанию
expires_at_str = result.get('expires_at')
if expires_at_str:
try:
expires_at = datetime.fromisoformat(expires_at_str)
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=UTC)
except (ValueError, TypeError):
expires_at = datetime.now(UTC) + timedelta(minutes=30)
else:
expires_at = datetime.now(UTC) + timedelta(minutes=30)
# Сохраняем в БД
rollypay_crud = import_module('app.database.crud.rollypay')
local_payment = await rollypay_crud.create_rollypay_payment(
db=db,
user_id=user_id,
order_id=order_id,
amount_kopeks=amount_kopeks,
currency=currency,
description=description,
payment_url=payment_url,
payment_method=payment_method_type or 'sbp',
rollypay_payment_id=rollypay_payment_id,
expires_at=expires_at,
metadata_json=metadata,
)
logger.info(
'RollyPay: создан платеж',
order_id=order_id,
user_id=user_id,
amount_rubles=amount_rubles,
currency=currency,
)
return {
'order_id': order_id,
'rollypay_payment_id': rollypay_payment_id,
'amount_kopeks': amount_kopeks,
'amount_rubles': amount_rubles,
'currency': currency,
'payment_url': payment_url,
'expires_at': expires_at.isoformat(),
'local_payment_id': local_payment.id,
}
except Exception as e:
logger.exception('RollyPay: ошибка создания платежа', error=e)
return None
async def process_rollypay_webhook(
self,
db: AsyncSession,
payload: dict[str, Any],
) -> bool:
"""
Обрабатывает webhook от RollyPay.
Подпись проверяется в webserver/payments.py до вызова этого метода.
Args:
db: Сессия БД
payload: JSON тело webhook (signature проверена в webserver)
Returns:
True если платеж успешно обработан
"""
try:
event_type = payload.get('event_type')
rollypay_payment_id = payload.get('payment_id')
order_id = payload.get('order_id')
rollypay_status = payload.get('status')
if not rollypay_payment_id or not rollypay_status:
logger.warning('RollyPay webhook: отсутствуют обязательные поля', payload=payload)
return False
# Определяем is_paid по event
is_confirmed = event_type == 'payment.paid'
# Ищем платеж по order_id (наш) или rollypay_payment_id
rollypay_crud = import_module('app.database.crud.rollypay')
payment = None
if order_id:
payment = await rollypay_crud.get_rollypay_payment_by_order_id(db, order_id)
if not payment and rollypay_payment_id:
payment = await rollypay_crud.get_rollypay_payment_by_rollypay_id(db, rollypay_payment_id)
if not payment:
logger.warning(
'RollyPay webhook: платеж не найден',
order_id=order_id,
rollypay_payment_id=rollypay_payment_id,
)
return False
# Lock payment row immediately to prevent concurrent webhook processing (TOCTOU race)
locked = await rollypay_crud.get_rollypay_payment_by_id_for_update(db, payment.id)
if not locked:
logger.error('RollyPay: не удалось заблокировать платёж', payment_id=payment.id)
return False
payment = locked
# Проверка дублирования (re-check from locked row)
if payment.is_paid:
logger.info('RollyPay webhook: платеж уже обработан', order_id=payment.order_id)
return True
# Маппинг статуса
status_info = ROLLYPAY_STATUS_MAP.get(rollypay_status, ('pending', False))
internal_status, is_paid = status_info
# Если event = payment.paid, принудительно считаем оплаченным
if is_confirmed:
is_paid = True
internal_status = 'success'
callback_payload = {
'rollypay_payment_id': rollypay_payment_id,
'order_id': order_id,
'status': rollypay_status,
'event_type': event_type,
'amount': payload.get('amount'),
'currency': payload.get('currency'),
}
# Проверка суммы ДО обновления статуса
if is_paid:
amount_value = payload.get('amount')
if amount_value is not None:
received_kopeks = round(float(amount_value) * 100)
if abs(received_kopeks - payment.amount_kopeks) > 1:
logger.error(
'RollyPay amount mismatch',
expected_kopeks=payment.amount_kopeks,
received_kopeks=received_kopeks,
order_id=payment.order_id,
)
await rollypay_crud.update_rollypay_payment_status(
db=db,
payment=payment,
status='amount_mismatch',
is_paid=False,
rollypay_payment_id=rollypay_payment_id,
callback_payload=callback_payload,
)
return False
# Финализируем платеж если оплачен — без промежуточного commit
if is_paid:
# Inline field assignments to keep FOR UPDATE lock intact
payment.status = internal_status
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.rollypay_payment_id = rollypay_payment_id or payment.rollypay_payment_id
payment.callback_payload = callback_payload
payment.updated_at = datetime.now(UTC)
await db.flush()
return await self._finalize_rollypay_payment(
db, payment, rollypay_payment_id=rollypay_payment_id, trigger='webhook'
)
# Для не-success статусов можно безопасно коммитить
payment = await rollypay_crud.update_rollypay_payment_status(
db=db,
payment=payment,
status=internal_status,
is_paid=False,
rollypay_payment_id=rollypay_payment_id,
callback_payload=callback_payload,
)
return True
except Exception as e:
logger.exception('RollyPay webhook: ошибка обработки', error=e)
return False
async def _finalize_rollypay_payment(
self,
db: AsyncSession,
payment: Any,
*,
rollypay_payment_id: str | None,
trigger: str,
) -> bool:
"""Создаёт транзакцию, начисляет баланс и отправляет уведомления.
FOR UPDATE lock must be acquired by the caller before invoking this method.
"""
payment_module = import_module('app.services.payment_service')
rollypay_crud = import_module('app.database.crud.rollypay')
# FOR UPDATE lock already acquired by caller — just check idempotency
if payment.transaction_id:
logger.info(
'RollyPay платеж уже связан с транзакцией',
order_id=payment.order_id,
transaction_id=payment.transaction_id,
trigger=trigger,
)
return True
# Read fresh metadata AFTER lock to avoid stale data
metadata = dict(getattr(payment, 'metadata_json', {}) or {})
# --- Guest purchase flow ---
from app.services.payment.common import try_fulfill_guest_purchase
guest_result = await try_fulfill_guest_purchase(
db,
metadata=metadata,
payment_amount_kopeks=payment.amount_kopeks,
provider_payment_id=str(rollypay_payment_id) if rollypay_payment_id else payment.order_id,
provider_name='rollypay',
)
if guest_result is not None:
return True
# Ensure paid fields are set (idempotent — caller may have already set them)
if not payment.is_paid:
payment.status = 'success'
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.updated_at = datetime.now(UTC)
balance_already_credited = bool(metadata.get('balance_credited'))
user = await payment_module.get_user_by_id(db, payment.user_id)
if not user:
logger.error('Пользователь не найден для RollyPay', user_id=payment.user_id)
return False
# Загружаем промогруппы в асинхронном контексте
await db.refresh(user, attribute_names=['promo_group', 'user_promo_groups'])
for user_promo_group in getattr(user, 'user_promo_groups', []):
await db.refresh(user_promo_group, attribute_names=['promo_group'])
promo_group = user.get_primary_promo_group()
subscription = getattr(user, 'subscription', None)
referrer_info = format_referrer_info(user)
transaction_external_id = str(rollypay_payment_id) if rollypay_payment_id else payment.order_id
# Проверяем дупликат транзакции
existing_transaction = None
if transaction_external_id:
existing_transaction = await payment_module.get_transaction_by_external_id(
db,
transaction_external_id,
PaymentMethod.ROLLYPAY,
)
display_name = settings.get_rollypay_display_name()
description = f'Пополнение через {display_name}'
transaction = existing_transaction
created_transaction = False
if not transaction:
transaction = await payment_module.create_transaction(
db,
user_id=payment.user_id,
type=TransactionType.DEPOSIT,
amount_kopeks=payment.amount_kopeks,
description=description,
payment_method=PaymentMethod.ROLLYPAY,
external_id=transaction_external_id,
is_completed=True,
created_at=getattr(payment, 'created_at', None),
commit=False,
)
created_transaction = True
await rollypay_crud.link_rollypay_payment_to_transaction(db, payment=payment, transaction_id=transaction.id)
should_credit_balance = created_transaction or not balance_already_credited
if not should_credit_balance:
logger.info('RollyPay платеж уже зачислил баланс ранее', order_id=payment.order_id)
return True
# Lock user row to prevent concurrent balance race conditions
from app.database.crud.user import lock_user_for_update
user = await lock_user_for_update(db, user)
old_balance = user.balance_kopeks
was_first_topup = not user.has_made_first_topup
user.balance_kopeks += payment.amount_kopeks
user.updated_at = datetime.now(UTC)
await db.commit()
await db.refresh(user)
# Emit deferred side-effects after atomic commit
from app.database.crud.transaction import emit_transaction_side_effects
await emit_transaction_side_effects(
db,
transaction,
amount_kopeks=payment.amount_kopeks,
user_id=payment.user_id,
type=TransactionType.DEPOSIT,
payment_method=PaymentMethod.ROLLYPAY,
external_id=transaction_external_id,
)
topup_status = '\U0001f195 Первое пополнение' if was_first_topup else '\U0001f504 Пополнение'
try:
from app.services.referral_service import process_referral_topup
await process_referral_topup(
db,
user.id,
payment.amount_kopeks,
getattr(self, 'bot', None),
)
except Exception as error:
logger.error('Ошибка обработки реферального пополнения RollyPay', error=error)
if was_first_topup and not user.has_made_first_topup and not user.referred_by_id:
user.has_made_first_topup = True
await db.commit()
await db.refresh(user)
if getattr(self, 'bot', None):
try:
from app.services.admin_notification_service import AdminNotificationService
notification_service = AdminNotificationService(self.bot)
await notification_service.send_balance_topup_notification(
user,
transaction,
old_balance,
topup_status=topup_status,
referrer_info=referrer_info,
subscription=subscription,
promo_group=promo_group,
db=db,
)
except Exception as error:
logger.error('Ошибка отправки админ уведомления RollyPay', error=error)
if getattr(self, 'bot', None) and user.telegram_id:
try:
keyboard = await self.build_topup_success_keyboard(user)
await self.bot.send_message(
user.telegram_id,
(
'\u2705 <b>Пополнение успешно!</b>\n\n'
f'\U0001f4b0 Сумма: {settings.format_price(payment.amount_kopeks)}\n'
f'\U0001f4b3 Способ: {display_name}\n'
f'\U0001f194 Транзакция: {transaction.id}\n\n'
'Баланс пополнен автоматически!'
),
parse_mode='HTML',
reply_markup=keyboard,
)
except Exception as error:
logger.error('Ошибка отправки уведомления пользователю RollyPay', error=error)
try:
from app.services.payment.common import send_cart_notification_after_topup
await send_cart_notification_after_topup(user, payment.amount_kopeks, db, getattr(self, 'bot', None))
except Exception as error:
logger.error(
'Ошибка при работе с сохраненной корзиной для пользователя',
user_id=payment.user_id,
error=error,
exc_info=True,
)
metadata['balance_change'] = {
'old_balance': old_balance,
'new_balance': user.balance_kopeks,
'credited_at': datetime.now(UTC).isoformat(),
}
metadata['balance_credited'] = True
payment.metadata_json = metadata
await db.commit()
logger.info(
'Обработан RollyPay платеж',
order_id=payment.order_id,
user_id=payment.user_id,
trigger=trigger,
)
return True
async def check_rollypay_payment_status(
self,
db: AsyncSession,
order_id: str,
) -> dict[str, Any] | None:
"""Проверяет статус платежа через API."""
try:
rollypay_crud = import_module('app.database.crud.rollypay')
payment = await rollypay_crud.get_rollypay_payment_by_order_id(db, order_id)
if not payment:
logger.warning('RollyPay payment not found', order_id=order_id)
return None
if payment.is_paid:
return {
'payment': payment,
'status': 'success',
'is_paid': True,
}
# Проверяем через API по rollypay_payment_id
if payment.rollypay_payment_id:
try:
order_data = await rollypay_service.get_payment(payment.rollypay_payment_id)
rollypay_status = order_data.get('status')
if rollypay_status:
status_info = ROLLYPAY_STATUS_MAP.get(rollypay_status, ('pending', False))
internal_status, is_paid = status_info
if is_paid:
# Проверка суммы
api_amount = order_data.get('amount')
if api_amount is not None:
received_kopeks = round(float(api_amount) * 100)
if abs(received_kopeks - payment.amount_kopeks) > 1:
logger.error(
'RollyPay amount mismatch (API check)',
expected_kopeks=payment.amount_kopeks,
received_kopeks=received_kopeks,
order_id=payment.order_id,
)
await rollypay_crud.update_rollypay_payment_status(
db=db,
payment=payment,
status='amount_mismatch',
is_paid=False,
rollypay_payment_id=payment.rollypay_payment_id,
callback_payload={
'check_source': 'api',
'rollypay_order_data': order_data,
},
)
return {
'payment': payment,
'status': 'amount_mismatch',
'is_paid': False,
}
# Acquire FOR UPDATE lock before finalization
locked = await rollypay_crud.get_rollypay_payment_by_id_for_update(db, payment.id)
if not locked:
logger.error('RollyPay: не удалось заблокировать платёж', payment_id=payment.id)
return None
payment = locked
if payment.is_paid:
logger.info('RollyPay платеж уже обработан (api_check)', order_id=payment.order_id)
return {
'payment': payment,
'status': 'success',
'is_paid': True,
}
logger.info('RollyPay payment confirmed via API', order_id=payment.order_id)
# Inline field updates — NO intermediate commit that would release FOR UPDATE lock
payment.status = 'success'
payment.is_paid = True
payment.paid_at = datetime.now(UTC)
payment.callback_payload = {
'check_source': 'api',
'rollypay_order_data': order_data,
}
payment.updated_at = datetime.now(UTC)
await db.flush()
await self._finalize_rollypay_payment(
db,
payment,
rollypay_payment_id=payment.rollypay_payment_id,
trigger='api_check',
)
elif internal_status != payment.status:
# Обновляем статус если изменился
payment = await rollypay_crud.update_rollypay_payment_status(
db=db,
payment=payment,
status=internal_status,
)
except Exception as e:
logger.error('Error checking RollyPay payment status via API', error=e)
return {
'payment': payment,
'status': payment.status or 'pending',
'is_paid': payment.is_paid,
}
except Exception as e:
logger.exception('RollyPay: ошибка проверки статуса', error=e)
return None
@@ -146,6 +146,49 @@ def _get_method_defaults() -> dict:
'default_max': settings.SEVERPAY_MAX_AMOUNT_KOPEKS,
'available_sub_options': None,
},
'paypear': {
'default_display_name': settings.get_paypear_display_name(),
'is_configured': settings.is_paypear_enabled(),
'default_min': settings.PAYPEAR_MIN_AMOUNT_KOPEKS,
'default_max': settings.PAYPEAR_MAX_AMOUNT_KOPEKS,
'available_sub_options': [
{'id': 'bank_card', 'name': 'Карта'},
{'id': 'sbp', 'name': 'СБП'},
{'id': 'sberpay', 'name': 'SberPay'},
{'id': 'tpay', 'name': 'T-Pay'},
],
},
'rollypay': {
'default_display_name': settings.get_rollypay_display_name(),
'is_configured': settings.is_rollypay_enabled(),
'default_min': settings.ROLLYPAY_MIN_AMOUNT_KOPEKS,
'default_max': settings.ROLLYPAY_MAX_AMOUNT_KOPEKS,
'available_sub_options': [
{'id': 'sbp', 'name': 'СБП'},
{'id': 'card', 'name': 'Карта'},
{'id': 'crypto', 'name': 'Криптовалюта'},
],
},
'overpay': {
'default_display_name': settings.get_overpay_display_name(),
'is_configured': settings.is_overpay_enabled(),
'default_min': settings.OVERPAY_MIN_AMOUNT_KOPEKS,
'default_max': settings.OVERPAY_MAX_AMOUNT_KOPEKS,
'available_sub_options': [
{'id': 'card', 'name': 'Карта'},
{'id': 'fps', 'name': 'СБП'},
],
},
'aurapay': {
'default_display_name': settings.get_aurapay_display_name(),
'is_configured': settings.is_aurapay_enabled(),
'default_min': settings.AURAPAY_MIN_AMOUNT_KOPEKS,
'default_max': settings.AURAPAY_MAX_AMOUNT_KOPEKS,
'available_sub_options': [
{'id': 'card', 'name': 'Карта'},
{'id': 'sbp', 'name': 'СБП'},
],
},
}
@@ -188,6 +231,10 @@ DEFAULT_METHOD_ORDER = [
'kassa_ai',
'riopay',
'severpay',
'paypear',
'rollypay',
'overpay',
'aurapay',
]
+35
View File
@@ -21,6 +21,7 @@ from app.database.models import (
HeleketPayment,
KassaAiPayment,
MulenPayPayment,
OverpayPayment,
Pal24Payment,
PaymentMethod,
PlategaPayment,
@@ -649,6 +650,39 @@ async def _search_severpay(db: AsyncSession, params: SearchParams) -> list[Pendi
return records
async def _search_overpay(db: AsyncSession, params: SearchParams) -> list[PendingPayment]:
stmt = select(OverpayPayment).options(selectinload(OverpayPayment.user)).order_by(desc(OverpayPayment.created_at))
stmt = _apply_date_filter(stmt, OverpayPayment.created_at, params.cutoff, params.upper_bound)
if params.search:
kind = _detect_user_search_kind(params.search)
if kind == _UserSearchKind.INVOICE:
conditions = [
OverpayPayment.order_id.ilike(f'%{_escape_like(params.search)}%'),
OverpayPayment.overpay_payment_id.ilike(f'%{_escape_like(params.search)}%'),
]
stmt = stmt.where(or_(*conditions))
else:
stmt = _apply_user_join_filter(stmt, OverpayPayment, kind, params.search)
stmt = stmt.limit(MAX_RECORDS_PER_PROVIDER)
result = await db.execute(stmt)
records: list[PendingPayment] = []
for payment in result.scalars().all():
record = _build_record(
PaymentMethod.OVERPAY,
payment,
identifier=payment.order_id,
amount_kopeks=payment.amount_kopeks,
status=payment.status or '',
is_paid=bool(payment.is_paid),
expires_at=getattr(payment, 'expires_at', None),
)
if record:
records.append(record)
return records
async def _search_stars(db: AsyncSession, params: SearchParams) -> list[PendingPayment]:
stmt = (
select(Transaction)
@@ -702,6 +736,7 @@ _PROVIDER_SEARCH_MAP: dict[PaymentMethod, Any] = {
PaymentMethod.KASSA_AI: _search_kassa_ai,
PaymentMethod.RIOPAY: _search_riopay,
PaymentMethod.SEVERPAY: _search_severpay,
PaymentMethod.OVERPAY: _search_overpay,
PaymentMethod.TELEGRAM_STARS: _search_stars,
}
+242
View File
@@ -30,10 +30,14 @@ from app.services.payment import (
WataPaymentMixin,
YooKassaPaymentMixin,
)
from app.services.payment.aurapay import AuraPayPaymentMixin
from app.services.payment.cloudpayments import CloudPaymentsPaymentMixin
from app.services.payment.freekassa import FreekassaPaymentMixin
from app.services.payment.kassa_ai import KassaAiPaymentMixin
from app.services.payment.overpay import OverpayPaymentMixin
from app.services.payment.paypear import PayPearPaymentMixin
from app.services.payment.riopay import RioPayPaymentMixin
from app.services.payment.rollypay import RollyPayPaymentMixin
from app.services.payment.severpay import SeverPayPaymentMixin
from app.services.platega_service import PlategaService
from app.services.wata_service import WataService
@@ -332,6 +336,152 @@ async def link_severpay_payment_to_transaction(*args, **kwargs):
return await severpay_crud.link_severpay_payment_to_transaction(*args, **kwargs)
async def create_paypear_payment(*args, **kwargs):
paypear_crud = import_module('app.database.crud.paypear')
return await paypear_crud.create_paypear_payment(*args, **kwargs)
async def get_paypear_payment_by_order_id(*args, **kwargs):
paypear_crud = import_module('app.database.crud.paypear')
return await paypear_crud.get_paypear_payment_by_order_id(*args, **kwargs)
async def get_paypear_payment_by_paypear_id(*args, **kwargs):
paypear_crud = import_module('app.database.crud.paypear')
return await paypear_crud.get_paypear_payment_by_paypear_id(*args, **kwargs)
async def get_paypear_payment_by_id(*args, **kwargs):
paypear_crud = import_module('app.database.crud.paypear')
return await paypear_crud.get_paypear_payment_by_id(*args, **kwargs)
async def get_paypear_payment_by_id_for_update(*args, **kwargs):
paypear_crud = import_module('app.database.crud.paypear')
return await paypear_crud.get_paypear_payment_by_id_for_update(*args, **kwargs)
async def update_paypear_payment_status(*args, **kwargs):
paypear_crud = import_module('app.database.crud.paypear')
return await paypear_crud.update_paypear_payment_status(*args, **kwargs)
async def link_paypear_payment_to_transaction(*args, **kwargs):
paypear_crud = import_module('app.database.crud.paypear')
return await paypear_crud.link_paypear_payment_to_transaction(*args, **kwargs)
# --- RollyPay CRUD wrappers ---
async def create_rollypay_payment(*args, **kwargs):
rollypay_crud = import_module('app.database.crud.rollypay')
return await rollypay_crud.create_rollypay_payment(*args, **kwargs)
async def get_rollypay_payment_by_order_id(*args, **kwargs):
rollypay_crud = import_module('app.database.crud.rollypay')
return await rollypay_crud.get_rollypay_payment_by_order_id(*args, **kwargs)
async def get_rollypay_payment_by_rollypay_id(*args, **kwargs):
rollypay_crud = import_module('app.database.crud.rollypay')
return await rollypay_crud.get_rollypay_payment_by_rollypay_id(*args, **kwargs)
async def get_rollypay_payment_by_id(*args, **kwargs):
rollypay_crud = import_module('app.database.crud.rollypay')
return await rollypay_crud.get_rollypay_payment_by_id(*args, **kwargs)
async def get_rollypay_payment_by_id_for_update(*args, **kwargs):
rollypay_crud = import_module('app.database.crud.rollypay')
return await rollypay_crud.get_rollypay_payment_by_id_for_update(*args, **kwargs)
async def update_rollypay_payment_status(*args, **kwargs):
rollypay_crud = import_module('app.database.crud.rollypay')
return await rollypay_crud.update_rollypay_payment_status(*args, **kwargs)
async def link_rollypay_payment_to_transaction(*args, **kwargs):
rollypay_crud = import_module('app.database.crud.rollypay')
return await rollypay_crud.link_rollypay_payment_to_transaction(*args, **kwargs)
# --- Overpay CRUD wrappers ---
async def create_overpay_payment(*args, **kwargs):
overpay_crud = import_module('app.database.crud.overpay')
return await overpay_crud.create_overpay_payment(*args, **kwargs)
async def get_overpay_payment_by_order_id(*args, **kwargs):
overpay_crud = import_module('app.database.crud.overpay')
return await overpay_crud.get_overpay_payment_by_order_id(*args, **kwargs)
async def get_overpay_payment_by_overpay_id(*args, **kwargs):
overpay_crud = import_module('app.database.crud.overpay')
return await overpay_crud.get_overpay_payment_by_overpay_id(*args, **kwargs)
async def get_overpay_payment_by_id(*args, **kwargs):
overpay_crud = import_module('app.database.crud.overpay')
return await overpay_crud.get_overpay_payment_by_id(*args, **kwargs)
async def get_overpay_payment_by_id_for_update(*args, **kwargs):
overpay_crud = import_module('app.database.crud.overpay')
return await overpay_crud.get_overpay_payment_by_id_for_update(*args, **kwargs)
async def update_overpay_payment_status(*args, **kwargs):
overpay_crud = import_module('app.database.crud.overpay')
return await overpay_crud.update_overpay_payment_status(*args, **kwargs)
async def link_overpay_payment_to_transaction(*args, **kwargs):
overpay_crud = import_module('app.database.crud.overpay')
return await overpay_crud.link_overpay_payment_to_transaction(*args, **kwargs)
async def create_aurapay_payment(*args, **kwargs):
aurapay_crud = import_module('app.database.crud.aurapay')
return await aurapay_crud.create_aurapay_payment(*args, **kwargs)
async def get_aurapay_payment_by_order_id(*args, **kwargs):
aurapay_crud = import_module('app.database.crud.aurapay')
return await aurapay_crud.get_aurapay_payment_by_order_id(*args, **kwargs)
async def get_aurapay_payment_by_invoice_id(*args, **kwargs):
aurapay_crud = import_module('app.database.crud.aurapay')
return await aurapay_crud.get_aurapay_payment_by_invoice_id(*args, **kwargs)
async def get_aurapay_payment_by_id(*args, **kwargs):
aurapay_crud = import_module('app.database.crud.aurapay')
return await aurapay_crud.get_aurapay_payment_by_id(*args, **kwargs)
async def get_aurapay_payment_by_id_for_update(*args, **kwargs):
aurapay_crud = import_module('app.database.crud.aurapay')
return await aurapay_crud.get_aurapay_payment_by_id_for_update(*args, **kwargs)
async def update_aurapay_payment_status(*args, **kwargs):
aurapay_crud = import_module('app.database.crud.aurapay')
return await aurapay_crud.update_aurapay_payment_status(*args, **kwargs)
async def link_aurapay_payment_to_transaction(*args, **kwargs):
aurapay_crud = import_module('app.database.crud.aurapay')
return await aurapay_crud.link_aurapay_payment_to_transaction(*args, **kwargs)
# Mapping from model_name to getter function name for providers
# where it differs from the standard get_{model_name}_payment_by_id pattern.
_GETTER_OVERRIDES: dict[str, str] = {
@@ -355,6 +505,10 @@ class PaymentService(
KassaAiPaymentMixin,
RioPayPaymentMixin,
SeverPayPaymentMixin,
PayPearPaymentMixin,
RollyPayPaymentMixin,
OverpayPaymentMixin,
AuraPayPaymentMixin,
):
"""Основной интерфейс платежей, делегирующий работу специализированным mixin-ам."""
@@ -774,6 +928,94 @@ class PaymentService(
}
return None
# --- PayPear ----------------------------------------------------------
if payment_method == 'paypear':
if not settings.is_paypear_enabled():
logger.warning('PayPear is not enabled, cannot create guest payment')
return None
result = await self.create_paypear_payment(
db=db,
user_id=None,
amount_kopeks=amount_kopeks,
description=description,
return_url=return_url,
)
if result:
await _patch_guest_metadata(result['local_payment_id'], 'paypear')
return {
'payment_url': result.get('payment_url'),
'payment_id': result.get('paypear_id') or result.get('order_id'),
'provider': 'paypear',
}
return None
# --- RollyPay ---------------------------------------------------------
if payment_method == 'rollypay':
if not settings.is_rollypay_enabled():
logger.warning('RollyPay is not enabled, cannot create guest payment')
return None
result = await self.create_rollypay_payment(
db=db,
user_id=None,
amount_kopeks=amount_kopeks,
description=description,
return_url=return_url,
)
if result:
await _patch_guest_metadata(result['local_payment_id'], 'rollypay')
return {
'payment_url': result.get('payment_url'),
'payment_id': result.get('rollypay_payment_id') or result.get('order_id'),
'provider': 'rollypay',
}
return None
# --- Overpay ----------------------------------------------------------
if payment_method == 'overpay':
if not settings.is_overpay_enabled():
logger.warning('Overpay is not enabled, cannot create guest payment')
return None
result = await self.create_overpay_payment(
db=db,
user_id=None,
amount_kopeks=amount_kopeks,
description=description,
return_url=return_url,
)
if result:
await _patch_guest_metadata(result['local_payment_id'], 'overpay')
return {
'payment_url': result.get('payment_url'),
'payment_id': result.get('overpay_payment_id') or result.get('order_id'),
'provider': 'overpay',
}
return None
# --- AuraPay ----------------------------------------------------------
if payment_method == 'aurapay':
if not settings.is_aurapay_enabled():
logger.warning('AuraPay is not enabled, cannot create guest payment')
return None
result = await self.create_aurapay_payment(
db=db,
user_id=None,
amount_kopeks=amount_kopeks,
description=description,
return_url=return_url,
)
if result:
await _patch_guest_metadata(result['local_payment_id'], 'aurapay')
return {
'payment_url': result.get('payment_url'),
'payment_id': result.get('aurapay_invoice_id') or result.get('order_id'),
'provider': 'aurapay',
}
return None
# --- Telegram Stars ---------------------------------------------------
if payment_method == 'telegram_stars':
if not settings.TELEGRAM_STARS_ENABLED:
@@ -76,6 +76,7 @@ SUPPORTED_MANUAL_CHECK_METHODS: frozenset[PaymentMethod] = frozenset(
PaymentMethod.KASSA_AI,
PaymentMethod.RIOPAY,
PaymentMethod.SEVERPAY,
PaymentMethod.OVERPAY,
}
)
@@ -96,6 +97,7 @@ SUPPORTED_AUTO_CHECK_METHODS: frozenset[PaymentMethod] = frozenset(
PaymentMethod.KASSA_AI,
PaymentMethod.RIOPAY,
PaymentMethod.SEVERPAY,
PaymentMethod.OVERPAY,
}
)
@@ -125,6 +127,8 @@ def method_display_name(method: PaymentMethod) -> str:
return settings.get_riopay_display_name()
if method == PaymentMethod.SEVERPAY:
return settings.get_severpay_display_name()
if method == PaymentMethod.OVERPAY:
return settings.get_overpay_display_name()
if method == PaymentMethod.TELEGRAM_STARS:
return 'Telegram Stars'
return method.value
@@ -155,6 +159,8 @@ def _method_is_enabled(method: PaymentMethod) -> bool:
return settings.is_riopay_enabled()
if method == PaymentMethod.SEVERPAY:
return settings.is_severpay_enabled()
if method == PaymentMethod.OVERPAY:
return settings.is_overpay_enabled()
return False
+265
View File
@@ -0,0 +1,265 @@
"""Сервис для работы с API PayPear (paypear.ru)."""
import hashlib
import hmac
import uuid
from base64 import b64encode
from typing import Any
import aiohttp
import structlog
from app.config import settings
logger = structlog.get_logger(__name__)
API_BASE_URL = 'https://api.paypear.ru/v1'
class PayPearAPIError(Exception):
"""Ошибка API PayPear."""
def __init__(self, status_code: int, message: str):
self.status_code = status_code
self.message = message
super().__init__(f'PayPear API error ({status_code}): {message}')
class PayPearService:
"""Сервис для работы с API PayPear."""
def __init__(self):
self._session: aiohttp.ClientSession | None = None
@property
def shop_id(self) -> str:
return settings.PAYPEAR_SHOP_ID or ''
@property
def secret_key(self) -> str:
return settings.PAYPEAR_SECRET_KEY or ''
def _basic_auth_header(self) -> str:
"""Генерирует HTTP Basic Auth заголовок."""
credentials = f'{self.shop_id}:{self.secret_key}'
encoded = b64encode(credentials.encode('utf-8')).decode('utf-8')
return f'Basic {encoded}'
async def _get_session(self) -> aiohttp.ClientSession:
"""Возвращает переиспользуемую HTTP-сессию."""
if self._session is None or self._session.closed:
self._session = aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=30),
)
return self._session
async def close(self) -> None:
"""Закрывает HTTP-сессию."""
if self._session and not self._session.closed:
await self._session.close()
self._session = None
async def create_payment(
self,
*,
order_id: str,
amount_rubles: float,
currency: str = 'RUB',
payment_method_type: str = 'sbp',
description: str = '',
return_url: str | None = None,
webhook_url: str | None = None,
metadata: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
Создает платеж через API PayPear.
POST /v1/payment/
"""
idempotence_key = str(uuid.uuid4())
payload: dict[str, Any] = {
'amount': {
'value': f'{amount_rubles:.2f}',
'currency': currency,
},
'order_id': order_id,
'payment_method_data': {
'type': payment_method_type,
},
}
if description:
payload['description'] = description
if return_url:
payload['confirmation'] = {
'type': 'redirect',
'return_url': return_url,
}
if webhook_url:
payload['webhook_url'] = webhook_url
if metadata:
payload['metadata'] = metadata
logger.info(
'PayPear API create_payment',
order_id=order_id,
amount_rubles=amount_rubles,
currency=currency,
payment_method_type=payment_method_type,
)
try:
session = await self._get_session()
async with session.post(
f'{API_BASE_URL}/payment/',
json=payload,
headers={
'Content-Type': 'application/json',
'Authorization': self._basic_auth_header(),
'Idempotence-Key': idempotence_key,
},
) as response:
data = await response.json(content_type=None)
if response.status == 200 and data.get('success') is True:
result = data.get('result', {})
logger.info(
'PayPear API payment created',
order_id=order_id,
paypear_id=result.get('id'),
)
return result
error_msg = data.get('message') or data.get('error') or str(data)
logger.error(
'PayPear create_payment error',
status_code=response.status,
error_msg=error_msg,
response_data=data,
)
raise PayPearAPIError(response.status, error_msg)
except aiohttp.ClientError as e:
logger.exception('PayPear API connection error', error=e)
raise
async def get_payment(self, payment_id: str) -> dict[str, Any]:
"""
Получает информацию о платеже по ID.
GET /v1/payment/{id}/
"""
logger.info('PayPear get_payment', payment_id=payment_id)
try:
session = await self._get_session()
async with session.get(
f'{API_BASE_URL}/payment/{payment_id}/',
headers={
'Authorization': self._basic_auth_header(),
},
) as response:
data = await response.json(content_type=None)
if response.status == 200 and data.get('success') is True:
return data.get('result', {})
error_msg = data.get('message') or data.get('error') or str(data)
logger.error(
'PayPear get_payment error',
status_code=response.status,
error_msg=error_msg,
)
raise PayPearAPIError(response.status, error_msg)
except aiohttp.ClientError as e:
logger.exception('PayPear API connection error', error=e)
raise
async def get_payment_by_order_id(self, order_id: str) -> dict[str, Any]:
"""
Получает информацию о платеже по order_id.
GET /v1/payment/order/{order_id}/
"""
logger.info('PayPear get_payment_by_order_id', order_id=order_id)
try:
session = await self._get_session()
async with session.get(
f'{API_BASE_URL}/payment/order/{order_id}/',
headers={
'Authorization': self._basic_auth_header(),
},
) as response:
data = await response.json(content_type=None)
if response.status == 200 and data.get('success') is True:
return data.get('result', {})
error_msg = data.get('message') or data.get('error') or str(data)
logger.error(
'PayPear get_payment_by_order_id error',
status_code=response.status,
error_msg=error_msg,
)
raise PayPearAPIError(response.status, error_msg)
except aiohttp.ClientError as e:
logger.exception('PayPear API connection error', error=e)
raise
# PayPear documented webhook source IPs
WEBHOOK_ALLOWED_IPS: set[str] = {'158.160.85.101'}
def verify_webhook_signature(self, raw_body: bytes, received_signature: str, client_ip: str | None = None) -> bool:
"""Верификация webhook PayPear.
PayPear documentation does not specify the exact signature algorithm.
We try HMAC-SHA256(secret_key, body_without_signature_field) the most common pattern.
If signature verification fails, fall back to IP allowlist check (recommended by PayPear docs).
"""
import json as json_mod
# Try signature verification (body without 'signature' field, sorted keys, compact separators)
if received_signature and self.secret_key:
try:
payload = json_mod.loads(raw_body)
payload_without_sig = {k: v for k, v in payload.items() if k != 'signature'}
body_to_sign = json_mod.dumps(payload_without_sig, separators=(',', ':'), sort_keys=True).encode(
'utf-8'
)
expected = hmac.new(
self.secret_key.encode('utf-8'),
body_to_sign,
hashlib.sha256,
).hexdigest()
if hmac.compare_digest(expected, received_signature):
return True
# Try without sort_keys (original key order)
body_to_sign_unsorted = json_mod.dumps(payload_without_sig, separators=(',', ':')).encode('utf-8')
expected_unsorted = hmac.new(
self.secret_key.encode('utf-8'),
body_to_sign_unsorted,
hashlib.sha256,
).hexdigest()
if hmac.compare_digest(expected_unsorted, received_signature):
return True
logger.debug('PayPear signature mismatch, falling back to IP check')
except Exception as e:
logger.debug('PayPear signature verify error, falling back to IP check', error=e)
# Fallback: IP allowlist (recommended by PayPear docs)
if client_ip and client_ip in self.WEBHOOK_ALLOWED_IPS:
return True
logger.warning('PayPear webhook: signature mismatch and IP not in allowlist', client_ip=client_ip)
return False
# Singleton instance
paypear_service = PayPearService()

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