-
Notifications
You must be signed in to change notification settings - Fork 4
/
apis.py
1427 lines (1237 loc) · 67.2 KB
/
apis.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
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import pandas as pd
import datetime as dt
from flask import Flask, request, jsonify, json
from flask_cors import CORS
from aws_utils import upload_to_s3
from cron_utils import is_valid_cron
from celery import Celery
import urllib
import os
import uuid
from connections import connections
from database_entry import add_requests, add_volunteers_to_db, contact_us_form_add, \
add_user, request_matching, update_requests_db, update_volunteers_db, \
blacklist_token, send_sms, send_otp, resend_otp, verify_otp, update_nearby_volunteers_db, \
add_request_verification_db, update_request_v_db, update_request_status, save_request_sms_url, add_message, \
add_cron_job, update_schedule_db, send_raven_v1
from data_fetching import get_ticker_counts, get_private_map_data, get_public_map_data, get_user_id, \
accept_request_page, request_data_by_uuid, request_data_by_id, volunteer_data_by_id, \
website_requests_display, get_requests_list, get_source_list, website_success_stories, \
verify_volunteer_exists, check_past_verification, get_volunteers_assigned_to_request, \
get_type_list, get_moderator_list, get_unverified_requests, get_requests_assigned_to_volunteer, \
accept_request_page_secure, get_assigned_requests, user_data_by_id, website_requests_display_secure, get_messages, \
get_user_access_type, request_verification_data_by_id, get_user_list, cron_job_by_id, verify_user,\
get_completed_requests,completed_website_requests_display, completed_request_page
from partner_assignment import generate_uuid, message_all_volunteers, getCityAddr
from auth import encode_auth_token, decode_auth_token, login_required, volunteer_login_req
from utils import capture_api_exception
from message_templates import old_reg_sms, new_reg_sms, new_request_sms, new_request_mod_sms, request_verified_sms, \
request_accepted_v_sms, request_accepted_r_sms, request_accepted_m_sms, request_rejected_sms, \
request_closed_v_sms, request_closed_r_sms, request_closed_m_sms, a_request_closed_v_sms, \
a_request_closed_r_sms, a_request_closed_m_sms, url_start, url_retriever, key_word
from settings import server_type, SECRET_KEY, neighbourhood_radius, search_radius
from whatsapp_fn import send_moderator_msg
import mailer_fn as mailer
import cred_config as cc
# In[ ]:
# Allow edit of source from verification page
# Allow user to enter urgent (immediate, needed in <24 hours)/not urgent (needed in 24-48 hours)
# Allow users to see urgent requests
# In[ ]:
def datetime_converter(o):
if isinstance(o, dt.datetime):
return dt.datetime.strftime(o, '%a, %d %b %y, %I:%M%p %Z')
# In[ ]:
app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = SECRET_KEY
# In[ ]:
# For Request/Help form submission.
@app.route('/create_request', methods=['POST'])
@capture_api_exception
def create_request():
name = request.form.get('name')
mob_number = request.form.get('mob_number')
email_id = request.form.get('email_id', '')
age = request.form.get('age')
address = request.form.get('address')
geoaddress = request.form.get('geoaddress', address)
user_request = request.form.get('request')
latitude = request.form.get('latitude', 0.0)
longitude = request.form.get('longitude', 0.0)
source = request.form.get('source', 'covidsos')
status = request.form.get('status', 'received')
country = request.form.get('country', 'India')
managed_by = request.form.get('managed_by', 0)
members_impacted = request.form.get('members_impacted', 2)
current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330)
city = getCityAddr(latitude, longitude)
uuid = generate_uuid()
filled_by_name = request.form.get('filled_by_name', name)
filled_by_mob_number = request.form.get('filled_by_mob_number', mob_number)
req_dict = {'timestamp': [current_time], 'name': [name], 'mob_number': [mob_number], 'email_id': [email_id],
'country': [country], 'address': [address], 'geoaddress': [geoaddress], 'latitude': [latitude],
'longitude': [longitude], 'source': [source], 'age': [age], 'request': [user_request],
'status': [status], 'uuid': [uuid], 'managed_by': [managed_by], 'members_impacted': [members_impacted],
'city': [city], 'volunteers_reqd': [1],'filled_by_name':[filled_by_name],'filled_by_mob_number':[filled_by_mob_number]}
df = pd.DataFrame(req_dict)
df['email_id'] = df['email_id'].fillna('')
expected_columns = ['timestamp', 'name', 'mob_number', 'email_id', 'country', 'address', 'geoaddress', 'latitude',
'longitude', 'source', 'request', 'age', 'status', 'members_impacted', 'uuid', 'managed_by',
'city', 'volunteers_reqd','filled_by_name','filled_by_mob_number']
x, y = add_requests(df[expected_columns])
r_df = request_data_by_uuid(uuid)
if r_df is not None:
v_req_dict = {'r_id': [r_df.loc[0, 'r_id']], 'why': [None], 'what': [None], 'where': [geoaddress],
'verification_status': ['pending'], 'verified_by': [managed_by],
'timestamp': [current_time], 'financial_assistance': [0], 'urgent': ['no']}
expected_columns = ['timestamp', 'r_id', 'what', 'why', 'where', 'verification_status', 'verified_by',
'financial_assistance', 'urgent']
v_df = pd.DataFrame(v_req_dict)
W, Z = add_request_verification_db(v_df[expected_columns])
response = {'Response': {}, 'status': x, 'string_response': y}
if (x):
# move to async
# sms_text = new_request_sms.format(name=name, source=source)
# send_sms(sms_text, sms_to=int(mob_number), sms_type='transactional', send=True)
sms_params_1 = {"var1":key_word,"var2":name,"var3":source,"var4":url_retriever("new_request_sms")}
send_raven_v1("a_request_received",sms_to=int(mob_number), send=True,body_parameters=sms_params_1)
# mod_sms_text = new_request_mod_sms.format(source=source, uuid=str(uuid))
save_request_sms_url(uuid, 'verify_link', url_start + "verify/{uuid}".format(uuid=uuid))
moderator_list = get_moderator_list()
for i_number in moderator_list:
sms_params_2 = {"var1":key_word,"var2":name,"var3":url_start,"var4":uuid}
send_raven_v1("a_request_verification_moderat",sms_to=int(i_number),send=True,body_parameters=sms_params_2)
# send_moderator_msg(i_number,mod_sms_text)
# send_sms(mod_sms_text, sms_to=int(i_number), sms_type='transactional', send=True)
return json.dumps(response)
# In[ ]:
@app.route('/create_volunteer', methods=['POST'])
@capture_api_exception
def add_volunteer():
name = request.form.get('name')
mob_number = request.form.get('mob_number')
email_id = request.form.get('email_id', '')
address = request.form.get('address')
geoaddress = request.form.get('geoaddress', address)
latitude = request.form.get('latitude', 0.0)
longitude = request.form.get('longitude', 0.0)
source = request.form.get('source')
status = request.form.get('status', 1)
country = request.form.get('country', 'India')
support_type = request.form.get('support_type', '1,2,3,4,5')
current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330)
city = getCityAddr(latitude, longitude)
req_dict = {'timestamp': [current_time], 'name': [name], 'mob_number': [mob_number], 'email_id': [email_id],
'country': [country], 'address': [address], 'geoaddress': [geoaddress], 'latitude': [latitude],
'longitude': [longitude],
'source': [source], 'status': [status], 'support_type': [support_type], 'city': [city]}
df = pd.DataFrame(req_dict)
expected_columns = ['timestamp', 'name', 'mob_number', 'email_id', 'country', 'address', 'geoaddress', 'latitude',
'longitude', 'source', 'status', 'support_type', 'city']
x, y = add_volunteers_to_db(df)
if (x):
if (y == 'Volunteer already exists. Your information has been updated'):
# v_sms_text = old_reg_sms
params_1={"var1":key_word, "var2":url_retriever("a_existing_user_registration")}
send_raven_v1("a_existing_user_registration",sms_to=int(mob_number),send=True,body_parameters=params_1)
else:
# v_sms_text = new_reg_sms
params_1 = {"var1": key_word, "var2": url_retriever("a_new_user_registration")}
send_raven_v1("a_new_user_registration", sms_to=int(mob_number), send=True, body_parameters=params_1)
# send_sms(v_sms_text, sms_to=int(mob_number), sms_type='transactional', send=True)
response = {'Response': {}, 'status': x, 'string_response': y}
return json.dumps(response)
@app.route('/create_ngo_request', methods=['POST'])
@capture_api_exception
@login_required
def ngo_request_form(*args, **kwargs):
name = request.form.get('name')
mob_number = request.form.get('mob_number')
email_id = request.form.get('email_id', '')
age = request.form.get('age', 70)
address = request.form.get('address')
geoaddress = request.form.get('geoaddress', address)
user_request = request.form.get('request')
latitude = request.form.get('latitude', 0.0)
longitude = request.form.get('longitude', 0.0)
city = getCityAddr(latitude, longitude)
source = request.form.get('source', 'covidsos')
if ((source == 'undefined') or (source == '')):
source = 'covidsos'
status = request.form.get('status', 'received')
if (status == ''):
status = 'received'
country = request.form.get('country', 'India')
uuid = generate_uuid()
what = request.form.get('what')
why = request.form.get('why')
financial_assistance = request.form.get('financial_assistance', 0)
if (financial_assistance == ''):
financial_assistance = 0
verification_status = 'pending'
where = geoaddress
verified_by = kwargs.get('user_id', 0)
urgent_status = request.form.get('urgent', 'no')
volunteers_reqd = request.form.get('volunteer_count', 1)
members_impacted = request.form.get('members_impacted', 2)
current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330)
user_df = user_data_by_id(verified_by)
if(user_df.shape[0]>0):
filled_by_name = user_df.loc[0,'name']
filled_by_mob_number = user_df.loc[0,'mob_number']
else:
filled_by_name = name
filled_by_mob_number = mob_number
req_dict = {'timestamp': [current_time], 'name': [name], 'mob_number': [mob_number], 'email_id': [email_id],
'country': [country], 'address': [address], 'geoaddress': [geoaddress], 'latitude': [latitude],
'longitude': [longitude],
'source': [source], 'age': [age], 'request': [user_request], 'status': [status], 'uuid': [uuid],
'volunteers_reqd': [volunteers_reqd], 'managed_by': [verified_by],
'members_impacted': [members_impacted], 'city': [city],'filled_by_name':[filled_by_name],
'filled_by_mob_number':[filled_by_mob_number]}
df = pd.DataFrame(req_dict)
df['email_id'] = df['email_id'].fillna('')
expected_columns = ['timestamp', 'name', 'mob_number', 'email_id', 'country', 'address', 'geoaddress', 'latitude',
'longitude', 'source', 'request', 'age', 'status', 'members_impacted', 'uuid', 'managed_by',
'city', 'volunteers_reqd','filled_by_name','filled_by_mob_number']
x1, y1 = add_requests(df[expected_columns])
r_df = request_data_by_uuid(uuid)
r_v_dict = {'r_id': [r_df.loc[0, 'r_id']], 'why': [why], 'what': [what], 'where': [where],
'verification_status': [verification_status], 'verified_by': [verified_by], 'timestamp': [current_time],
'financial_assistance': [financial_assistance], 'urgent': [urgent_status]}
df = pd.DataFrame(r_v_dict)
expected_columns = ['timestamp', 'r_id', 'what', 'why', 'where', 'verification_status', 'verified_by',
'financial_assistance', 'urgent']
x2, y2 = add_request_verification_db(df[expected_columns])
if (x1):
# move to async
sms_params_1 = {"var1":key_word,"var2":name,"var3":source,"var4":url_retriever("new_request_sms")}
send_raven_v1("a_request_received",sms_to=int(mob_number), send=True,body_parameters=sms_params_1)
# sms_text = new_request_sms.format(source=source, name=name)
# send_sms(sms_text, sms_to=int(mob_number), sms_type='transactional', send=True)
# mod_sms_text = new_request_mod_sms.format(source=source, uuid=str(uuid))
save_request_sms_url(uuid, 'verify_link', url_start + "verify/{uuid}".format(uuid=uuid))
moderator_list = get_moderator_list()
for i_number in moderator_list:
sms_params_2 = {"var1":key_word,"var2":name,"var3":url_start,"var4":uuid}
send_raven_v1("a_request_verification_moderat",sms_to=int(i_number),send=True,body_parameters=sms_params_2)
# send_moderator_msg(i_number,mod_sms_text)
# send_sms(mod_sms_text, sms_to=int(i_number), sms_type='transactional', send=True)
response = {'Response': {}, 'status': x1, 'string_response': y1}
return response
@app.route('/create_full_request', methods=['POST'])
@capture_api_exception
def full_request_form():
name = request.form.get('name')
mob_number = request.form.get('mob_number')
email_id = request.form.get('email_id', '')
age = request.form.get('age', 70)
address = request.form.get('address')
geoaddress = request.form.get('geoaddress', address)
user_request = request.form.get('request')
latitude = request.form.get('latitude', 0.0)
longitude = request.form.get('longitude', 0.0)
city = getCityAddr(latitude, longitude)
source = request.form.get('source', 'covidsos')
if ((source == 'undefined') or (source == '')):
source = 'covidsos'
status = request.form.get('status', 'received')
if (status == ''):
status = 'received'
country = request.form.get('country', 'India')
uuid = generate_uuid()
what = request.form.get('what')
why = request.form.get('why')
financial_assistance = request.form.get('financial_assistance', 0)
if (financial_assistance == ''):
financial_assistance = 0
verification_status = 'pending'
where = geoaddress
managed_by = request.form.get('managed_by', 0)
urgent_status = request.form.get('urgent', 'no')
volunteers_reqd = request.form.get('volunteer_count', 1)
members_impacted = request.form.get('members_impacted', 2)
filled_by_name = request.form.get('filled_by_name', name)
filled_by_mob_number = request.form.get('filled_by_mob_number', mob_number)
current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330)
req_dict = {'timestamp': [current_time], 'name': [name], 'mob_number': [mob_number], 'email_id': [email_id],
'country': [country], 'address': [address], 'geoaddress': [geoaddress], 'latitude': [latitude],
'longitude': [longitude],
'source': [source], 'age': [age], 'request': [user_request], 'status': [status], 'uuid': [uuid],
'volunteers_reqd': [volunteers_reqd], 'managed_by': [managed_by],
'members_impacted': [members_impacted], 'city': [city],'filled_by_name':[filled_by_name],
'filled_by_mob_number':[filled_by_mob_number]}
df = pd.DataFrame(req_dict)
df['email_id'] = df['email_id'].fillna('')
expected_columns = ['timestamp', 'name', 'mob_number', 'email_id', 'country', 'address', 'geoaddress', 'latitude',
'longitude', 'source', 'request', 'age', 'status', 'members_impacted', 'uuid', 'managed_by',
'city', 'volunteers_reqd','filled_by_name','filled_by_mob_number']
x1, y1 = add_requests(df[expected_columns])
r_df = request_data_by_uuid(uuid)
r_v_dict = {'r_id': [r_df.loc[0, 'r_id']], 'why': [why], 'what': [what], 'where': [where],
'verification_status': [verification_status], 'verified_by': [managed_by], 'timestamp': [current_time],
'financial_assistance': [financial_assistance], 'urgent': [urgent_status]}
df = pd.DataFrame(r_v_dict)
expected_columns = ['timestamp', 'r_id', 'what', 'why', 'where', 'verification_status', 'verified_by',
'financial_assistance', 'urgent']
x2, y2 = add_request_verification_db(df[expected_columns])
if (x1):
# move to async
sms_params_1 = {"var1":key_word,"var2":name,"var3":source,"var4":url_retriever("new_request_sms")}
send_raven_v1("a_request_received",sms_to=int(mob_number), send=True,body_parameters=sms_params_1)
# sms_text = new_request_sms.format(source=source, name=name)
# send_sms(sms_text, sms_to=int(mob_number), sms_type='transactional', send=True)
# mod_sms_text = new_request_mod_sms.format(source=source, uuid=str(uuid))
save_request_sms_url(uuid, 'verify_link', url_start + "verify/{uuid}".format(uuid=uuid))
moderator_list = get_moderator_list()
for i_number in moderator_list:
sms_params_2 = {"var1":key_word,"var2":name,"var3":url_start,"var4":uuid}
send_raven_v1("a_request_verification_moderat",sms_to=int(i_number),send=True,body_parameters=sms_params_2)
# send_moderator_msg(i_number,mod_sms_text)
# send_sms(mod_sms_text, sms_to=int(i_number), sms_type='transactional', send=True)
response = {'Response': {}, 'status': x1, 'string_response': y1}
return response
# In[ ]:
@app.route('/login', methods=['POST'])
@capture_api_exception
def login_request():
name = request.form.get('username')
password = request.form.get('password')
response = verify_user(name, password)
user_id, access_type = get_user_id(name, password)
if not user_id:
return {'Response': {}, 'status': False, 'string_response': 'Failed to find user.'}
if(response['status']==True):
response['Response']['auth_token'] = encode_auth_token(f'{user_id} {access_type}').decode()
return json.dumps(response)
# In[ ]:
@app.route('/logout', methods=['POST'])
@capture_api_exception
def logout_request():
auth_header = request.headers.get('Authorization')
auth_token = auth_header.split(" ")[1] if auth_header else ''
if not auth_token:
return json.dumps({'Response': {}, 'status': False, 'string_response': 'No valid login found'})
resp, success = decode_auth_token(auth_token)
if not success:
return json.dumps({'Response': {}, 'status': False, 'string_response': 'No valid login found'})
success = blacklist_token(auth_token)
message = 'Logged out successfully' if success else 'Failed to logout'
return json.dumps({'Response': {}, 'status': success, 'string_response': message})
# In[ ]:
@app.route('/request_otp', methods=['POST'])
@capture_api_exception
def send_otp_request():
mob_number = request.form.get('mob_number')
if not verify_volunteer_exists(mob_number)['status']:
return json.dumps({'Response': {}, 'status': False, 'string_response': 'No user found for this mobile number'})
response, success = send_otp(mob_number)
return json.dumps({'Response': {}, 'status': success, 'string_response': response})
@app.route('/resend_otp', methods=['POST'])
@capture_api_exception
def resend_otp_request():
mob_number = request.form.get('mob_number')
if not verify_volunteer_exists(mob_number)['status']:
return json.dumps({'Response': {}, 'status': False, 'string_response': 'No user found for this mobile number'})
response, success = resend_otp(mob_number)
return json.dumps({'Response': {}, 'status': success, 'string_response': response})
@app.route('/verify_otp', methods=['POST'])
@capture_api_exception
def verify_otp_request():
mob_number = request.form.get('mob_number')
otp = request.form.get('otp')
userData = verify_volunteer_exists(mob_number)
if not userData['status']:
return json.dumps({'Response': {}, 'status': False, 'string_response': 'No user found for this mobile number'})
response, success = verify_otp(otp, mob_number)
responseObj = {}
if success:
user_id = int(str(userData['volunteer_id']))
country = userData['country']
name = userData['name']
encodeKey = f'{user_id} {country}'
responseObj = {'auth_token': encode_auth_token(encodeKey).decode(), 'name': name, 'volunteer_id': user_id}
return json.dumps({'Response': responseObj, 'status': success, 'string_response': response})
# In[ ]:
@app.route('/new_user', methods=['POST'])
@capture_api_exception
@login_required
def new_user(*args, **kwargs):
name = request.form.get('name')
mob_number = request.form.get('mob_number')
email_id = request.form.get('email_id')
password = request.form.get('password')
organisation = request.form.get('organisation')
auth_user_org = kwargs.get('organisation')
creator_access_type = request.form.get('creator_access_type')
user_access_type = request.form.get('user_access_type')
creator_user_id = request.form.get('creator_user_id')
verification_team = request.form.get('verification_team', 1)
current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330)
if auth_user_org != 'covidsos' and auth_user_org != organisation:
return {'Response': {}, 'status': False, 'string_response': 'You cannot create a user of another organisation.'}
if (user_access_type == 'moderator'):
access_type = 2
elif (user_access_type == 'viewer'):
access_type = 3
elif (user_access_type == 'superuser'):
response = {'Response': {}, 'status': False, 'string_response': 'You cannot create superuser'}
return json.dumps(response)
else:
response = {'Response': {}, 'status': False, 'string_response': 'Invalid access type'}
return json.dumps(response)
req_dict = {'creation_date': [current_time], 'name': [name], 'mob_number': [mob_number], 'email_id': [email_id],
'organisation': [organisation], 'password': [password], 'access_type': [access_type],
'created_by': [creator_user_id], 'verification_team': [verification_team]}
df = pd.DataFrame(req_dict)
if (creator_access_type == 'superuser'):
response = add_user(df)
user_id, access_type = get_user_id(mob_number, password)
if not user_id:
return {'Response': {}, 'status': False, 'string_response': 'Failed to create user. Please try again later'}
response['auth_token'] = encode_auth_token(f'{user_id} {access_type}').decode()
else:
response = {'Response': {}, 'status': False,
'string_response': 'User does not have permission to create new users'}
return json.dumps(response)
# In[ ]:
@app.route('/reachout_form', methods=['POST'])
@capture_api_exception
def add_org_request():
name = request.form.get('name')
organisation = request.form.get('organisation')
email_id = request.form.get('email_id')
mob_number = request.form.get('mob_number')
current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330)
comments = request.form.get('comments')
req_dict = {'timestamp': [current_time], 'name': [name], 'organisation': [organisation], 'mob_number': [mob_number],
'email_id': [email_id],
'source': ['website'], 'comments': [comments]}
df = pd.DataFrame(req_dict)
expected_columns = ['timestamp', 'name', 'organisation', 'mob_number', 'email_id', 'source', 'comments']
x, y = contact_us_form_add(df)
response = {'Response': {}, 'status': x, 'string_response': y}
return json.dumps(response)
# In[ ]:
@app.route('/top_ticker', methods=['GET'])
@capture_api_exception
def ticker_counts():
response = get_ticker_counts()
return json.dumps(response)
# In[ ]:
@app.route('/request_status_list', methods=['GET'])
@capture_api_exception
def request_status_list():
response = get_requests_list()
return json.dumps(response)
# In[ ]:
@app.route('/source_list', methods=['GET'])
@capture_api_exception
def request_source_list():
response = get_source_list()
return json.dumps(response)
# In[ ]:
@app.route('/support_type_list', methods=['GET'])
@capture_api_exception
def support_type_list():
get_type = request.args.get('type')
if ((get_type == 'volunteer') or (get_type == 'request')):
response = get_type_list(get_type)
return json.dumps(response)
else:
return json.dumps({'Response': {}, 'status': False, 'string_response': 'Incorrect response'})
# In[ ]:
@app.route('/private_map_data', methods=['GET'])
@capture_api_exception
@login_required
def private_map_data(*args, **kwargs):
org = kwargs.get('organisation', '')
response = get_private_map_data(org)
return json.dumps({'Response': response, 'status': True, 'string_response': 'Full data sent'},
default=datetime_converter)
# In[ ]:
@app.route('/public_map_data', methods=['GET'])
@capture_api_exception
def public_map_data():
response = get_public_map_data()
return json.dumps({'Response': response, 'status': True, 'string_response': 'Public data sent'})
# In[ ]:
@app.route('/assign_volunteer', methods=['POST'])
@capture_api_exception
@login_required
def assign_volunteer(*args, **kwargs):
org = kwargs.get('organisation', '')
volunteer_id = request.form.get('volunteer_id')
request_id = request.form.get('request_id')
# TODO:
# Change matched_by to use user_id/volunteer_id from kwargs instead of form data
# change matched_by datatype to int and convert all existing values to be numeric
matched_by = request.form.get('matched_by')
response = assign_request_to_volunteer(volunteer_id, request_id, matched_by, org)
return json.dumps(response)
@app.route('/assign_request', methods=['POST'])
@capture_api_exception
@volunteer_login_req
def assign_request(*args, **kwargs):
volunteer_id = kwargs.get('volunteer_id')
request_id = request.form.get('request_id')
matched_by = request.form.get('matched_by', 0)
response = assign_request_to_volunteer(volunteer_id, request_id, matched_by, 'covidsos')
return json.dumps(response)
def assign_request_to_volunteer(volunteer_id, request_id, matched_by, org):
r_df = request_data_by_id(request_id)
v_df = volunteer_data_by_id(volunteer_id)
if (r_df.shape[0] == 0):
return {'status': False, 'string_response': 'Request ID does not exist.', 'Response': {}}
if (v_df.shape[0] == 0):
return {'status': False, 'string_response': 'Volunteer does not exist', 'Response': {}}
else:
if org != 'covidsos' and not (r_df.loc[0, 'source'] == v_df.loc[0, 'source'] == org):
return {'status': False,
'string_response': 'Organisation not same for all: requester, volunteer and matchmaker',
'Response': {}}
if (r_df.loc[0, 'status'] in ['received', 'verified', 'pending']):
current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330)
req_dict = {'volunteer_id': [volunteer_id], 'request_id': [r_df.loc[0, 'r_id']],
'matching_by': [matched_by], 'timestamp': [current_time]}
df = pd.DataFrame(req_dict)
# Add entry in request_matching table
response = request_matching(df)
# Update request status as matched
if response['status'] == True:
volunteers_assigned = get_volunteers_assigned_to_request(request_id)
if r_df.loc[0, 'volunteers_reqd'] == len(volunteers_assigned):
response_2 = update_requests_db({'id': request_id}, {'status': 'matched'})
response_3 = update_nearby_volunteers_db({'r_id': request_id}, {'status': 'expired'})
# Send to Volunteer
params_1 = {"var1":key_word,"var2":r_df.loc[0, 'name'],"var3":r_df.loc[0, 'mob_number'],"var4":r_df.loc[0, 'request'],"var5":r_df.loc[0, 'geoaddress'],
"var6":url_retriever("a_accepted_request_vol")}
send_raven_v1("a_accepted_request_vol",int(v_df.loc[0, 'mob_number']), send=True,body_parameters=params_1)
# v_sms_text = request_accepted_v_sms.format(r_name=r_df.loc[0, 'name'], mob_number=r_df.loc[0, 'mob_number'],
# request=r_df.loc[0, 'request'],
# address=r_df.loc[0, 'geoaddress'])
# send_sms(v_sms_text, int(v_df.loc[0, 'mob_number']), sms_type='transactional', send=True)
# Send to Requestor
params_2 = {"var1":key_word,"var2":url_retriever("a_accepted_request_requestor")}
send_raven_v1("a_accepted_request_requestor",int(r_df.loc[0, 'mob_number']), send=True,body_parameters=params_2)
# r_sms_text = request_accepted_r_sms
#.format(v_name=v_df.loc[0, 'name'], mob_number=v_df.loc[0, 'mob_number'])
# send_sms(r_sms_text, int(r_df.loc[0, 'mob_number']), sms_type='transactional', send=True)
# Send to Moderator
params_3 = {"var1":key_word,"var2":v_df.loc[0, 'name'],"var3":v_df.loc[0, 'mob_number'],"var4":r_df.loc[0, 'name'],"var5":r_df.loc[0, 'mob_number']}
# m_sms_text = request_accepted_m_sms.format(v_name=v_df.loc[0, 'name'],
# v_mob_number=v_df.loc[0, 'mob_number'],
# r_name=r_df.loc[0, 'name'],
# r_mob_number=r_df.loc[0, 'mob_number'])
moderator_list = get_moderator_list()
for i_number in moderator_list:
send_raven_v1("a_acc_request_mod", int(i_number), send=True, body_parameters=params_3)
# send_moderator_msg(i_number, m_sms_text)
# send_sms(m_sms_text, int(i_number), sms_type='transactional', send=True)
else:
return {'status': False, 'string_response': 'Request already assigned/closed/completed', 'Response': {}}
return response
# In[ ]:
@app.route('/auto_assign_volunteer', methods=['POST'])
@capture_api_exception
def auto_assign_volunteer():
v_id = request.form.get('volunteer_id')
uuid = request.form.get('uuid')
matching_by = 'autoassigned'
task_action = request.form.get('task_action')
r_df = request_data_by_uuid(uuid)
v_df = volunteer_data_by_id(v_id)
if (r_df.shape[0] == 0):
return json.dumps({'status': False, 'string_response': 'Request ID does not exist.', 'Response': {}})
if (v_df.shape[0] == 0):
return json.dumps({'status': False, 'string_response': 'Volunteer does not exist', 'Response': {}})
else:
r_id = r_df.loc[0, 'r_id']
if (((r_df.loc[0, 'status'] == 'received') or (r_df.loc[0, 'status'] == 'verified') or (
r_df.loc[0, 'status'] == 'pending')) & (task_action == 'accepted')):
current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330)
req_dict = {'volunteer_id': [v_id], 'request_id': [r_id], 'matching_by': [matching_by],
'timestamp': [current_time]}
df = pd.DataFrame(req_dict)
response = request_matching(df)
response_2 = update_requests_db({'id': r_id}, {'status': 'matched'})
response_3 = update_nearby_volunteers_db({'r_id': r_id}, {'status': 'expired'})
# Send to Volunteer
params_1 = {"var1":key_word,"var2":r_df.loc[0, 'name'],"var3":r_df.loc[0, 'mob_number'],"var4":r_df.loc[0, 'request'],"var5":r_df.loc[0, 'geoaddress'],
"var6":url_retriever("a_accepted_request_vol")}
send_raven_v1("a_accepted_request_vol",int(v_df.loc[0, 'mob_number']), send=True,body_parameters=params_1)
# v_sms_text = request_accepted_v_sms.format(r_name=r_df.loc[0, 'name'], mob_number=r_df.loc[0, 'mob_number'],
# request=r_df.loc[0, 'request'],
# address=r_df.loc[0, 'geoaddress'])
# send_sms(v_sms_text, int(v_df.loc[0, 'mob_number']), sms_type='transactional', send=True)
# Send to Requestor
params_2 = {"var1":key_word,"var2":url_retriever("a_accepted_request_requestor")}
send_raven_v1("a_accepted_request_requestor",int(r_df.loc[0, 'mob_number']), send=True,body_parameters=params_2)
# r_sms_text = request_accepted_r_sms
#.format(v_name=v_df.loc[0, 'name'], mob_number=v_df.loc[0, 'mob_number'])
# send_sms(r_sms_text, int(r_df.loc[0, 'mob_number']), sms_type='transactional', send=True)
return json.dumps(response)
elif ((r_df.loc[0, 'status'] == 'received') or (r_df.loc[0, 'status'] == 'verified') or (
r_df.loc[0, 'status'] == 'pending')):
response_3 = update_nearby_volunteers_db({'r_id': r_id, 'v_id': v_id}, {'status': 'expired'})
return json.dumps({'status': True, 'string_response': 'Request rejected', 'Response': {}})
else:
return json.dumps({'status': False, 'string_response': 'Request already assigned', 'Response': {}})
# In[ ]:
# get requests that are available to be assigned to volunteers
@app.route('/accept_page', methods=['GET'])
@capture_api_exception
def request_accept_page():
uuid = request.args.get('uuid')
df = accept_request_page(uuid)
if (df.shape[0] == 0):
return json.dumps(
{'Response': {}, 'status': False, 'string_response': 'This page does not exist. Redirecting to homepage'})
else:
return json.dumps(
{'Response': df.to_dict('records'), 'status': True, 'string_response': 'Request related data extracted'})
# In[ ]:
# Get request data by uuid along with its existing verification data
# TODO: Change method to GET
@app.route('/verify_request_page', methods=['POST'])
@capture_api_exception
@login_required
def verify_request_page(*args, **kwargs):
uuid = request.form.get('uuid')
auth_user_org = kwargs.get('organisation', '')
r_df = request_data_by_uuid(uuid)
c_1 = ['r_id', 'name', 'mob_number', 'geoaddress', 'latitude', 'longitude', 'request', 'status', 'timestamp',
'source', 'volunteers_reqd', 'members_impacted']
# Check if request verification table already has a row, then also send info from request verification data along with it.
if (r_df.shape[0] == 0):
return json.dumps({'status': False, 'string_response': 'Request ID does not exist.', 'Response': {}})
if auth_user_org != 'covidsos' and r_df.loc[0, 'source'] != auth_user_org:
return json.dumps({'status': False, 'string_response': 'Your organisation and that of the request dont match.',
'Response': {}})
past_df, past_status = check_past_verification(str(r_df.loc[0, 'r_id']))
c_2 = ['r_id', 'why', 'what', 'request_address', 'urgent', 'financial_assistance']
if (past_status):
full_df = r_df[c_1].merge(past_df[c_2], how='left', on='r_id')
else:
past_df = pd.DataFrame(columns=c_2)
past_df[c_2] = ""
full_df = r_df[c_1].merge(past_df[c_2], how='left', on='r_id').fillna('')
if (full_df.loc[0, 'status'] == 'received'):
return json.dumps(
{'Response': full_df.to_dict('records')[0], 'status': True, 'string_response': 'Request data extracted'},
default=datetime_converter)
else:
return json.dumps({'Response': {}, 'status': False, 'string_response': 'Request already verified/rejected'})
# In[ ]:
# mark verified/rejected and create a verification table entry with verification data
@app.route('/verify_request', methods=['POST'])
@capture_api_exception
@login_required
def verify_request(*args, **kwargs):
uuid = request.form.get('uuid')
what = request.form.get('what')
why = request.form.get('why')
financial_assistance = request.form.get('financial_assistance', 0)
if (financial_assistance == ''):
financial_assistance = 0
verification_status = request.form.get('verification_status')
verified_by = kwargs.get('user_id', 0)
r_id = request.form.get('r_id')
name = request.form.get('name')
where = request.form.get('geoaddress')
mob_number = request.form.get('mob_number')
urgent_status = request.form.get('urgent', 'no')
auth_user_org = kwargs.get('organisation', '')
source = request.form.get('source', 'covidsos')
if (source == 'undefined'):
source = 'covidsos'
volunteers_reqd = request.form.get('volunteer_count', 1)
current_time = dt.datetime.utcnow() + dt.timedelta(minutes=330)
members_impacted = request.form.get('members_impacted', 2)
if (verification_status is None):
return json.dumps({'Response': {}, 'status': False, 'string_response': 'Please send verification status'})
if ((r_id is None) or (uuid is None)):
return json.dumps({'Response': {}, 'status': False, 'string_response': 'Please send UUID/request ID'})
r_df = request_data_by_uuid(uuid)
if auth_user_org != 'covidsos' and r_df.loc[0, 'source'] != auth_user_org:
return json.dumps({'status': False, 'string_response': 'Your organisation and that of the request dont match.',
'Response': {}})
if (r_df.shape[0] == 0):
return json.dumps({'Response': {}, 'status': False, 'string_response': 'Invalid UUID/request ID'})
if (r_df.loc[0, 'source'] != source):
response_0 = update_requests_db({'uuid': uuid}, {'source': source})
if (r_df.loc[0, 'status'] == 'received'):
r_v_dict = {'r_id': [r_id], 'why': [why], 'what': [what], 'where': [where],
'verification_status': [verification_status], 'verified_by': [verified_by],
'timestamp': [current_time], 'financial_assistance': [financial_assistance],
'urgent': [urgent_status]}
df = pd.DataFrame(r_v_dict)
expected_columns = ['timestamp', 'r_id', 'what', 'why', 'where', 'verification_status', 'verified_by',
'financial_assistance', 'urgent']
response_2 = update_requests_db({'uuid': uuid},
{'status': verification_status, 'volunteers_reqd': volunteers_reqd,
'members_impacted': members_impacted})
print('updated the status')
past_df, past_status = check_past_verification(str(r_id))
if (past_status == True):
r_v_dict = {'r_id': r_id, 'why': why, 'what': what, 'where': where,
'verification_status': verification_status, 'verified_by': verified_by,
'timestamp': current_time, 'financial_assistance': financial_assistance,
'urgent': urgent_status}
rv_dict = {x: r_v_dict[x] for x in r_v_dict}
update_request_v_db({'id': (past_df.loc[0, 'id'])}, rv_dict)
else:
expected_columns = ['timestamp', 'r_id', 'what', 'why', 'where', 'verification_status', 'verified_by',
'financial_assistance', 'urgent']
x, y = add_request_verification_db(df[expected_columns])
if (verification_status == 'verified'):
params_1 = {"var1":key_word,"var2":url_retriever("a_verified_req")}
send_raven_v1("a_verified_req",sms_to=int(mob_number), send=True,body_parameters=params_1)
# requestor_text = request_verified_sms
# send_sms(requestor_text, sms_to=int(mob_number), sms_type='transactional', send=True)
message_all_volunteers(uuid, neighbourhood_radius, search_radius)
ru_dict_where = {'uuid': uuid}
ru_dict_set = {'managed_by': verified_by}
update_requests_db(ru_dict_where, ru_dict_set)
else:
params_2 = {"var1":key_word}
send_raven_v1("a_rejected_request_to_reqstr",sms_to=int(mob_number), send=True, body_parameters=params_2)
# requestor_text = request_rejected_sms
# send_sms(requestor_text, sms_to=int(mob_number), sms_type='transactional', send=True)
return json.dumps(
{'Response': {}, 'status': response_2['status'], 'string_response': response_2['string_response']})
else:
return json.dumps({'Response': {}, 'status': False, 'string_response': 'Request already verified/rejected'})
# In[ ]:
@app.route('/all_requests', methods=['GET'])
@capture_api_exception
@login_required
def fetch_all_requests(*args, **kwargs):
org = kwargs.get('organisation', 'covidsos')
response = {}
df = get_unverified_requests(org)
if (df.shape[0] > 0):
response["unverified_requests"] = df.to_dict('records')
else:
response["unverified_requests"] = {}
pending_requests = website_requests_display_secure(org)
if pending_requests.shape[0]>0:
response["pending_requests"] = pending_requests.to_dict('records')
completed_requests = get_completed_requests(org)
if completed_requests.shape[0] > 0:
response["completed_requests"] = completed_requests.to_dict('records')
else:
response["pending_requests"] = {}
response["completed_requests"] = {}
ar_df = get_assigned_requests(org)
if (ar_df.shape[0] > 0):
response["assigned_requests"] = ar_df.to_dict('records')
else:
response["assigned_requests"] = {}
return json.dumps(
{'Response': response, 'status': True, 'string_response': 'Request data extracted'},
default=datetime_converter)
@app.route('/pending_requests', methods=['GET'])
@capture_api_exception
def pending_requests():
response = website_requests_display()
return json.dumps({'Response': response.to_dict('records'), 'status': True, 'string_response': 'Request data extracted'},
default=datetime_converter)
@app.route('/admin_completed_requests', methods=['GET'])
@capture_api_exception
@login_required
def admin_completed_requests(*args, **kwargs):
org = kwargs.get('organisation', '')
if (org == 'covidsos'):
response = get_completed_requests(org)
return json.dumps({'Response': response.to_dict('records'), 'status': True, 'string_response': 'Request data extracted'},
default=datetime_converter)
else:
response = get_completed_requests(org)
return json.dumps({'Response': response.to_dict('records'), 'status': True, 'string_response': 'Request data extracted'},
default=datetime_converter)
@app.route('/completed_page', methods=['GET'])
@capture_api_exception
def request_completed_page():
uuid = request.args.get('uuid')
v_id = request.args.get('v_id')
df = completed_request_page(uuid,v_id)
if (df.shape[0] == 0):
return json.dumps(
{'Response': {}, 'status': False, 'string_response': 'This page does not exist. Redirecting to homepage'})
else:
return json.dumps(
{'Response': df.to_dict('records'), 'status': True, 'string_response': 'Request related data extracted'})
@app.route('/completed_requests', methods=['GET'])
@capture_api_exception
def completed_requests(*args, **kwargs):
response = completed_website_requests_display()
return json.dumps({'Response': response.to_dict('records'), 'status': True,
'string_response': 'Completed requests data extracted'}, default=datetime_converter)
@app.route('/admin_pending_requests', methods=['GET'])
@capture_api_exception
@login_required
def admin_pending_requests(*args, **kwargs):
org = kwargs.get('organisation', '')
if (org == 'covidsos'):
response = website_requests_display_secure(org)
return json.dumps({'Response': response.to_dict('records'), 'status': True, 'string_response': 'Request data extracted'},
default=datetime_converter)
else:
response = website_requests_display(org)
return json.dumps({'Response': response.to_dict('records'), 'status': True, 'string_response': 'Request data extracted'},
default=datetime_converter)
# In[ ]:
@app.route('/unverified_requests', methods=['GET'])
@capture_api_exception
@login_required
def unverified_requests(*args, **kwargs):
org = kwargs.get('organisation', '')
df = get_unverified_requests(org)
if (df.shape[0] > 0):
return json.dumps(
{'Response': df.to_dict('records'), 'status': True, 'string_response': 'Request data extracted'},
default=datetime_converter)
else:
return json.dumps({'Response': {}, 'status': True, 'string_response': 'No unverified requests found'},
default=datetime_converter)
# In[ ]:
@app.route('/accepted_requests', methods=['GET'])
@capture_api_exception
@login_required
def assigned_requests(*args, **kwargs):
org = kwargs.get('organisation', '')
df = get_assigned_requests(org)
if (df.shape[0] > 0):
return json.dumps(
{'Response': df.to_dict('records'), 'status': True, 'string_response': 'Request data extracted'},
default=datetime_converter)
else:
return json.dumps({'Response': {}, 'status': True, 'string_response': 'No open requests found'},
default=datetime_converter)
# In[ ]:
@app.route('/success_stories', methods=['GET'])
@capture_api_exception
def success_stories():
response = website_success_stories()
return json.dumps({'Response': response, 'status': True, 'string_response': 'Success stories data extracted'})
@app.route('/volunteer-requests', methods=['GET'])
@capture_api_exception
@volunteer_login_req
def volunteer_tickets(*args, **kwargs):
volunteer_id = kwargs['volunteer_id']
volunteer_reqs = get_requests_assigned_to_volunteer(volunteer_id)
return json.dumps({'Response': volunteer_reqs, 'status': True, 'string_response': 'Data sent'})
@app.route('/request-info', methods=['GET'])
@capture_api_exception
@volunteer_login_req
def get_request_info(*args, **kwargs):
request_uuid = request.args.get('uuid', '')
request_data = accept_request_page_secure(request_uuid)
request_data = request_data.to_dict('records')
return json.dumps({'Response': request_data, 'status': True, 'string_response': 'Data sent'})
@app.route('/admin-request-info', methods=['GET'])
@capture_api_exception
@login_required
def get_admin_request_info(*args, **kwargs):
request_uuid = request.args.get('uuid', '')
request_data = accept_request_page_secure(request_uuid)
request_data = request_data.to_dict('records')
return json.dumps({'Response': request_data, 'status': True, 'string_response': 'Data sent'})
@app.route('/vol-update-request', methods=['POST'])
@capture_api_exception
@volunteer_login_req