-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
382 lines (332 loc) · 13.8 KB
/
Copy pathdatabase.py
File metadata and controls
382 lines (332 loc) · 13.8 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Veritabanı Bağlantı ve İşlem Modülü
MySQL veritabanı ile güvenli bağlantı ve CRUD işlemleri
"""
import os
import logging
import mysql.connector
from mysql.connector import pooling, Error
from typing import List, Dict, Optional, Any
from datetime import datetime
from dotenv import load_dotenv
# .env dosyasını yükle
load_dotenv()
class DatabaseConnection:
"""MySQL veritabanı bağlantı ve işlem sınıfı"""
def __init__(self):
"""Veritabanı bağlantısını başlat"""
self.config = {
'host': os.getenv('DB_HOST', 'localhost'),
'user': os.getenv('DB_USER', 'root'),
'password': os.getenv('DB_PASSWORD', ''),
'database': os.getenv('DB_NAME', 'vergi_bot_db'),
'charset': 'utf8mb4',
'collation': 'utf8mb4_unicode_ci',
'autocommit': True,
'raise_on_warnings': True
}
# Connection pool konfigürasyonu
self.pool_config = {
'pool_name': 'vergi_bot_pool',
'pool_size': 5,
'pool_reset_session': True,
**self.config
}
self.pool = None
self.connection = None
self.logger = self.setup_logging()
def setup_logging(self):
"""Logging konfigürasyonu"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
return logging.getLogger(__name__)
def connect(self):
"""Veritabanı bağlantısı kur"""
try:
# Connection pool oluştur
self.pool = pooling.MySQLConnectionPool(**self.pool_config)
self.logger.info("✅ MySQL connection pool oluşturuldu")
# Test bağlantısı
test_conn = self.pool.get_connection()
if test_conn.is_connected():
test_conn.close()
self.logger.info("✅ Veritabanı bağlantısı başarılı")
return True
except Error as e:
self.logger.error(f"❌ Veritabanı bağlantı hatası: {str(e)}")
# Fallback: Direkt bağlantı dene
return self.direct_connect()
except Exception as e:
self.logger.error(f"❌ Beklenmeyen veritabanı hatası: {str(e)}")
return False
def direct_connect(self):
"""Direkt veritabanı bağlantısı (pool olmadan)"""
try:
self.connection = mysql.connector.connect(**self.config)
if self.connection.is_connected():
self.logger.info("✅ Direkt veritabanı bağlantısı başarılı")
return True
except Error as e:
self.logger.error(f"❌ Direkt bağlantı hatası: {str(e)}")
return False
def get_connection(self):
"""Bağlantı al (pool'dan veya direkt)"""
try:
if self.pool:
return self.pool.get_connection()
elif self.connection and self.connection.is_connected():
return self.connection
else:
# Yeniden bağlan
if self.connect():
return self.connection
return None
except Exception as e:
self.logger.error(f"❌ Bağlantı alma hatası: {str(e)}")
return None
def execute_query(self, query: str, params: tuple = None, fetch: bool = True) -> Optional[List[Dict]]:
"""Güvenli SQL sorgusu çalıştır"""
connection = None
cursor = None
try:
connection = self.get_connection()
if not connection:
raise Exception("Veritabanı bağlantısı alınamadı")
cursor = connection.cursor(dictionary=True)
# Parametreli sorgu çalıştır
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
# SELECT sorguları için sonuçları al
if fetch and query.strip().upper().startswith('SELECT'):
results = cursor.fetchall()
return results
# INSERT/UPDATE/DELETE sorguları için commit
if not query.strip().upper().startswith('SELECT'):
connection.commit()
return [{'affected_rows': cursor.rowcount, 'last_insert_id': cursor.lastrowid}]
return []
except Error as e:
self.logger.error(f"❌ SQL hatası: {str(e)}")
self.logger.error(f"❌ Query: {query}")
if connection:
connection.rollback()
return None
except Exception as e:
self.logger.error(f"❌ Veritabanı işlem hatası: {str(e)}")
return None
finally:
if cursor:
cursor.close()
if connection and self.pool:
connection.close() # Pool'a geri ver
def execute_many(self, query: str, params_list: List[tuple]) -> bool:
"""Çoklu insert/update işlemi"""
connection = None
cursor = None
try:
connection = self.get_connection()
if not connection:
return False
cursor = connection.cursor()
cursor.executemany(query, params_list)
connection.commit()
self.logger.info(f"✅ {cursor.rowcount} kayıt işlendi")
return True
except Error as e:
self.logger.error(f"❌ Batch işlem hatası: {str(e)}")
if connection:
connection.rollback()
return False
finally:
if cursor:
cursor.close()
if connection and self.pool:
connection.close()
# Kullanıcı işlemleri
def add_user(self, user_id: int, username: str, chat_id: int) -> bool:
"""Yeni kullanıcı ekle"""
try:
result = self.execute_query(
"""INSERT IGNORE INTO users (user_id, username, chat_id, created_at, is_active)
VALUES (%s, %s, %s, %s, %s)""",
(user_id, username, chat_id, datetime.now(), True),
fetch=False
)
return result is not None
except Exception as e:
self.logger.error(f"❌ Kullanıcı ekleme hatası: {str(e)}")
return False
def get_user(self, user_id: int) -> Optional[Dict]:
"""Kullanıcı bilgilerini getir"""
try:
result = self.execute_query(
"SELECT * FROM users WHERE user_id = %s",
(user_id,)
)
return result[0] if result else None
except Exception as e:
self.logger.error(f"❌ Kullanıcı getirme hatası: {str(e)}")
return None
def update_user_reminder(self, user_id: int, reminder_days: int) -> bool:
"""Kullanıcı hatırlatma ayarlarını güncelle"""
try:
result = self.execute_query(
"UPDATE users SET reminder_days = %s WHERE user_id = %s",
(reminder_days, user_id),
fetch=False
)
return result is not None
except Exception as e:
self.logger.error(f"❌ Hatırlatma güncelleme hatası: {str(e)}")
return False
def get_active_users_with_reminders(self) -> List[Dict]:
"""Hatırlatması aktif kullanıcıları getir"""
try:
result = self.execute_query(
"SELECT * FROM users WHERE is_active = TRUE AND reminder_days IS NOT NULL"
)
return result or []
except Exception as e:
self.logger.error(f"❌ Aktif kullanıcılar getirme hatası: {str(e)}")
return []
# Vergi takvimi işlemleri
def add_tax_event(self, tax_type: str, deadline_date: datetime, description: str, source: str = 'GİB') -> bool:
"""Vergi takvimi etkinliği ekle"""
try:
result = self.execute_query(
"""INSERT INTO tax_calendar (tax_type, deadline_date, description, source)
VALUES (%s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
description = VALUES(description),
updated_at = CURRENT_TIMESTAMP""",
(tax_type, deadline_date, description, source),
fetch=False
)
return result is not None
except Exception as e:
self.logger.error(f"❌ Vergi etkinliği ekleme hatası: {str(e)}")
return False
def get_upcoming_tax_events(self, days_ahead: int = 30) -> List[Dict]:
"""Yaklaşan vergi etkinliklerini getir"""
try:
result = self.execute_query(
"""SELECT * FROM tax_calendar
WHERE deadline_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL %s DAY)
ORDER BY deadline_date ASC""",
(days_ahead,)
)
return result or []
except Exception as e:
self.logger.error(f"❌ Yaklaşan vergi etkinlikleri hatası: {str(e)}")
return []
# Duyuru işlemleri
def add_announcement(self, title: str, content: str, url: str = '', source: str = 'GİB',
category: str = 'Duyuru', published_date: datetime = None) -> bool:
"""Duyuru ekle"""
try:
if not published_date:
published_date = datetime.now()
result = self.execute_query(
"""INSERT IGNORE INTO announcements
(title, content, url, source, category, published_date)
VALUES (%s, %s, %s, %s, %s, %s)""",
(title, content, url, source, category, published_date),
fetch=False
)
return result is not None
except Exception as e:
self.logger.error(f"❌ Duyuru ekleme hatası: {str(e)}")
return False
def get_recent_announcements(self, limit: int = 10) -> List[Dict]:
"""Son duyuruları getir"""
try:
result = self.execute_query(
"""SELECT * FROM announcements
ORDER BY published_date DESC, created_at DESC
LIMIT %s""",
(limit,)
)
return result or []
except Exception as e:
self.logger.error(f"❌ Son duyurular getirme hatası: {str(e)}")
return []
# İstatistik fonksiyonları
def get_user_count(self) -> int:
"""Aktif kullanıcı sayısını getir"""
try:
result = self.execute_query(
"SELECT COUNT(*) as count FROM users WHERE is_active = TRUE"
)
return result[0]['count'] if result else 0
except Exception as e:
self.logger.error(f"❌ Kullanıcı sayısı hatası: {str(e)}")
return 0
def get_database_stats(self) -> Dict:
"""Veritabanı istatistiklerini getir"""
try:
stats = {}
# Kullanıcı sayısı
stats['users'] = self.get_user_count()
# Vergi etkinlikleri sayısı
result = self.execute_query("SELECT COUNT(*) as count FROM tax_calendar")
stats['tax_events'] = result[0]['count'] if result else 0
# Duyuru sayısı
result = self.execute_query("SELECT COUNT(*) as count FROM announcements")
stats['announcements'] = result[0]['count'] if result else 0
# Hatırlatması aktif kullanıcı sayısı
result = self.execute_query(
"SELECT COUNT(*) as count FROM users WHERE is_active = TRUE AND reminder_days IS NOT NULL"
)
stats['users_with_reminders'] = result[0]['count'] if result else 0
return stats
except Exception as e:
self.logger.error(f"❌ İstatistik hatası: {str(e)}")
return {}
def close_connection(self):
"""Bağlantıları kapat"""
try:
if self.connection and self.connection.is_connected():
self.connection.close()
self.logger.info("✅ Direkt veritabanı bağlantısı kapatıldı")
except Exception as e:
self.logger.error(f"❌ Bağlantı kapatma hatası: {str(e)}")
# Test fonksiyonu
def test_database():
"""Veritabanı bağlantısını test et"""
print("🔧 Veritabanı Bağlantı Testi")
print("-" * 40)
db = DatabaseConnection()
try:
# Bağlantı testi
if db.connect():
print("✅ Bağlantı başarılı")
else:
print("❌ Bağlantı başarısız")
return
# Basit sorgu testi
result = db.execute_query("SELECT 1 as test")
if result:
print("✅ Sorgu testi başarılı")
else:
print("❌ Sorgu testi başarısız")
# İstatistik testi
stats = db.get_database_stats()
if stats:
print("✅ İstatistik testi başarılı")
for key, value in stats.items():
print(f" {key}: {value}")
else:
print("❌ İstatistik testi başarısız")
print("\n✅ Tüm testler başarılı!")
except Exception as e:
print(f"❌ Test hatası: {str(e)}")
finally:
db.close_connection()
if __name__ == "__main__":
test_database()