File size: 28,913 Bytes
b3ad1d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import json
import time
import datetime
import requests
import paramiko
from dotenv import load_dotenv
from selenium import webdriver
import webbrowser
import os
from datetime import date
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from request_json.sbt_request_generator import generate_request

load_dotenv()
REDIRECT_URL = os.environ.get("REDIRECT_URL")
_base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
CUSTOMER_TOKEN = os.environ.get("CUSTOMER_TOKEN")
APP_ID = os.environ.get("APP_ID")
CLIENT_ID = os.environ.get("CLIENT_ID")
CLIENT_SECRET = os.environ.get("CLIENT_SECRET")



def connect():
    ssh_host = '18.166.103.96'
    ssh_user = 'ec2-user'
    ssh_key_path = '.ssh/ipygg-api-test.pem'
    
    ssh_client = paramiko.SSHClient()
    ssh_client.load_system_host_keys()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_key = paramiko.RSAKey.from_private_key_file(ssh_key_path)
    ssh_client.connect(ssh_host, username=ssh_user, pkey=ssh_key)
    print("Successfully connected to the test server")

    transport = ssh_client.get_transport()
    if transport.is_active():
        print("SSH connection is active")
    else:
        print("SSH connection is not active")

    return ssh_client


def command():
    mysql_host = 'awseb-e-az6qppyyjf-stack-awsebrdsdatabase-g7iebolqxtzk.ccrm7ijo8xsm.ap-east-1.rds.amazonaws.com'
    mysql_user = 'iPYGG'
    mysql_password = 'yt1uQ8aiTd!2cY6K2re342!G6g'
    mysql_command = f"mysql -h {mysql_host} -u {mysql_user} -p{mysql_password} -e "
    return mysql_command


def initialize_SBTdb(ssh_client):
    # ssh_client.exec_command(command() + "'DROP DATABASE IF EXISTS test_SBTdb'")
    try:
        ssh_client.exec_command(command() + "'CREATE DATABASE IF NOT EXISTS SBTdb'")
        ssh_client.exec_command(command() + """'USE SBTdb; 
                                    CREATE TABLE IF NOT EXISTS token_key (
                                        user_id VARCHAR(233) NOT NULL PRIMARY KEY,
                                        token_id VARCHAR(233),
                                        decryption_key VARBINARY(255),
                                        ipfs_link1 VARCHAR(255),
                                        ipfs_link2 VARCHAR(255),
                                        ipfs_link3 VARCHAR(255),
                                        membership_status VARCHAR(255)
                                    );'""")
    except Exception as e:
        print(e)


def close(ssh_client):
    ssh_client.close()




# **************************API calls**************************
def store_attribute(db_name, table_name, restriction_name, restriction_value, attribute_name, attribute_value):
    ssh_client = connect()
    try:
        # Check if the row already exists
        select_query = f"SELECT COUNT(*) AS count FROM {table_name} WHERE {restriction_name}='{restriction_value}'"
        stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE {db_name}; {select_query}\"")
        count_str = stdout.read().decode()
        print("output: ", count_str)

        count_line = count_str.split('\n')[1]
        count = int(count_line)
        print("error:", stderr.read().decode())

        if count > 0:
            # Update the existing row
            update_query = f"UPDATE {table_name} SET {attribute_name}='{attribute_value}' WHERE {restriction_name}='{restriction_value}'"
            stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE {db_name}; {update_query}\"")
            print("error:", stderr.read().decode())
        else:
            # Insert a new row
            insert_query = f"INSERT INTO {table_name} ({restriction_name}, {attribute_name}) VALUES ('{restriction_value}', '{attribute_value}')"
            stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE {db_name}; {insert_query}\"")
            print("error:", stderr.read().decode())
    except Exception as e:
        print("ha! Exception!")
        print(e)
    close(ssh_client)

def get_attribute(db_name, table_name, restriction, restriction_value, attribute_name):
    ssh_client = connect()
    try:
        query = f"SELECT {attribute_name} FROM {table_name} WHERE {restriction}='{restriction_value}'"
        stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE {db_name}; {query}\"")
        print("output: ", stdout)
        print("error:", stderr.read().decode())
    except Exception as e:
        print(e)
    result = stdout.read().decode().strip()
    rows = result.splitlines()
    attribute_value = rows[1]
    close(ssh_client)
    return attribute_value

def get_attribute_2(db_name, table_name, restriction_1, restriction_value_1, restriction_2, restriction_value_2, attribute_name):
    ssh_client = connect()
    try:
        query = f"SELECT {attribute_name} FROM {table_name} WHERE {restriction_1}='{restriction_value_1}' AND {restriction_2}='{restriction_value_2}'"
        stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE {db_name}; {query}\"")
        print("output: ", stdout, "end")
        # print("error:", stderr.read().decode())
    except Exception as e:
        print(e)
        stdout = ""
    # rows = stdout.read().decode().strip()
    result = stdout.read().decode().strip()
    rows = result.splitlines()
    # print ("result:", rows)
    attribute_value = rows[1]
    # print ("result2:", attribute_value)
    close(ssh_client)
    return attribute_value

# called through API\metadata
def store_ipfs(user_id, ipfs_link, link_num):
    ssh_client = connect()
    try:
        if(link_num==1):
            store_query = f"INSERT INTO token_key (user_id, ipfs_link1) VALUES ('{user_id}', '{ipfs_link}') ON DUPLICATE KEY UPDATE ipfs_link1 = '{ipfs_link}'"
        elif(link_num==2):
            store_query = f"INSERT INTO token_key (user_id, ipfs_link2) VALUES ('{user_id}', '{ipfs_link}') ON DUPLICATE KEY UPDATE ipfs_link2 = '{ipfs_link}'"        
        elif(link_num==3):
            store_query = f"INSERT INTO token_key (user_id, ipfs_link3) VALUES ('{user_id}', '{ipfs_link}') ON DUPLICATE KEY UPDATE ipfs_link3 = '{ipfs_link}'"
        stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE SBTdb; {store_query}\"")
        print("error:", stderr.read().decode())

    except Exception as e:
        print(e)
    close(ssh_client)

# called through API\minting
def store_token(ipfs_link1, ipfs_link2, ipfs_link3, membership_status, user_id, token_id):
    ssh_client = connect()
    # check if the record already exists
    check_query = f"SELECT COUNT(*) FROM token_key WHERE user_id='{user_id}'"
    stdin, stdout, stderr = ssh_client.exec_command(f"{command()} 'USE SBTdb; {check_query}'")
    
    count_str = stdout.read().decode()
    count_line = count_str.split('\n')[1]
    count = int(count_line)
    print(f"count: {count}")
    

    if count == 0:
        # if the record doesn't exist, insert a new record
        try:
            insert_query = f"INSERT INTO token_key (user_id, token_id, ipfs_link1, ipfs_link2, ipfs_link3, membership_status) VALUES ('{user_id}', '{token_id}', '{ipfs_link1}', '{ipfs_link2}', '{ipfs_link3}', '{membership_status}')"
            stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE SBTdb; {insert_query}\"")
            print("error:", stderr.read().decode())
        except Exception as e:
            print(e)
    else:
        # if the record exists, update the existing record
        try:
            update_query = f"UPDATE token_key SET token_id='{token_id}', ipfs_link1='{ipfs_link1}', ipfs_link2='{ipfs_link2}', ipfs_link3='{ipfs_link3}', membership_status='{membership_status}' WHERE user_id='{user_id}'"
            # sql_query = f"USE SBTdb ;{update_query}"
            stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE SBTdb; {update_query}\"")
            print("error:", stderr.read().decode())
        except Exception as e:
            print(e)

    close(ssh_client)
    return token_id
    

# called through API\general, KYC, marketing
def get_userinfo(user_id, token_id, type):
    ssh_client = connect()

    info = {}
    try:
        query = f"SELECT token_id FROM token_key WHERE user_id='{user_id}' "
        stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE SBTdb; {query}\"")
        print("error:", stderr.read().decode())
    except Exception as e:
        print(e)

    token_id_str = stdout.read().decode()
    print("token_id_str:", token_id_str)
    token_id_db = token_id_str.split('\n')[1]

    if token_id_db == token_id:
        if type == "general":
            retrieve_query = f"SELECT facebook_id FROM ipygg_users WHERE user_id='{user_id}'"
            stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE ipygg; {retrieve_query}\"")
            print("error:", stderr.read().decode())
            facebook_id = stdout.read().decode().split('\n')[1]
            info['facebook_id'] = facebook_id
        elif type == "KYC":
            retrieve_query = f"SELECT email, salutation, first_name, last_name, birthday, country, region, location, address, postcode, area_code, phone, hk_id, passport FROM ipygg_users WHERE user_id='{user_id}'"
            stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE ipygg; {retrieve_query}\"")
            print("error:", stderr.read().decode())
            info_list = stdout.read().decode().split('\n')[1].split('\t')
            info = {
                'email': info_list[0],
                'salutation': info_list[1],
                'first_name': info_list[2],
                'last_name': info_list[3],
                'birthday': info_list[4],
                'country': info_list[5],
                'region': info_list[6],
                'location': info_list[7],
                'address': info_list[8],
                'postcode': info_list[9],
                'area_code': info_list[10],
                'phone': info_list[11],
                'hk_id': info_list[12],
                'passport': info_list[13]
                }
            info['dual_passport'] = False      #TODO: add dual_passport to ipygg_users
        elif type == "marketing":
            retrieve_query = f"SELECT email, facebook_id, wealth_level FROM ipygg_users WHERE user_id='{user_id}'"
            stdin, stdout, stderr = ssh_client.exec_command(f"{command()} \"USE ipygg; {retrieve_query}\"")
            print("error:", stderr.read().decode())
            info_list = stdout.read().decode().split('\n')[1].split('\t')
            info['email'] = info_list[0]
            info['facebook_id'] = info_list[1]
            info['wealth_level'] = info_list[2]
        close(ssh_client)
        return True, info
    else:
        close(ssh_client)
        return False, info

# def update_Status(request_id, status, user_id, institution_id, latest_update_date=time.localtime().tm_mday):
#     conn, cursor = get_conn_and_cursor(request_id)

#     try:
#         sql = "update request_log set status = \"{}\" where user_id = \"{}\" AND " \
#               "institution_id = \"{}\" AND request_id = \"{}\";".format(
#             status, user_id, institution_id, request_id)
#         # addRequestLog(request_id, sql)
#         # cursor.execute(sql)
#         # conn.commit()
#     except Exception as e:
#         print(e)
#         # addRequestLog(request_id, "Could not update user Status")

def getCustomerToken(request_id, user_id):
    """
       Returns: *customer token* for generating link token
       Uses: *Client ID*, *Client secret* (Defined in constants.py)
       Url: "https://api.prod.finverse.net/auth/customer/token"
       Section 0 in the Flowchart
    """
    url = "https://api.prod.finverse.net/auth/customer/token"
    payload = json.dumps({
        "client_id": f"{CLIENT_ID}",
        "client_secret": f"{CLIENT_SECRET}",
        "grant_type": "client_credentials"
    })
    headers = {
        'X-Request-Id': f'{user_id}-{int(time.time())}',
        'Content-Type': 'application/json'
    }
    response = requests.request(
        "POST", url, headers=headers, data=payload).json()
    # logger(
    #     request_id, f'=============headers X-Request-Id============\n{headers["X-Request-Id"]}')
    # logger(
    #     request_id, f'============1 post response==========\n{response}')
    return response["access_token"]

def getLinkToken(customer_token, request_id, user_id):
    url = "https://api.prod.finverse.net/link/token"
    payload = json.dumps({
        "client_id": f"{CLIENT_ID}",
        "user_id": user_id,
        "redirect_uri": f"{REDIRECT_URL}",
        "state": "ipygg_stateparameter",
        "grant_type": "client_credentials",
        "response_mode": "form_post",
        "response_type": "code",
        "automatic_data_refresh": "",
        "countries": [],
        "institution_id": "",
        "institution_status": "",
        "language": "",
        "link_mode": "test",
        "products_requested": [],
        "products_supported": [],
        "ui_mode": "redirect",
        "user_type": []
    })
    headers = {
        'X-Request-Id': f'{user_id}-{int(time.time())}',
        'Authorization': f'Bearer {customer_token}',
        'Content-Type': 'application/json'
    }
    try:
        print(request_id, "Trying to get login ID from finverse")
        response = requests.request("POST", url, headers=headers, data=payload)
        j = response.json()
        link_url = j["link_url"]
        print(request_id, link_url)

        if 'error' in j.keys():
            if j['error']['code'] == 40001:
                print(j)
                return 404

        # finverse_connector.update_refresh_token(user_id, j['login_identity_id'], j['refresh_token'], institution_id,
        #                                         request_id, date)
        return j['link_url']
    except Exception as e:
        print(request_id, "Unable to refresh")
        print(request_id, e)


def getLoginID(customer_token, request_id, user_id):
    """
    Returns: *link token*
    Uses: *Customer token*, *login refresh token*
    Documentation: Data API -> 12-Data Refresh -> POST /auth/token/refresh (1st step in the Refresh flow)
    URL: https://api.prod.finverse.net/auth/token/refresh
    Section 9 in the Flowchart
    """

    url = "https://api.prod.finverse.net/login_identity"
    payload = json.dumps({
    })
    headers = {
        'X-Request-Id': f'{user_id}-{int(time.time())}',
        'Authorization': f'Bearer {customer_token}',
        'Content-Type': 'application/json'
    }
    try:
        print(request_id, "Trying to get login ID from finverse")
        response = requests.request("GET", url, headers=headers)
        j = response.json()
        login_id = j["login_identity"]["login_identity_id"]
        print(request_id, login_id)

        if 'error' in j.keys():
            if j['error']['code'] == 40001:
                print(j)
                return 404

        # finverse_connector.update_refresh_token(user_id, j['login_identity_id'], j['refresh_token'], institution_id,
        #                                         request_id, date)
        return j['access_token']
    except Exception as e:
        print(request_id, "Unable to refresh")
        print(request_id, e)


def getLinkCode(user_id, request_id, code, customer_token):
    url = "https://api.prod.finverse.net/auth/token"
    payload = {
        "client_id": f"{CLIENT_ID}",
        "code": f"{code}",
        "redirect_uri": f"{REDIRECT_URL}",
        "grant_type": "authorization_code"
    }
    headers = {
        'X-Request-Id': f'{user_id}-{int(time.time())}',
        'Authorization': f'Bearer {customer_token}',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    try:
        print(request_id, "Trying to get link code from finverse")
        response = requests.request("POST", url, headers=headers, data=payload)
        j = response.json()
        # print(j)
        login_id = j["login_identity_id"]
        login_id_token = j["access_token"]
        refresh_token = j["refresh_token"]
        print(f'{request_id}, login id: {login_id} , refresh token: {refresh_token}')

        if 'error' in j.keys():
            if j['error']['code'] == 40001:
                return 404

        # finverse_connector.update_refresh_token(user_id, j['login_identity_id'], j['refresh_token'], institution_id,
        #                                         request_id, date)
        return login_id_token
    except Exception as e:
        print(request_id, "Unable to get link code")
        print(request_id, e)
    

def getRefreshedToken(customer_token, request_id, user_id, refresh_token, institution_id, date, redirect_uri):
    """
    Returns: *link token*
    Uses: *Customer token*, *login refresh token*
    Documentation: Data API -> 12-Data Refresh -> POST /auth/token/refresh (1st step in the Refresh flow)
    URL: https://api.prod.finverse.net/auth/token/refresh
    Section 9 in the Flowchart
    """

    url = "https://api.prod.finverse.net/auth/token/refresh"
    payload = json.dumps({
        "redirect_uri": f"{redirect_uri}",
        "grant_type": "client_credentials",
        "code": ""
    })
    headers = {
        'X-Request-Id': f'{user_id}-{int(time.time())}',
        'Authorization': f'Bearer {customer_token}',
        'Content-Type': 'application/json'
    }
    try:
        print(request_id, "Trying to get refreshed credentials from finverse")
        response = requests.request("POST", url, headers=headers, data=payload)
        j = response.json()
        print(request_id, j)

        if 'error' in j.keys():
            if j['error']['code'] == 40001:
                return 404

        # finverse_connector.update_refresh_token(user_id, j['login_identity_id'], j['refresh_token'], institution_id,
        #                                         request_id, date)
        return j['access_token']
    except Exception as e:
        print(request_id, "Unable to refresh")
        print(request_id, e)

def get_pdf(userId, statement_id, login_identity_token, request_id):
    try:
        # logger(request_id, f"\nfetching PDF for {statement_id}")
        url = f"https://api.prod.finverse.net/statements/{statement_id}?redirect=false"
        payload = {}
        headers = {
            'X-Request-Id': f'{userId}-{int(time.time())}',
            'Authorization': f'Bearer {login_identity_token}',
            'Content-Type': "application/json"
        }
        response = requests.get(url, headers=headers, data=payload).json()
        # print(request_id, "response")
        link = response['statement_links'][0]['url']
        # print(f'link is : {link}')
        return link
    except Exception as e:
        print(request_id, f"Error in get_pdf")
        print(request_id, e)
        # finverse_connector.update_Status(
        #     request_id, "50200", userId, institution_id)      
        #   

def statements_fetch(userId,  institution_id, login_identity_token, request_id):
    try:
        # logger(request_id, "fetching statements from finverse")
        url = f"https://api.prod.finverse.net/statements"

        payload = {}
        headers = {
            'X-Request-Id': f'{userId}-{int(time.time())}',
            'Authorization': f'Bearer {login_identity_token}',
            'Content-Type': 'application/json'
        }

        response = requests.get(url, headers=headers, data=payload).json()
        print(request_id, f"The response is :\n{response}")
        statement = response["statements"]
        print(f'statement: {statement[0]["id"]}')
        # for statement in response['statements']:
        # #     name = statement['name'] + ' ' + statement['date']
        if statement != None:
            statement = get_pdf(userId, statement[0]["id"], login_identity_token, request_id)
            return statement, 200
        else:
            print('no statement')
            return 0
    except Exception as e:
        print(request_id, f"Error in statements_fetch")
        print(request_id, e)
        # finverse_connector.update_Status(
        #     request_id, "50200", userId, institution_id)
        return 500


def check_if_token_exists(user_id, institution_id, request_id):
    """
    Searches: if user exists in user_and_login_identity table
                and if value of *refresh_allowed* is 1
    Section 1 in the Flowchart
    """
    # db_name, table_name, restriction, restriction_value, attribute_name
    user_details = get_attribute_2('ipygg', 'user_and_login_identity', 'user_id', user_id, 'institution_id', institution_id, '*')
    if user_details != "":
        print(user_details)
        # refresh_token = user_details[6]
        refresh_allowed = user_details[-1]
        print(refresh_allowed)
        if refresh_allowed == "1":
            return user_details
        else:
            return 0
    else:
        return 0

        
def statements_report(userId, institutionId, requestId, date):
    try:
        # finverse_connector.add_status(
        #     requestId, "10000", userId, institutionId, 'PDFs', date)
        customer_token = getCustomerToken(requestId, userId)
        print(customer_token)

        # addRequestLog(requestId, f"Fetching PDFs for {userId} with {institutionId} institutionID")
        # userInfo = check_if_token_exists(
        #     userId, institutionId, requestId)
        userInfo = 1
        
        print(f'userInfo: {userInfo}')

        if userInfo == 0:
            # createUserAccount()
            print(requestId, "User does not have any accounts")
            return 500  # user does not exist
        else:
            # refresh_token = userInfo[-2]
            search_url = getLinkToken(customer_token, requestId, userId)
            driver = webdriver.Chrome()
            driver.get(search_url)
            wait = WebDriverWait(driver, 50).until(EC.url_contains("code="))
            url = driver.current_url
            time.sleep(5)
            url_list = url.split("code=",1)[1]
            code = url_list[:26]
            print(f'code is {code}')
            # webbrowser.open(search_url)
            # where user input
            # code = input("Enter code:")
            time.sleep(5)
            login_identity_token = getLinkCode(requestId,userId,code,customer_token)

        pdf_link = statements_fetch(userId, institutionId, login_identity_token, requestId)
        if pdf_link!= 500:
            # pdf_link = get_pdf(userId, statement_list['id'], login_identity_token, requestId)
            webbrowser.open(pdf_link[0])
            return pdf_link
        else:
            return 500

    except Exception as e:
        print(requestId, "Fetching PDFs failed")
        print(requestId, e)
        print(e)
        return 500  # Fetching error

# pdf_link = get_pdf(userId="1001001", statement_id="01H4RJ02B5Q7ZTX9S3TPFWNQT0", login_identity_token="eyJhbGciOiJSUzI1NiIsImtpZCI6Imp3dC9jcnlwdG9LZXlzL2p3dC1rZXkvY3J5cHRvS2V5VmVyc2lvbnMvMSIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJodHRwczovL2FwaS5wcm9kLmZpbnZlcnNlLm5ldCIsImNsaWVudElkIjoiMDFHMUc1TjdLTVlaNEZDVlo3NkU3VDZORjAiLCJjdXN0b21lckFwcElkIjoiMDFHMUc1TjdOMkc3UVNLNDNXUDZLR002UjYiLCJleHAiOjE2ODg3NDk5NDMsImlhdCI6MTY4ODc0NjM0MywiaXNzIjoiZmludmVyc2UtcHJvZCIsImxvZ2luSWRlbnRpdHlJZCI6IjAxSDRSSFpLV0ZNUVI5MEZXMTNIQUFQNks1Iiwic2NvcGUiOiJhY2NvdW50IHRyYW5zYWN0aW9uIGlkZW50aXR5IGxvZ2luSWRlbnRpdHk6c2VsZiBsb2dpbklkZW50aXR5OmRlbGV0ZSBsb2dpbklkZW50aXR5OnVwZGF0ZSBsaW5rOnRva2VuIHN0YXRlbWVudDpyZWFkIGFjY291bnRfbnVtYmVyIGJhbGFuY2VfaGlzdG9yeSBwYXltZW50OmdldCBpbmNvbWU6Z2V0IGNvbXBvc2l0ZV9zdGF0ZW1lbnQiLCJzdWIiOiIwMUg0UkhaS1dGTVFSOTBGVzEzSEFBUDZLNSJ9.AbmNVOWDAQm9wnxLqpQuHpSBWp7L1IRCXNAeT-FWaXO3hsYOCzsfyA1DObn1XOHbGV-HoYXHGPrDThORrfFOBKjH6yW7-W41UQDjlRIGVsXxYUwJsHAV8ytuDoyIk8rqoPVNALHsU4rOzXYIpplI-7HMgYAzjRXAP50x0KL4Ks5pyGYokmnq2nElKi_nC1XFlsPjYuVnJ_88xZF6hOugoZgU8Mq4P59RUTUUksTWWW8BthCKr1sakKYcBEbIp2efv8Upfc_feY-z4j4qI1V_PHiXUIatqr71kOMbJ3xNkhzEIXNh_SdK4u3C7SW1ZZhivTaFakTUhMazvg3xtalUZq_EZViLg4OJTmUB1gjYEBoPMpUwlQcJXgXpwtUh-9cEo99ufw0oB9trc4ocdfMYzw0kavfmPZqPHgu3HdX7Ofi0Fxgh8-AvRqlr3eVjmL54u8js5A9n43LaZ7oQgOxs82mm0XfAeX_alhzID3IVo-ZDpGkQ8hV-19-X2APhSt75tCMwFvHBfDd8QRfSyCPL0Yqi01jzT1TiVyP7yV2RjaDJQPcXk81nbgEGL_kwfLbCjpWeZSoJi15vAEhEGpM7pnuRHplLq59v6ARCfU1kRXI1Huva5S5X196Cfk7T9gBtqfUkT3oETNIkR8UxQmwp5BQHXtKMcMU8C4h4W3WAsd8", request_id="request1234")
# webbrowser.open(pdf_link)
# print(f'{pdf_link} finished')

def get_today_date():
    today = date.today()
    return str(today)

# Example for what will be returned
# 2023-06-29

################### MAIN ############################
def get_bs(userId="1836660007822863504716", institutionId="00000005",requestId="request1234"):
    standard_names = {'boch': "Consolidated Statement",
                        'hangseng': "Statement of",
                        'hsbc': "Statement - HSBC One Account",
                        'sc': "statementOfAccount"}

    # records = statements_report("1836660007822863504716","00000005","request1234","05072023")
    # userId, institutionId, requestId, date
    pdf_link = statements_report(userId, institutionId, requestId, str(get_today_date()))
    # get_pdf(userId,  institution_id, records[0]['id'], login_identity_token, request_id)
    if pdf_link != 500:
                print(f"successfully get bank report with link: {pdf_link}")

def get_transactions(user_id, login_identity_token):
    """
       Returns: *customer token* for generating link token
       Uses: *Client ID*, *Client secret* (Defined in constants.py)
       Url: "https://api.prod.finverse.net/transactions?offset=0&limit=100"
       Section 0 in the Flowchart
    """
    url = "https://api.prod.finverse.net/transactions?offset=0&limit=100"
    # payload = json.dumps({
    #     "client_id": f"{CLIENT_ID}",
    #     "client_secret": f"{CLIENT_SECRET}",
    #     "grant_type": "client_credentials"
    # })
    headers = {
        'X-Request-Id': f'{user_id}-{int(time.time())}',
        'Authorization': f'Bearer {login_identity_token}',
        'Content-Type': 'application/json'
    }
    response = requests.request(
        "GET", url, headers=headers).json()
    
    transaction_record = response["transactions"]
    
    print(f"getting transactions: {transaction_record}")
    
    return response["transactions"]


def past_transactions(userId="1836660007822863504716", institutionId="00000005",requestId="request1234"):
    try:
        # finverse_connector.add_status(
        #     requestId, "10000", userId, institutionId, 'PDFs', date)
        customer_token = getCustomerToken(requestId, userId)
        print(customer_token)

        # addRequestLog(requestId, f"Fetching PDFs for {userId} with {institutionId} institutionID")
        # userInfo = check_if_token_exists(
        #     userId, institutionId, requestId)
        userInfo = 1
        print(f'userInfo: {userInfo}')

        if userInfo == 0:
            # createUserAccount()
            print(requestId, "User does not have any accounts")
            return 500  # user does not exist
        else:
            search_url = getLinkToken(customer_token, requestId, userId)
            driver = webdriver.Chrome()
            driver.get(search_url)
            wait = WebDriverWait(driver, 50).until(EC.url_contains("code="))
            url = driver.current_url
            time.sleep(5)
            url_list = url.split("code=",1)[1]
            code = url_list[:26]
            print(f'code is {code}')
            time.sleep(5)
            login_identity_token = getLinkCode(requestId,userId,code,customer_token)

        transaction_record = get_transactions(userId, login_identity_token)
        # transaction_record = transaction_record[:10]
        print('printing transactions records')
        item_num = 0
        for item in transaction_record:
            if str(datetime.date.today().year) in item["created_at"]:
                item_num = item_num + 1
                # print(item)
            transaction_data = {
                "endpoint": "SBT",
                "apiType": "store_finverse_verif",
                "requestId": "request1234",
                "userId": userId # a string
            }
        if (item_num >= 100):
            print("user has more than 100 transactions in the past year")
            transaction_data["finverseVerif"] = "True" # a string "True" or "False"
            # post true
        else:
            print("user has no more than 100 transactions in the past year")
            transaction_data["finverseVerif"] = "False" # a string "True" or "False"
            # post false
        generate_request(transaction_data)

    except Exception as e:
        print(requestId, "Fetching transactions failed")
        print(requestId, e)