Skip to content

Commit

Permalink
refactor: improve user creation and profile management
Browse files Browse the repository at this point in the history
- Updated user profile view to enhance response formatting and error handling.
- Refactored user email setup logic for better readability.
- Introduced company_name field in KeycloakUserDTO for user creation.
- Adjusted CommerceSerializer to include organization_name during user creation.
- Cleaned up code formatting for improved maintainability.
  • Loading branch information
ericosta-dev committed Dec 4, 2024
1 parent 2c47ad8 commit 545b08c
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 35 deletions.
62 changes: 34 additions & 28 deletions connect/api/v1/account/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
ChangePasswordSerializer,
ChangeLanguageSerializer,
SearchUserSerializer,
UserEmailSetupSerializer
UserEmailSetupSerializer,
)
from connect.api.v1.keycloak import KeycloakControl
from connect.authentication.models import User
Expand Down Expand Up @@ -83,7 +83,9 @@ def upload_photo(self, request, **kwargs): # pragma: no cover
user.save(update_fields=["photo"])

# Update avatar on integrations
celery_app.send_task("update_user_photo", args=[user.email, self._get_photo_url(user)])
celery_app.send_task(
"update_user_photo", args=[user.email, self._get_photo_url(user)]
)

# Update avatar in all rocket chat registered
for authorization in user.authorizations_user.all():
Expand Down Expand Up @@ -180,7 +182,9 @@ def set_two_factor_authentication(self, request, **kwargs):
OrganizationAuthorization.set_2fa(user)
return Response(status=status.HTTP_200_OK, data={"email": user.email})
else:
return Response(status=status.HTTP_404_NOT_FOUND, data={"response": response})
return Response(
status=status.HTTP_404_NOT_FOUND, data={"response": response}
)

@action(
detail=True,
Expand Down Expand Up @@ -214,20 +218,18 @@ def add_additional_information(self, request, **kwargs):
"last_update_profile",
"position",
"company_segment",
"company_phone_number"
"company_phone_number",
]

if "utm" in user_info:
user.utm = user_info.get("utm")
updated_fields.append("utm")

user.save(
update_fields=updated_fields
)
user.save(update_fields=updated_fields)
data = dict(
send_request_flow=settings.SEND_REQUEST_FLOW,
flow_uuid=settings.FLOW_MARKETING_UUID,
token_authorization=settings.TOKEN_AUTHORIZATION_FLOW_MARKETING
token_authorization=settings.TOKEN_AUTHORIZATION_FLOW_MARKETING,
)
user.send_request_flow_user_info(data)
response = dict(
Expand All @@ -237,14 +239,18 @@ def add_additional_information(self, request, **kwargs):
segment=user.company_segment,
number_people=user.number_people,
weni_helps=user.weni_helps,
company_phone_number=user.company_phone_number
company_phone_number=user.company_phone_number,
),
user=dict(
phone=user.phone,
last_update_profile=user.last_update_profile,
position=user.position.split(":")[1] if user.position and "other:" in user.position else user.position,
utm=user.utm
)
position=(
user.position.split(":")[1]
if user.position and "other:" in user.position
else user.position
),
utm=user.utm,
),
)
return Response(status=200, data=response)
except Exception as e:
Expand All @@ -262,7 +268,9 @@ def receive_emails(self, request, **kwargs):
try:
setup = user.email_setup
if "receive_organization_emails" in data.keys():
setup.receive_organization_emails = data.get("receive_organization_emails")
setup.receive_organization_emails = data.get(
"receive_organization_emails"
)
setup.save(update_fields=["receive_organization_emails"])
if "receive_project_emails" in data.keys():
setup.receive_project_emails = data.get("receive_project_emails")
Expand All @@ -276,7 +284,9 @@ def receive_emails(self, request, **kwargs):
response = UserEmailSetupSerializer(setup).data
return Response(status=200, data=response)
except Exception as e:
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR, data={"message": e})
return Response(
status=status.HTTP_500_INTERNAL_SERVER_ERROR, data={"message": e}
)

@action(
detail=True,
Expand All @@ -294,18 +304,16 @@ def get_user_company_info(self, request, **kwargs):
organization = authorization.organization
first_user = organization.authorizations.order_by("created_at").first().user

if first_user.id != user.id:
organization_data = dict(
uuid=str(organization.uuid),
name=organization.name,
authorization=authorization.role
)
response.append(
dict(
organization=organization_data,
company=first_user.get_company_data
)
organization_data = dict(
uuid=str(organization.uuid),
name=organization.name,
authorization=authorization.role,
)
response.append(
dict(
organization=organization_data, company=first_user.get_company_data
)
)

return Response(status=status.HTTP_200_OK, data=response)

Expand Down Expand Up @@ -334,9 +342,7 @@ class SearchUserViewSet(mixins.ListModelMixin, GenericViewSet): # pragma: no co

def list(self, request, *args, **kwargs):
if len(request.query_params.get("search", "")) == 0:
raise ValidationError(
_("The search field needed the text to search.")
)
raise ValidationError(_("The search field needed the text to search."))
queryset = self.filter_queryset(self.get_queryset())[: self.limit]
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
7 changes: 5 additions & 2 deletions connect/api/v2/commerce/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,13 @@ def create(self, validated_data):
try:
# Create Keycloak user
try:
user_dto = KeycloakUserDTO(email=user_email)
user_dto = KeycloakUserDTO(
email=user_email,
company_name=validated_data.get("organization_name"),
)
create_keycloak_user_use_case = CreateKeycloakUserUseCase(user_dto)
user_info = create_keycloak_user_use_case.execute()
except Exception as e:
except Exception:
raise serializers.ValidationError(
{"user_email": "User already exists in Keycloak"}
)
Expand Down
5 changes: 0 additions & 5 deletions connect/api/v2/commerce/views.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
from django.db import transaction
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import GenericViewSet

from connect.api.v2.commerce.permissions import CanCommunicateInternally
from connect.api.v2.commerce.serializers import CommerceSerializer
from connect.api.v2.organizations.serializers import OrganizationSeralizer
from connect.api.v2.paginations import CustomCursorPagination
from connect.api.v2.projects.serializers import ProjectSerializer
from connect.common.models import Organization
from connect.usecases.users.create import CreateKeycloakUserUseCase
from connect.usecases.users.user_dto import KeycloakUserDTO


class CommerceOrganizationViewSet(GenericViewSet):
Expand Down
1 change: 1 addition & 0 deletions connect/usecases/users/create.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ def execute(self) -> dict:
user = User.objects.create_user(
username=self.user_dto.username,
email=self.user_dto.username,
company_name=self.user_dto.company_name,
)

return {
Expand Down
1 change: 1 addition & 0 deletions connect/usecases/users/user_dto.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class KeycloakUserDTO:
first_name: str = ""
last_name: str = ""
credentials: List[Dict] = None
company_name: str = ""

def __post_init__(self):
self.username = self.email

0 comments on commit 545b08c

Please sign in to comment.