-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubscriptions.py
More file actions
250 lines (190 loc) · 7.99 KB
/
subscriptions.py
File metadata and controls
250 lines (190 loc) · 7.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
"""
Модуль для работы с подписками и проверки прав доступа
"""
from enum import Enum
from datetime import datetime
from typing import Optional, Tuple
from database import Database
from config import OWNER_USER_IDS
# Инициализация базы данных для проверок
db = Database()
class SubscriptionType(Enum):
"""Типы подписок"""
FREE = "FREE"
PRO = "PRO"
PRO_LIFETIME = "PRO_LIFETIME"
# Лимиты для FREE пользователей
FREE_MAX_PURCHASES = 10
FREE_ALLOWED_ASSETS = ['btc'] # Только BTC для FREE
def get_user_subscription(user_id: int) -> Tuple[SubscriptionType, Optional[datetime]]:
"""
Получить тип подписки пользователя и дату истечения
Returns:
tuple: (SubscriptionType, expires_at или None для lifetime)
"""
conn = db.get_connection()
cursor = conn.cursor()
try:
cursor.execute('''
SELECT subscription_type, subscription_expires_at
FROM users
WHERE user_id = ?
''', (user_id,))
row = cursor.fetchone()
conn.close()
if row:
sub_type_str, expires_at_str = row
if sub_type_str:
try:
sub_type = SubscriptionType(sub_type_str)
except ValueError:
sub_type = SubscriptionType.FREE
else:
sub_type = SubscriptionType.FREE
expires_at = None
if expires_at_str:
try:
expires_at = datetime.fromisoformat(expires_at_str)
except (ValueError, TypeError):
expires_at = None
# Проверяем, не истекла ли подписка PRO
if sub_type == SubscriptionType.PRO and expires_at:
if expires_at < datetime.now():
# Подписка истекла, возвращаем FREE
update_user_subscription(user_id, SubscriptionType.FREE, None)
return SubscriptionType.FREE, None
return sub_type, expires_at
else:
# Пользователь не найден, возвращаем FREE по умолчанию
return SubscriptionType.FREE, None
except Exception as e:
print(f"Ошибка при получении подписки пользователя: {e}")
conn.close()
return SubscriptionType.FREE, None
def update_user_subscription(user_id: int, subscription_type: SubscriptionType,
expires_at: Optional[datetime] = None) -> bool:
"""
Обновить подписку пользователя
Args:
user_id: ID пользователя
subscription_type: Тип подписки
expires_at: Дата истечения (None для lifetime)
Returns:
bool: Успешность операции
"""
conn = db.get_connection()
cursor = conn.cursor()
try:
expires_at_str = expires_at.isoformat() if expires_at else None
cursor.execute('''
UPDATE users
SET subscription_type = ?, subscription_expires_at = ?
WHERE user_id = ?
''', (subscription_type.value, expires_at_str, user_id))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Ошибка при обновлении подписки: {e}")
conn.close()
return False
def has_pro_access(user_id: int) -> bool:
"""
Проверить, есть ли у пользователя PRO доступ
Returns:
bool: True если PRO или PRO_LIFETIME или владелец бота
"""
# Владельцы бота всегда имеют полный доступ
if user_id in OWNER_USER_IDS:
return True
sub_type, _ = get_user_subscription(user_id)
return sub_type in [SubscriptionType.PRO, SubscriptionType.PRO_LIFETIME]
def can_add_asset(user_id: int, asset: str) -> Tuple[bool, str]:
"""
Проверить, может ли пользователь добавить актив
Args:
user_id: ID пользователя
asset: Название актива (btc, gold)
Returns:
tuple: (разрешено, сообщение об ошибке)
"""
# Владельцы бота могут добавлять любые активы
if user_id in OWNER_USER_IDS:
return True, ""
sub_type, _ = get_user_subscription(user_id)
if sub_type in [SubscriptionType.PRO, SubscriptionType.PRO_LIFETIME]:
return True, ""
# FREE пользователь может добавлять только BTC
if asset.lower() not in FREE_ALLOWED_ASSETS:
return False, "gold_not_allowed"
return True, ""
def can_add_purchase(user_id: int) -> Tuple[bool, str, int]:
"""
Проверить, может ли пользователь добавить покупку
Args:
user_id: ID пользователя
Returns:
tuple: (разрешено, сообщение, текущее количество покупок)
"""
# Владельцы бота не имеют ограничений
if user_id in OWNER_USER_IDS:
return True, "", 0
sub_type, _ = get_user_subscription(user_id)
if sub_type in [SubscriptionType.PRO, SubscriptionType.PRO_LIFETIME]:
return True, "", 0
# Для FREE пользователя проверяем лимит покупок
transactions = db.get_user_transactions(user_id)
purchase_count = len(transactions)
if purchase_count >= FREE_MAX_PURCHASES:
return False, "max_purchases_reached", purchase_count
return True, "", purchase_count
def can_view_statistics(user_id: int) -> bool:
"""
Проверить, может ли пользователь просматривать детальную статистику и графики
Returns:
bool: True если PRO или PRO_LIFETIME
"""
return has_pro_access(user_id)
def can_view_charts(user_id: int) -> bool:
"""
Проверить, может ли пользователь просматривать графики
Returns:
bool: True если PRO или PRO_LIFETIME
"""
return has_pro_access(user_id)
def can_use_extended_reserve(user_id: int) -> bool:
"""
Проверить, может ли пользователь использовать расширенный резерв
Returns:
bool: True если PRO или PRO_LIFETIME
"""
return has_pro_access(user_id)
def get_subscription_info(user_id: int) -> dict:
"""
Получить информацию о подписке пользователя для отображения
Returns:
dict: Информация о подписке
"""
# Владельцы бота всегда имеют PRO_LIFETIME
if user_id in OWNER_USER_IDS:
return {
'type': SubscriptionType.PRO_LIFETIME,
'type_name': 'PRO_LIFETIME',
'expires_at': None,
'is_pro': True,
'days_left': None, # Бессрочно
'is_owner': True
}
sub_type, expires_at = get_user_subscription(user_id)
info = {
'type': sub_type,
'type_name': sub_type.value,
'expires_at': expires_at,
'is_pro': has_pro_access(user_id),
'is_owner': False
}
if sub_type == SubscriptionType.PRO and expires_at:
info['days_left'] = (expires_at - datetime.now()).days
elif sub_type == SubscriptionType.PRO_LIFETIME:
info['days_left'] = None # Бессрочно
return info