Skip to content

Commit

Permalink
feat: adding project type and view to set project type
Browse files Browse the repository at this point in the history
  • Loading branch information
ericosta-dev committed Nov 13, 2024
1 parent 46d36e5 commit d9aaa43
Show file tree
Hide file tree
Showing 6 changed files with 308 additions and 155 deletions.
138 changes: 74 additions & 64 deletions connect/api/v2/projects/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
OpenedProject,
ProjectRole,
TemplateProject,
TypeProject,
)
from connect.internals.event_driven.producer.rabbitmq_publisher import RabbitmqPublisher
from connect.template_projects.models import TemplateType
Expand Down Expand Up @@ -52,7 +53,8 @@ class Meta:
"authorization",
"project_type",
"description",
"brain_on"
"brain_on",
"type",
]
ref_name = None

Expand All @@ -78,6 +80,7 @@ class Meta:
authorization = serializers.SerializerMethodField(style={"show": False})
project_type = serializers.SerializerMethodField()
brain_on = serializers.BooleanField(default=False)
type = serializers.ChoiceField(choices=TypeProject.choices)

def get_project_type(self, obj):
if obj.is_template:
Expand All @@ -91,16 +94,18 @@ def create(self, validated_data):

template_uuid = self.context["request"].data.get("uuid")
is_template = self.context["request"].data.get("template", False)
brain_on = self.context["request"].data.get('brain_on', False)
brain_on = self.context["request"].data.get("brain_on", False)

if extra_data:
template_uuid = extra_data.get("uuid", template_uuid)
is_template = extra_data.get("template", is_template)
brain_on = extra_data.get('brain_on', False)
brain_on = extra_data.get("brain_on", False)
project_template_type = None
template_name = "blank"
if is_template:
project_template_type_queryset = TemplateType.objects.filter(uuid=template_uuid)
project_template_type_queryset = TemplateType.objects.filter(
uuid=template_uuid
)
if project_template_type_queryset.exists():
project_template_type = project_template_type_queryset.first()
template_name = project_template_type.name
Expand All @@ -112,7 +117,8 @@ def create(self, validated_data):
created_by=user,
template_type=template_name,
project_template_type=project_template_type,
description=validated_data.get("description", None)
description=validated_data.get("description", None),
type=validated_data.get("type", TypeProject.GENERAL),
)

self.send_request_flow_product(user)
Expand All @@ -122,71 +128,79 @@ def create(self, validated_data):
extra_data.update(
{
"project": instance.uuid,
"authorization": instance.get_user_authorization(user).uuid
"authorization": instance.get_user_authorization(user).uuid,
}
)

template_serializer = TemplateProjectSerializer(data=extra_data, context=self.context["request"])
template_serializer = TemplateProjectSerializer(
data=extra_data, context=self.context["request"]
)
template_serializer.is_valid()
template_project = template_serializer.save()

if type(template_project) == dict:
if isinstance(template_project, dict):
return template_project

return instance

def publish_create_project_message(
self,
instance,
brain_on: bool = False
):
def publish_create_project_message(self, instance, brain_on: bool = False):

authorizations = []
for authorization in instance.organization.authorizations.all():
if authorization.can_contribute:
authorizations.append({"user_email": authorization.user.email, "role": authorization.role})
authorizations.append(
{"user_email": authorization.user.email, "role": authorization.role}
)

extra_fields = self.context["request"].data.get("globals")
if extra_fields is None:
extra_fields = self.context["request"].data.get("project", {}).get("globals", {})
extra_fields = (
self.context["request"].data.get("project", {}).get("globals", {})
)

message_body = {
"uuid": str(instance.uuid),
"name": instance.name,
"is_template": instance.is_template,
"user_email": instance.created_by.email if instance.created_by else None,
"date_format": instance.date_format,
"template_type_uuid": str(instance.project_template_type.uuid) if instance.project_template_type else None,
"template_type_uuid": (
str(instance.project_template_type.uuid)
if instance.project_template_type
else None
),
"timezone": str(instance.timezone),
"organization_id": instance.organization.inteligence_organization,
"extra_fields": extra_fields if instance.is_template else {},
"authorizations": authorizations,
"description": instance.description,
"organization_uuid": str(instance.organization.uuid),
"brain_on": brain_on,
"type": instance.type,
}
rabbitmq_publisher = RabbitmqPublisher()
rabbitmq_publisher.send_message(message_body, exchange="projects.topic", routing_key="")
rabbitmq_publisher.send_message(
message_body, exchange="projects.topic", routing_key=""
)

def send_request_flow_product(self, user):

if Project.objects.filter(created_by=user).count() == 1:
data = dict(
send_request_flow=settings.SEND_REQUEST_FLOW_PRODUCT,
flow_uuid=settings.FLOW_PRODUCT_UUID,
token_authorization=settings.TOKEN_AUTHORIZATION_FLOW_PRODUCT
token_authorization=settings.TOKEN_AUTHORIZATION_FLOW_PRODUCT,
)
celery_app.send_task("send_user_flow_info", args=[data, user.email])

def update(self, instance, validated_data):
name = validated_data.get("name", instance.name)
description = validated_data.get("description", instance.description)
message_body = {
"project_uuid": str(instance.uuid),
"description": description
}
message_body = {"project_uuid": str(instance.uuid), "description": description}
rabbitmq_publisher = RabbitmqPublisher()
rabbitmq_publisher.send_message(message_body, exchange="update-projects.topic", routing_key="")
rabbitmq_publisher.send_message(
message_body, exchange="update-projects.topic", routing_key=""
)
celery_app.send_task(
"update_project",
args=[instance.uuid, name],
Expand All @@ -206,7 +220,9 @@ def get_authorization(self, obj):
).data
return data

def create_flows_project(self, data: dict, user: User, is_template: bool, project_uuid: str):
def create_flows_project(
self, data: dict, user: User, is_template: bool, project_uuid: str
):
flow_instance = FlowsRESTClient()
created = False
try:
Expand All @@ -229,7 +245,7 @@ def create_flows_project(self, data: dict, user: User, is_template: bool, projec
except Exception as error:
flows_info = {
"data": {"message": "Could not create project"},
"status": status.HTTP_500_INTERNAL_SERVER_ERROR
"status": status.HTTP_500_INTERNAL_SERVER_ERROR,
}
logger.error(f"Could not create project {error}")

Expand Down Expand Up @@ -272,11 +288,13 @@ def validate_project_authorization(self, authorization):
if authorization.role == 0:
return False, {
"message": "Project authorization not setted",
"status": status.HTTP_500_INTERNAL_SERVER_ERROR
"status": status.HTTP_500_INTERNAL_SERVER_ERROR,
}
return True, {}

def create_globals_omie(self, project: Project, user_email: str): # pragma: no cover
def create_globals_omie(
self, project: Project, user_email: str
): # pragma: no cover
from connect.api.v1.internal.flows.mp9.client_omie import Omie

response_data = {}
Expand All @@ -291,12 +309,15 @@ def create_globals_omie(self, project: Project, user_email: str): # pragma: no
else:
globals_dict = data.get("project").get("globals")

if project.template_type in [Project.TYPE_OMIE_PAYMENT_FINANCIAL, Project.TYPE_OMIE_PAYMENT_FINANCIAL_CHAT_GPT]:
if project.template_type in [
Project.TYPE_OMIE_PAYMENT_FINANCIAL,
Project.TYPE_OMIE_PAYMENT_FINANCIAL_CHAT_GPT,
]:
default_globals = {
"nome_da_empresa": f"{project.name}",
"nome_do_bot": f"{project.name}",
"status_boleto_para_desconsiderar": "Recebido, Cancelado",
"tipo_credenciamento": "email"
"tipo_credenciamento": "email",
}
elif project.template_type in [Project.TYPE_OMIE_LEAD_CAPTURE]:
default_globals = {
Expand All @@ -308,17 +329,13 @@ def create_globals_omie(self, project: Project, user_email: str): # pragma: no

flow_organization = str(project.flow_organization)
try:
omie.create_globals(
flow_organization,
user_email,
globals_dict
)
omie.create_globals(flow_organization, user_email, globals_dict)
created = True
except Exception as error:
logger.error(f"Create globals: {error}")
response_data = {
"data": {"message": "Could not create global"},
"status": status.HTTP_500_INTERNAL_SERVER_ERROR
"status": status.HTTP_500_INTERNAL_SERVER_ERROR,
}
return created, response_data

Expand All @@ -330,7 +347,7 @@ def create(self, validated_data):
wa_demo_token="wa-demo-12345",
redirect_url="https://wa.me/5582123456?text=wa-demo-12345",
flow_uuid=None,
classifier_uuid=None
classifier_uuid=None,
)

return template
Expand All @@ -342,17 +359,18 @@ def _create(self, validated_data):
data = {}
if project.template_type in Project.HAS_GLOBALS:

common_templates = [Project.TYPE_SAC_CHAT_GPT, Project.TYPE_LEAD_CAPTURE_CHAT_GPT]
common_templates = [
Project.TYPE_SAC_CHAT_GPT,
Project.TYPE_LEAD_CAPTURE_CHAT_GPT,
]

if project.template_type in common_templates:
created, data = self.create_globals(
str(project.flow_organization),
str(authorization.user.email)
str(project.flow_organization), str(authorization.user.email)
)
else:
created, data = self.create_globals_omie(
project,
str(authorization.user.email)
project, str(authorization.user.email)
)

if not created:
Expand All @@ -364,15 +382,15 @@ def _create(self, validated_data):
# Project delete
return message

ok, access_token = project.organization.get_ai_access_token(authorization.user.email, project)
ok, access_token = project.organization.get_ai_access_token(
authorization.user.email, project
)
if not ok:
# Project delete
return access_token

created, classifier_uuid = project.create_classifier(
authorization,
project.template_type,
access_token
authorization, project.template_type, access_token
)
if not created:
# Project delete
Expand All @@ -391,7 +409,7 @@ def _create(self, validated_data):
wa_demo_token="wa-demo-12345",
redirect_url="https://wa.me/5582123456?text=wa-demo-12345",
flow_uuid=flow_uuid,
classifier_uuid=classifier_uuid
classifier_uuid=classifier_uuid,
)

return template
Expand All @@ -413,10 +431,7 @@ def create_globals(self, project_uuid: str, user_email: str): # pragma: no cove
globals_list = []

for key, value in globals_dict.items():
payload = {
"name": key,
"value": value
}
payload = {"name": key, "value": value}
payload.update(body)
globals_list.append(payload)

Expand All @@ -431,7 +446,7 @@ def create_globals(self, project_uuid: str, user_email: str): # pragma: no cove
logger.error(f"Create globals: {error}")
response_data = {
"data": {"message": "Could not create global"},
"status": status.HTTP_500_INTERNAL_SERVER_ERROR
"status": status.HTTP_500_INTERNAL_SERVER_ERROR,
}
created = False
return created, response_data
Expand All @@ -441,13 +456,7 @@ class ProjectUpdateSerializer(serializers.ModelSerializer):

class Meta:
model = Project
fields = [
"name",
"timezone",
"date_format",
"uuid",
"description"
]
fields = ["name", "timezone", "date_format", "uuid", "description"]
ref_name = None

name = serializers.CharField(max_length=500, required=False)
Expand Down Expand Up @@ -493,7 +502,9 @@ def get_authorizations(self, obj):

def get_existing_authorizations(self, obj):
exclude_roles = [ProjectRole.SUPPORT.value]
queryset = obj.project_authorizations.exclude(role__in=exclude_roles).select_related('user')
queryset = obj.project_authorizations.exclude(
role__in=exclude_roles
).select_related("user")

return [
{
Expand Down Expand Up @@ -533,7 +544,9 @@ def get_pending_authorizations_data(self, obj):
]

def get_pending_rocketchat_role(self, email):
rocket_authorization = RequestRocketPermission.objects.filter(email=email).first()
rocket_authorization = RequestRocketPermission.objects.filter(
email=email
).first()

if rocket_authorization:
return rocket_authorization.role
Expand All @@ -559,9 +572,6 @@ class Meta:
project = serializers.SerializerMethodField()

def get_project(self, obj):
data = ProjectSerializer(
obj.project,
context=self.context
).data
data = ProjectSerializer(obj.project, context=self.context).data

return data
Loading

0 comments on commit d9aaa43

Please sign in to comment.