-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathviews.py
4116 lines (3711 loc) · 182 KB
/
views.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 ast
import csv
import gzip
import json
import logging
import operator
import os
import pickle
import random
import re
import shutil
import string
import sys
import threading
import uuid
from calendar import c
from concurrent.futures import ThreadPoolExecutor, as_completed
from functools import reduce
from pickle import TRUE
from urllib.parse import parse_qs, unquote, urlparse
import boto3
import django
import dropbox
import numpy as np
import pandas as pd
import requests
from azure.storage.blob import BlobServiceClient
from django.conf import settings
from django.contrib.admin.utils import get_model_from_relation
from django.contrib.auth.hashers import check_password, make_password
from django.core.cache import cache
from django.core.files.base import ContentFile
from django.db import transaction
# from django.http import HttpResponse
from django.db.models import (
DEFERRED,
CharField,
Count,
F,
Func,
OuterRef,
Q,
Subquery,
Sum,
Value,
)
from django.db.models.functions import Concat
# from django.db.models.functions import Index, Substr
from django.http import JsonResponse
from django.shortcuts import render
from drf_braces.mixins import MultipleSerializersViewMixin
from google.oauth2.credentials import Credentials
from google.oauth2.service_account import Credentials as ServiceAccountCredentials
from googleapiclient.discovery import build
from jsonschema import ValidationError
from psycopg2 import connect
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
from python_http_client import exceptions
from pytube import Channel, Playlist, YouTube
from rest_framework import generics, pagination, status, viewsets
from rest_framework.decorators import action, api_view
from rest_framework.exceptions import ValidationError
from rest_framework.parsers import JSONParser, MultiPartParser
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ViewSet
from uritemplate import partial
from accounts.models import User, UserRole
from accounts.serializers import (
UserCreateSerializer,
UserSerializer,
UserUpdateSerializer,
)
from ai.open_ai_utils import qdrant_embeddings_delete_file_id
from ai.retriever.conversation_retrival import ConversationRetrival
from ai.retriever.manual_retrival import Retrival
from ai.vector_db_builder.vector_build import create_vector_db, insert_auto_cat_data
from connectors.models import Connectors
from connectors.serializers import ConnectorsListSerializer
from core.constants import Constants, NumericalConstants
from core.serializer_validation import (
OrganizationSerializerValidator,
UserCreateSerializerValidator,
)
from core.settings import BASE_DIR
from core.utils import (
CustomPagination,
Utils,
csv_and_xlsx_file_validatation,
date_formater,
generate_api_key,
generate_hash_key_for_dashboard,
read_contents_from_csv_or_xlsx_file,
)
from datahub.models import (
DatahubDocuments,
Datasets,
DatasetV2,
DatasetV2File,
Organization,
Resource,
StandardisationTemplate,
UserOrganizationMap,
)
from datahub.serializers import (
ResourceAutoCatSerializer, # Added for Auto Categorizaion
)
from datahub.serializers import (
DatahubDatasetFileDashboardFilterSerializer,
DatahubDatasetsSerializer,
DatahubDatasetsV2Serializer,
DatahubThemeSerializer,
DatasetFileV2NewSerializer,
DatasetSerializer,
DatasetUpdateSerializer,
DatasetV2DetailNewSerializer,
DatasetV2ListNewSerializer,
DatasetV2NewListSerializer,
DatasetV2Serializer,
DatasetV2TempFileSerializer,
DatasetV2Validation,
DropDocumentSerializer,
OrganizationSerializer,
ParticipantSerializer,
PolicyDocumentSerializer,
RecentDatasetListSerializer,
RecentSupportTicketSerializer,
ResourceAPIBuilderSerializer,
ResourceFileSerializer,
ResourceSerializer,
ResourceUsagePolicySerializer,
StandardisationTemplateUpdateSerializer,
StandardisationTemplateViewSerializer,
TeamMemberCreateSerializer,
TeamMemberDetailsSerializer,
TeamMemberListSerializer,
TeamMemberUpdateSerializer,
UsageUpdatePolicySerializer,
UserOrganizationCreateSerializer,
UserOrganizationMapSerializer,
)
from participant.models import SupportTicket
from participant.serializers import (
ParticipantSupportTicketSerializer,
TicketSupportSerializer,
)
from utils import custom_exceptions, file_operations, string_functions, validators
from utils.authentication_services import authenticate_user
from utils.embeddings_creation import VectorDBBuilder
from utils.file_operations import (
check_file_name_length,
filter_dataframe_for_dashboard_counties,
generate_fsp_dashboard,
generate_knfd_dashboard,
generate_omfp_dashboard,
)
from utils.jwt_services import http_request_mutation
from utils.youtube_helper import get_youtube_url
from .models import (
Category,
DatasetSubCategoryMap,
LangchainPgCollection,
LangchainPgEmbedding,
Messages,
Policy,
ResourceFile,
ResourceSubCategoryMap,
ResourceUsagePolicy,
SubCategory,
UsagePolicy,
)
from .serializers import (
APIBuilderSerializer,
CategorySerializer,
CategorySubcategoryInputSerializer,
FileItemSerializer,
FileResponseSerializer,
LangChainEmbeddingsSerializer,
MessagesChunksRetriveSerializer,
MessagesRetriveSerializer,
MessagesSerializer,
ParticipantCostewardSerializer,
PolicySerializer,
ResourceFileSerializer,
ResourceListSerializer,
ResourceUsagePolicyDetailSerializer,
SourceDetailsSerializer,
SubCategorySerializer,
UsagePolicyDetailSerializer,
UsagePolicySerializer,
)
# Replace 'YOUR_API_KEY' with your actual API key
LOGGER = logging.getLogger(__name__)
con = None
class DefaultPagination(pagination.PageNumberPagination):
"""
Configure Pagination
"""
page_size = 5
class TeamMemberViewSet(GenericViewSet):
"""Viewset for Product model"""
serializer_class = TeamMemberListSerializer
queryset = User.objects.all()
pagination_class = CustomPagination
def create(self, request, *args, **kwargs):
"""POST method: create action to save an object by sending a POST request"""
try:
serializer = TeamMemberCreateSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
except ValidationError as e:
return Response(e.detail, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
LOGGER.error(e,exc_info=True)
return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def list(self, request, *args, **kwargs):
"""GET method: query all the list of objects from the Product model"""
# queryset = self.filter_queryset(self.get_queryset())
queryset = User.objects.filter(Q(status=True) & (Q(role__id=2) | Q(role__id=5)))
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def retrieve(self, request, pk):
"""GET method: retrieve an object or instance of the Product model"""
team_member = self.get_object()
serializer = TeamMemberDetailsSerializer(team_member)
# serializer.is_valid(raise_exception=True)
return Response(serializer.data, status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs):
"""PUT method: update or send a PUT request on an object of the Product model"""
try:
instance = self.get_object()
# request.data["role"] = UserRole.objects.get(role_name=request.data["role"]).id
serializer = TeamMemberUpdateSerializer(instance, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
except ValidationError as e:
return Response(e.detail, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
LOGGER.error(e,exc_info=True)
return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def destroy(self, request, pk):
"""DELETE method: delete an object"""
team_member = self.get_object()
team_member.status = False
# team_member.delete()
team_member.save()
return Response(status=status.HTTP_204_NO_CONTENT)
class OrganizationViewSet(GenericViewSet):
"""
Organisation Viewset.
"""
serializer_class = OrganizationSerializer
queryset = Organization.objects.all()
pagination_class = CustomPagination
parser_class = MultiPartParser
def perform_create(self, serializer):
"""
This function performs the create operation of requested serializer.
Args:
serializer (_type_): serializer class object.
Returns:
_type_: Returns the saved details.
"""
return serializer.save()
def create(self, request, *args, **kwargs):
"""POST method: create action to save an organization object using User ID (IMPORTANT: Using USER ID instead of Organization ID)"""
try:
user_obj = User.objects.get(id=request.data.get(Constants.USER_ID))
user_org_queryset = UserOrganizationMap.objects.filter(user_id=request.data.get(Constants.USER_ID)).first()
if user_org_queryset:
return Response(
{"message": ["User is already associated with an organization"]},
status=status.HTTP_400_BAD_REQUEST,
)
else:
with transaction.atomic():
# create organization and userorganizationmap object
print("Creating org & user_org_map")
OrganizationSerializerValidator.validate_website(request.data)
org_serializer = OrganizationSerializer(data=request.data, partial=True)
org_serializer.is_valid(raise_exception=True)
org_queryset = self.perform_create(org_serializer)
user_org_serializer = UserOrganizationMapSerializer(
data={
Constants.USER: user_obj.id,
Constants.ORGANIZATION: org_queryset.id,
} # type: ignore
)
user_org_serializer.is_valid(raise_exception=True)
self.perform_create(user_org_serializer)
data = {
"user_map": user_org_serializer.data.get("id"),
"org_id": org_queryset.id,
"organization": org_serializer.data,
}
return Response(data, status=status.HTTP_201_CREATED)
except ValidationError as e:
return Response(e.detail, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
LOGGER.error(e,exc_info=True)
return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def list(self, request, *args, **kwargs):
"""GET method: query the list of Organization objects"""
try:
user_org_queryset = (
UserOrganizationMap.objects.select_related(Constants.USER, Constants.ORGANIZATION)
.filter(organization__status=True)
.all()
)
page = self.paginate_queryset(user_org_queryset)
user_organization_serializer = ParticipantSerializer(page, many=True)
return self.get_paginated_response(user_organization_serializer.data)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response(str(error), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def retrieve(self, request, pk):
"""GET method: retrieve an object of Organization using User ID of the User (IMPORTANT: Using USER ID instead of Organization ID)"""
try:
user_obj = User.objects.get(id=pk, status=True)
user_org_queryset = UserOrganizationMap.objects.prefetch_related(
Constants.USER, Constants.ORGANIZATION
).filter(user=pk)
if not user_org_queryset:
data = {Constants.USER: {"id": user_obj.id}, Constants.ORGANIZATION: "null"}
return Response(data, status=status.HTTP_200_OK)
org_obj = Organization.objects.get(id=user_org_queryset.first().organization_id)
user_org_serializer = OrganizationSerializer(org_obj)
data = {
Constants.USER: {"id": user_obj.id},
Constants.ORGANIZATION: user_org_serializer.data,
}
return Response(data, status=status.HTTP_200_OK)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response(str(error), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def update(self, request, pk):
"""PUT method: update or PUT request for Organization using User ID of the User (IMPORTANT: Using USER ID instead of Organization ID)"""
user_obj = User.objects.get(id=pk, status=True)
user_org_queryset = (
UserOrganizationMap.objects.prefetch_related(Constants.USER, Constants.ORGANIZATION).filter(user=pk).all()
)
if not user_org_queryset:
return Response({}, status=status.HTTP_404_NOT_FOUND) # 310-360 not covered 4
OrganizationSerializerValidator.validate_website(request.data)
organization_serializer = OrganizationSerializer(
Organization.objects.get(id=user_org_queryset.first().organization_id),
data=request.data,
partial=True,
)
try:
organization_serializer.is_valid(raise_exception=True)
self.perform_create(organization_serializer)
data = {
Constants.USER: {"id": pk},
Constants.ORGANIZATION: organization_serializer.data,
"user_map": user_org_queryset.first().id,
"org_id": user_org_queryset.first().organization_id,
}
return Response(
data,
status=status.HTTP_201_CREATED,
)
except ValidationError as e:
return Response(e.detail, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
LOGGER.error(e,exc_info=True)
return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def destroy(self, request, pk):
"""DELETE method: delete an object"""
try:
user_obj = User.objects.get(id=pk, status=True)
user_org_queryset = UserOrganizationMap.objects.select_related(Constants.ORGANIZATION).get(user_id=pk)
org_queryset = Organization.objects.get(id=user_org_queryset.organization_id)
org_queryset.status = False
self.perform_create(org_queryset)
return Response(status=status.HTTP_204_NO_CONTENT)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response(str(error), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class ParticipantViewSet(GenericViewSet):
"""
This class handles the participant CRUD operations.
"""
parser_class = JSONParser
serializer_class = UserCreateSerializer
queryset = User.objects.all()
pagination_class = CustomPagination
def perform_create(self, serializer):
"""
This function performs the create operation of requested serializer.
Args:
serializer (_type_): serializer class object.
Returns:
_type_: Returns the saved details.
"""
return serializer.save()
def generate_random_password(self, length=12):
"""Generates a random password with the given length."""
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(characters) for _ in range(length))
@authenticate_user(model=Organization)
@transaction.atomic
def create(self, request, *args, **kwargs):
"""POST method: create action to save an object by sending a POST request"""
OrganizationSerializerValidator.validate_website(request.data)
org_serializer = OrganizationSerializer(data=request.data, partial=True)
org_serializer.is_valid(raise_exception=True)
org_queryset = self.perform_create(org_serializer)
org_id = org_queryset.id
data=request.data.copy()
UserCreateSerializerValidator.validate_phone_number_format(request.data)
generated_password = self.generate_random_password()
hashed_password = make_password(generated_password)
# Add the hashed password to the request data
data.update({'password': hashed_password})
user_serializer = UserCreateSerializer(data=data)
user_serializer.is_valid(raise_exception=True)
user_saved = self.perform_create(user_serializer)
user_org_serializer = UserOrganizationMapSerializer(
data={
Constants.USER: user_saved.id,
Constants.ORGANIZATION: org_id,
} # type: ignore
)
user_org_serializer.is_valid(raise_exception=True)
self.perform_create(user_org_serializer)
try:
if user_saved.on_boarded_by:
# datahub_admin = User.objects.filter(id=user_saved.on_boarded_by).first()
admin_full_name = string_functions.get_full_name(
user_saved.on_boarded_by.first_name,
user_saved.on_boarded_by.last_name,
)
else:
datahub_admin = User.objects.filter(role_id=1).first()
admin_full_name = string_functions.get_full_name(datahub_admin.first_name, datahub_admin.last_name)
participant_full_name = string_functions.get_full_name(
request.data.get("first_name"), request.data.get("last_name")
)
data = {
Constants.datahub_name: os.environ.get(Constants.DATAHUB_NAME, Constants.datahub_name),
"as_user": "Co-Steward" if user_saved.role == 6 else "Participant",
"participant_admin_name": participant_full_name,
"participant_organization_name": request.data.get("name"),
"datahub_admin": admin_full_name,
"password": generated_password,
Constants.datahub_site: os.environ.get(Constants.DATAHUB_SITE, Constants.datahub_site),
}
email_render = render(request, Constants.WHEN_DATAHUB_ADMIN_ADDS_PARTICIPANT, data)
mail_body = email_render.content.decode("utf-8")
Utils().send_email(
to_email=request.data.get("email"),
content=mail_body,
subject=Constants.PARTICIPANT_ORG_ADDITION_SUBJECT
+ os.environ.get(Constants.DATAHUB_NAME, Constants.datahub_name),
)
except ValidationError as e:
return Response(e.detail, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
LOGGER.error(e,exc_info=True)
return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response(user_org_serializer.data, status=status.HTTP_201_CREATED)
def list(self, request, *args, **kwargs):
"""GET method: query all the list of objects from the Product model"""
on_boarded_by = request.GET.get("on_boarded_by", None)
co_steward = request.GET.get("co_steward", False)
approval_status = request.GET.get(Constants.APPROVAL_STATUS, True)
name = request.GET.get(Constants.NAME, "")
filter = {Constants.ORGANIZATION_NAME_ICONTAINS: name} if name else {}
if on_boarded_by:
roles = (
UserOrganizationMap.objects.select_related(Constants.USER, Constants.ORGANIZATION)
.filter(
user__status=True,
user__on_boarded_by=on_boarded_by,
user__role=3,
user__approval_status=approval_status,
**filter,
)
.order_by("-user__updated_at")
.all()
)
elif co_steward:
roles = (
UserOrganizationMap.objects.select_related(Constants.USER, Constants.ORGANIZATION)
.filter(user__status=True, user__role=6, **filter)
.order_by("-user__updated_at")
.all()
)
page = self.paginate_queryset(roles)
participant_serializer = ParticipantCostewardSerializer(page, many=True)
return self.get_paginated_response(participant_serializer.data)
else:
roles = (
UserOrganizationMap.objects.select_related(Constants.USER, Constants.ORGANIZATION)
.filter(
user__status=True,
user__role=3,
user__on_boarded_by=None,
user__approval_status=approval_status,
**filter,
)
.order_by("-user__updated_at")
.all()
)
page = self.paginate_queryset(roles)
participant_serializer = ParticipantSerializer(page, many=True)
return self.get_paginated_response(participant_serializer.data)
def retrieve(self, request, pk):
"""GET method: retrieve an object or instance of the Product model"""
roles = (
UserOrganizationMap.objects.prefetch_related(Constants.USER, Constants.ORGANIZATION)
.filter(user__status=True, user=pk)
.first()
)
participant_serializer = ParticipantSerializer(roles, many=False)
if participant_serializer.data:
return Response(participant_serializer.data, status=status.HTTP_200_OK)
return Response([], status=status.HTTP_200_OK)
@authenticate_user(model=Organization)
@transaction.atomic
def update(self, request, *args, **kwargs):
"""PUT method: update or send a PUT request on an object of the Product model"""
try:
participant = self.get_object()
user_serializer = self.get_serializer(participant, data=request.data, partial=True)
user_serializer.is_valid(raise_exception=True)
organization = Organization.objects.get(id=request.data.get(Constants.ID))
OrganizationSerializerValidator.validate_website(request.data)
organization_serializer = OrganizationSerializer(organization, data=request.data, partial=True)
organization_serializer.is_valid(raise_exception=True)
user_data = self.perform_create(user_serializer)
self.perform_create(organization_serializer)
if user_data.on_boarded_by:
admin_full_name = string_functions.get_full_name(user_data.first_name, user_data.last_name)
else:
datahub_admin = User.objects.filter(role_id=1).first()
admin_full_name = string_functions.get_full_name(datahub_admin.first_name, datahub_admin.last_name)
participant_full_name = string_functions.get_full_name(participant.first_name, participant.last_name)
data = {
Constants.datahub_name: os.environ.get(Constants.DATAHUB_NAME, Constants.datahub_name),
"participant_admin_name": participant_full_name,
"participant_organization_name": organization.name,
"datahub_admin": admin_full_name,
Constants.datahub_site: os.environ.get(Constants.DATAHUB_SITE, Constants.datahub_site),
}
# update data & trigger_email
email_render = render(request, Constants.DATAHUB_ADMIN_UPDATES_PARTICIPANT_ORGANIZATION, data)
mail_body = email_render.content.decode("utf-8")
Utils().send_email(
to_email=participant.email,
content=mail_body,
subject=Constants.PARTICIPANT_ORG_UPDATION_SUBJECT
+ os.environ.get(Constants.DATAHUB_NAME, Constants.datahub_name),
)
data = {
Constants.USER: user_serializer.data,
Constants.ORGANIZATION: organization_serializer.data,
}
return Response(data, status=status.HTTP_201_CREATED)
except ValidationError as e:
return Response(e.detail, status=status.HTTP_400_BAD_REQUEST)
except Exception as e:
LOGGER.error(e,exc_info=True)
return Response(str(e), status=status.HTTP_500_INTERNAL_SERVER_ERROR)
@authenticate_user(model=Organization)
def destroy(self, request, pk):
"""DELETE method: delete an object"""
participant = self.get_object()
user_organization = (
UserOrganizationMap.objects.select_related(Constants.ORGANIZATION).filter(user_id=pk).first()
)
organization = Organization.objects.get(id=user_organization.organization_id)
if participant.status:
participant.status = False
try:
if participant.on_boarded_by:
datahub_admin = participant.on_boarded_by
else:
datahub_admin = User.objects.filter(role_id=1).first()
admin_full_name = string_functions.get_full_name(datahub_admin.first_name, datahub_admin.last_name)
participant_full_name = string_functions.get_full_name(participant.first_name, participant.last_name)
data = {
Constants.datahub_name: os.environ.get(Constants.DATAHUB_NAME, Constants.datahub_name),
"participant_admin_name": participant_full_name,
"participant_organization_name": organization.name,
"datahub_admin": admin_full_name,
Constants.datahub_site: os.environ.get(Constants.DATAHUB_SITE, Constants.datahub_site),
}
# delete data & trigger_email
self.perform_create(participant)
email_render = render(
request,
Constants.DATAHUB_ADMIN_DELETES_PARTICIPANT_ORGANIZATION,
data,
)
mail_body = email_render.content.decode("utf-8")
Utils().send_email(
to_email=participant.email,
content=mail_body,
subject=Constants.PARTICIPANT_ORG_DELETION_SUBJECT
+ os.environ.get(Constants.DATAHUB_NAME, Constants.datahub_name),
)
# Set the on_boarded_by_id to null if co_steward is deleted
User.objects.filter(on_boarded_by=pk).update(on_boarded_by=None)
return Response(
{"message": ["Participant deleted"]},
status=status.HTTP_204_NO_CONTENT,
)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response({"message": ["Internal server error"]}, status=500)
elif participant.status is False:
return Response(
{"message": ["participant/co-steward already deleted"]},
status=status.HTTP_204_NO_CONTENT,
)
return Response({"message": ["Internal server error"]}, status=500)
@action(detail=False, methods=["post"], permission_classes=[AllowAny])
def get_list_co_steward(self, request, *args, **kwargs):
try:
users = (
User.objects.filter(role__id=6, status=True)
.values("id", "userorganizationmap__organization__name")
.distinct("userorganizationmap__organization__name")
)
data = [
{
"user": user["id"],
"organization_name": user["userorganizationmap__organization__name"],
}
for user in users
]
return Response(data, status=200)
except Exception as e:
LOGGER.error(e, exc_info=True)
return Response({"message": str(e)}, status=500)
class MailInvitationViewSet(GenericViewSet):
"""
This class handles the mail invitation API views.
"""
def create(self, request, *args, **kwargs):
"""
This will send the mail to the requested user with content.
Args:
request (_type_): Api request object.
Returns:
_type_: Retuns the sucess response with message and status code.
"""
try:
email_list = request.data.get("to_email")
emails_found, emails_not_found = ([] for i in range(2))
# for email in email_list:
# if User.objects.filter(email=email):
# emails_found.append(email)
# else:
# emails_not_found.append(email)
user = User.objects.filter(role_id=1).first()
full_name = user.first_name + " " + str(user.last_name) if user.last_name else user.first_name
data = {
"datahub_name": os.environ.get("DATAHUB_NAME", "datahub_name"),
"participant_admin_name": full_name,
"datahub_site": os.environ.get("DATAHUB_SITE", "datahub_site"),
}
# render email from query_email template
for email in email_list:
try:
email_render = render(request, "datahub_admin_invites_participants.html", data)
mail_body = email_render.content.decode("utf-8")
Utils().send_email(
to_email=[email],
content=mail_body,
subject=os.environ.get("DATAHUB_NAME", "datahub_name")
+ Constants.PARTICIPANT_INVITATION_SUBJECT,
)
emails_found.append(email)
except Exception as e:
emails_not_found.append()
failed = f"No able to send emails to this emails: {emails_not_found}"
LOGGER.warning(failed)
return Response(
{
"message": f"Email successfully sent to {emails_found}",
"failed": failed,
},
status=status.HTTP_200_OK,
)
except ValidationError as e:
return Response(e.detail, status=status.HTTP_400_BAD_REQUEST)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response(
{"Error": f"Failed to send email"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR,
) # type: ignore
class DropDocumentView(GenericViewSet):
"""View for uploading organization document files"""
parser_class = MultiPartParser
serializer_class = DropDocumentSerializer
def create(self, request, *args, **kwargs):
"""Saves the document files in temp location before saving"""
serializer = self.get_serializer(data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
try:
# get file, file name & type from the form-data
key = list(request.data.keys())[0]
file = serializer.validated_data[key]
file_type = str(file).split(".")[-1]
file_name = str(key) + "." + file_type
file_operations.remove_files(file_name, settings.TEMP_FILE_PATH)
file_operations.file_save(file, file_name, settings.TEMP_FILE_PATH)
return Response(
{key: [f"{file_name} uploading in progress ..."]},
status=status.HTTP_201_CREATED,
)
except ValidationError as e:
return Response(e.detail, status=status.HTTP_400_BAD_REQUEST)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
@action(detail=False, methods=["delete"])
def delete(self, request):
"""remove the dropped documents"""
try:
key = list(request.data.keys())[0]
file_operations.remove_files(key, settings.TEMP_FILE_PATH)
return Response({}, status=status.HTTP_204_NO_CONTENT)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class DocumentSaveView(GenericViewSet):
"""View for uploading all the datahub documents and content"""
serializer_class = PolicyDocumentSerializer
queryset = DatahubDocuments.objects.all()
@action(detail=False, methods=["get"])
def get(self, request):
"""GET method: retrieve an object or instance of the Product model"""
try:
file_paths = file_operations.file_path(settings.DOCUMENTS_URL)
datahub_obj = DatahubDocuments.objects.last()
content = {
Constants.GOVERNING_LAW: datahub_obj.governing_law if datahub_obj else None,
Constants.PRIVACY_POLICY: datahub_obj.privacy_policy if datahub_obj else None,
Constants.TOS: datahub_obj.tos if datahub_obj else None,
Constants.LIMITATIONS_OF_LIABILITIES: datahub_obj.limitations_of_liabilities if datahub_obj else None,
Constants.WARRANTY: datahub_obj.warranty if datahub_obj else None,
}
documents = {
Constants.GOVERNING_LAW: file_paths.get("governing_law"),
Constants.PRIVACY_POLICY: file_paths.get("privacy_policy"),
Constants.TOS: file_paths.get("tos"),
Constants.LIMITATIONS_OF_LIABILITIES: file_paths.get("limitations_of_liabilities"),
Constants.WARRANTY: file_paths.get("warranty"),
}
if not datahub_obj and not file_paths:
data = {"content": content, "documents": documents}
return Response(data, status=status.HTTP_200_OK)
elif not datahub_obj:
data = {"content": content, "documents": documents}
return Response(data, status=status.HTTP_200_OK)
elif datahub_obj and not file_paths:
data = {"content": content, "documents": documents}
return Response(data, status=status.HTTP_200_OK)
elif datahub_obj and file_paths:
data = {"content": content, "documents": documents}
return Response(data, status=status.HTTP_200_OK)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response({}, status=status.HTTP_404_NOT_FOUND)
def create(self, request, *args, **kwargs):
try:
serializer = self.get_serializer(data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
with transaction.atomic():
serializer.save()
# save the document files
file_operations.create_directory(settings.DOCUMENTS_ROOT, [])
file_operations.files_move(settings.TEMP_FILE_PATH, settings.DOCUMENTS_ROOT)
return Response(
{"message": "Documents and content saved!"},
status=status.HTTP_201_CREATED,
)
except ValidationError as e:
return Response(e.detail, status=status.HTTP_400_BAD_REQUEST)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
@action(detail=False, methods=["get"])
def put(self, request, *args, **kwargs):
"""Saves the document content and files"""
try:
# instance = self.get_object()
datahub_obj = DatahubDocuments.objects.last()
serializer = self.get_serializer(datahub_obj, data=request.data)
serializer.is_valid(raise_exception=True)
with transaction.atomic():
serializer.save()
file_operations.create_directory(settings.DOCUMENTS_ROOT, [])
file_operations.files_move(settings.TEMP_FILE_PATH, settings.DOCUMENTS_ROOT)
return Response(
{"message": "Documents and content updated!"},
status=status.HTTP_201_CREATED,
)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
class DatahubThemeView(GenericViewSet):
"""View for modifying datahub branding"""
parser_class = MultiPartParser
serializer_class = DatahubThemeSerializer
def create(self, request, *args, **kwargs):
"""generates the override css for datahub"""
# user = User.objects.filter(email=request.data.get("email", ""))
# user = user.first()
data = {}
try:
banner = request.data.get("banner", "null")
banner = None if banner == "null" else banner
button_color = request.data.get("button_color", "null")
button_color = None if button_color == "null" else button_color
if not banner and not button_color:
data = {"banner": "null", "button_color": "null"}
elif banner and not button_color:
file_name = file_operations.file_rename(str(banner), "banner")
shutil.rmtree(settings.THEME_ROOT)
os.mkdir(settings.THEME_ROOT)
os.makedirs(settings.CSS_ROOT)
file_operations.file_save(banner, file_name, settings.THEME_ROOT)
data = {"banner": file_name, "button_color": "null"}
elif not banner and button_color:
css = ".btn { background-color: " + button_color + "; }"
file_operations.remove_files(file_name, settings.THEME_ROOT)
file_operations.file_save(
ContentFile(css),
settings.CSS_FILE_NAME,
settings.CSS_ROOT,
)
data = {"banner": "null", "button_color": settings.CSS_FILE_NAME}
elif banner and button_color:
shutil.rmtree(settings.THEME_ROOT)
os.mkdir(settings.THEME_ROOT)
os.makedirs(settings.CSS_ROOT)
file_name = file_operations.file_rename(str(banner), "banner")
file_operations.remove_files(file_name, settings.THEME_ROOT)
file_operations.file_save(banner, file_name, settings.THEME_ROOT)
css = ".btn { background-color: " + button_color + "; }"
file_operations.remove_files(file_name, settings.THEME_ROOT)
file_operations.file_save(
ContentFile(css),
settings.CSS_FILE_NAME,
settings.CSS_ROOT,
)
data = {"banner": file_name, "button_color": settings.CSS_FILE_NAME}
# set datahub admin user status to True
# user.on_boarded = True
# user.save()
return Response(data, status=status.HTTP_201_CREATED)
except ValidationError as e:
return Response(e.detail, status=status.HTTP_400_BAD_REQUEST)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
@action(detail=False, methods=["get"])
def get(self, request):
"""retrieves Datahub Theme attributes"""
file_paths = file_operations.file_path(settings.THEME_URL)
# css_path = file_operations.file_path(settings.CSS_ROOT)
css_path = settings.CSS_ROOT + settings.CSS_FILE_NAME
data = {}
try:
css_attribute = file_operations.get_css_attributes(css_path, "background-color")
if not css_path and not file_paths:
data = {"banner": "null", "css": "null"}
elif not css_path:
data = {"banner": file_paths, "css": "null"}
elif css_path and not file_paths:
data = {"banner": "null", "css": {"btnBackground": css_attribute}}
elif css_path and file_paths:
data = {"banner": file_paths, "css": {"btnBackground": css_attribute}}
return Response(data, status=status.HTTP_200_OK)
except Exception as error:
LOGGER.error(error, exc_info=True)
return Response({}, status=status.HTTP_400_BAD_REQUEST)
@action(detail=False)
def put(self, request, *args, **kwargs):
data = {}
try:
banner = request.data.get("banner", "null")