File size: 32,604 Bytes
3b0afe1
edee679
16c32c6
3b0afe1
 
 
91794fe
 
 
0ebc988
91794fe
e3d9e7e
9ea317e
7cffc90
 
 
 
 
 
e3d9e7e
9ea317e
 
e3d9e7e
9ea317e
 
e3d9e7e
 
9ea317e
 
9835398
4ea10fb
e3d9e7e
6fe9705
 
 
56c2d00
6fe9705
 
4ea10fb
8eea621
1959ad7
 
 
 
 
9ea317e
 
 
9f74cf3
58cae0c
3b0afe1
 
6e5ec17
3b0afe1
 
40c4f6f
568706e
 
3b0afe1
 
 
 
 
 
 
 
aaf4b83
02c1a34
 
c64a996
 
0d590a3
 
02c1a34
8854564
aaf4b83
 
c60c13e
02c1a34
 
8854564
3b0afe1
 
 
 
40c4f6f
3b0afe1
 
1d05f9c
91794fe
 
 
 
 
 
ff2f4f2
b639d39
fc0a8f9
 
 
 
 
 
 
 
b639d39
9a54d5a
fc0a8f9
 
 
 
 
 
 
 
9a54d5a
ff2f4f2
b639d39
ff2f4f2
fc0a8f9
b639d39
 
 
 
 
 
fc0a8f9
b639d39
 
 
9a54d5a
559c07c
9a54d5a
 
 
 
 
 
b54c0ac
 
 
fc0a8f9
b639d39
 
b54c0ac
9a54d5a
11adb51
ff2f4f2
 
760796a
 
6fe9705
 
549d039
 
 
efab428
 
549d039
 
6fe9705
ff2f4f2
6fe9705
 
 
549d039
 
6fe9705
549d039
6fe9705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ea317e
 
 
 
11adb51
9ea317e
 
 
11adb51
9ea317e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11adb51
9ea317e
 
6c60c6b
9ea317e
 
 
6c60c6b
11adb51
 
 
 
 
e3d9e7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11adb51
c60c13e
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14af27b
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40c4f6f
3b0afe1
 
40c4f6f
3b0afe1
 
40c4f6f
3b0afe1
40c4f6f
69c75b8
3b0afe1
 
 
 
 
04d4d7b
 
 
 
 
 
6540fed
04d4d7b
 
 
 
 
fba775c
 
 
04d4d7b
 
fba775c
 
 
 
 
 
 
 
04d4d7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c977bc
61688b6
547dedc
adb7cc4
 
 
 
 
 
3d64fc1
 
3b0afe1
adb7cc4
e0c01fb
61688b6
 
 
 
 
3b0afe1
 
 
6be9f95
 
adb7cc4
6be9f95
adb7cc4
 
 
6be9f95
 
 
 
 
 
6d66942
3b0afe1
 
 
 
adb7cc4
3b0dddb
 
 
3b0afe1
e0c01fb
6be9f95
 
 
 
 
 
7b699a2
6be9f95
6d66942
6be9f95
7b699a2
6d66942
6be9f95
 
 
7b699a2
6d66942
 
7b699a2
6d66942
6be9f95
e0c01fb
 
3b0afe1
6be9f95
e0c01fb
6be9f95
3b0afe1
0a3e3b6
6be9f95
 
adb7cc4
8578d73
 
 
adb7cc4
6be9f95
 
 
 
 
3b0afe1
 
 
 
c9f3409
3b0afe1
 
 
 
 
 
 
 
 
 
 
ba7ecbd
3b0afe1
 
 
 
 
d6502ff
 
40f4dc8
 
 
 
 
 
e4f605f
d6502ff
 
832db13
 
 
 
 
2f1eeaa
 
 
 
d6502ff
2f1eeaa
 
 
 
 
3f56d68
dc5702a
6d66942
3f56d68
 
2f1eeaa
 
 
3f56d68
 
dc5702a
5a67db9
dc5702a
5a67db9
3f56d68
2f1eeaa
 
e4c74f9
 
 
d6502ff
 
 
 
 
 
832db13
d6502ff
ba7ecbd
d6502ff
 
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6723e97
 
 
 
 
 
 
5fa984e
 
 
 
2ff4383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a2a453d
2ff4383
 
 
 
de261a4
 
 
2ff4383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa984e
e16ded1
3b0afe1
 
 
5fa984e
 
6cadefe
 
3b0afe1
 
 
6cadefe
51209a6
21416a0
 
3b0afe1
 
 
21416a0
51209a6
93e28e6
 
3b0afe1
 
 
93e28e6
 
2409275
 
3b0afe1
 
 
2409275
51209a6
d0a921f
 
3b0afe1
 
 
d0a921f
40c4f6f
dfeb4d9
 
3b0afe1
 
 
dfeb4d9
40c4f6f
093826a
 
3b0afe1
 
 
093826a
40c4f6f
bd7bcf1
 
3b0afe1
 
 
bd7bcf1
40c4f6f
4f15ddd
 
3b0afe1
 
 
4f15ddd
40c4f6f
30d9d78
 
3b0afe1
 
 
30d9d78
40c4f6f
2844e4a
 
3b0afe1
 
 
2844e4a
3b0afe1
9ed0eaa
13a3385
3b0afe1
 
 
 
4f15ddd
b9757a6
 
3b0afe1
 
 
b9757a6
1d05f9c
fafa910
 
 
 
 
 
5fa984e
 
 
 
 
 
 
3b0afe1
 
 
 
 
 
 
 
 
e0c01fb
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e5ec17
9368cf0
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e0c01fb
3b0afe1
 
e0c01fb
9368cf0
3b0afe1
e0c01fb
3b0afe1
e0c01fb
edee679
3b0afe1
 
 
 
e0c01fb
3b0afe1
 
 
 
 
69c75b8
e0c01fb
afbd53b
e0c01fb
 
4818e9b
3b0afe1
e0c01fb
3b0afe1
e0c01fb
4595fee
e976dab
 
 
3b0afe1
e976dab
3b0afe1
 
 
 
e976dab
3b0afe1
 
e976dab
3b0afe1
 
 
 
 
 
e976dab
3b0afe1
 
 
 
 
 
 
e976dab
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
668afb7
3b0afe1
 
 
885c383
3b0afe1
 
 
 
 
 
e976dab
3b0afe1
 
e976dab
3b0afe1
 
 
 
e976dab
3b0afe1
 
 
e976dab
 
 
 
 
3b0afe1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e976dab
3b0afe1
 
e976dab
3b0afe1
 
 
 
 
 
 
 
e976dab
 
 
 
 
 
 
9ea317e
 
 
 
 
 
 
33de58e
62530ca
9ea317e
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
from flask import Flask, request, render_template_string, render_template, jsonify
import sqlite3
import os
import random
import requests
import time
import re
import json
import base64

from unidecode import unidecode

api_key_sys = os.getenv('api_key_sys')  
# Ваш API-ключ
gc_url_gru = os.getenv('gc_url_gru')

gc_url_export = os.getenv('gc_url_export')  # URL для экспорта данных

start_up = os.getenv('start_up')  

gc_url = os.getenv('gc_url')   
gc_api = os.getenv('gc_api')  

wa_url = os.getenv('wa_url') 
wa_api_key = os.getenv('wa_api_key') 


up_db = os.getenv('up_db') 

id_gru = os.getenv('id_gru') 
date_from = "2022-01-01"


export_id = ""  

code_executed = False


status = "active"
json_data = '''

{"success":true,"error_message":"","error":false,"info": {"fields":["id","Email","Тип регистрации","Создан","Последняя активность","Имя","Фамилия","Телефон","Дата рождения","Возраст","Страна","Город","От партнера","Руч продлен Клуба","Промокод","bonus_05_23","Клуб 255 - колл. оплат","Согласен с договором оферты и политикой конфиденциальности","Согласен на рассылку","vk_id","chat_id","ws_st","ws_stop","web_st","fin_prog","shop_st","curator","pr1","pr2","pr3","pr4","pr5","ad_url","Ответ сервера","Откуда пришел","utm_source","utm_medium","utm_campaign","utm_term","utm_content","utm_group","ID партнера","Email партнера","ФИО партнера","ФИО менеджера","VK-ID","ID группы","Добавлен в группу"],"items": [["296260454","Lelechka18-05@mail.ru","Зарегистрировался самостоятельно","2023-02-13 22:20:42","2024-07-05 10:21:18","Ольга","Горшкова","79150408998","1988-05-18","36","Россия","Москва","","","PSYDM5_0","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","2993783","2023-09-03 12:19:08"],["315668856","julia20041986@mail.ru","Зарегистрировался самостоятельно","2023-05-25 16:05:43","2024-07-10 16:43:06","Юлия","Грищук","+79527936944","1986-11-13","38","Германия","Калининград ","","","","","","","","","","","","","","","","","","","","","","","https:\/\/webinar.riverpsy.com\/","telegram-bot","","","","","","","","","","","2993783","2023-09-03 12:19:08"],["316251009","elenakrylova9@gmail.com","Зарегистрировался самостоятельно","2023-05-29 13:26:11","2024-07-13 10:49:42","Елена","","+33614075834","","","Франция","","","","","","","","","","","","","","","","","","","","","","","","","telegram-channel","","","","","","","","","","","2993783","2023-09-03 12:19:08"],["323062565","Cboyak@mail.ru","Зарегистрировался самостоятельно","2023-07-05 11:08:11","2024-07-05 22:28:50","Старухина","Ксения","79872598129","","","Россия","","","","","","","","","","","","","","","","","","","","","","","","https:\/\/www.google.ru\/","google*","organic","","","","","","","","","20712833","2993783","2023-09-03 12:19:08"],["392646517","Skryabina.irina82@gmail.com","Приглашен администратором","2024-06-03 19:11:09","2024-07-10 13:54:45","Ирина","сотрудник","79124871139","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","2993783","2024-06-03 19:24:01"]]}}


'''




app = Flask(__name__, template_folder="./")
app.config['DEBUG'] = True
UPLOAD_FOLDER = 'static'

if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

DATABASES = ['data_gc.db', 'data1.db', 'data2.db', 'data3.db', 'data4.db', 'data5.db']

def init_db(db_name):
    conn = sqlite3.connect(db_name)
    cursor = conn.cursor()
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS contacts (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            phone TEXT NOT NULL,
            email TEXT NOT NULL,
            vk_id TEXT NOT NULL,
            chat_id TEXT NOT NULL,
            ws_statys TEXT NOT NULL,
            ws_stop TEXT NOT NULL,
            web_statys INTEGER,
            fin_progress INTEGER,
            shop_statys_full TEXT NOT NULL,
            curator TEXT NOT NULL,
            pr1 TEXT NOT NULL,
            pr2 TEXT NOT NULL,
            pr3 TEXT NOT NULL,
            pr4 TEXT NOT NULL,
            pr5 TEXT NOT NULL,
            ad_url TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()

for db in DATABASES:
    init_db(db)







# Функции для выполнения HTTP запросов
def fetch(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        print(f"GET запрос к {url} выполнен успешно.")
        return response.json()
    except requests.RequestException as e:
        print(f"Ошибка при выполнении GET запроса к {url}: {e}")
        return None

def send_notification(url, data):
    try:
        response = requests.post(url, json=data)
        response.raise_for_status()
        print(f"POST запрос к {url} выполнен успешно.")
        return response.json()
    except requests.RequestException as e:
        print(f"Ошибка при выполнении POST запроса к {url}: {e}")
        return None

# Основная функция для отправки запросов
def send_requests():
    global code_executed, export_id
    print(f"Функция send_requests вызвана. start_up: {start_up}, code_executed: {code_executed}")

    if start_up == '1' and not code_executed:
        try:
            # Первый запрос
            url_template = f"{gc_url_gru}/{id_gru}/users?key={gc_api}&created_at[from]={date_from}&status={status}"
            data = fetch(url_template)
            if data and data.get("success"):
                export_id = data.get("info", {}).get("export_id", "")
                print("Export ID:", export_id)

                # Отправка оповещения на другой сервер
                notification_url = "https://skyauto.me/cllbck/217669590/29245685/bGZuMDRZZUpLZ3VJR2oxcC9CQmh0UT0?api=1&uid=535939344"  # Замените на ваш URL
                notification_data = {
                    "message": "Первый запрос был выполнен",
                    "export_id": export_id
                }
                notification_response = send_notification(notification_url, notification_data)
                print("Ответ от сервера оповещения:", notification_response)

                code_executed = True  # Устанавливаем флаг выполнения кода
            else:
                raise Exception(f"Ошибка в ответе от сервера: {data.get('error_message') if data else 'Нет данных'}")
        except Exception as e:
            print(f"Ошибка: {e}")
    else:
        print("Системная переменная start_up не равна '1' или код уже выполнялся.")

# Функция для отправки второго запроса
def send_second_request(export_id):
    if export_id is None:
        raise Exception("export_id is None")
    # Формирование URL для второго запроса
    export_url_template = f"{gc_url_export}/{export_id}?key={gc_api}"
    try:
        response = requests.get(export_url_template)
        response.raise_for_status()
        print("Ответ сервера:")
        print(response.text)  # Вывод ответа сервера в консоль
    except requests.RequestException as e:
        print(f"Ошибка при выполнении запроса: {e}")

# Маршрут для экспорта пользователя
@app.route('/export_user', methods=['GET'])
def export_user():
    try:
        send_second_request(export_id)
        return "Запрос выполнен", 200
    except Exception as e:
        return json.dumps({"error": str(e)}), 500















def load_data_from_json():
    data = json.loads(json_data)
    items = data['info']['items']
    fields = data['info']['fields']

    db = 'data_gc.db'  # Указываем конкретную базу данных
    conn = sqlite3.connect(db)
    cursor = conn.cursor()

    for item in items:
        user_data = dict(zip(fields, item))
        # Проверяем наличие значений для полей и устанавливаем значения по умолчанию, если они отсутствуют
        user_data.setdefault('vk_id', '')
        user_data.setdefault('chat_id', '')
        user_data.setdefault('ws_st', '')
        user_data.setdefault('ws_stop', '')
        user_data.setdefault('web_st', '')
        user_data.setdefault('fin_prog', '')
        user_data.setdefault('shop_st', '')
        user_data.setdefault('curator', '')
        user_data.setdefault('pr1', '')
        user_data.setdefault('pr2', '')
        user_data.setdefault('pr3', '')
        user_data.setdefault('pr4', '')
        user_data.setdefault('pr5', '')
        user_data.setdefault('ad_url', '')

        # Убираем плюс в начале телефона, если он присутствует
        if 'Телефон' in user_data and user_data['Телефон'].startswith('+'):
            user_data['Телефон'] = user_data['Телефон'][1:]

        query = '''
        INSERT INTO contacts (
         name, phone, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator
        ) VALUES (
         :Имя, :Телефон, :Email, :vk_id, :chat_id, :ws_st, :ws_stop, :web_st, :fin_prog, :shop_st, :pr1, :pr2, :pr3, :pr4, :pr5, :ad_url, :curator
        )
        '''
        cursor.execute(query, user_data)

    conn.commit()
    conn.close()

@app.before_first_request
def before_first_request():
    load_data_from_json()






















    
def randomize_message(template):
    def replace_placeholder(match):
        options = match.group(1).split('|')
        return random.choice(options)

    return re.sub(r'\{([^}]+)\}', replace_placeholder, template)

def clean_phone_number(phone):
    if phone.startswith('+'):
        return phone[1:]
    return phone

def send_message(chat_id, message):
    #base_url = os.getenv('wa_url')
    #api_key = os.getenv('wa_api_key')
    full_url = f"{wa_url}{wa_api_key}"
    payload = {
        "chatId": chat_id,
        "message": message
    }
    headers = {
        'Content-Type': 'application/json'
    }
    response = requests.request("POST", full_url, headers=headers, json=payload)
    try:
        response_json = response.json()
    except ValueError:
        response_json = {"error": "Invalid JSON response"}
    return response_json

def check_and_send_mailings(mesage_db1, clean_db):
    try:
        results = []
        for database in DATABASES:
            conn = sqlite3.connect(database)
            cursor = conn.cursor()
            cursor.execute('SELECT name, phone FROM contacts')
            contacts = cursor.fetchall()
            conn.close()

            for contact in contacts:
                name = contact[0]
                chat_id = f"{clean_phone_number(contact[1])}@c.us"
                message = randomize_message(mesage_db1)
                message = message.replace('[[nemes]]', name)  # Подстановка имени
                send_result = send_message(chat_id, message)
                results.append({
                    "chat_id": chat_id,
                    "message": message,
                    "result": send_result
                })

            if clean_db == '1':
                conn = sqlite3.connect(database)
                cursor = conn.cursor()
                cursor.execute('DELETE FROM contacts')
                conn.commit()
                conn.close()

        return jsonify({"status": "success", "results": results}), 200
    except Exception as e:
        print(f"Error sending mailings: {e}")
        return jsonify({"status": "error", "message": str(e)}), 500

#С проверкой sys
@app.route('/start_db', methods=['GET'])
def start_mailings():
    mesage_db1 = request.args.get('mesage')
    clean_db = request.args.get('clean_db')
    api_sys_control = request.args.get('api_sys')
    

    if not mesage_db1:
        return "Parameter 'mesage' is required.", 400

    if api_sys_control != api_key_sys:
        return "EUR 22", 200

    return check_and_send_mailings(mesage_db1, clean_db)




        


@app.route('/add_data_gc', methods=['GET'])
def add_data_gc():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "err api key", 200

        name = request.args.get('name')
        phone = request.args.get('phone')
        email = request.args.get('email')
        vk_id = request.args.get('vk_id', '')
        chat_id = request.args.get('chat_id')
        ws_statys = request.args.get('ws_st')
        ws_stop = request.args.get('ws_stop')
        web_statys = request.args.get('web_st', 0, type=int)
        fin_progress = request.args.get('fin_prog', 0, type=int)
        shop_statys_full = request.args.get('shop_st')
        pr1 = request.args.get('pr1')
        pr2 = request.args.get('pr2')
        pr3 = request.args.get('pr3')
        pr4 = request.args.get('pr4')
        pr5 = request.args.get('pr5')
        ad_url = request.args.get('ad_url')
        curator = request.args.get('curator')

        if not name or not phone or not email:
            return "Parameters 'name', 'phone', and 'email' are required.", 400

        # Clean up phone number by removing any leading plus sign
        if phone.startswith('+'):
            phone = phone[1:]

        conn = sqlite3.connect('data_gc.db')
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM contacts WHERE phone = ? OR email = ?', (phone, email))
        existing_contact = cursor.fetchone()

        if existing_contact:
            cursor.execute('''
                UPDATE contacts SET
                    name = ?, email = ?, vk_id = ?, chat_id = ?, ws_statys = ?, ws_stop = ?, 
                    web_statys = ?, fin_progress = ?, shop_statys_full = ?, pr1 = ?, pr2 = ?, 
                    pr3 = ?, pr4 = ?, pr5 = ?, ad_url = ?, curator = ?
                WHERE phone = ? OR email = ?
            ''', (name, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
                  shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator, phone, email))
        else:
            cursor.execute('''
                INSERT INTO contacts (
                    name, phone, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
                    shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (name, phone, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
                  shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator))

        conn.commit()
        conn.close()

        return f"Contact updated/added: {name} - {phone} - {email}", 200
    except Exception as e:
        print(f"Error adding/updating contact: {e}")
        return "Internal Server Error", 500











@app.route('/add_data_ras', methods=['GET'])
def add_data_ras():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        name = request.args.get('name')
        phone = request.args.get('phone')
        email = request.args.get('email')
        vk_id = request.args.get('vk_id', '')
        chat_id = request.args.get('chat_id', '')
        ws_statys = request.args.get('ws_st', '')
        ws_stop = request.args.get('ws_stop', '')
        web_statys = request.args.get('web_st', 0, type=int)
        fin_progress = request.args.get('fin_prog', 0, type=int)
        shop_statys_full = request.args.get('shop_st', '')
        pr1 = request.args.get('pr1', '')
        pr2 = request.args.get('pr2', '')
        pr3 = request.args.get('pr3', '')
        pr4 = request.args.get('pr4', '')
        pr5 = request.args.get('pr5', '')
        ad_url = request.args.get('ad_url', '')
        curator = request.args.get('curator', '')

        if not name or not phone or not email:
            return "Parameters 'name', 'phone', and 'email' are required.", 400

        # Clean up phone number by removing any leading plus sign
        if phone.startswith('+'):
            phone = phone[1:]

        conn = sqlite3.connect('data1.db')
        cursor = conn.cursor()
        cursor.execute('SELECT * FROM contacts WHERE phone = ? OR email = ?', (phone, email))
        existing_contact = cursor.fetchone()

        if existing_contact:
            cursor.execute('''
                UPDATE contacts SET
                    name = ?, email = ?, vk_id = ?, chat_id = ?, ws_statys = ?, ws_stop = ?, 
                    web_statys = ?, fin_progress = ?, shop_statys_full = ?, pr1 = ?, pr2 = ?, 
                    pr3 = ?, pr4 = ?, pr5 = ?, ad_url = ?, curator = ?
                WHERE phone = ? OR email = ?
            ''', (name, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
                  shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator, phone, email))
        else:
            cursor.execute('''
                INSERT INTO contacts (
                    name, phone, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
                    shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (name, phone, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
                  shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator))

        conn.commit()
        conn.close()

        return f"Contact updated/added: {name} - {phone} - {email}", 200
    except Exception as e:
        print(f"Error adding/updating contact: {e}")
        return "Internal Server Error", 500



    


       




        

@app.route('/data_gc')
def show_data_gc():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        conn = sqlite3.connect('data_gc.db')
        cursor = conn.cursor()
        cursor.execute('SELECT name, phone, email FROM contacts')
        contacts = cursor.fetchall()
        cursor.execute('SELECT COUNT(*) FROM contacts')
        total_users = cursor.fetchone()[0]
        conn.close()

        return render_template('data_gc.html', contacts=contacts, total_users=total_users)
    except Exception as e:
        print(f"Error showing contacts: {e}")
        return "Internal Server Error", 500




@app.route('/data_gc_tab', methods=['GET'])
def data_gc_tab():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('data_gc_tab.html')








@app.route('/data_gc_tab_out', methods=['GET'])
def data_gc_tab_out():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        conn = sqlite3.connect('data_gc.db')
        cursor = conn.cursor()
        cursor.execute('''
            SELECT id, name, phone, email, vk_id, chat_id, ws_statys, ws_stop, web_statys, fin_progress, 
            shop_statys_full, pr1, pr2, pr3, pr4, pr5, ad_url, curator 
            FROM contacts
        ''')
        contacts = cursor.fetchall()
        conn.close()

        contacts_json = [{
            'id': contact[0], 'name': contact[1], 'phone': contact[2], 'email': contact[3],
            'vk_id': contact[4], 'chat_id': contact[5], 'ws_statys': contact[6], 'ws_stop': contact[7],
            'web_statys': contact[8], 'fin_progress': contact[9], 'shop_statys_full': contact[10], 'curator': contact[17],
            'pr1': contact[11], 'pr2': contact[12], 'pr3': contact[13], 'pr4': contact[14],
            'pr5': contact[15], 'ad_url': contact[16]
        } for contact in contacts]
        return jsonify(contacts_json), 200
    except Exception as e:
        error_message = f"Error getting data from data_gc: {e}"
        print(error_message)
        return error_message, 500







        
        


@app.route('/data_ras')
def show_data_ras():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        conn = sqlite3.connect('data1.db')
        cursor = conn.cursor()
        cursor.execute('SELECT name, phone, email FROM contacts')
        contacts = cursor.fetchall()
        cursor.execute('SELECT COUNT(*) FROM contacts')
        total_users = cursor.fetchone()[0]
        conn.close()

        return render_template('data_ras.html', contacts=contacts, total_users=total_users)
    except Exception as e:
        print(f"Error showing contacts: {e}")
        return "Internal Server Error", 500







































































@app.route('/biz_v', methods=['GET'])
def biz_v():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('biz_v.html')

@app.route('/send_request', methods=['POST'])
def send_request():
    token = request.form.get('token')
    url = 'https://online.bizon365.ru/api/v1/webinars/reports/getlist?minDate=2021-08-06T00:00:00'
    
    response = requests.get(url, headers={'X-Token': token})
    
    if response.status_code == 200:
        data = response.json()
        webinar_ids = [item['webinarId'] for item in data['list']]
        return jsonify(webinar_ids)
    else:
        return jsonify({'error': 'Failed to fetch data from the API'}), response.status_code






















@app.route('/ver', methods=['GET'])
def veref():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('ver.html')

@app.route('/se_mes', methods=['GET'])
def se_mes():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes.html')

@app.route('/se_mes_im', methods=['GET'])
def se_mes_im():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_im.html')

@app.route('/se_mes_ran', methods=['GET'])
def se_mes_ran():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_ran.html')

@app.route('/se_mes_im_ran', methods=['GET'])
def se_mes_im_ran():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_im_ran.html')

@app.route('/se_mes_im2', methods=['GET'])
def se_mes_im2():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_im2.html')

@app.route('/se_mes_f', methods=['GET'])
def se_mes_f():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_f.html')

@app.route('/up_gr', methods=['GET'])
def up_gr():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('up_gr.html')

@app.route('/up_user_gp', methods=['GET'])
def up_user_gp():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('up_user_gp.html')

@app.route('/del_user_gp', methods=['GET'])
def del_user_gp():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('del_user_gp.html')

@app.route('/up_ad', methods=['GET'])
def up_ad():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('up_ad.html')

@app.route('/del_ad', methods=['GET'])
def del_ad():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('del_ad.html')

@app.route('/se_opr', methods=['GET'])
def se_opr():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_opr.html')

@app.route('/online', methods=['GET'])
def online():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('online.html')

@app.route('/se_mes_f_gc', methods=['GET'])
def se_mes_f_gc():
    api_sys_control = request.args.get('api_sys')
    if api_sys_control != api_key_sys:
        return "EUR 22", 200
    return render_template('se_mes_f_gc.html')














@app.route('/total_users', methods=['GET'])
def total_users():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        total_users_gc = 0
        total_users_ras = 0

        conn_gc = sqlite3.connect('data_gc.db')
        cursor_gc = conn_gc.cursor()
        cursor_gc.execute('SELECT COUNT(*) FROM contacts')
        total_users_gc = cursor_gc.fetchone()[0]
        conn_gc.close()

        conn_ras = sqlite3.connect('data1.db')
        cursor_ras = conn_ras.cursor()
        cursor_ras.execute('SELECT COUNT(*) FROM contacts')
        total_users_ras = cursor_ras.fetchone()[0]
        conn_ras.close()

        return jsonify({
            "total_users_gc": total_users_gc,
            "total_users_ras": total_users_ras
        }), 200
    except Exception as e:
        print(f"Error getting total users: {e}")
        return "Internal Server Error", 500








@app.route('/all_users_gc', methods=['GET'])
def all_users_gc():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        conn = sqlite3.connect('data_gc.db')
        cursor = conn.cursor()
        cursor.execute('SELECT name, phone, email FROM contacts')
        contacts = cursor.fetchall()
        conn.close()

        return jsonify(contacts), 200
    except Exception as e:
        print(f"Error getting all users from data_gc: {e}")
        return "Internal Server Error", 500



@app.route('/all_users_ras', methods=['GET'])
def all_users_ras():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        conn = sqlite3.connect('data1.db')
        cursor = conn.cursor()
        cursor.execute('SELECT name, phone, email FROM contacts')
        contacts = cursor.fetchall()
        conn.close()

        return jsonify(contacts), 200
    except Exception as e:
        print(f"Error getting all users from data_ras: {e}")
        return "Internal Server Error", 500




        

@app.route('/gc_db_no_email', methods=['GET'])
def gc_db_no_email():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        # Чтение параметров из GET-запроса
        name_d = request.args.get('name', '')
        phone_d = request.args.get('phone', '')
        pr1_d = request.args.get('pr1', '')
        pr2_d = request.args.get('pr2', '')
        pr3_d = request.args.get('pr3', '')

        # Проверка базы данных на наличие email по номеру телефона
        conn = sqlite3.connect('data_gc.db')
        cursor = conn.cursor()
        cursor.execute('SELECT email FROM contacts WHERE phone = ?', (phone_d,))
        result = cursor.fetchone()
        email_d = result[0] if result else ''
        conn.close()

        # Формирование JSON
        json_data = {
            "user": {
                "email": email_d,
                "phone": phone_d,
                "first_name": name_d,
                "addfields": {
                    "pr1": pr1_d,
                    "pr2": pr2_d,
                    "pr3": pr3_d
                }
            },
            "system": {
                "refresh_if_exists": 1
            },
            "session": {
                "utm_source": "",
                "utm_medium": "",
                "utm_content": "",
                "utm_campaign": "",
                "utm_group": "",
                "gcpc": "",
                "gcao": "",
                "referer": ""
            }
        }

        # Конвертация JSON в Base64
        json_str = json.dumps(json_data)
        params_d = base64.b64encode(json_str.encode('utf-8')).decode('utf-8')

        # Данные для отправки в теле запроса
        data = {
            'key': gc_api,
            'action': 'add',
            'params': params_d
        }

        # Отправка POST-запроса с данными в формате "form-data"
        response = requests.post(gc_url, data=data)

        # Возвращаем ответ от тестового адреса
        return {
            'status_code': response.status_code,
            'response_body': response.text
        }
    except Exception as e:
        print(f"Error in gc_db_no_email: {e}")
        return "Internal Server Error", 500





@app.route('/gc_db_email', methods=['GET'])
def gc_db_email():
    try:
        api_sys_control = request.args.get('api_sys')

        if api_sys_control != api_key_sys:
            return "EUR 22", 200

        # Чтение параметров из GET-запроса
        name_d = request.args.get('name', '')
        email_d = request.args.get('email', '')
        phone_d = request.args.get('phone', '')
        pr1_d = request.args.get('pr1', '')
        pr2_d = request.args.get('pr2', '')
        pr3_d = request.args.get('pr3', '')

        # Формирование JSON
        json_data = {
            "user": {
                "email": email_d,
                "phone": phone_d,
                "first_name": name_d,
                "addfields": {
                    "pr1": pr1_d,
                    "pr2": pr2_d,
                    "pr3": pr3_d
                }
            },
            "system": {
                "refresh_if_exists": 1
            },
            "session": {
                "utm_source": "",
                "utm_medium": "",
                "utm_content": "",
                "utm_campaign": "",
                "utm_group": "",
                "gcpc": "",
                "gcao": "",
                "referer": ""
            }
        }

        # Конвертация JSON в Base64
        json_str = json.dumps(json_data)
        params_d = base64.b64encode(json_str.encode('utf-8')).decode('utf-8')

        # Данные для отправки в теле запроса
        data = {
            'key': gc_api,
            'action': action_d,
            'params': params_d
        }

        # Отправка POST-запроса с данными в формате "form-data"
        response = requests.post(gc_url, data=data)

        # Возвращаем ответ от тестового адреса
        return {
            'status_code': response.status_code,
            'response_body': response.text
        }
    except Exception as e:
        print(f"Error in gc_db_email: {e}")
        return "Internal Server Error", 500














if __name__ == '__main__':
    send_requests()
    app.run(host='0.0.0.0', port=int(os.environ.get('PORT', 7860)))