-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
5332 lines (4841 loc) · 327 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import imaplib
import base64
import os
import time
from configparser import ConfigParser, ExtendedInterpolation
import wget
import urllib
import xlrd
import uuid
import csv
from bson.objectid import ObjectId
import json
from datetime import datetime
import requests
from difflib import get_close_matches
from requests import post, get, delete
import sys
import time
import xlwt
import xlutils
from xlutils.copy import copy
import shutil
import re
from xlrd import open_workbook
from xlutils.copy import copy as xl_copy
import logging
import logging.handlers
import time
from logging.handlers import TimedRotatingFileHandler
import xlsxwriter
import argparse
import sys
from os import path
import pandas as pd
import openpyxl
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border
from openpyxl.styles import colors
from openpyxl.cell import Cell
import gdown
# get current working directory
currentDirectory = os.getcwd()
# Read config file
config = ConfigParser()
config.read('common_config/config.ini')
# email regex
regex = "\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"
# Global variable declaration
criteriaLookUp = dict()
millisecond = None
programNameInp = None
environment = None
observationId = None
solutionName = None
pointBasedValue = None
entityType = None
allow_multiple_submissions = None
scopeEntityType = ""
programName = None
userEntity = None
roles = ""
mainRole = ""
dictCritLookUp = {}
isProgramnamePresent = None
solutionLanguage = None
keyWords = None
entityTypeId = None
solutionDescription = None
creator = None
dikshaLoginId = None
criteriaName = None
solutionId = None
API_log = None
listOfFoundRoles = []
entityToUpload = None
programID = None
programExternalId = None
programDescription = None
criteriaLookUp = dict()
themesSheetList = []
themeRubricFileObj = dict()
criteriaLevelsReport = False
ecm_sections = dict()
criteriaLevelsCount = 0
numberOfResponses = 0
criteriaIdNameDict = dict()
criteriaLevels = list()
matchedShikshalokamLoginId = None
scopeEntities = []
scopeRoles = []
countImps = 0
ecmToSection = dict()
entitiesPGM = []
entitiesPGMID = []
solutionRolesArr = []
startDateOfResource = None
endDateOfResource = None
startDateOfProgram = None
endDateOfProgram = None
rolesPGM =None
solutionRolesArray = []
solutionStartDate = ""
solutionEndDate = ""
projectCreator = ""
orgIds = []
OrgName = []
ccRootOrgName = None
ccRootOrgId = None
certificatetemplateid = None
question_sequence_arr = []
# function to map course to program
# As per the discussion with products team, course is currently taken down from the product until further notice
def courseMapToProgram(accessToken, courseLink, parentFolder):
terminatingMessage("---> Course not part of the product ...")
# # split url and get the do id
# getDo = courseLink.split("/do_")
# cleanDo = getDo[1].split("/")
# # content read url
# ReadCourseURL = config.get(environment, 'host') + config.get(environment, 'readCourseURL') + "do_" + str(cleanDo[0])
# # content read payload
# payload = {}
# # content read headers
# headers = {'Content-Type': 'application/json', 'ts': '2017-05-25 10:18:56:578+0530',
# 'Authorization': 'Bearer ' + config.get(environment, 'Authorization'),
# 'X-authenticated-user-token': accessToken}
# # hit content read api
# responseReadCourse = requests.request("GET", ReadCourseURL, headers=headers, data=payload)
# # prepare message for api hit log
# messageArr = ["*************** Read Course ***************", "Read Course URL : " + str(ReadCourseURL)]
# # write api hit log
# createAPILog(parentFolder, messageArr)
# # check content read api status
# if responseReadCourse.status_code == 200:
# # parse response JSON into a dictionary
# responseReadCourse = responseReadCourse.json()
# # fetch required info from the response
# courseName = responseReadCourse['result']['content']['name']
# courseDesc = responseReadCourse['result']['content']['description']
# CourseExternalID = "COURSE_" + str(cleanDo[0]) + "-" + str(millisecond) + "-" + courseName.replace(" ", "_")
# # prepare message for api hit log
# messageArr = ["Course Name : " + str(courseName), "Course Description : " + str(courseDesc)]
# # write api hit log
# createAPILog(parentFolder, messageArr)
# # course solution creation
# PGM_COURSE_MAPPINGurl = config.get(environment, 'host') + config.get(environment, 'courseProgramMapping')
# # course solution payload
# payload = json.dumps({
# "name": courseName,
# "description": courseDesc,
# "link": courseLink,
# "externalId": "COURSE_" + str(cleanDo[0]) + "-" + str(millisecond) + "-" + courseName.replace(" ", "_"),
# "type": "course",
# "subType": "course",
# "programExternalId": programExternalId.lstrip().rstrip(),
# "isReusable": False
# })
# # course solution header
# headers = {'X-authenticated-user-token': accessToken,
# 'internal-access-token': config.get(environment, 'internal-access-token'),
# 'Content-Type': 'application/json',
# 'Authorization': 'Bearer ' + config.get(environment, 'Authorization')}
# # hit solution creation API
# responseCourseMap = requests.request("POST", PGM_COURSE_MAPPINGurl, headers=headers, data=payload)
# # API hit log
# messageArr = ["*************** Course Mapping ***************",
# "Course Program Mapping URL : " + str(PGM_COURSE_MAPPINGurl),
# "Response : " + str(responseCourseMap.text)]
# createAPILog(parentFolder, messageArr)
# if responseCourseMap.status_code == 200:
# responseCourseMap = responseCourseMap.json()
# courseSolutionId = responseCourseMap["result"]["_id"]
# print("--->Course mapped to program.")
# prepareProgramSuccessSheet(MainFilePath, parentFolder, programFile, CourseExternalID,
# courseSolutionId, accessToken)
# return courseSolutionId
# else:
# print("XXXXXXXXX ---- Course to program mapping Failed. ----- XXXXXXXX")
# else:
# print("XXXXXXXXX --- Course read API failed ----- XXXXXXXXX")
# print("XXXXXXXXX --- Check API hit logs ----- XXXXXXXXX")
def checkIfObsMappedToProgram(accessToken, obsExt, parentFolder):
# fetch observation solution details API end points
fetchSolutionDetailsURL = config.get(environment, 'INTERNAL_KONG_IP') + config.get(environment,'fetchSolutionDetails') + "observation&page=1&limit=10&search=" + str(obsExt)
# fetch observation solution details payload
payload = {}
# fetch observation solution header
headers = {'Content-Type': 'application/json',
'Authorization': 'Bearer ' + config.get(environment, 'internal-access-token'),
'X-authenticated-user-token': accessToken, 'X-Channel-id': config.get(environment, 'X-Channel-id')}
responseSearchSol = requests.request("POST", fetchSolutionDetailsURL, headers=headers, data=payload)
listOfFoundSolutionIds = {}
if responseSearchSol.status_code == 200:
# parse list of Observations into a python dictionary
responseSearchSol = responseSearchSol.json()
# iterate through each _id of solution and fetch the solution dump
for eachSol in responseSearchSol['result']['data']:
fetchSolutionDumpURL = config.get(environment, 'INTERNAL_KONG_IP') + config.get(environment, 'fetchSolutionDump') + eachSol['_id']
headersSolutionDumpURL = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + config.get(environment, 'Authorization'),
'X-authenticated-user-token': accessToken,
'X-Channel-id': config.get(environment, 'X-Channel-id'),
'internal-access-token': config.get(environment, 'internal-access-token')
}
responseSolDump = requests.request("POST", fetchSolutionDumpURL, headers=headersSolutionDumpURL)
if responseSolDump.status_code == 200:
responseSolDump = responseSolDump.json()
# save details of observation
listOfFoundSolutionIds[eachSol['_id']] = {"externalId": responseSolDump['result']['externalId'],
"isReusable": str(responseSolDump['result']['isReusable']),
"programId": responseSolDump['result']['programId']}
# create API logs
createAPILog(parentFolder, ["List of solutions found : " + str(listOfFoundSolutionIds)])
return listOfFoundSolutionIds
# program creation function
def programCreation(accessToken, parentFolder, externalId, pName, pDescription, keywords, entities, roles, orgIds,creatorKeyCloakId, creatorName,entitiesPGM,mainRole,rolesPGM):
messageArr = []
messageArr.append("++++++++++++ Program Creation ++++++++++++")
# program creation url
programCreationurl = config.get(environment, 'INTERNAL_KONG_IP') + config.get(environment, 'programCreationurl')
messageArr.append("Program Creation URL : " + programCreationurl)
# program creation payload
payload = json.dumps({
"externalId": externalId,
"name": pName,
"description": pDescription,
"resourceType": [
"program"
],
"language": [
"English"
],
"keywords": keywords,
"concepts": [],
"createdFor": orgIds,
"rootOrganisations": orgIds,
"imageCompression": {
"quality": 10
},
"creator": creatorName,
"owner": creatorKeyCloakId,
"author": creatorKeyCloakId,
"scope": {
"entityType": scopeEntityType,
"entities": entities,
"roles": roles
}})
messageArr.append("Body : " + str(payload))
headers = {'X-authenticated-user-token': accessToken,
'internal-access-token': config.get(environment, 'internal-access-token'),
'Content-Type': 'application/json',
'Authorization':config.get(environment, 'Authorization')}
# program creation
responsePgmCreate = requests.request("POST", programCreationurl, headers=headers, data=(payload))
messageArr.append("Program Creation Status Code : " + str(responsePgmCreate.status_code))
messageArr.append("Program Creation Response : " + str(responsePgmCreate.text))
messageArr.append("Program body : " + str(payload))
# save logs
createAPILog(parentFolder, messageArr)
# check status
fileheader = [pName, ('Program Sheet Validation'), ('Passed')]
createAPILog(parentFolder, messageArr)
apicheckslog(parentFolder, fileheader)
if responsePgmCreate.status_code == 200:
responsePgmCreateResp = responsePgmCreate.json()
else:
# terminate execution
terminatingMessage("Program creation API failed. Please check logs.")
# this function is used to create the sheet of PDPM for API requerment
def programmappingpdpmsheetcreation(MainFilePath,accessToken, program_file,programexternalId,parentFolder):
pdpmsheet = MainFilePath+ "/pdpmmapping/"
if not os.path.exists(pdpmsheet):
os.mkdir(pdpmsheet)
wbproject = xlrd.open_workbook(program_file, on_demand=True)
projectSheetNames = wbproject.sheet_names()
mappingsheet = wbproject.sheet_by_name('Program Details')
keysProject = [mappingsheet.cell(1, col_index_env).value for col_index_env in
range(mappingsheet.ncols)]
pdpmcolo1 = ["user","role","entity","entityOperation","keycloak-userId","acl_school","acl_cluster","programOperation",
"platform_role","programs","_arrayFields"]
with open(pdpmsheet + 'mapping.csv', 'w',encoding='utf-8') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=',',lineterminator='\n')
writer.writerows([pdpmcolo1])
wbPgm = xlrd.open_workbook(program_file, on_demand=True)
global programNameInp
sheetNames = wbPgm.sheet_names()
for sheetEnv in sheetNames:
if sheetEnv == "Instructions":
pass
elif sheetEnv.strip().lower() == 'program details':
print("--->Checking Program details sheet...")
detailsEnvSheet = wbPgm.sheet_by_name(sheetEnv)
keysEnv = [detailsEnvSheet.cell(1, col_index_env).value for col_index_env in
range(detailsEnvSheet.ncols)]
for row_index_env in range(2, detailsEnvSheet.nrows):
dictDetailsEnv = {keysEnv[col_index_env]: detailsEnvSheet.cell(row_index_env, col_index_env).value
for
col_index_env in range(detailsEnvSheet.ncols)}
programNameInp = dictDetailsEnv['Title of the Program'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Title of the Program'] else terminatingMessage("\"Title of the Program\" must not be Empty in \"Program details\" sheet")
extIdPGM = dictDetailsEnv['Program ID'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Program ID'] else terminatingMessage("\"Program ID\" must not be Empty in \"Program details\" sheet")
programdesigner = dictDetailsEnv['Diksha username/user id/email id/phone no. of Program Designer'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Program ID'] else terminatingMessage("\"Diksha username/user id/email id/phone no. of Program Designer\" must not be Empty in \"Program details\" sheet")
userDetails = fetchUserDetails(environment, accessToken, programdesigner)
creatorKeyCloakId = userDetails[0]
creatorName = userDetails[1]
if "PROGRAM_DESIGNER" in userDetails[3]:
creatorKeyCloakId = userDetails[0]
creatorName = userDetails[1]
else :
terminatingMessage("user does't have program designer role")
pdpmcolo1 = [creatorName, " ", " ", " ", creatorKeyCloakId, " ", " ","ADD","PROGRAM_DESIGNER", extIdPGM, "programs"]
with open(pdpmsheet + 'mapping.csv', 'a',encoding='utf-8') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=',',lineterminator='\n')
writer.writerows([pdpmcolo1])
fileheader = [creatorName,"program designer mapped successfully","Passed"]
apicheckslog(parentFolder,fileheader)
elif sheetEnv.strip().lower() == 'program manager details':
print("--->Program Manager Details...")
detailsEnvSheet = wbPgm.sheet_by_name(sheetEnv)
keysEnv = [detailsEnvSheet.cell(1, col_index_env).value for col_index_env in
range(detailsEnvSheet.ncols)]
for row_index_env in range(2, detailsEnvSheet.nrows):
dictDetailsEnv = {keysEnv[col_index_env]: detailsEnvSheet.cell(row_index_env, col_index_env).value
for
col_index_env in range(detailsEnvSheet.ncols)}
if str(dictDetailsEnv['Is a SSO user?']).strip() == "YES":
programmanagername2 = dictDetailsEnv['Diksha user id ( profile ID)'] if dictDetailsEnv['Diksha user id ( profile ID)'] else terminatingMessage("\"Diksha user id ( profile ID)\" must not be Empty in \"Program details\" sheet")
else:
try :
programmanagername2 = dictDetailsEnv['Login ID on DIKSHA'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Login ID on DIKSHA'] else terminatingMessage("\"Login ID on DIKSHA\" must not be Empty in \"Program details\" sheet")
userDetails = fetchUserDetails(environment, accessToken, programmanagername2)
except :
programmanagername2 = dictDetailsEnv['Diksha user id ( profile ID)'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Diksha user id ( profile ID)'] else terminatingMessage("\"Diksha user id ( profile ID)\" must not be Empty in \"Program details\" sheet")
userDetails = fetchUserDetails(environment, accessToken, programmanagername2)
userDetails = fetchUserDetails(environment, accessToken, programmanagername2)
creatorKeyCloakId = userDetails[0]
creatorName = userDetails[1]
if "PROGRAM_MANAGER" in userDetails[3]:
creatorKeyCloakId = userDetails[0]
creatorName = userDetails[1]
else:
terminatingMessage("user does't have program manager role")
pdpmcolo1 = [creatorName, " ", " ", " ", creatorKeyCloakId, " ", " ","ADD","PROGRAM_MANAGER", extIdPGM, "programs"]
with open(pdpmsheet + 'mapping.csv', 'a',encoding='utf-8') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=',',lineterminator='\n')
writer.writerows([pdpmcolo1])
messageArr.append("Response : " + str(pdpmcolo1))
createAPILog(parentFolder, messageArr)
fileheader = [creatorName,"program manager mapped succesfully","Passed"]
apicheckslog(parentFolder,fileheader)
# this function is used for call the api and map the pdpm roles which we created
def Programmappingapicall(MainFilePath,accessToken, program_file,parentFolder):
urlpdpmapi = config.get(environment, 'INTERNAL_KONG_IP') + config.get(environment, 'Pdpmurl')
headerpdpmApi = {
'Authorization': config.get(environment, 'Authorization'),
'X-authenticated-user-token': accessToken,
'X-Channel-id': config.get(environment, 'X-Channel-id'),
'internal-access-token': config.get(environment, 'internal-access-token')
}
payload = {}
filesProject = {
'userRoles': open(MainFilePath + '/pdpmmapping/mapping.csv', 'rb')
}
responseProgrammappingApi = requests.post(url=urlpdpmapi, headers=headerpdpmApi,
data=payload,
files=filesProject)
messageArr = ["program mapping sheet.",
"File path : " + MainFilePath + '/pdpmmapping/mapping.csv']
messageArr.append("Upload status code : " + str(responseProgrammappingApi.status_code))
createAPILog(parentFolder, messageArr)
if responseProgrammappingApi.status_code == 200:
print('--->program manager and designer mapping is Success')
with open(MainFilePath + '/pdpmmapping/mappinginternal.csv', 'w+',encoding='utf-8') as projectRes:
projectRes.write(responseProgrammappingApi.text)
messageArr.append("Response : " + str(responseProgrammappingApi.text))
createAPILog(parentFolder, messageArr)
else:
messageArr.append("Response : " + str(responseProgrammappingApi.text))
createAPILog(parentFolder, messageArr)
fileheader = ["PDPM mapping","PDPM mapping is failed","Failed","check PDPM sheet"]
apicheckslog(parentFolder,fileheader)
sys.exit()
# This function checks for the sequince
def check_sequence(arr):
for i in range(1, len(arr)):
if arr[i] != arr[i - 1] + 1:
return False
return True
# Open and validate program sheet
def programsFileCheck(filePathAddPgm, accessToken, parentFolder, MainFilePath):
program_file = filePathAddPgm
# open excel file
wbPgm = xlrd.open_workbook(filePathAddPgm, on_demand=True)
global programNameInp
sheetNames = wbPgm.sheet_names()
# list of sheets in the program sheet
pgmSheets = ["Instructions", "Program Details", "Resource Details","Program Manager Details"]
# checking the sheets in the program sheet
if (len(sheetNames) == len(pgmSheets)) and ((set(sheetNames) == set(pgmSheets))):
print("--->Program Template detected.<---")
# iterate through the sheets
for sheetEnv in sheetNames:
if sheetEnv == "Instructions":
# skip Instructions sheet
pass
elif sheetEnv.strip().lower() == 'program details':
print("--->Checking Program details sheet...")
detailsEnvSheet = wbPgm.sheet_by_name(sheetEnv)
keysEnv = [detailsEnvSheet.cell(1, col_index_env).value for col_index_env in
range(detailsEnvSheet.ncols)]
for row_index_env in range(2, detailsEnvSheet.nrows):
dictDetailsEnv = {keysEnv[col_index_env]: detailsEnvSheet.cell(row_index_env, col_index_env).value
for
col_index_env in range(detailsEnvSheet.ncols)}
programNameInp = dictDetailsEnv['Title of the Program'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Title of the Program'] else terminatingMessage("\"Title of the Program\" must not be Empty in \"Program details\" sheet")
extIdPGM = dictDetailsEnv['Program ID'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Program ID'] else terminatingMessage("\"Program ID\" must not be Empty in \"Program details\" sheet")
returnvalues = []
global entitiesPGM
entitiesPGM = dictDetailsEnv['Targeted state at program level'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Targeted state at program level'] else terminatingMessage("\"Targeted state at program level\" must not be Empty in \"Program details\" sheet")
districtentitiesPGM = dictDetailsEnv['Targeted district at program level'].encode('utf-8').decode('utf-8')
global startDateOfProgram, endDateOfProgram
startDateOfProgram = dictDetailsEnv['Start date of program']
endDateOfProgram = dictDetailsEnv['End date of program']
global scopeEntityType
scopeEntityType = "state"
if districtentitiesPGM:
entitiesPGM = districtentitiesPGM
EntityType = "district"
else:
entitiesPGM = entitiesPGM
EntityType = "state"
scopeEntityType = EntityType
global entitiesPGMID
entitiesPGMID = fetchEntityId(parentFolder, accessToken,
entitiesPGM.lstrip().rstrip().split(","), scopeEntityType)
global orgIds
if not getProgramInfo(accessToken, parentFolder, programNameInp.encode('utf-8').decode('utf-8')):
extIdPGM = dictDetailsEnv['Program ID'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Program ID'] else terminatingMessage("\"Program ID\" must not be Empty in \"Program details\" sheet")
if str(dictDetailsEnv['Program ID']).strip() == "Do not fill this field":
terminatingMessage("change the program id")
descriptionPGM = dictDetailsEnv['Description of the Program'].encode('utf-8').decode('utf-8') if dictDetailsEnv[
'Description of the Program'] else terminatingMessage(
"\"Description of the Program\" must not be Empty in \"Program details\" sheet")
keywordsPGM = dictDetailsEnv['Keywords'].encode('utf-8').decode('utf-8')
entitiesPGM = dictDetailsEnv['Targeted state at program level'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Targeted state at program level'] else terminatingMessage("\"Targeted state at program level\" must not be Empty in \"Program details\" sheet")
districtentitiesPGM = dictDetailsEnv['Targeted district at program level'].encode('utf-8').decode('utf-8')
# selecting entity type based on the users input
if districtentitiesPGM:
entitiesPGM = districtentitiesPGM
EntityType = "district"
else:
entitiesPGM = entitiesPGM
EntityType = "state"
scopeEntityType = EntityType
mainRole = dictDetailsEnv['Targeted role at program level'] if dictDetailsEnv['Targeted role at program level'] else terminatingMessage("\"Targeted role at program level\" must not be Empty in \"Program details\" sheet")
global rolesPGM
rolesPGM = dictDetailsEnv['Targeted subrole at program level'] if dictDetailsEnv['Targeted subrole at program level'] else terminatingMessage("\"Targeted subrole at program level\" must not be Empty in \"Program details\" sheet")
if "teacher" in mainRole.strip().lower():
rolesPGM = str(rolesPGM).strip() + ",TEACHER"
userDetails = fetchUserDetails(environment, accessToken, dictDetailsEnv['Diksha username/user id/email id/phone no. of Program Designer'])
OrgName=userDetails[4]
orgIds=fetchOrgId(environment, accessToken, parentFolder, OrgName)
creatorKeyCloakId = userDetails[0]
creatorName = userDetails[2]
messageArr = []
scopeEntityType = EntityType
# fetch entity details
entitiesPGMID = fetchEntityId(parentFolder, accessToken,entitiesPGM.lstrip().rstrip().split(","), scopeEntityType)
# sys.exit()
# fetch sub-role details
rolesPGMID = fetchScopeRole(parentFolder, accessToken, rolesPGM.lstrip().rstrip().split(","))
# sys.exit()
# call function to create program
programCreation(accessToken, parentFolder, extIdPGM, programNameInp, descriptionPGM,keywordsPGM.lstrip().rstrip().split(","), entitiesPGMID, rolesPGMID, orgIds,creatorKeyCloakId, creatorName,entitiesPGM,mainRole,rolesPGM)
# sys.exit()
programmappingpdpmsheetcreation(MainFilePath, accessToken, program_file, extIdPGM,parentFolder)
# map PM / PD to the program
Programmappingapicall(MainFilePath, accessToken, program_file,parentFolder)
# check if program is created or not
if getProgramInfo(accessToken, parentFolder, programNameInp):
print("Program Created SuccessFully.")
else :
terminatingMessage("Program creation failed! Please check logs.")
elif sheetEnv.strip().lower() == 'resource details':
# checking Resource details sheet
print("--->Checking Resource Details sheet...")
detailsEnvSheet = wbPgm.sheet_by_name(sheetEnv)
keysEnv = [detailsEnvSheet.cell(1, col_index_env).value for col_index_env in
range(detailsEnvSheet.ncols)]
# iterate through each row in Resource Details sheet and validate
for row_index_env in range(2, detailsEnvSheet.nrows):
dictDetailsEnv = {keysEnv[col_index_env]: detailsEnvSheet.cell(row_index_env, col_index_env).value
for
col_index_env in range(detailsEnvSheet.ncols)}
resourceNamePGM = dictDetailsEnv['Name of resources in program'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Name of resources in program'] else terminatingMessage("\"Name of resources in program\" must not be Empty in \"Resource Details\" sheet")
resourceTypePGM = dictDetailsEnv['Type of resources'].encode('utf-8').decode('utf-8') if dictDetailsEnv['Type of resources'] else terminatingMessage("\"Type of resources\" must not be Empty in \"Resource Details\" sheet")
resourceLinkOrExtPGM = dictDetailsEnv['Resource Link']
resourceStatusOrExtPGM = dictDetailsEnv['Resource Status'] if dictDetailsEnv['Resource Status'] else terminatingMessage("\"Resource Status\" must not be Empty in \"Resource Details\" sheet")
# setting start and end dates globally.
global startDateOfResource, endDateOfResource
startDateOfResource = dictDetailsEnv['Start date of resource']
endDateOfResource = dictDetailsEnv['End date of resource']
# checking resource types and calling relevant functions
if resourceTypePGM.lstrip().rstrip().lower() == "course":
coursemapping = courseMapToProgram(accessToken, resourceLinkOrExtPGM, parentFolder)
if startDateOfResource:
startDateArr = str(startDateOfResource).split("-")
bodySolutionUpdate = {"startDate": startDateArr[2] + "-" + startDateArr[1] + "-" + startDateArr[0] + "T00:00:00.000Z"}
solutionUpdate(parentFolder, accessToken, coursemapping, bodySolutionUpdate)
if endDateOfResource:
endDateArr = str(endDateOfResource).split("-")
bodySolutionUpdate = {
"endDate": endDateArr[2] + "-" + endDateArr[1] + "-" + endDateArr[0] + "T23:59:59.000Z"}
solutionUpdate(parentFolder, accessToken, coursemapping, bodySolutionUpdate)
# Function create File structure for Program
def createFileStructForProgram(programFile):
if not os.path.isdir('programFiles'):
os.mkdir('programFiles')
if "\\" in str(programFile):
fileNameSplit = str(programFile).split('\\')[-1:]
elif "/" in str(programFile):
fileNameSplit = str(programFile).split('/')[-1:]
else:
fileNameSplit = str(programFile)
if ".xlsx" in fileNameSplit:
ts = str(time.time()).replace(".", "_")
folderName = fileNameSplit.replace(".xlsx", "-" + str(ts))
os.mkdir('programFiles/' + str(folderName))
path = os.path.join('programFiles', str(folderName))
else:
terminatingMessage("File Error.")
returnPathStr = os.path.join('programFiles', str(folderName))
return returnPathStr
# Function create File structure for Solutions
def createFileStruct(MainFilePath, addObservationSolution):
if not os.path.isdir(MainFilePath + '/SolutionFiles'):
os.mkdir(MainFilePath + '/SolutionFiles')
if "\\" in str(addObservationSolution):
fileNameSplit = str(addObservationSolution).split('\\')[-1:]
elif "/" in str(addObservationSolution):
fileNameSplit = str(addObservationSolution).split('/')[-1:]
else:
fileNameSplit = str(addObservationSolution)
if ".xlsx" in str(fileNameSplit[0]):
ts = str(time.time()).replace(".", "_")
folderName = fileNameSplit[0].replace(".xlsx", "-" + str(ts))
os.mkdir(MainFilePath + '/SolutionFiles/' + str(folderName))
path = os.path.join(MainFilePath + '/SolutionFiles', str(folderName))
path = os.path.join(path, str('apiHitLogs'))
os.mkdir(path)
else:
terminatingMessage("File Error.offff")
returnPathStr = os.path.join(MainFilePath + '/SolutionFiles', str(folderName))
if not os.path.isdir(returnPathStr + "/user_input_file"):
os.mkdir(returnPathStr + "/user_input_file")
shutil.copy(addObservationSolution, os.path.join(returnPathStr + "user_input_file"))
shutil.copy(programFile, os.path.join(returnPathStr + "user_input_file"))
return returnPathStr
# function to accept only csv file as input in command line argument
def valid_file(param):
base, ext = os.path.splitext(param)
if ext.lower() not in ('.xlsx'):
raise argparse.ArgumentTypeError('File must have a csv extension')
return param
# function to check environment
def envCheck():
try:
config.get(environment, 'keyclockAPIUrl')
return True
except Exception as e:
print(e)
return False
# Generate access token for the APIs.
def generateAccessToken(solutionName_for_folder_path):
# production search user api - start
headerKeyClockUser = {'Content-Type': config.get(environment, 'keyclockAPIContent-Type')}
# responseKeyClockUser = requests.post(url=config.get(environment, 'host') + config.get(environment, 'keyclockAPIUrl'), headers=headerKeyClockUser,
# data=str(config.get(environment, 'keyclockAPIBody')))
responseKeyClockUser = requests.request("POST", config.get(environment, 'host') + config.get(environment, 'keyclockAPIUrl'), headers=headerKeyClockUser, data= str (config.get(environment, 'keyclockAPIBody')))
messageArr = []
messageArr.append("URL : " + str(config.get(environment, 'keyclockAPIUrl')))
messageArr.append("Body : " + str(config.get(environment, 'keyclockAPIBody')))
messageArr.append("Status Code : " + str(responseKeyClockUser.status_code))
if responseKeyClockUser.status_code == 200:
responseKeyClockUser = responseKeyClockUser.json()
accessTokenUser = responseKeyClockUser['access_token']
messageArr.append("Acccess Token : " + str(accessTokenUser))
createAPILog(solutionName_for_folder_path, messageArr)
fileheader = ["Access Token","Access Token succesfully genarated","Passed"]
apicheckslog(solutionName_for_folder_path,fileheader)
print("--->Access Token Generated!")
return accessTokenUser
print("Error in generating Access token")
print("Status code : " + str(responseKeyClockUser.status_code))
createAPILog(solutionName_for_folder_path, messageArr)
fileheader = ["Access Token", "Error in generating Access token", "Failed",responseKeyClockUser.status_code+"Check access token api"]
apicheckslog(solutionName_for_folder_path, fileheader)
fileheader = ["Access Token", "Error in generating Access token", "Failed","Check Headers of api"]
apicheckslog(solutionName_for_folder_path, fileheader)
terminatingMessage("Please check API logs.")
# Function to search for programs
def getProgramInfo(accessTokenUser, solutionName_for_folder_path, programNameInp):
global programID, programExternalId, programDescription, isProgramnamePresent, programName
programName = programNameInp
programUrl = config.get(environment, 'INTERNAL_KONG_IP') + config.get(environment, 'fetchProgramInfoApiUrl')
print(programUrl)
payload = json.dumps({
"query": {
"name": programNameInp.lstrip().rstrip(),
"isAPrivateProgram": False,
"status": "active"
},
"mongoIdKeys": []
})
headersProgramSearch = {'Authorization': config.get(environment, 'Authorization'),
'Content-Type': 'application/json', 'X-authenticated-user-token': accessTokenUser,
'internal-access-token': config.get(environment, 'internal-access-token')}
responseProgramSearch = requests.post(url=programUrl, headers=headersProgramSearch,data=payload)
print(responseProgramSearch.text)
messageArr = []
messageArr.append("Program Search API")
messageArr.append("URL : " + programUrl)
messageArr.append("Status Code : " + str(responseProgramSearch.status_code))
messageArr.append("Response : " + str(responseProgramSearch.text))
createAPILog(solutionName_for_folder_path, messageArr)
messageArr = []
if responseProgramSearch.status_code == 200:
print('--->Program fetch API Success')
messageArr.append("--->Program fetch API Success")
responseProgramSearch = responseProgramSearch.json()
countOfPrograms = len(responseProgramSearch['result'])
messageArr.append("--->Program Count : " + str(countOfPrograms))
if countOfPrograms == 0:
messageArr.append("No program found with the name : " + str(programName.lstrip().rstrip()))
messageArr.append("******************** Preparing for program Upload **********************")
print("No program found with the name : " + str(programName.lstrip().rstrip()))
print("******************** Preparing for program Upload **********************")
createAPILog(solutionName_for_folder_path, messageArr)
fileheader = ["Program name fetch","Successfully fetched program name","Passed"]
apicheckslog(solutionName_for_folder_path,fileheader)
return False
else:
getProgramDetails = []
for eachPgm in responseProgramSearch['result']:
if eachPgm['isAPrivateProgram'] == False:
programID = eachPgm['_id']
programExternalId = eachPgm['externalId']
programDescription = eachPgm['description']
isAPrivateProgram = eachPgm['isAPrivateProgram']
getProgramDetails.append([programID, programExternalId, programDescription, isAPrivateProgram])
if len(getProgramDetails) == 0:
print("Total " + str(len(getProgramDetails)) + " backend programs found with the name : " + programName.lstrip().rstrip())
messageArr.append("Total " + str(len(getProgramDetails)) + " backend programs found with the name : " + programName.lstrip().rstrip())
createAPILog(solutionName_for_folder_path, messageArr)
fileheader = ["program find api is running","found"+str(len(
getProgramDetails))+"programs in backend","Failed","found"+str(len(
getProgramDetails))+"programs ,check logs"]
apicheckslog(solutionName_for_folder_path,fileheader)
terminatingMessage("Aborting...")
elif len(getProgramDetails) > 1:
print("Total " + str(len(getProgramDetails)) + " backend programs found with the name : " + programName.lstrip().rstrip())
messageArr.append("Total " + str(len(getProgramDetails)) + " backend programs found with the name : " + programName.lstrip().rstrip())
createAPILog(solutionName_for_folder_path, messageArr)
terminatingMessage("Aborting...")
else:
programID = getProgramDetails[0][0]
programExternalId = getProgramDetails[0][1]
programDescription = getProgramDetails[0][2]
isAPrivateProgram = getProgramDetails[0][3]
isProgramnamePresent = True
messageArr.append("programID : " + str(programID))
messageArr.append("programExternalId : " + str(programExternalId))
messageArr.append("programDescription : " + str(programDescription))
messageArr.append("isAPrivateProgram : " + str(isAPrivateProgram))
createAPILog(solutionName_for_folder_path, messageArr)
else:
print("Program search API failed...")
messageArr.append("Program search API failed...")
createAPILog(solutionName_for_folder_path, messageArr)
terminatingMessage("Response Code : " + str(responseProgramSearch.status_code))
return True
# function to create API hit logs
def createAPILog(solutionName_for_folder_path, messageArr):
file_exists = solutionName_for_folder_path + '/apiHitLogs/apiLogs.txt'
# check if the file existis or not and create a file
if not path.exists(file_exists):
API_log = open(file_exists, "w", encoding='utf-8')
API_log.write("===============================================================================")
API_log.write("\n")
API_log.write("ENVIRONMENT : " + str(environment))
API_log.write("\n")
API_log.write("===============================================================================")
API_log.write("\n")
API_log.close()
API_log = open(file_exists, "a", encoding='utf-8')
API_log.write("\n")
for msg in messageArr:
API_log.write(msg)
API_log.write("\n")
API_log.close()
def apicheckslog(solutionName_for_folder_path, messageArr):
file_exists = solutionName_for_folder_path + '/apiHitLogs/apiLogs.csv'
# global fileheader
fileheader = ["Resource","Process","Status","Remark"]
if not path.exists(file_exists):
with open(file_exists, 'w', newline='',encoding='utf-8') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=',',lineterminator='\n')
writer.writerows([fileheader])
with open(file_exists, 'a', newline='',encoding='utf-8') as file:
writer = csv.writer(file, quoting=csv.QUOTE_NONNUMERIC, delimiter=',',lineterminator='\n')
writer.writerows([messageArr])
def checkEmailValidation(email):
if (re.search(regex, email)):
return True
else:
return False
# Fetch user details
def fetchUserDetails(environment, accessToken, dikshaId):
global OrgName
url = config.get(environment, 'host') + config.get(environment, 'userInfoApiUrl')
messageArr = ["User search API called."]
headers = {'Content-Type': 'application/json',
'Authorization': config.get(environment, 'AuthorizationForHost'),
'x-authenticated-user-token': accessToken}
isEmail = checkEmailValidation(dikshaId.lstrip().rstrip())
if isEmail:
body = "{\n \"request\": {\n \"filters\": {\n \t\"email\": \"" + dikshaId.lstrip().rstrip() + "\"\n },\n \"fields\" :[],\n \"limit\": 1000,\n \"sort_by\": {\"createdDate\": \"desc\"}\n }\n}"
else:
body = "{\n \"request\": {\n \"filters\": {\n \t\"userName\": \"" + dikshaId.lstrip().rstrip() + "\"\n },\n \"fields\" :[],\n \"limit\": 1000,\n \"sort_by\": {\"createdDate\": \"desc\"}\n }\n}"
responseUserSearch = requests.request("POST", url, headers=headers, data=body)
print(dikshaId)
if responseUserSearch.status_code == 200:
responseUserSearch = responseUserSearch.json()
if responseUserSearch['result']['response']['content']:
userKeycloak = responseUserSearch['result']['response']['content'][0]['userId']
userName = responseUserSearch['result']['response']['content'][0]['userName']
firstName = responseUserSearch['result']['response']['content'][0]['firstName']
rootOrgId = responseUserSearch['result']['response']['content'][0]['rootOrgId']
for index in responseUserSearch['result']['response']['content'][0]['organisations']:
if rootOrgId == index['organisationId']:
roledetails = index['roles']
rootOrgName = index['orgName']
OrgName.append(index['orgName'])
print(roledetails)
else:
terminatingMessage("-->Given username/email is not present in DIKSHA platform<--.")
else:
print(responseUserSearch.text)
terminatingMessage("User fetch API failed. Check logs.")
return [userKeycloak, userName, firstName,roledetails,rootOrgName,rootOrgId]
# fetch org Ids
def fetchOrgId(environment, accessToken, parentFolder, OrgName):
url = config.get(environment, 'host') + config.get(environment, 'fetchOrgDetails')
messageArr = ["Org search API called."]
headers = {'Content-Type': 'application/json',
'Authorization': config.get(environment, 'Authorization'),
'x-authenticated-user-token': accessToken}
orgIds = []
organisations = str(OrgName).split(",")
for org in organisations:
orgBody = {"id": "",
"ts": "",
"params": {
"msgid": "",
"resmsgid": "",
"status": "success"
},
"request": {
"filters": {
"orgName": str(org).strip()
}
}}
responseOrgSearch = requests.request("POST", url, headers=headers, data=json.dumps(orgBody))
print(responseOrgSearch)
if responseOrgSearch.status_code == 200:
responseOrgSearch = responseOrgSearch.json()
if responseOrgSearch['result']['response']['content']:
orgId = responseOrgSearch['result']['response']['content'][0]['id']
orgIds.append(orgId)
messageArr.append("orgApi : " + str(url))
messageArr.append("orgBody : " + str(orgBody))
messageArr.append("orgAPI response: " + str(responseOrgSearch))
messageArr.append("orgIds : " + str(orgIds))
else:
messageArr.append("orgApi : " + str(url))
messageArr.append("orgBody : " + str(orgBody))
messageArr.append("orgAPI response: " + str(responseOrgSearch))
createAPILog(parentFolder, messageArr)
terminatingMessage("Given Organisation/ State tenant is not present in DIKSHA platform.")
else:
messageArr.append("orgApi : " + str(url))
messageArr.append("headers : " + str(headers))
messageArr.append("orgBody : " + str(orgBody))
createAPILog(parentFolder, messageArr)
print(responseOrgSearch.text)
terminatingMessage("Organisation/ State tenant fetch API failed. Check logs.")
return orgIds
# Print message and terminate the program
def terminatingMessage(msg):
print(msg)
sys.exit()
def fetchEntityId(solutionName_for_folder_path, accessToken, entitiesNameList, scopeEntityType):
urlFetchEntityListApi = config.get(environment, 'host')+config.get(environment, 'searchForLocation')
headerFetchEntityListApi = {
'Content-Type': config.get(environment, 'Content-Type'),
'Authorization': config.get(environment, 'AuthorizationForHost'),
'X-authenticated-user-token': accessToken,
'X-Channel-id': config.get(environment, 'X-Channel-id'),
}
payload = {
"request": {
"filters": {
"type": scopeEntityType
},
"limit": 1000
}
}
responseFetchEntityListApi = requests.post(url=urlFetchEntityListApi, headers=headerFetchEntityListApi,data=json.dumps(payload))
messageArr = ["Entities List Fetch API executed.", "URL : " + str(urlFetchEntityListApi),
"Status : " + str(responseFetchEntityListApi.status_code)]
createAPILog(solutionName_for_folder_path, messageArr)
if responseFetchEntityListApi.status_code == 200:
responseFetchEntityListApi = responseFetchEntityListApi.json()
entitiesLookup = dict()
entityToUpload = list()
for listEntities in responseFetchEntityListApi['result']['response']:
entitiesLookup[listEntities['name'].lower().lstrip().rstrip()] = listEntities['id'].lstrip().rstrip()
entitiesFlag = False
for eachUserEntity in entitiesNameList:
try:
entityId = entitiesLookup[eachUserEntity.lower().lstrip().rstrip()]
entitiesFlag = True
except:
entitiesFlag = False
if entitiesFlag:
entityToUpload.append(entityId)
else:
print("Entity Not found in DB...")
print("Entity name : " + str(eachUserEntity))
messageArr = ["Entity Not found : ", "URL : " + str(eachUserEntity)]
createAPILog(solutionName_for_folder_path, messageArr)
messageArr = ["Entities to upload : " + str(entityToUpload)]
createAPILog(solutionName_for_folder_path, messageArr)
if len(entityToUpload) == 0:
terminatingMessage("--->Scope Entity error.")
return entityToUpload
else:
messageArr = ["Error in Location search",str(responseFetchEntityListApi.status_code)]
createAPILog(solutionName_for_folder_path, messageArr)
terminatingMessage("---> Error in location search.")
def fetchScopeRole(solutionName_for_folder_path, accessToken, roleNameList):
urlFetchRolesListApi = config.get(environment, 'INTERNAL_KONG_IP') + config.get(environment, 'listOfRolesApi')
headerFetchRolesListApi = {
'Content-Type': config.get(environment, 'Content-Type'),
'Authorization': config.get(environment, 'Authorization'),
'X-authenticated-user-token': accessToken,
'X-Channel-id': config.get(environment, 'X-Channel-id'),
}
responseFetchRolesListApi = requests.post(url=urlFetchRolesListApi, headers=headerFetchRolesListApi)
rolesLookup = dict()
rolesReturn = list()
messageArr = ["Roles list fetch API called.", "URL : " + str(urlFetchRolesListApi),
"Status Code : " + str(responseFetchRolesListApi.status_code)]
createAPILog(solutionName_for_folder_path, messageArr)
if responseFetchRolesListApi.status_code == 200:
responseFetchRolesListApi = responseFetchRolesListApi.json()
for listRoles in responseFetchRolesListApi['result']:
eachDict = dict()
eachDict['id'] = listRoles['_id'].lstrip().rstrip()
eachDict['code'] = listRoles['code'].lstrip().rstrip()
rolesLookup[listRoles['code']] = eachDict['id']
rolesReturn.append(listRoles['code'].lstrip().rstrip())
else:
terminatingMessage("---> error in subroles API.")
userRolesFromInp = roleNameList
listOfFoundRoles = list()
if len(userRolesFromInp) == 0:
terminatingMessage("Roles fields must not be empty.")
for ur in userRolesFromInp:
rolesFlag = True
try:
roleDetails = rolesLookup[ur.lstrip().rstrip()]
rolesFlag = True
except:
rolesFlag = False
if rolesFlag:
print("Role Found... : " + ur)
listOfFoundRoles.append(ur)
else:
if "all" in userRolesFromInp:
listOfFoundRoles = ["all"]
else: