-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
database.py
1146 lines (886 loc) · 30 KB
/
database.py
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import datetime
import sqlite3 as sq
from typing import Any, Dict, List
from core.service_provider.order_status import OrderStatus
logger = logging.getLogger(__name__)
connection = sq.connect("./database.db")
def sql_start():
if connection:
logger.info("Database connected successfully")
else:
raise Exception("Critical error! Failed to connect to database!")
cursor = connection.cursor()
cursor.execute(
"""CREATE TABLE IF NOT EXISTS category (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name TEXT NOT NULL,
parent_id INTEGER,
service INTEGER
)"""
)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS product (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
category_id INTEGER NOT NULL,
name TEXT NOT NULL,
minorder INTEGER,
maxorder INTEGER NOT NULL,
price INTEGER NOT NULL,
service_id INTEGER NOT NULL,
service_provider TEXT NOT NULL,
is_active BOOLEAN NOT NULL DEFAULT 1
)"""
)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
user_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
service_id INTEGER NOT NULL,
quantity INTEGER NOT NULL,
sum INTEGER NOT NULL,
url TEXT NOT NULL,
date DATETIME,
order_id INTEGER,
status TEXT,
refund INTEGER,
bot_id INTEGER
)"""
)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS user(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
user_id INTEGER NOT NULL,
balance FLOAT NOT NULL,
check_activate INTEGER,
affiliate_id INTEGER,
bot_id INTEGER
)"""
)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS Channel(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
channel_id INTEGER NOT NULL,
channel_name TEXT NOT NULL,
channel_url TEXT
)"""
)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS CheckForUser(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
from_user_id INTEGER NOT NULL,
sum INTEGER NOT NULL,
quantity INTEGER NOT NULL,
url TEXT NOT NULL,
linkcheckid INTEGER NOT NULL,
UserActivate TEXT,
typecheck TEXT NOT NULL,
id_channel TEXT,
total_quantity INTEGER NOT NULL
)"""
)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS Bots(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
api_key TEXT NOT NULL,
id_user INTEGER NOT NULL,
bot_username TEXT
)"""
)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS history(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
user_id TEXT NOT NULL,
sum INTEGER NOT NULL,
type TEXT NOT NULL,
date DATETIME NOT NULL,
time DATETIME NOT NULL,
from_user_id INTEGER,
order_id INTEGER
)"""
)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS paylink(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
user_id BIGINTEGER NOT NULL,
order_id VARCHAR(100) NOT NULL,
payment_system VARCHAR(100) NOT NULL,
bot_id INTEGER NOT_NULL,
amount FLOAT NOT NULL,
currency VARCHAR(10) NOT NULL,
created_at DATETIME NOT NULL,
status VARCHAR(20) NOT NULL
)"""
)
cursor.execute(
"""CREATE TABLE IF NOT EXISTS service(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
name VARCHAR(50) NOT NULL UNIQUE,
is_active BOOLEAN NOT NULL DEFAULT 1
)
"""
)
connection.commit()
sql_start()
def dict_factory(cursor, row):
data = {}
for idx, col in enumerate(cursor.description):
data[col[0]] = row[idx]
return data
def add_category(
name: str,
parent_id: int | None = None,
) -> int | None:
cursor = connection.cursor()
result = cursor.execute(
f"SELECT id FROM category WHERE name = '{name}'"
f"AND parent_id = '{parent_id}'"
).fetchone()
if not result:
result = cursor.execute(
f"INSERT INTO category (name, parent_id)"
f" VALUES ('{name}', '{parent_id}')"
" RETURNING RowId"
).fetchone()
connection.commit()
return result[0]
def get_subcategories(
name,
category_id,
):
cursor = connection.cursor()
name = cursor.execute(
f"SELECT id FROM category WHERE name = '{name}'"
f" AND parent_id = '{category_id}'"
)
return name.fetchone()[0]
def get_products(
provider_name: str,
) -> List[Dict[str, Any]]:
cursor = connection.cursor()
cursor.row_factory = dict_factory
products = cursor.execute(
f"SELECT * FROM product WHERE service_provider = '{provider_name}'"
).fetchall()
return products
def set_product_is_active(
product_id: int,
is_active: bool,
):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE product SET is_active = '{int(is_active)}'
WHERE id = '{product_id}'"""
)
connection.commit()
def update_product(
service_id: int,
min_quantity: int,
max_quantity: int,
price: int,
):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE product SET
minorder = '{min_quantity}',
maxorder = '{max_quantity}',
price = '{price}'
WHERE service_id = '{service_id}'"""
)
connection.commit()
def add_product(
category_id: int,
name: str,
min_quantity: int,
max_quantity: int,
price: float,
service_id: int,
service_provider: str,
is_active: bool = True,
):
cursor = connection.cursor()
product = cursor.execute(
f"""SELECT name FROM product
WHERE category_id = '{category_id}' AND name = '{name}'"""
).fetchone()
if not product:
cursor.execute(
f"""INSERT INTO product (
category_id, name, minorder, maxorder, price, service_id,
service_provider
) VALUES (
'{category_id}', '{name}', '{min_quantity}',
'{max_quantity}', '{price}', '{service_id}',
'{service_provider}'
)"""
)
connection.commit()
res = "товар успешно добавлен"
return res
else:
res = "такой товар уже есть"
return res
async def add_user(
user_id: int,
bot_id: int,
):
cursor = connection.cursor()
cursor.execute(
f"""INSERT INTO user (user_id, balance, check_activate, bot_id)
VALUES ('{user_id}', '{0}', '{0}', '{bot_id}')"""
)
connection.commit()
def update_user_affiliate(
user_id: int,
affiliate_id: int,
):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE user SET affiliate_id = '{affiliate_id}'
WHERE user_id = '{user_id}'"""
)
connection.commit()
async def UpdateBalance(user_id, Sum):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE user SET balance = balance + '{Sum}'
WHERE user_id = '{user_id}'"""
)
connection.commit()
async def WriteOffTheBalance(user_id, Sum):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE user SET balance = balance - '{Sum}'
WHERE user_id = '{user_id}' """
)
connection.commit()
async def is_user_exists(user_id: int) -> bool:
cursor = connection.cursor()
result = cursor.execute(
f"""SELECT id FROM user WHERE user_id = '{user_id}'"""
).fetchall()
return bool(len(result))
async def AddChanel(channel_id, Name, Url):
cursor = connection.cursor()
channel = cursor.execute(
f"""SELECT * FROM Channel WHERE channel_id = '{channel_id}'"""
).fetchone()
if not channel:
cursor.execute(
f"""INSERT INTO Channel (channel_id, channel_name, channel_url)
VALUES ('{channel_id}', '{Name}', '{Url}')"""
)
connection.commit()
async def GetChannelTitle(ChannelId):
cursor = connection.cursor()
channel = cursor.execute(
f"""SELECT channel_name FROM Channel
WHERE channel_id = '{ChannelId}'"""
).fetchone()[0]
return channel
async def GetChannelId(ChannelUrl):
cursor = connection.cursor()
channel = cursor.execute(
f"""SELECT channel_id FROM Channel
WHERE channel_name = '{ChannelUrl}'"""
).fetchone()
return channel
async def GetChannelUrl(ChannelID):
cursor = connection.cursor()
result = cursor.execute(
f"""SELECT channel_url FROM Channel WHERE channel_id = '{ChannelID}'"""
).fetchone()
return result[0] if result else None
async def AddCheck(
user_id,
price,
url,
linkcheckid,
TypeCheck,
quantity=1,
total_quantity=1,
) -> int:
cursor = connection.cursor()
cursor.execute(
f"""INSERT INTO CheckForUser (
from_user_id, sum, quantity, url, linkcheckid, typecheck,
total_quantity) VALUES (
'{user_id}', '{price}', '{quantity}', '{url}', '{linkcheckid}',
'{TypeCheck}', '{total_quantity}')
RETURNING RowId
"""
)
check_id = cursor.fetchone()[0]
connection.commit()
return check_id
async def GetCheckForUser(user_id=None, CheckId=None, LinkCheckId=None):
cursor = connection.cursor()
if user_id is not None:
check = cursor.execute(
f"""SELECT * FROM CheckForUser WHERE from_user_id = '{user_id}'"""
).fetchall()
elif CheckId is not None:
check = cursor.execute(
f"""SELECT * FROM CheckForUser WHERE id = '{CheckId}'"""
).fetchone()
elif LinkCheckId is not None:
check = cursor.execute(
f"""SELECT * FROM CheckForUser
WHERE linkcheckid = '{LinkCheckId}'"""
).fetchone()
return check
async def UpdateQuantityAndActivate(LinkIdCheck, IdActivate):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE CheckForUser SET quantity = quantity - 1
WHERE linkcheckid = '{LinkIdCheck}'"""
)
UserActivate = cursor.execute(
f"""SELECT USerActivate FROM CheckForUser
WHERE linkcheckid = '{LinkIdCheck}'"""
).fetchone()[0]
if UserActivate is None or UserActivate == "":
Id_User = f"{IdActivate}"
else:
Id_User = f"{UserActivate},{IdActivate}"
cursor.execute(
f"""UPDATE CheckForUser SET UserActivate = '{Id_User}'
WHERE linkcheckid = '{LinkIdCheck}'"""
)
connection.commit()
async def UpdateChannel(LinkIdCheck, Id_Channel):
cursor = connection.cursor()
ChanID = cursor.execute(
f"""SELECT id_channel FROM CheckForUser
WHERE linkcheckid = '{LinkIdCheck}'"""
).fetchone()[0]
if ChanID is None or ChanID == "":
Id_Channel = f"{Id_Channel}"
else:
Id_Channel = f"{ChanID},{Id_Channel}"
cursor.execute(
f"""UPDATE CheckForUser SET id_channel = '{Id_Channel}'
WHERE linkcheckid = '{LinkIdCheck}'"""
)
connection.commit()
async def DeleteChannelFromCheck(RealCheckId, ChannelID):
cursor = connection.cursor()
ChanID = cursor.execute(
f"""SELECT id_channel FROM CheckForUser WHERE id = '{RealCheckId}'"""
).fetchone()[0]
IDDeletes = ChanID.split(",")
IDDeletes.remove(str(ChannelID))
Id_channel = ",".join(IDDeletes)
cursor.execute(
f"""UPDATE CheckForUser SET id_channel = '{Id_channel}'
WHERE id = '{RealCheckId}'"""
)
connection.commit()
def add_bot(
api_token: str,
id_user: int,
bot_username: str,
):
cursor = connection.cursor()
Bots = cursor.execute(
f"SELECT * FROM Bots WHERE api_key = '{api_token}'"
).fetchone()
if not Bots:
cursor.execute(
f"""INSERT INTO Bots (api_key, id_user, bot_username) VALUES (
'{api_token}', '{id_user}', '{bot_username}')"""
)
connection.commit()
return True
else:
return False
def delete_bot(api_key):
cursor = connection.cursor()
cursor.execute(f"DELETE FROM Bots WHERE api_key = '{api_key}'")
connection.commit()
async def Add_History(
user_id,
sum,
type,
from_user_id: int | None = None,
order_id: int | None = None,
):
cursor = connection.cursor()
date = datetime.date.today()
time = datetime.datetime.now().time()
cursor.execute(
f"""INSERT INTO history (user_id, sum, type, date, time, from_user_id,
order_id) VALUES (
'{user_id}', '{sum}', '{type}', '{date}', '{time}',
'{from_user_id}', '{order_id}')"""
)
connection.commit()
async def Get_History(user_id):
cursor = connection.cursor()
res = cursor.execute(
f"""SELECT * FROM history WHERE user_id = '{user_id}'"""
).fetchall()
return res
def get_personal_checks_count(user_id: int) -> int:
return _get_checks_count_for_user(user_id, "personal")
def get_multi_checks_count(user_id: int) -> int:
return _get_checks_count_for_user(user_id, "multi")
def _get_checks_count_for_user(user_id: int, check_type: str) -> int:
cursor = connection.cursor()
result = cursor.execute(
"SELECT COUNT(*) FROM CheckForUser"
f" WHERE from_user_id = '{user_id}' AND typecheck = '{check_type}'"
)
try:
return int(result.fetchone()[0])
except ValueError:
return 0
def get_user_balance(user_id: int) -> float:
cursor = connection.cursor()
result = cursor.execute(
"SELECT balance FROM user" f" WHERE user_id = '{user_id}'"
)
try:
return round(float(result.fetchone()[0]), 2)
except ValueError:
return 0
def get_checks_for_user(user_id: int, check_type: str) -> List[Any]:
cursor = connection.cursor()
result = cursor.execute(
"SELECT * FROM CheckForUser"
f" WHERE from_user_id = '{user_id}' AND typecheck = '{check_type}'"
)
return result.fetchall()
def get_multi_hecks_for_user(user_id: int) -> List[Any]:
return get_checks_for_user(user_id, "multi")
def get_personal_checks_for_user(user_id: int) -> List[Any]:
return get_checks_for_user(user_id, "personal")
def get_check_by_id(check_id: int) -> List[Any]:
cursor = connection.cursor()
result = cursor.execute(
"SELECT * FROM CheckForUser" f" WHERE id = '{check_id}'"
)
return result.fetchone()
def get_check_by_check_number(check_number: int) -> Dict[str, Any]:
cursor = connection.cursor()
cursor.row_factory = dict_factory
result = cursor.execute(
"SELECT * FROM CheckForUser" f" WHERE linkcheckid = '{check_number}'"
)
return result.fetchone()
def get_check_by_user_id_and_check_id(
user_id: int, check_id: int
) -> List[Any]:
cursor = connection.cursor()
result = cursor.execute(
"SELECT * FROM CheckForUser"
f" WHERE from_user_id = '{user_id}' AND id = '{check_id}'"
)
return result.fetchone()
def delete_check_by_id(check_id: int):
cursor = connection.cursor()
cursor.execute(f"DELETE FROM CheckForUser WHERE id = '{check_id}'")
connection.commit()
def get_all_channels() -> List[Any]:
cursor = connection.cursor()
result = cursor.execute("SELECT * FROM Channel")
return result.fetchall()
def get_channels_for_check(check_id: int) -> List[Any]:
check = get_check_by_id(check_id)
if not check or not check[8]:
return []
channels_in_check_ids = list(
filter(lambda channel_id: channel_id != "", check[8].split(","))
)
if not channels_in_check_ids:
return []
channels = list(
filter(
lambda channel: str(channel[1]) in channels_in_check_ids,
get_all_channels(),
)
)
return channels
def get_channel_by_id(channel_id: int) -> List[Any]:
cursor = connection.cursor()
result = cursor.execute(
"SELECT * FROM Channel" f" WHERE channel_id = '{channel_id}'"
)
return result.fetchone()
def get_paylink_data_by_order_id(order_id: str) -> Dict[str, Any]:
cursor = connection.cursor()
cursor.row_factory = dict_factory
result = cursor.execute(
f"SELECT * FROM Paylink WHERE order_id = '{order_id}'"
)
return result.fetchone()
def get_bot_token_by_id(bot_id: int) -> str | None:
cursor = connection.cursor()
result = cursor.execute(f"SELECT api_key FROM Bots WHERE id = '{bot_id}'")
bot_id = result.fetchone()
return bot_id[0] if bot_id else None
def get_bot_id_by_token(token: str) -> int | None:
cursor = connection.cursor()
result = cursor.execute(f"SELECT id FROM Bots WHERE api_key = '{token}'")
bot_id = result.fetchone()
return bot_id[0] if bot_id else None
def get_bot_data_by_token(token: str) -> Dict[str, Any] | None:
cursor = connection.cursor()
cursor.row_factory = dict_factory
result = cursor.execute(f"SELECT * FROM Bots WHERE api_key = '{token}'")
return result.fetchone()
def get_bot_data_by_id(bot_id: int) -> Dict[str, Any] | None:
cursor = connection.cursor()
cursor.row_factory = dict_factory
result = cursor.execute(f"SELECT * FROM Bots WHERE id = '{bot_id}'")
return result.fetchone()
def update_bot_username(
bot_id: int,
username: str,
):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE Bots SET bot_username = '{username}'
WHERE id = '{bot_id}'""",
)
connection.commit()
def add_paylink(
user_id: int,
order_id: str,
payment_system: str,
bot_id: int,
amount: float,
currency: str = "RUB",
):
cursor = connection.cursor()
result = cursor.execute(
f"""
INSERT INTO Paylink
(user_id, order_id, payment_system, bot_id, amount, created_at, status,
currency)
VALUES
('{user_id}', '{order_id}', '{payment_system}', '{bot_id}', '{amount}',
'{datetime.datetime.now()}', 'pending', '{currency}')
RETURNING RowId
"""
)
paylink_id = result.fetchone()[0]
connection.commit()
return paylink_id
def update_paylink_order_id(
paylink_id: int,
order_id: str,
):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE Paylink SET order_id = '{order_id}'
WHERE id = '{paylink_id}'""",
)
connection.commit()
def set_paylink_paid(paylink_id: int, amount: float):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE Paylink SET status = 'paid', amount = '{amount}'
WHERE id = '{paylink_id}'""",
)
connection.commit()
def update_user_balance(
user_id: int,
amount: float,
):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE user SET balance = balance + '{amount}'
WHERE user_id = '{user_id}'""",
)
connection.commit()
def get_affiliate_id(user_id: int) -> int | None:
cursor = connection.cursor()
cursor.execute(
f"""SELECT affiliate_id FROM user WHERE user_id = '{user_id}'"""
)
return cursor.fetchone()[0]
def get_referrals(
user_id: int,
depth: int = 1,
) -> List[Any]:
cursor = connection.cursor()
cursor.row_factory = dict_factory
referrals = cursor.execute(
f"""SELECT * FROM user WHERE affiliate_id = '{user_id}'"""
).fetchall()
while depth > 1:
for referral in referrals:
referrals.extend(
cursor.execute(
f"""SELECT * FROM user
WHERE affiliate_id = '{referral["user_id"]}'"""
).fetchall()
)
return referrals
def get_total_bonus_amount(
user_id: int,
) -> int:
cursor = connection.cursor()
cursor.execute(
f"""SELECT SUM(sum) FROM history
WHERE user_id = {user_id}
AND type = 'Бонус - Новый реферал'
OR type = 'Бонус - Заказ услуги рефералом'"""
)
return cursor.fetchone()[0] or 0
def get_active_categories(
limit: int,
page: int,
services: List[str],
) -> List[Dict[str, Any]]:
cursor = connection.cursor()
cursor.row_factory = dict_factory
query = f"""SELECT DISTINCT category.* FROM category
LEFT JOIN category as subcategory
ON subcategory.parent_id = category.id
LEFT JOIN product
ON category.id = product.category_id
OR subcategory.id = product.category_id
WHERE category.parent_id = 'None' AND product.is_active = 1
AND product.service_provider IN ({",".join(["?"] * len(services))})
LIMIT ? OFFSET ?"""
params = [*services, limit + 1, (page - 1) * limit]
result = cursor.execute(query, params)
return result.fetchall()
def get_active_subcategories(
limit: int,
page: int,
services: List[str],
parent_id: int | None = None,
) -> List[Dict[str, Any]]:
cursor = connection.cursor()
cursor.row_factory = dict_factory
query = f"""SELECT DISTINCT category.* FROM category
INNER JOIN product ON category.id = product.category_id
WHERE category.parent_id = ? AND product.is_active = 1
AND product.service_provider IN ({",".join(["?"] * len(services))})
LIMIT ? OFFSET ?"""
params = [parent_id, *services, limit + 1, (page - 1) * limit]
result = cursor.execute(query, params)
return result.fetchall()
def get_active_products(
limit: int,
page: int,
category_id: int,
services: List[str],
) -> List[Dict[str, Any]]:
cursor = connection.cursor()
cursor.row_factory = dict_factory
query = f"""SELECT * FROM product
WHERE category_id = ? AND is_active = 1
AND service_provider IN ({",".join(["?"] * len(services))})
LIMIT ? OFFSET ?"""
params = [category_id, *services, limit + 1, (page - 1) * limit]
result = cursor.execute(query, params)
return result.fetchall()
def get_product_by_id(
product_id: int,
) -> Dict[str, Any]:
cursor = connection.cursor()
cursor.row_factory = dict_factory
result = cursor.execute(f"SELECT * FROM product WHERE id = '{product_id}'")
return result.fetchone()
def add_order(
user_id: int,
product_id: int,
service_id: int,
quantity: int,
total_amount: float,
url: str,
bot_id: int | None,
) -> int | None:
cursor = connection.cursor()
result = cursor.execute(
f"""INSERT INTO orders (
user_id, product_id, service_id, quantity, sum, url, date,
status, bot_id
) VALUES (
'{user_id}', '{product_id}', '{service_id}', '{quantity}',
'{total_amount}', '{url}', '{datetime.datetime.now()}',
'{OrderStatus.PENDING_PAYMENT.value}', '{bot_id}'
) RETURNING RowId"""
)
internal_order_id = result.fetchone()[0]
connection.commit()
return internal_order_id
def get_order_by_id(order_id: int) -> Dict[str, Any]:
cursor = connection.cursor()
cursor.row_factory = dict_factory
result = cursor.execute(
f"""SELECT orders.*, product.name, product.service_provider FROM orders
LEFT JOIN product ON orders.product_id = product.id
WHERE orders.id = '{order_id}'"""
)
return result.fetchone()
def get_orders_for_pagination(
user_id: int | None = None,
order_id_like: int | None = None,
statuses: List[OrderStatus] | None = None,
limit: int | None = None,
page: int | None = None,
user_id_like: str | None = None,
link_like: str | None = None,
) -> List[Dict[str, Any]]:
cursor = connection.cursor()
cursor.row_factory = dict_factory
query = """SELECT orders.*, product.name FROM orders
LEFT JOIN product ON orders.product_id = product.id"""
if any((user_id, statuses, user_id_like, link_like)):
query += " WHERE"
conditions = []
if user_id:
conditions.append(f"user_id = '{user_id}'")
if user_id_like:
conditions.append(f"user_id LIKE '%{str(user_id_like)}%'")
if statuses:
statuses_string = ",".join(
[f"'{status.value}'" for status in statuses]
)
conditions.append(f"status IN ({statuses_string})")
if link_like:
conditions.append(f"url LIKE '%{link_like}%'")
if order_id_like:
conditions.append(
f"order_id LIKE '%{str(order_id_like)}%' OR orders.id = '{str(order_id_like)}'" # noqa
)
query += " " + " AND ".join(conditions)
if limit:
query += f" LIMIT {limit + 1}"
if page:
query += f" OFFSET {(page - 1) * limit}"
result = cursor.execute(query)
return result.fetchall()
def update_order_status(
order_id: int,
status: OrderStatus,
) -> None:
cursor = connection.cursor()
cursor.execute(
f"""UPDATE orders SET status = '{status.value}'
WHERE id = '{order_id}'"""
)
connection.commit()
def update_order_status_and_external_id(
order_id: int,
status: OrderStatus,
external_id: int,
):
cursor = connection.cursor()
cursor.execute(
f"""UPDATE orders SET
status = '{status.value}', order_id = '{external_id}'
WHERE id = '{order_id}'"""
)
connection.commit()
def get_orders_ids_for_check(service: str) -> List[int]:
cursor = connection.cursor()
cursor.execute(
f"""SELECT orders.id, orders.order_id FROM orders
LEFT JOIN product ON orders.product_id = product.id
WHERE service_provider = '{service}'
AND status in ('{OrderStatus.STARTING.value}',
'{OrderStatus.IN_PROGRESS.value}')"""
)
return cursor.fetchall()