-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlistSortedOrganizationGammas-developer.py
2707 lines (2321 loc) · 105 KB
/
listSortedOrganizationGammas-developer.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 os
import math
import csv
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
from botocore.exceptions import ClientError
import boto3
from opensearchpy import OpenSearch, RequestsHttpConnection, AWSV4SignerAuth
from boto3.dynamodb.conditions import Key
import AppSyncHelper
import redis
import botocore
import DynamoDBHelper
import json
from datetime import datetime, timedelta
import uuid
import time
import threading
from collections import defaultdict
from chaliceHelper import app
from chalice import BadRequestError, UnauthorizedError, AuthResponse, ChaliceViewError
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Alignment, Border, Side, Font
import traceback
from gql_queries import *
OPENSEARCH_DOMAIN_ENDPOINT = os.environ['OPENSEARCH_DOMAIN_ENDPOINT']
OPENSEARCH_PORT = 443
REGION = os.environ['REGION'] # e.g. us-west-1
CREDENTIALS = boto3.Session().get_credentials()
AWS_AUTH = AWSV4SignerAuth(CREDENTIALS, REGION)
STAGE_TABLE_NAME = os.environ['API_STRALIGN_STAGETABLE_NAME']
GAMMA_TABLE_NAME = os.environ['API_STRALIGN_GAMMATABLE_NAME']
# DEPARTMENTGAMMA_TABLE_NAME = os.environ['API_STRALIGN_DEPARTMENTGAMMATABLE_NAME']
DEPARTMENT_TABLE_NAME = os.environ['API_STRALIGN_DEPARTMENTTABLE_NAME']
API_STRALIGN_USERTABLE_NAME = os.environ['API_STRALIGN_USERTABLE_NAME']
API_STRALIGN_PRIORITYBATCHTABLE_NAME = os.environ['API_STRALIGN_PRIORITYBATCHTABLE_NAME']
def get_graphql_client():
gql_client = AppSyncHelper.create_graphql_client()
return gql_client
GQL_CLIENT = get_graphql_client()
REDIS_CLIENT = redis.Redis(
host=os.environ["ELASTICACHE_CLUSTER_ENDPOINT"], port=os.environ["ELASTICACHE_CLUSTER_PORT"], db=0)
BUCKET_NAME = os.environ['STORAGE_STRALIGNUPLOADS_BUCKETNAME']
LAMBDA_CLIENT = boto3.client('lambda')
FUNCTION_SCHEDULEDCOMPARISONQUEUER_NAME = os.environ['FUNCTION_SCHEDULEDCOMPARISONQUEUER_NAME']
# @app.authorizer(ttl_seconds=30)
# def my_auth(auth_request):
# # Validate auth_request.token, and then:
# print("my_auth called")
# print("auth_request", auth_request)
# print("auth_request.token", auth_request.token)
# return AuthResponse(routes=['/export/rankings'], principal_id='username')
def get_global_ses_client():
global SES_CLIENT
if 'SES_CLIENT' not in globals():
SES_CLIENT = boto3.client('ses')
return SES_CLIENT
def get_global_opensearch_client():
global OPENSEARCH_CLIENT
if 'OPENSEARCH_CLIENT' not in globals():
OPENSEARCH_CLIENT = OpenSearch(
hosts=[f'{OPENSEARCH_DOMAIN_ENDPOINT}:{OPENSEARCH_PORT}'],
http_auth=AWS_AUTH,
use_ssl=True,
verify_certs=True,
connection_class=RequestsHttpConnection
)
return OPENSEARCH_CLIENT
def get_global_s3_client():
global S3_CLIENT
if 'S3_CLIENT' not in globals():
S3_CLIENT = boto3.client('s3')
return S3_CLIENT
def get_global_dynamodb_resource():
global DYNAMODB_RESOURCE
if 'DYNAMODB_RESOURCE' not in globals():
DYNAMODB_RESOURCE = boto3.resource(
'dynamodb', config=botocore.client.Config(max_pool_connections=1000))
return DYNAMODB_RESOURCE
def get_global_stage_table():
global STAGE_TABLE
if 'STAGE_TABLE' not in globals():
STAGE_TABLE = get_global_dynamodb_resource().Table(STAGE_TABLE_NAME)
return STAGE_TABLE
def get_global_department_table():
global DEPARTMENT_TABLE
if 'DEPARTMENT_TABLE' not in globals():
DEPARTMENT_TABLE = get_global_dynamodb_resource().Table(DEPARTMENT_TABLE_NAME)
return DEPARTMENT_TABLE
# def get_global_department_gamma_table():
# global DEPARTMENTGAMMA_TABLE
# if 'DEPARTMENTGAMMA_TABLE' not in globals():
# DEPARTMENTGAMMA_TABLE = get_global_dynamodb_resource().Table(
# DEPARTMENTGAMMA_TABLE_NAME)
# return DEPARTMENTGAMMA_TABLE
def get_global_gamma_table():
global GAMMA_TABLE
if 'GAMMA_TABLE' not in globals():
GAMMA_TABLE = get_global_dynamodb_resource().Table(GAMMA_TABLE_NAME)
return GAMMA_TABLE
def get_GQL_paginated(gqlClient, query, params, list_query_name, result):
nextToken = None
count = 1
while (nextToken != None or count < 2):
count += 1
response = gqlClient.execute(query, variable_values=params)
# print(response)
result.extend(response[list_query_name]["items"])
nextToken = response[list_query_name].get("nextToken", None)
params["nextToken"] = nextToken
# print(nextToken)
return result
def upload_to_s3(file_path, file_name):
start = time.time()
get_global_s3_client().upload_file(
Filename=file_path,
Bucket=os.environ["STORAGE_STRALIGNUPLOADS_BUCKETNAME"],
Key="public/" + file_name
)
print("time taken to upload file", file_name, time.time()-start)
return "public/" + file_name
def update_rankings(lambda_client, organization_id, aggregates=False):
params = {
"organization_id": organization_id
}
if aggregates:
params['aggregates'] = aggregates
lambda_client.invoke(
FunctionName=os.environ['FUNCTION_SCORECALCULATIONSTATUSTRIGGERPYTHON_NAME'],
InvocationType='Event',
Payload=json.dumps(params).encode('utf-8'),
)
print("invoked rankings updater")
return
def get_last_dates(today):
days_to_sunday = (today.weekday() - 6) % 7
last_sunday_date = today - timedelta(days=days_to_sunday)
first_day_of_current_month = today.replace(day=1)
last_month_last_date = first_day_of_current_month - timedelta(days=1)
quarter_offset = (today.month - 1) % 3 + 1
first_day_of_current_quarter = today.replace(
month=today.month - quarter_offset + 1, day=1)
last_quarter_last_date = first_day_of_current_quarter - timedelta(days=1)
return [last_sunday_date.strftime('%Y-%m-%d'), last_month_last_date.strftime('%Y-%m-%d'), last_quarter_last_date.strftime('%Y-%m-%d')]
def get_last_login_date(userID, today_date, result):
query_params = {
"userID": userID,
"date": today_date
}
last_login_items = get_graphql_client().execute(get_last_login_date_query,
variable_values=query_params)["loginHistoriesByUserIDAndDate"]["items"]
if last_login_items:
result.append(last_login_items[0]['date'])
return result
def get_s3_rank_history(s3_client, yearly_rank_history, yearly_file_key):
try:
s3_response = json.loads(s3_client.get_object(Bucket=BUCKET_NAME, Key=yearly_file_key)[
'Body'].read().decode('utf-8'))
# print("s3 response", s3_response)
yearly_rank_history.update(s3_response)
except Exception as e:
print("error", e)
return yearly_rank_history
# def get_s3_yearly_previous_ranks(s3_client, yearly_rank_history, yearly_file_key, userID, s3_response={}):
# start = time.time()
# today_date = datetime.now().date()
# threads = []
# result = []
# threads.append(threading.Thread(target=get_last_login_date,
# args=(userID, today_date.strftime('%Y-%m-%d'), result,)))
# threads[-1].start()
# get_s3_rank_history(s3_client, s3_response, yearly_file_key)
# last_saturday_date, last_month_last_date, last_quarter_last_date = get_last_dates(
# today_date)
# for thread in threads:
# thread.join()
# last_login_date = result[0] if result else '00-00-0000'
# yearly_rank_history.update({k: {"Week": v.get(last_saturday_date, {"Rank": -1})["Rank"], "Month": v.get(last_month_last_date, {"Rank": -1})["Rank"],
# "Quarter": v.get(last_quarter_last_date, {"Rank": -1})["Rank"], "lastLogin": v.get(last_login_date, {"Rank": -1})["Rank"]}
# for k, v in s3_response.items()})
# print("time taken to fetch s3 rank history", time.time() - start)
# return s3_response, yearly_rank_history
def apply_filters(merged_rankings, filters):
if not filters:
return merged_rankings
print("filters", filters)
owner_filters = filters.get("byMe", "")
rank_filters = filters.get("Ranks", {})
stage_filters = filters.get("Stage", {})
department_filters = filters.get("Department", [])
created_date_filters = filters.get("Created", [])
fixed_ranks = bool(rank_filters.get("Assigned", True))
default_ranks = bool(rank_filters.get("Default", True))
levels = {stage for stage, val in stage_filters.items() if val}
departments = set(department_filters)
user_id = owner_filters
date_range = [datetime.strptime(
created_date, '%Y-%m-%dT%H:%M:%S.%fZ') for created_date in created_date_filters]
filtered_rankings = [
{
"Rank": i + 1,
**ranking
}
for i, ranking in enumerate(merged_rankings)
if (fixed_ranks or ranking["Gamma"]["fixedRank"] <= 0) and
(default_ranks or ranking["Gamma"]["fixedRank"] >= 0) and
(not departments or any(item in departments for item in ranking["Gamma"]["departments"])) and
(not levels or ranking["Gamma"]["level"]["id"] in levels) and
(not user_id or ranking["Gamma"]["user"]["id"] == user_id) and
(not date_range or date_range[0] <= datetime.strptime(
ranking["Gamma"]["createdAt"], '%Y-%m-%dT%H:%M:%S.%fZ') <= date_range[1])
]
return filtered_rankings
def get_default_rankings(gql_client, organizationID, pages, all_rankings, default_rankings):
start = time.time()
params = {
"organizationID": organizationID,
"nextToken": None
}
if pages:
for page in pages:
start = (page-1)*50
end = start + 50
if start < len(all_rankings):
keys = [key for key in all_rankings[start: end]]
else:
return []
filter_string = '{{or: [{}]}}'.format(
', '.join('{{id: {{eq: "{}"}}}}'.format(key) for key in keys)
)
get_gammas_query_modified = get_gammas_query.format(filter_string)
get_GQL_paginated(
gql_client, gql(get_gammas_query_modified), params, "gammasByOrganizationID", default_rankings["items"])
else:
get_gammas_query_modified = get_gammas_query.format('{}')
get_GQL_paginated(
gql_client, gql(get_gammas_query_modified), params, "gammasByOrganizationID", default_rankings["items"])
print("time taken to fetch default ranking", time.time() - start)
return default_rankings
def get_all_item_all_ranks(REDIS_CLIENT, priority_batch_id, current_rank=True, previous_rank=True, default_rank=True, no_rank=True):
items_with_ranks = {}
if current_rank:
# Get all items with their ranks from the sorted set
items_with_ranks = REDIS_CLIENT.zrange(
priority_batch_id, 0, -1, withscores=True)
# print("items_with_ranks", items_with_ranks)
# Get the previous ranks from the hash
previous_ranks = {}
if previous_rank:
previous_ranks = REDIS_CLIENT.zrange(
f'{priority_batch_id}:previous_rank', 0, -1, withscores=True)
previous_ranks = {item.decode('utf-8'): int(rank)
for item, rank in previous_ranks}
# print("previous_ranks", previous_ranks)
no_ranks = {}
if no_rank:
no_ranks = REDIS_CLIENT.zrange(
f'{priority_batch_id}:no_rank', 0, -1, withscores=True)
# Get the default ranks from the hash
default_ranks = {}
if default_rank:
default_ranks = REDIS_CLIENT.hgetall(
f'{priority_batch_id}:default_rank')
# print("default_ranks", default_ranks)
# Combine the ranks and previous ranks into a dictionary
redis_ranks = {
item.decode('utf-8'): {
'rank': int(rank),
'previous_rank': int(previous_ranks.get(item, -1)),
'default_rank': int(default_ranks.get(item, -1))
}
for item, rank in items_with_ranks
}
no_ranks = {
item.decode('utf-8'): createdAt
for item, createdAt in no_ranks
if not redis_ranks.get(item.decode('utf-8'))
}
# Sort the dictionary by rank in ascending order
redis_ranks = dict(sorted(redis_ranks.items(), key=lambda x: x[1]['rank']))
return redis_ranks, no_ranks
def get_redis_rankings(REDIS_CLIENT, priorityBatchID, redis_rankings, no_rankings, current_rank=True, previous_rank=True, default_rank=True, no_rank=True):
start = time.time()
redis_rankings["items"], no_rankings["items"] = get_all_item_all_ranks(
REDIS_CLIENT, priorityBatchID, current_rank, previous_rank, default_rank, no_rank)
# print("redis_rankings", redis_rankings)
print("time taken to fetch redis ranking", time.time()-start)
return redis_rankings, no_rankings
def get_redis_rank(REDIS_CLIENT, priorityBatchID, itemID, rank):
rank.append(REDIS_CLIENT.zscore(priorityBatchID, itemID))
return rank
def create_ranking_excel_file(merged_rankings, timenow, file_keys):
HEADER_ROW_HEIGHT = 20
ROW_HEIGHT = 17
header_row_fill = PatternFill(
start_color='DFEDF9', end_color='DFEDF9', fill_type="solid")
data_row_even_fill = PatternFill(
start_color='F7FAFD', end_color='F7FAFD', fill_type="solid")
data_row_odd_fill = PatternFill(
start_color='FFFFFF', end_color='FFFFFF', fill_type="solid")
# Create a new workbook and select the active sheet
workbook = Workbook()
sheet = workbook.active
headers = ['Rank', 'Title', 'Stage', 'Change', 'Previous']
header_row_border = Border(
bottom=Side(style='thin'))
# adjust header row height for better readability
sheet.row_dimensions[1].height = HEADER_ROW_HEIGHT
# Apply formatting to the header row
for col_num, header in enumerate(headers, start=1):
cell = sheet.cell(row=1, column=col_num)
cell.value = header
cell.alignment = Alignment(horizontal='center')
# cell.font = cell.font.copy(size=12, bold=True)
cell.font = Font(size=12, bold=True)
cell.fill = header_row_fill
cell.border = header_row_border
# Iterate over the merged rankings and populate the spreadsheet
for item in merged_rankings:
# rank = i + 1 if item['isRanked'] else '-'
rank = item['Gamma']['fixedRank'] if item['Gamma']['fixedRank'] > 0 else (
item['Rank'] if item['isRanked'] else '-')
title = item['Gamma']['title']
stage = item['Gamma']['level']['name']
if item['Gamma']['fixedRank'] < 0:
previous = '-' if (item['Gamma'].get('previousRank', None)
) in [None, -1] else item['Gamma']['previousRank']
else:
previous = item['Gamma']['fixedRank']
change = previous - \
rank if isinstance(previous, int) and isinstance(
rank, int) else '-'
sheet.append([rank, title, stage, change, previous])
column_dimensions = [
('A', 10), ('B', 80), ('C', 18), ('D', 10), ('E', 10)
]
for col, width in column_dimensions:
sheet.column_dimensions[col].width = width
# Apply formatting to data rows
for row in sheet.iter_rows(min_row=2, max_row=sheet.max_row):
i = row[0].row
# adjust data row height for better readability
sheet.row_dimensions[i].height = ROW_HEIGHT
row_fill = data_row_even_fill if i % 2 == 0 else data_row_odd_fill
for cell in row:
cell.alignment = Alignment(wrap_text=True, horizontal='center')
# cell.font = cell.font.copy(size=12)
cell.font = Font(size=12, bold=False)
cell.fill = row_fill
# Save the workbook
file_name = "Rankings" + timenow + ".xlsx"
file_path = "/tmp/" + file_name
workbook.save(file_path)
# file_key = upload_to_s3(file_path, file_name)
file_keys.append(file_path)
return file_path
def create_excel_file(merged_rankings, users, objectives, departments, vote_counts, rating_counts, export_data):
file_keys = []
threads = []
timenow = datetime.now().strftime("%m-%d-%Y%H-%M-%S.%f")
threads.append(threading.Thread(target=create_ranking_excel_file,
args=(merged_rankings, timenow, file_keys,)))
threads[-1].start()
if export_data == 'All':
vote_sheet_headers = ['Title', 'User']
vote_sheet_headers.extend(
[f"{objective['name']} ({status})" for objective in objectives for status in ['Compared', 'Selected']])
rating_sheet_headers = ['Title', 'User']
rating_sheet_headers.extend(
[f"{objective['name']} ({status})" for objective in objectives for status in ['Rating Sum']])
# Writing vote_counts to CSV
vote_counts_file_name = "/tmp/Votes" + timenow + ".csv"
file_keys.append(vote_counts_file_name)
with open(vote_counts_file_name, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=vote_sheet_headers)
# Write the header rows
# First header row
writer.writerow(dict(zip(vote_sheet_headers, vote_sheet_headers)))
# Write the data
for item in merged_rankings:
gamma_value = vote_counts[item['Gamma']['id']]
for user in users:
row = {"Title": item['Gamma']
['title'], "User": user['email']}
for objective in objectives:
objective_value = gamma_value[objective['id']]
user_value = objective_value[user['id']]
row.update(
{f"{objective['name']} (Compared)": user_value['comparison_count'],
f"{objective['name']} (Selected)": user_value['selection_count']})
writer.writerow(row)
# Writing rating_counts to CSV
rating_counts_file_name = "/tmp/Ratings" + timenow + ".csv"
file_keys.append(rating_counts_file_name)
with open(rating_counts_file_name, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=rating_sheet_headers)
# Write the header rows
# First header row
writer.writerow(
dict(zip(rating_sheet_headers, rating_sheet_headers)))
# Write the data
for item in merged_rankings:
gamma_value = vote_counts[item['Gamma']['id']]
for user in users:
row = {"Title": item['Gamma']
['title'], "User": user['email']}
for objective in objectives:
objective_value = gamma_value[objective['id']]
user_value = objective_value[user['id']]
row.update(
{f"{objective['name']} (Rating Sum)": user_value})
writer.writerow(row)
for thread in threads:
thread.join()
return file_keys
def get_departments_by_organization(gql_client, organization_id, departments):
params = {
'organizationID': organization_id
}
res = gql_client.execute(
get_departments_by_organization_query, variable_values=params).get('departmentsByOrganizationID', {"items": []})['items']
departments.update(
{department['id']: department['name'] for department in res})
return departments
def get_user_emails(user_ids, user_details):
user_keys = [{'id': user_id} for user_id in user_ids]
users = DynamoDBHelper.batch_get(get_global_dynamodb_resource(), API_STRALIGN_USERTABLE_NAME, user_keys, [
'id', 'email', 'firstName', 'lastName'])
user_details.update({user['id']: user for user in users})
return user_details
# may need to modify dynamodb helper batch get method to use ExpressionAttributeNames
def get_department_names(department_ids, department_details):
department_keys = [{'id': department_id}
for department_id in department_ids]
expression_attribute_names = {'#n': 'name'}
departments = DynamoDBHelper.batch_get(get_global_dynamodb_resource(), DEPARTMENT_TABLE_NAME, department_keys, [
'id', '#n'], expression_attribute_names)
department_details.update(
{department['id']: department['name'] for department in departments})
return department_details
def get_organization_user_vote_aggregates(gql_client, organization_id, gamma_vote_aggregates):
params = {
'organizationID': organization_id
}
gamma_vote_aggregates.extend(gql_client.execute(
get_organization_user_vote_aggregates_query, variable_values=params).get('getOrganizationGammaUserVotesAggregates', {'buckets': []})['buckets'])
# gamma_vote_aggregates.update(
# {gamma_bucket['key']: gamma_bucket for gamma_bucket in res['buckets']})
return gamma_vote_aggregates
def get_organization_user_rating_aggregates(gql_client, organization_id, gamma_rating_aggregates):
params = {
'organizationID': organization_id
}
gamma_rating_aggregates.extend(gql_client.execute(
get_organization_user_rating_aggregates_query, variable_values=params).get('getOrganizationGammaUserRatingsAggregates', {'buckets': []})['buckets'])
# gamma_rating_aggregates.update(
# {gamma_bucket['key']: gamma_bucket for gamma_bucket in res['buckets']})
return gamma_rating_aggregates
def get_users_by_organization(gql_client, organization_id, users):
params = {
'organizationID': organization_id,
'nextToken': None
}
users = get_GQL_paginated(
gql_client, get_users_by_organization_query, params, "usersByOrganizationID", users)
return users
def get_objectives_by_organization(gql_client, organization_id, objectives):
params = {
'organizationObjectivesId': organization_id,
'nextToken': None
}
objectives = get_GQL_paginated(
gql_client, get_objectives_by_organization_query, params, "objectivesByOrganizationObjectivesId", objectives)
return objectives
def send_email_attachment(destination, subject, username, file_keys):
# emailData = {
# "email": "email",
# "password": "password",
# "login_link": "https://d25d5goqjgy5td.cloudfront.net/login"
# }
file_names = [key.split('/')[-1] for key in file_keys]
file_name = "<br>".join(file_names)
emailData = {
"username": username,
"filename": file_name,
}
now = datetime.now()
est = now - timedelta(hours=4)
try:
msg = MIMEMultipart()
msg['From'] = SENDER_EMAIL
msg['To'] = destination
msg['Subject'] = est.strftime('%m-%d-%Y') + " " + subject
body = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>StrAlign</title>
<style>
body,
html {{
font-family: Arial, Helvetica, sans-serif;
}}
p {{
font-size: 15px;
line-height: 22px;
color: #161616;
}}
</style>
</head>
<body topmargin="0">
<table
width="600"
border="0"
align="center"
cellpadding="0"
cellspacing="0"
class="bgtext"
>
<thead>
<tr>
<th width="100%;" style="display: block; margin: 20px 0">
<a href="#"
><img
class="header-logo-image"
src="https://stralign-static-files.s3.amazonaws.com/logo.png"
alt="StrAlign"
title="StrAlign"
/></a>
</th>
</tr>
</thead>
<tbody style="background-color: #f8f8f8">
<tr>
<td colspan="1">
<table
width="100%"
border="0"
align="center"
cellpadding="8"
cellspacing="0"
class="bgtext"
>
<tr>
<div
style="
background-color: white;
border-radius: 12px;
width: 85%;
margin: 20px auto 20px;
padding: 5px 20px 30px;
"
>
<h4><b>Dear {username},</b></h4>
<p>Please find the exported file attachments below:</p>
<p>
{filename}
</p>
</div>
</tr>
<tr>
<th
width="100%;"
style="display: block; margin: 20px 0 0; padding-bottom: 0"
>
<a href="#"
><img
src="https://stralign-static-files.s3.amazonaws.com/Facebook.png"
alt="fb"
style="height: 21px"
/></a>
<a href="#"
><img
src="https://stralign-static-files.s3.amazonaws.com/TwitterCircle.png"
alt="insta"
style="height: 21px"
/></a>
<a href="#"
><img
src="https://stralign-static-files.s3.amazonaws.com/Linkedin.png"
alt="linkedin"
style="height: 21px"
/></a>
</th>
<th
width="100%;"
style="display: block; margin: 0; padding-top: 0"
>
<p
style="
margin-top: 0;
color: #646464;
font-weight: 500;
font-size: 13px;
"
>
© 2024 Echo Consulting, LLC<br />
Copyright all rights reserved.
</p>
</th>
</tr>
</table>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
</body>
</html>
""".format(**emailData)
msg.attach(MIMEText(body, 'html'))
# add the attachments
attachments = file_keys
for attachment in attachments:
part = MIMEBase('application', "octet-stream")
with open(attachment, 'rb') as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header(
'Content-Disposition', f'attachment; filename="{os.path.basename(attachment)}"')
msg.attach(part)
# send the email
raw_msg = msg.as_string()
response = get_global_ses_client().send_raw_email(
Source=SENDER_EMAIL,
Destinations=[destination],
RawMessage={'Data': raw_msg}
)
print("Email sent! Message ID:", response['MessageId'])
except ClientError as e:
print("Email not sent. Error message: ",
e.response['Error']['Message'])
return {
'statusCode': 200
}
@app.route('/export/rankings', cors=True, methods=['POST'], content_types=['application/json'])
def export_rankings():
event = app.current_request.to_dict()
body = app.current_request.json_body
print('received event:')
print(event)
print("body", body)
# read filters if any
priority_batch_id = body["priorityBatchID"]
organization_id = body["id"]
filters = body.get("filters", {})
export_data = body.get("exportData", "Rankings")
threads = []
users = []
objectives = []
redis_rankings = {}
default_rankings = {}
departments = {}
no_rankings = {}
gamma_vote_aggregates = []
gamma_rating_aggregates = []
# default_rankings = {}
# redis_rankings = {}
# no_rankings = {}
# threads = []
# threads.append(threading.Thread(target=get_redis_rankings,
# args=(REDIS_CLIENT, priorityBatchID, redis_rankings, no_rankings)))
# threads[-1].start()
# for thread in threads:
# thread.join()
# all_rankings = list(
# redis_rankings["items"].keys()) + list(no_rankings["items"].keys())
# all_ranks = len(all_rankings)
# pages = [i for i in range(1, math.ceil(all_ranks/50) + 1)]
# threads = []
# default_rankings["items"] = []
# threads.append(threading.Thread(target=get_default_rankings,
# args=(GQL_CLIENT, organizationID, pages, all_rankings, default_rankings,)))
# threads[-1].start()
# for thread in threads:
# thread.join()
# print("default_rankings", default_rankings["items"])
# print("redis_rankings", redis_rankings["items"])
# default_rankings["items"] = {
# item["id"]: item for item in default_rankings["items"]}
# merged_rankings = []
# merged_rankings = [{"isRanked": True, "Gamma": {**default_rankings["items"][k], "rank": v["rank"], "previousRank": v["previous_rank"]}}
# for k, v in redis_rankings["items"].items() if k in default_rankings["items"]]
# merged_rankings += [{"isRanked": False, "Gamma": {**item, "rank": 0, "previousRank": None}}
# for item in default_rankings["items"].values() if item["id"] not in redis_rankings["items"]]
# print("before filters", merged_rankings)
# # apply filters here:
# merged_rankings = apply_filters(merged_rankings, filters)
# print("after filters", merged_rankings)
# file_key = create_excel_file(merged_rankings)
# payload = {"fileKey": file_key}
default_rankings["items"] = []
threads.append(threading.Thread(target=get_default_rankings,
args=(GQL_CLIENT, organization_id, [], [], default_rankings,)))
threads[-1].start()
threads.append(threading.Thread(target=get_users_by_organization,
args=(get_graphql_client(), organization_id, users,)))
threads[-1].start()
threads.append(threading.Thread(target=get_redis_rankings,
args=(REDIS_CLIENT, priority_batch_id, redis_rankings, no_rankings)))
threads[-1].start()
threads.append(threading.Thread(target=get_organization_user_vote_aggregates,
args=(get_graphql_client(), organization_id, gamma_vote_aggregates,)))
threads[-1].start()
threads.append(threading.Thread(target=get_organization_user_rating_aggregates,
args=(get_graphql_client(), organization_id, gamma_rating_aggregates,)))
threads[-1].start()
threads.append(threading.Thread(target=get_departments_by_organization,
args=(get_graphql_client(), organization_id, departments,)))
threads[-1].start()
threads.append(threading.Thread(target=get_objectives_by_organization,
args=(get_graphql_client(), organization_id, objectives,)))
threads[-1].start()
for thread in threads:
thread.join()
print("objectives", objectives)
vote_counts = defaultdict(lambda: defaultdict(lambda: defaultdict(
lambda: {'comparison_count': 0, 'selection_count': 0})))
rating_counts = defaultdict(lambda: defaultdict(lambda: defaultdict(
lambda: 0)))
for gamma_bucket in gamma_vote_aggregates:
for objective_bucket in gamma_bucket['buckets']:
for vote_bucket in objective_bucket['votes']:
if int(vote_bucket['key']) == -1:
for unique_user in vote_bucket['unique_users']:
vote_counts[gamma_bucket['key']][objective_bucket['key']
][unique_user['key']]['comparison_count'] += unique_user['doc_count']
elif int(vote_bucket['key']) == 1:
for unique_user in vote_bucket['unique_users']:
vote_counts[gamma_bucket['key']][objective_bucket['key']
][unique_user['key']]['comparison_count'] += unique_user['doc_count']
vote_counts[gamma_bucket['key']][objective_bucket['key']
][unique_user['key']]['selection_count'] += unique_user['doc_count']
for gamma_bucket in gamma_rating_aggregates:
for objective_bucket in gamma_bucket['buckets']:
for unique_user in objective_bucket['unique_users']:
rating_counts[gamma_bucket['key']][objective_bucket['key']
][unique_user['key']] += unique_user['ratings_sum']['value']
print("redis_rankings", redis_rankings)
print("no_rankings", no_rankings)
all_rankings = list(
redis_rankings["items"].keys()) + list(no_rankings["items"].keys())
all_ranks = len(all_rankings)
default_rankings["items"] = {
item["id"]: item for item in default_rankings["items"]}
merged_rankings = []
merged_rankings = [{"isRanked": True, "Gamma": {**default_rankings["items"][k], "rank": v["rank"], "previousRank": v["previous_rank"]}}
for k, v in redis_rankings["items"].items() if k in default_rankings["items"]]
merged_rankings += [{"isRanked": False, "Gamma": {**item, "rank": 0, "previousRank": None}}
for item in default_rankings["items"].values() if item["id"] not in redis_rankings["items"]]
print("before filters", merged_rankings)
# apply filters here:
merged_rankings = apply_filters(merged_rankings, filters)
print("after filters", merged_rankings)
file_keys = create_excel_file(merged_rankings, users, objectives,
departments, vote_counts, rating_counts, export_data)
if os.environ["ENV"] in ["client", "live"]:
s3_file_keys = []
for file_key in file_keys:
s3_file_keys.append(upload_to_s3(
file_key, file_key.split('/')[-1]))
return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST'
},
'body': {"fileKeys": s3_file_keys}
}
else:
send_email_attachment(
body['email'], "Rankings Export Summary", body['name'], file_keys)
return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST'
},
'body': "Successfully sent the email"
}
def get_redis_default_ranks(REDIS_CLIENT, priority_batch_id):
return REDIS_CLIENT.hgetall(
f'{priority_batch_id}:default_rank')
def get_redis_ranks(REDIS_CLIENT, priority_batch_id, start_rank, end_rank, sort_direction="ASC"):
items = REDIS_CLIENT.zrange(
priority_batch_id, start_rank, end_rank, withscores=True)
return items
def get_redis_ranks_threaded(REDIS_CLIENT, priority_batch_id, start_rank, end_rank, ranks, sort_direction="ASC"):
res = REDIS_CLIENT.zrange(
priority_batch_id, start_rank, end_rank, withscores=True)
ranks.update({item.decode('utf-8'): int(rank)
for item, rank in res})
return ranks
def get_redis_ranks_count(REDIS_CLIENT, priority_batch_id):
total_ranks = REDIS_CLIENT.zcard(priority_batch_id)
return total_ranks
def get_redis_previous_ranks(REDIS_CLIENT, priority_batch_id, start_rank, end_rank, sort_direction="ASC"):
items = REDIS_CLIENT.zrange(
f'{priority_batch_id}:previous_rank', start_rank, end_rank, withscores=True)
return items
def get_redis_previous_ranks_count(REDIS_CLIENT, priority_batch_id):
total_previous_ranks = REDIS_CLIENT.zcard(
f'{priority_batch_id}:previous_rank')
return total_previous_ranks