-
Notifications
You must be signed in to change notification settings - Fork 0
/
mertide.py
executable file
·1757 lines (1492 loc) · 62.1 KB
/
mertide.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 python3
# USAGE: ./mertide.py -i merform.csv -d /path/to/disagg/files/ [-n] [-f formuid1234,formid2468] [-h]
# ./mertide.py -i merdirectory -d /path/to/disagg/files/ [-n] [-f formuid1234,formid2468] [-h]
# ./mertide.py --input=merform.csv --disaggs=/path/to/disagg/files/ [--noconnection] [--forms="formuid1234,formid2468"] [--help]
import os
import re
import csv
import sys
import copy
import json
import zlib
import base64
import getopt
import pprint
import random
import string
import urllib
import hashlib
import zipfile
import operator
import requests
import datetime
from collections import defaultdict
from xml.sax.saxutils import escape
# Output logging information to the screen and to logFile
# logFile is updated as the script runs, instead of only being complete at the end
def log(line, level = False):
if level == 'warn':
prefix = '*Warning: '
elif level == 'severe':
prefix = '**SEVERE: '
global severe
severe = True
else:
prefix = ''
print(prefix + line)
logFile.write(prefix + line + '\n')
logFile.flush()
os.fsync(logFile.fileno())
def getNumeratorDenominator(shortName):
numeratorDenominator=re.sub('^.* \((.*)\).*', r'\1', shortName)
numeratorDenominator=re.sub('([^,]*),.*', r'\1', numeratorDenominator)
if numeratorDenominator != 'D' and numeratorDenominator != 'N':
return 'Other'
return numeratorDenominator
def getDisagg(shortName):
if shortName.count(',') < 2:
return 'No Disagg'
else:
disagg=re.sub('^.* \((.*)\).*', r'\1', shortName)
disagg=re.sub('.*, (.*)', r'\1', disagg)
return disagg
# Remove files with funny names
def filenameChecker(filename):
bumFiles=['.DS_Store']
if filename in bumFiles:
return False
return True
# current fiscal year for fyoct
def curFyOct():
curQ=(int(datetime.datetime.now().strftime("%m"))+2)//3
curY=int(datetime.datetime.now().strftime("%Y"))
if curQ == 4:
curY = curY + 1
return str(curY)
# current year
def curYear():
return str(int(datetime.datetime.now().strftime("%Y")))
def curQuarter():
curQ = (int(datetime.datetime.now().strftime("%m"))+2) // 3
return str(curQ)
def curISOQuarter():
return "FY"+curYear()+"Q"+curQuarter()
# FIXME
def ISOQuarterToISOSAApr(ISOQuarter):
#2018Q4 -> 2018AprilS2
#2019Q1 -> 2018AprilS2
#2019Q2 -> 2019AprilS1
#2019Q3 -> 2019AprilS1
year = int(ISOQuarter[:4])
quarter = int(ISOQuarter[-1])
fyaprYear=0
fyaprSA=0
if quarter == 1:
fyoctYear = year-1
fyaprSA = 2
elif quarter == 2:
fyoctYear = year
fyaprSA = 1
elif quarter == 3:
fyoctYear = year
fyaprSA = 1
elif quarter == 4:
fyoctYear = year
fyaprSA = 2
return str(fyoctYear)+"AprilS"+str(fyaprSA)
def ISOQuarterToISOFYOctTARGET(ISOQuarter):
year = int(ISOQuarter[:4])
fyoctYear = year
return str(fyoctYear)+"Oct"
def ISOQuarterToISOFYOct(ISOQuarter):
year = int(ISOQuarter[:4])
quarter = int(ISOQuarter[-1])
fyoctYear = 0
if quarter < 4:
fyoctYear = year - 1
else:
fyoctYear = year
return str(fyoctYear)+"Oct"
def pepfarReportingQuarter(ISOQuarter,frequency):
quarter = int(ISOQuarter[-1])
if frequency == 'Quarterly':
return True
elif frequency == 'Semiannually' and (quarter == 1 or quarter == 3):
return True
elif frequency == 'Annually' and quarter == 3:
return True
return False
def ISOQuarterToFYOctQuarter(ISOQuarter):
year = int(ISOQuarter[:4])
quarter = int(ISOQuarter[-1])
fyoctYear=0
fyoctQuarter=0
if quarter == 1:
fyoctQuarter = 2
fyoctYear = year
elif quarter == 2:
fyoctQuarter = 3
fyoctYear = year
elif quarter == 3:
fyoctQuarter = 4
fyoctYear = year
elif quarter == 4:
fyoctQuarter = 1
fyoctYear = year+1
return str(fyoctYear)+"Q"+str(fyoctQuarter)
# Check to see if a string is a properly formatted DHIS2 uid
def isDhisUid(string):
if (len(string) != 11):
return False
if not bool(re.search('[A-Za-z]', string[:1])):
return False
if not bool(re.search('[A-Za-z0-9]{9}', string[1:11])):
return False
return True
# Find a data element, either using the dataElementCache or DHIS2
def getDataElement(uid, optionCombo=False):
if uid not in dataElementCache:
d = requests.get(api + 'dataElements.json', cookies=jsessionid,
params = {'paging': False, 'fields': 'name,shortName', 'filter': 'id:eq:' + uid})
try:
dataElementCache[uid] = d.json()['dataElements'][0]
except:
dataElementCache[uid] = {}
d = dataElementCache[uid]
if d:
d['id'] = uid
d['optionCombo'] = False
if optionCombo:
d['optionCombo'] = getCoc(optionCombo, uid)
else:
log('Data element ' + uid + ' is missing on ' + config['dhis']['baseurl'], 'warn')
return d
# Generate a random uid
def makeUid():
uid = random.choice(string.ascii_letters)
for i in range(0, 10):
uid += random.choice(string.ascii_letters+'0123456789')
return uid
# Return 5+input char ssid. This should be max 8 total, #TODO, limit returned result to 8 chars.
def makeSsid(htabType):
ssid = random.choice(string.ascii_letters)
for i in range(0, 4):
ssid += random.choice(string.ascii_letters+'0123456789')
return ssid + htabType
# Generate an SSID deterministically from a unique string, using sha
def makeSsidHash(uniqueName, htabType):
sha = hashlib.sha1((uniqueName).encode())
num = int(sha.hexdigest(), 16)
uid = ''
for i in range(0, 5):
mod = num % 26
num = int(num / 26)
uid += string.ascii_letters[mod]
uid += htabType
return uid
# Generate a UID deterministcally from a unique string, using sha
def makeUidHash(s):
if s=='':
return 'NotAUID'
hashBytes = bytearray(hashlib.sha256((s).encode()).digest())
uid = string.ascii_letters[hashBytes[0] % 52]
for i in range(1, 11):
uid += (string.ascii_letters+string.digits)[hashBytes[i] % 62]
return uid
# Turn string s into a name that's safe for metadata usage
def safeName(s):
s = s.replace('<', '_lt_') \
.replace('>', '_gt_') \
.replace('+', '_plus_')
s = re.sub('[\[\(\)\-\s\:,\\\|^&/]', '_', s)
s = re.sub('_+', '_', s)
s = re.sub('_$', '', s)
return s.lower()
# Same as safeName, but make it all uppercase as well
def codeName(s):
return safeName(s).upper()
# Within a vertical tab, find which horizontal tabs are present.
def findHtabs(vtab):
htabsPresent = set([]) # Set of htabs present in this list of rows
for indicator in vtab['indicators']:
for row in indicator['rows']:
if (row['de_dsd1']): htabsPresent.add("DSD")
if (row['de_ta1']): htabsPresent.add("TA")
if (row['de_cs1']): htabsPresent.add("CS")
if (row['de_na1']): htabsPresent.add("NA")
htabs = []
for htab in allHtabs:
if (htab['type'] in htabsPresent):
htabs.append(htab)
return htabs
# Within a row, find all data elements.
def findDataElementsFromRow(row):
dataElementsPresent = set([]) # Set of dataelements in the row
for de in ['de_dsd1', 'de_dsd2', 'de_dsd3', 'de_ta1', 'de_ta2', 'de_ta3', 'de_cs1', 'de_cs2', 'de_cs3', 'de_na1', 'de_na2', 'de_na3']:
if row[de]: dataElementsPresent.add(row[de])
return dataElementsPresent
# Find out if an indicator should be displayed in a given HTAB.
def htabInIndicator(htab, indicator):
for row in indicator['rows']:
if row['de_' + htab['type'].lower() + '1']:
return True
return False
# Add a dataElement to the data element list for this form
# and to all the dataElementGroups belonging to this form
def addDataElement(form, uid, groups, frequency, categoryCombo = False):
form['formDataElements'].add(uid)
for group in groups:
dataElementGroups[group].add(uid)
if categoryCombo:
catComboCache[uid] = categoryCombo
# Adds DEs used in forms to directory and label target/result.
if uid in masterDataElementList:
if form['name'].count('Targets') > 0:
formDataElementList[uid] = {'type': 'Target', 'name': masterDataElementList[uid]['name'], 'form': form['name'], 'categoryCombo': categoryCombo, 'frequency': frequency}
else:
formDataElementList[uid] = {'type': 'Result', 'name': masterDataElementList[uid]['name'], 'form': form['name'], 'categoryCombo': categoryCombo, 'frequency': frequency}
else:
log('Cannot find data element ' + uid + ' in DHIS2')
# Query the api to get all DE and put them in a master directory.
def getAllDataElements():
d = requests.get(api + 'dataElements.json', cookies=jsessionid,
params = {'paging': False, 'fields': 'name,shortName,id,categoryCombo[id]'})
for i in d.json()['dataElements']:
id = i['id']
masterDataElementList[id] = {'name' : i['name'], 'shortName': i['shortName'], 'id': i['id'], 'categoryComboID' : i['categoryCombo']['id']}
# Query the api to get all Category Option Combos and put them in a master directory
def getAllCategoryOptionCombos():
d = requests.get(api + 'categoryOptionCombos.json', cookies=jsessionid,
params = {'paging': False, 'fields': 'name,id,categoryCombo[name,id]'})
for i in d.json()['categoryOptionCombos']:
id = i['id']
masterCategoryOptionComboList[id] = {'name' : i['name'], 'id': i['id'], 'categoryComboName': i['categoryCombo']['name'], 'categoryComboID' : i['categoryCombo']['id']}
# Puts DE from forms into a list to be put in the data store.
def getDataElementCadence():
for key, value in formDataElementList.items():
if masterDataElementList[key]['shortName'].count('TARGET') == 0 and checkDataElementQuarter(formDataElementList[key]['frequency']):
a = {}
a['uid'] = masterDataElementList[key]['id']
a['shortName'] = masterDataElementList[key]['shortName']
dataElementCadence.append(a)
def checkDataElementQuarter(frequency):
quarter = int(favoritesISOQuarter[-1])
if frequency == 'Annually' and quarter == 3:
return True
elif frequency == 'Semiannually' and (quarter == 1 or quarter == 3):
return True
elif frequency == 'Quarterly' and (quarter >= 1 and quarter <= 4):
return True
else:
return False
def findCo(category, coc):
for option in category:
for co in coc['categoryOptions']:
if co['name'] == option:
return co['name']
return False
def getCocsFromOptions(options, uid):
optionCacheId = str(options) + '_' + uid
try:
if optionCacheId not in optionCache:
req = requests.get(api + 'dataElements/' + uid + '.json', cookies=jsessionid,
params = {'paging': False, 'fields': 'name,id,categoryCombo[name,id,categories[name,id,categoryOptions[name,id]],categoryOptionCombos[name,id,categoryOptions[name,id]]]'})
categoryCache = []
found = []
categories = req.json()['categoryCombo']['categories']
for i in range(len(categories)):
categoryCache.append({})
for co in categories[i]['categoryOptions']:
if co['name'] in options:
found.append(co['name'])
categoryCache[i] = {co['name']: True}
break
else:
categoryCache[i][co['name']] = True
for option in options:
if not(option in found):
raise ValueError('The option ' + option + ' was not found in the categories for data element ' + uid)
optionCache[optionCacheId] = []
cocs = req.json()['categoryCombo']['categoryOptionCombos']
for coc in cocs:
for category in categoryCache:
found = findCo(category, coc)
if not(found):
break
if found:
optionCache[optionCacheId].append(coc['id'])
cocCache[coc['id']] = coc['id']
if found in options:
cocCache2[coc['id']] = found
else:
cocCache2[coc['id']] = options[0]
except:
optionCache[optionCacheId] = []
return optionCache[optionCacheId]
# Get the category option combo that matches a given name and element
def getCoc(name, element):
try:
if (name + '_' + element) not in cocCache and name not in cocCache:
req = requests.get(api + 'dataElements/' + element + '.json', cookies=jsessionid,
params = {'paging': False, 'fields': 'id,name,categoryCombo[id,name,categoryOptionCombos[id,name]]',
'filter': 'categoryCombo.categoryOptionCombos.name:eq:' + name})
for coc in req.json()['categoryCombo']['categoryOptionCombos']:
cocCache2[coc['id']] = coc['name']
if coc['name'] == name:
cocCache[name + '_' + element] = coc['id']
if (name + '_' + element) not in cocCache:
cocCache[name + '_' + element] = False
except:
cocCache[name + '_' + element] = False
if name in cocCache:
return cocCache[name]
else:
return cocCache[name + '_' + element]
def getUids(term, suffix, alluids, uidCache):
if term == 'R':
return alluids
elif (term + '_' + suffix) in uidCache:
return uidCache[term + '_' + suffix]
else:
return []
# Given a MERtide expression, returns an array of MERtide expressions
# Used to split MERtide expressions with the command "options"
# e.g., R.options:"25-29","30-34" will become R.option:"25-29"+R.option:"30-34"
def splitMertideExpression(expression):
a = []
if '.options:' in expression:
try:
r = re.compile(r'(.+)\.options\:\s*\"([^:]+)\"(.*)')
s = r.search(expression)
for e in s.group(2).split('","'):
a.append(s.group(1) + '.option:"' + e + '"' + s.group(3))
except:
log('Syntax error: ' + expression + ' has an option that cannot be parsed', 'warn')
return
b = []
for i in a:
if '.options:' in i:
b.extend(splitMertideExpression(i))
else:
b.append(i)
if b:
return(b)
else:
return([expression])
# Given a MERtide expression, returns an array of parsed expression, data element, category option,
# category options list, category option combo, and missing value strategy override
def parseMertideExpression(expression):
# a is the variable to be returned, the array mentioned above
a = [urllib.parse.unquote(expression).strip(' '), False, [], [], [], []]
while '.optionCombo:' in a[0]:
try:
r = re.compile(r'(.+)\.optionCombo\:\s*\"(.*)\"')
s = r.search(a[0])
a[4].append(s.group(2)) # category option combos
a[0] = s.group(1)
except:
log('Syntax error: ' + a[0] + ' has an option combo that cannot be parsed', 'warn')
break
while '.options:' in a[0]:
try:
r = re.compile(r'(.+)\.options\:\s*([^:\.]*)(.*)')
s = r.search(a[0])
a[3].append(s.group(2)) # options lists
a[0] = s.group(1) + s.group(3)
except:
log('Syntax error: ' + a[0] + ' has options that cannot be parsed', 'warn')
break
while '.option:' in a[0]:
try:
r = re.compile(r'(.+)\.option\:\s*\"([^:]*)\"(.*)')
s = r.search(a[0])
a[2].append(s.group(2)) # category options
a[0] = s.group(1) + s.group(3)
except:
log('Syntax error: ' + a[0] + ' has an option that cannot be parsed', 'warn')
break
if '.missingValue:' in a[0]:
try:
r = re.compile(r'(.+)\.missingValue\:\s*\"([^:]*)\"(.*)')
s = r.search(a[0])
a[5] = s.group(2) # missing value strategy
a[0] = s.group(1) + s.group(3)
except:
log('Syntax error: ' + a[0] + ' has a missing value strategy that cannot be parsed', 'warn')
if '.de' in a[0]:
try:
r = re.compile(r'(.+)\.de(.*)')
s = r.search(a[0])
a[1] = int(s.group(2)) # data element
a[0] = s.group(1)
except:
log('Syntax error: ' + a[0] + ' has an element that cannot be parsed', 'warn')
return a
# Given a MERtide expression, returns an array of [vr, js, missingValue] where
# vr is an array of operands for validation rules, js is an array of operands for javascript,
# and missingValue is our sense of what to give DHIS2 for the missing value rule
def processMertideExpression(expression, rule, missingValue, which, uidCache, skipCache, dataElementCache):
vr = []
js = []
names = []
[ignore, operator, ignore2, suffix, alluids, allssids, priority, ruleText, ignore3] = rule
if '+' in expression:
termsNotSplit = expression.split('+')
else:
termsNotSplit = [expression]
for terms in termsNotSplit:
for term in splitMertideExpression(terms):
termnames = []
[term, element, options, ignore, optionCombos, missingValueOverride] = parseMertideExpression(term)
try:
if operator == 'autocalculate' or operator == 'exclusive_pair':
if term == 'R':
ssids = allssids
uids = alluids
else:
ssids = [makeSsidHash(term, suffix)]
uids = uidCache[term + '_' + suffix]
for i in range(len(ssids)):
if element:
js.append([ssids[i], [uids[element-1]]])
elif options:
cocs = getCocsFromOptions(options, uids[i])
js.append([ssids[i], cocs])
elif optionCombos:
for coc in optionCombos:
optionCombo = getCoc(coc, uids[i])
js.append([ssids[i], [optionCombo]])
else:
js.append([ssids[i]])
if operator != 'autocalculate':
uids = getUids(term, suffix, alluids, uidCache)
if element:
uids = [uids[element-1]]
for u in uids:
if options:
cocs = getCocsFromOptions(options, u)
for coc in cocs:
vr.append(getDataElement(u, coc).copy())
termnames.append(getDataElement(u, False)['shortName'] + ' option ' + ' and option '.join(options))
if optionCombos:
log('Syntax error: optionCombo used at the same time as option or options in rule ' + ruleText, 'warn')
else:
if optionCombos:
for coc in optionCombos:
vr.append(getDataElement(u, coc).copy())
termnames.append(dataElementCache[u]['shortName'] + ' option combo ' + 'and option combo '.join(optionCombos))
else:
vr.append(getDataElement(u, False).copy())
termnames.append(getDataElement(u, False)['shortName'])
if missingValue != 'NEVER_SKIP' and operator != 'exclusive_pair':
q = term
if term == 'R':
q = priority
elif term in skipCache:
q = skipCache[term]
if q in skip:
missingValue = 'SKIP_IF_ALL_VALUES_MISSING'
elif q in neverskip:
missingValue = 'NEVER_SKIP'
else:
log('Syntax error: ' + q + ' not associated with missing value strategy for rule ' + ruleText, 'warn')
if missingValueOverride:
if missingValueOverride in ['NEVER_SKIP', 'SKIP_IF_ALL_VALUES_MISSING', 'SKIP_IF_ANY_VALUES_MISSING']:
missingValue = missingValueOverride
else:
log('Warning: ' + missingValueOverride + ' is not a valid missing value override', 'warn')
except Exception as e:
log('Syntax error: Problem compiling ' + which + ' expression in ' + ruleText, 'warn')
if operator != 'autocalculate':
if '.options:' in terms:
[term, element, options, optionses, optionCombos, missingValueOverride] = parseMertideExpression(terms)
uids = getUids(term, suffix, alluids, uidCache)
namesuffix = suffix
if element:
uids = [uids[element-1]]
for u in uids:
namesuffix = ' options ' + ' and options '.join(optionses).replace('","', ', ').replace('"', '')
if options:
namesuffix = namesuffix + ' and option ' + ' and option '.join(options)
names.append(getDataElement(u, False)['shortName'] + namesuffix)
else:
names.extend(termnames)
return [vr, js, names, missingValue]
# Add an expression to a validation rule and returns the modified validation rule
def addExpression(j, side, sideData):
if ('description' in j[side]):
j[side]['description'] += ' + value'
j[side]['expression'] += '+'
else:
j[side]['description'] = 'Value'
j[side]['expression'] = ''
j[side]['dataElements'].add(sideData['id'])
if (sideData['optionCombo']):
j[side]['description'] += ' of element ' + sideData['id'] + ' (' + sideData['name'] + ') / ' + cocCache2[sideData['optionCombo']]
j[side]['expression'] += '#{' + sideData['id'] + '.' + sideData['optionCombo'] + '}'
else:
j[side]['description'] += ' of element ' + sideData['id'] + ' (' + sideData['name'] + ')'
j[side]['expression'] += '#{' + sideData['id'] + '}'
return j
# Given an array of elements, turn it into an array of hashes of {'id': element}
def reformatDataElements(elements):
a = []
for e in elements:
a.append({'id': e})
return a
# Create a string from an expression, in which two equivalent expressions will have the same string
#
# Note that in very rare circumstances, will give a false positive; for instance,
# {#aaaaaaaaaaa}+{#bbbbbbbbbbb} will be considered to be the same as {#aaaaaaaaaab}+{#abbbbbbbbbb}
# Hopefully that never occurs in practice!
def hashExpression(expression):
return ''.join(sorted(expression))
# Create a string from a rule, in which two equivalent rules will have the same string
# Deals with the situation of a + b <= c + d being the same as b + a <= d + c
# as well as a + b <= c + d being the same as c + d >= a + b
def hashRule(rule):
try:
# Sort both left and right expressions by character,
# so if two expressions add terms in different orders,
# they will still match
l = hashExpression(rule['leftSide']['expression'])
r = hashExpression(rule['rightSide']['expression'])
# Change greater_thans to less_thans
o = rule['operator']
if o.startswith('greater'):
l,r = r,l # swap left and right
o = o.replace('greater', 'less')
# Look up the operator in our operators hash
o = operators[o]
# Return the result
return l + o + r
except KeyError:
e = []
if 'leftSide' not in rule:
e.append('left side missing')
elif 'expression' not in rule['leftSide']:
e.append('left side expression missing')
if 'rightSide' not in rule:
e.append('right side missing')
elif 'expression' not in rule['rightSide']:
e.append('right side expression missing')
if e:
log('Due to ' + ' and '.join(e) + ', could not evaluate rule ' + rule['description'], 'warn')
else:
log('Could not evaluate either the left or right side of rule ' + rule['description'], 'warn')
return False
def encodeQuote(quote):
# The replace '%25' with '%' stops encoding from being effective with percentages
# but it does stop the double encoding that was stopping some rules from working
return '"' + urllib.parse.quote(quote[0][1:-1]).replace('%25', '%') + '"'
# Make and output a form. This is the core work.
def makeForm(form):
global exportIndicators
#pprint.pprint(form)
formFileName = safeName(form['name'])
form['formDataElements'] = set([])
outputHTML = htmlBefore
# Build major navigation (vtab navigation)
vtabNames = []
dynamicjs = ''
degs = {}
uidCache = {}
uidCache2 = []
warnUidCache = []
skipCache = {}
rules = []
for i in range(len(form['vtabs'])):
vtab = form['vtabs'][i]
outputHTML += majorNavHTML_li % (str(i+1), vtab['name']) + "\n"
outputHTML += majorNavHTML_after+"\n"
# Loop through the VTABs in a FORM:
for i in range(len(form['vtabs'])):
vtab = form['vtabs'][i]
htabs = findHtabs(vtab) # Find htabs referenced in this vtab
# Build minor navigation (htab navigation)
outputHTML += minorNavHTML_before % (str(i+1), str(i+1)) + "\n"
for htab in htabs:
outputHTML += minorNavHTML_li % (str(i+1), htab['type'], htab['label']) + "\n"
outputHTML += minorNavHTML_after + "\n"
# Loop through the HTABs in this VTAB:
for j in range(len(htabs)):
htab = htabs[j]
outputHTML += entryAreaHTML_start % (str(i+1), htab['type'])
# Loop through the Indicators in a VTAB (combined with HTAB):
for k in range(len(vtab['indicators'])):
indicator = vtab['indicators'][k]
subIndicatorsHTML = ""
subIndicatorsCount = 0
if htabInIndicator(htab, indicator):
for row in indicator['rows']:
# Some edge cases will mix DSD/TA/Other _exclusives_ inside the same indicator,
# make sure that we only echo out if it has a UID 1
if row['de_' + htab['type'].lower() + '1'] :
mutuallyExclusive = row['ctl_exclusive']
prefix = 'de_' + htab['type'].lower()
uids = []
ccs = {}
for k in ['1', '2', '3']:
uid = row[prefix + k]
val = open(comboDir + row['sub_disagg'] + '.html').read().find('{deuid' + k + '}')
coc = open(comboDir + row['sub_disagg'] + '.html').read()[val+9:val+20]
if val > 0:
ccs[uid] = masterCategoryOptionComboList[coc]['categoryComboID']
if uid and uid != 'null':
if uid in uidCache2 and uid not in warnUidCache:
log(form['name'] + ': The uid ' + uid + ' appears multiple times', 'warn')
warnUidCache.append(uid)
if masterDataElementList[uid]['categoryComboID'] not in ccs[uid]:
log ("The data element " + masterDataElementList[uid]['name'] +
" - " + uid + " DATIM cat combo " + masterDataElementList[uid]['categoryComboID'] +
" does not match the " + row['sub_disagg'] + ".html catcombo(s) " + ccs[uid], 'warn')
addDataElement(form, uid, form['dataElementGroups'], indicator['frequency'], ccs[uid])
uids.append(uid)
uidCache2.append(uid)
if not('autocalc' in row['sub_disagg'] and 'wide' in row['sub_disagg']):
# Will need to phase out when CC is removed from .csv
if val > 0:
if coc in masterCategoryOptionComboList:
if masterCategoryOptionComboList[coc]['categoryComboID'] != ccs[uid]:
log("Cat Combo: " + masterCategoryOptionComboList[coc]['categoryComboName'] +
" - " + masterCategoryOptionComboList[coc]['categoryComboID'] +
" found in " + row['sub_disagg'] + ".html does not match the form of cat combo " +
k + " " + ccs[uid] + " at " + indicator['name'], 'warn')
else:
log("Could not find coc in master list: " + row['sub_disagg'] + ". Val is " + str(val),'warn')
globals()['uid' + k] = uid
if row['ctl_uniqueid']:
if (row['ctl_uniqueid'] + '_' + htab['uidsuffix']) in uidCache:
log('Unique id ' + row['ctl_uniqueid'] + ' for htab ' + htab['uidsuffix'] + ' appears multiple times', 'severe')
uidCache[row['ctl_uniqueid'] + '_' + htab['uidsuffix']] = uids
skipCache[row['ctl_uniqueid']] = row['sub_priority']
ssid = makeSsidHash(row['ctl_uniqueid'], htab['uidsuffix'])
else:
ssid = makeSsid(htab['uidsuffix'])
uidCache[ssid] = uids
subIndicatorsHTML += '<div class="si_' + ssid + '">\n'
if 'autocalc' in row['sub_disagg'] and 'wide' in row['sub_disagg']:
ssids = [ssid, makeSsid(htab['uidsuffix']), makeSsid(htab['uidsuffix']), makeSsid(htab['uidsuffix'])]
if (';' in row['sub_text']):
sub_text_1, sub_text_2, sub_text_3 = row['sub_text'].split(';')
else:
sub_text_1, sub_text_2, sub_text_3 = ['', '', '']
subIndicatorsHTML += open(comboDir + row['sub_disagg'] + '.html').read().format(
priority=row['sub_priority'], priority_css='PEPFAR_Form_Priority_'+safeName(row['sub_priority']),
description=row['sub_heading'], sub_text_1=sub_text_1, sub_text_2=sub_text_2, sub_text_3=sub_text_3,
ssid1=ssids[1], ssid2=ssids[2], ssid3=ssids[3], deuid1=uid1, deuid2=uid2, deuid3=uid3) + '\n</div>\n\n\n'
else:
ssids = [ssid]
subIndicatorsHTML += open(comboDir + row['sub_disagg'] + '.html').read().format(
priority=row['sub_priority'], priority_css='PEPFAR_Form_Priority_'+safeName(row['sub_priority']),
description=row['sub_heading'], description2=row['sub_text'],
ssid=ssid, deuid1=uid1, deuid2=uid2, deuid3=uid3) + '\n</div>\n\n\n'
if row['ctl_exclusive']:
left = 'R'
action = 'exclusive_pair'
exclusions = row['ctl_exclusive'].split(';')
for e in exclusions:
rules.append([left, action, e, htab['uidsuffix'], uids, ssids, row['sub_priority'], 'ctl_exclusive ' + e + ' from row ' + row['ctl_exclusive'], form['periodType']])
if row['ctl_rules']:
if '"' in row['ctl_rules']:
row['ctl_rules'] = re.sub('"[^"]*"', encodeQuote, row['ctl_rules'])
if ';' in row['ctl_rules']:
rs = row['ctl_rules'].split(';')
else:
rs = [row['ctl_rules']]
for r in rs:
operator = False
if ('>=' in r):
operator = '>='
action = 'greater_than_or_equal_to'
elif ('<=' in r):
operator = '<='
action = 'less_than_or_equal_to'
elif ('==' in r):
operator = '=='
action = 'equal_to'
elif ('=' in r):
operator = '='
action = 'autocalculate'
elif ('!!!' in r):
operator = '!!!'
action = 'exclusive_pair'
else:
log('Syntax error: Cannot compile rule ' + urllib.parse.unquote(r) + ' as it does not have an operator (=, <=, >=, !!!)', 'warn')
if operator:
# Save the rules to process later in the script
a = r.split(operator)
left = a[0]
right = a[1].strip(' ')
if (re.search('[^A-Za-z0-9\_\-\+\%\s\.\,\:\"\/\(\)]', left)):
log('Syntax error: Rule ' + urllib.parse.unquote(r) + ' cannot be compiled as it either uses an illegal operator (=, <=, >= or !!! allowed) or the left expression has illegal characters (letters, numbers, spaces, parens, and certain symbols (".,_-:/+%) allowed)', 'warn')
elif (re.search('[^A-Za-z0-9\_\-\+\%\s\.\,\:\"\/\(\)]', right)):
log('Syntax error: Rule ' + urllib.parse.unquote(r) + ' cannot be compiled as it either uses an illegal operator (=, <=, >= or !!! allowed) or the right expression has illegal characters (letters, numbers, spaces, parens, and certain symbols (".,_-:/+%) allowed)', 'warn')
else:
rules.append([left, action, right, htab['uidsuffix'], uids, ssids, row['sub_priority'], 'ctl_rules row ' + urllib.parse.unquote(r), form['periodType']])
if row['dhis_ind'] and action == 'autocalculate' and left == 'R' and htab['uidsuffix'] != 'xta':
rules.append([left, 'indicator', right, htab['uidsuffix'], uids, ssids, row['sub_priority'], 'indicator for ctl_rules row ' + urllib.parse.unquote(r), row['dhis_ind']])
for x in range(1, 3):
j = 'degs' + str(x)
if row[j]:
d = row[j]
for uid in uids:
if d not in degs:
degs[d] = []
degs[d].append(uid)
subIndicatorsCount += 1
if(subIndicatorsCount > 0):
if(len(htabs) == 1):
outputHTML += indicatorHTML_before.format(name=indicator['name'], frequency=indicator['frequency'], title=htab['type'] + ': ' + indicator['name'])
else:
outputHTML += indicatorHTML_before.format(name=htab['label'] + ': ' + indicator['name'], frequency=indicator['frequency'], title=htab['type'] + ': ' + indicator['name'])
outputHTML += subIndicatorsHTML
outputHTML += indicatorHTML_after.format(title=htab['type'] + ' ' + indicator['name'])
outputHTML += entryAreaHTML_end
outputHTML += minorNavHTML_end
#skipping targets for now
#form['name'].count('Targets') == 0
if not(nofavorites) and form['name'].count('Narratives') == 0 and (not(specificForms) or form['uid'] in formsToOutput):
favoriteType = ''
if form['name'].count('Targets') > 0:
favoriteType = 'Targets'
elif form['name'].count('Results') > 0:
favoriteType = 'Results'
for i in range(len(form['vtabs'])):
vtab = form['vtabs'][i]
for k in range(len(vtab['indicators'])):
indicator = vtab['indicators'][k]
for row in indicator['rows']:
#check to see if the row is anything by AutoCalc
if row['sub_priority'] == 'Required' or row['sub_priority'] == 'Conditional' or row['sub_priority'] == 'Optional':
#Check to see if we should make a favorite for this indicator
#Check to see if this is actually an autocalc row that is mislabled
#print(indicator['name']+" - "+indicator['frequency'])
favoriteFirstDeShortName=getDataElement(list(findDataElementsFromRow(row))[0])['shortName']
#favoriteName="PEPFAR "+ISOQuarterToFYOctQuarter(favoritesISOQuarter)+" "+favoriteType+" "+indicator['name']+" "+getNumeratorDenominator(favoriteFirstDeShortName)+" "+getDisagg(favoriteFirstDeShortName)+" Completeness Review Precursor"
curISOQuarter="FY"+curYear()+"Q"+curQuarter()
favoriteName="PEPFAR "+favoritesISOQuarter+" "+favoriteType+" "+indicator['name']+" "+getNumeratorDenominator(favoriteFirstDeShortName)+" "+getDisagg(favoriteFirstDeShortName)+" Completeness Review Precursor"
favoriteDisplayName=favoriteName
favoriteDescription="This is an auto generated favorite made by MERTIDE, this is not intended to be deployed in its current form, but rather a precursor for PPM staff to create the completeness review pivot."
favoriteId=makeUidHash(favoriteName)
#log(favoriteName)
#no else statement, previous if that checks for a valid frequency would kick out sooner
favoriteISOPeriod=favoritesISOQuarter
favoritePeriodsPreCursor='{"periods": [{"id": ""}]}'
favoritePeriods=json.loads(favoritePeriodsPreCursor)
if favoriteType == 'Targets':
#favoriteISOPeriod=ISOQuarterToISOFYOctTARGET(favoritesISOQuarter)
#HARDCODE IS BAD
favoritePeriods['periods'][0]['id']='2019Oct'
elif indicator['frequency'] == 'Annually':
favoriteISOPeriod=ISOQuarterToISOFYOct(favoritesISOQuarter)
favoritePeriods['periods'][0]['id']=favoriteISOPeriod
elif indicator['frequency'] == 'Semiannually':
favoriteISOPeriod=ISOQuarterToISOSAApr(favoritesISOQuarter)
favoritePeriods['periods'][0]['id']=favoriteISOPeriod
elif indicator['frequency'] == 'Quarterly':
favoriteISOPeriod=favoritesISOQuarter
favoritePeriods['periods'][0]['id']=favoriteISOPeriod
favoriteDataDimensionsItems = {"dataDimensionItems": []}
for de in findDataElementsFromRow(row):
favoriteDataDimensionItemTypeFull = {"dataDimensionItemType": "DATA_ELEMENT","dataElement": {"id": ""}}
favoriteDataDimensionItemTypeFull["dataElement"]["id"] = str(de)
favoriteDataDimensionsItems["dataDimensionItems"].append(favoriteDataDimensionItemTypeFull)
favoriteNew=favoriteStub.copy()
favoriteNew['id'] = favoriteId
favoriteNew['name'] = favoriteName
favoriteNew['displayName'] = favoriteDisplayName
favoriteNew['description'] = favoriteDescription
favoriteNew['dataDimensionItems'] = favoriteDataDimensionsItems['dataDimensionItems']
favoriteNew['periods'] = favoritePeriods['periods']
if favoriteId not in favoritesCreated:
favoritesCreated.append(favoriteId)
if indicator['frequency'] == 'Annually':
favoriteAnnuallyJSON['reportTables'].append(favoriteNew)
if indicator['frequency'] == 'Semiannually':
favoriteSemiannuallyJSON['reportTables'].append(favoriteNew)
if indicator['frequency'] == 'Quarterly':
favoriteQuarterlyJSON['reportTables'].append(favoriteNew)
if not(noconnection):
for rule in rules:
# Get validation rule period
rulePeriod = rule[8]
[left, leftjs, leftnames, ignore] = processMertideExpression(rule[0], rule, False, 'left', uidCache, skipCache, dataElementCache)
[right, rightjs, rightnames, rightMissingValue] = processMertideExpression(rule[2], rule, False, 'right', uidCache, skipCache, dataElementCache)
if right or rightjs:
if rule[1] == 'autocalculate':
dynamicjs += " stella.autocalc(" + str(rightjs) + ", " + str(leftjs) + ");\n"
elif rule[1] == 'indicator':
if rule[3] == 'dsd':
temprule = rule.copy()
temprule[3] = 'xta'
[tempright, ignore1, temprightnames, ignore2] = processMertideExpression(rule[2], temprule, False, 'right', uidCache, skipCache, dataElementCache)
right.extend(tempright)
rightnames.extend(temprightnames)
n = []
for x in right:
if x['optionCombo']:
n.append('#{' + x['id'] + '.' + x['optionCombo'] + '}')
else:
n.append('#{' + x['id'] + '}')
[uid, name] = rule[8].split(';')
exportIndicators.append([name, uid, n, ' + '.join(rightnames)])
else:
if left != [{}] and right != [{}]:
j = {}
j['importance'] = 'MEDIUM'
j['ruleType'] = 'VALIDATION'
j['periodType'] = rulePeriod
j['operator'] = rule[1]
j['leftSide'] = {}
j['rightSide'] = {}
j['leftSide']['dataElements'] = set([])
j['rightSide']['dataElements'] = set([])
for l in left:
j = addExpression(j, 'leftSide', l)
if j['operator'] == 'less_than_or_equal_to' or j['operator'] == 'greater_than_or_equal_to' or j['operator'] == 'equal_to':
if j['operator'] == 'less_than_or_equal_to':
j['name'] = ' <= '
elif j['operator'] == 'greater_than_or_equal_to':
j['name'] = ' >= '
else:
j['name'] = ' == '
if rule[6] in skip: