File: //proc/thread-self/root/home/arjun/projects/buyercall/buyercall/blueprints/chat/endpoints.py
from uuid import uuid4
from datetime import datetime, timedelta
import logging as log
from flask import Blueprint, request, current_app
from flask_login import current_user
from buyercall.blueprints.chat.utils import authenticate
from buyercall.lib.util_rest import api_jsonify
from buyercall.blueprints.widgets.models import Widget
from buyercall.extensions import es_client
from buyercall.integrations.elasticsearch.utilities import insert_data_by_index, search_data
from buyercall.blueprints.chat.utils import ask_rasa
from buyercall.blueprints import flask_environment
from buyercall.blueprints.widgets.routing import get_available_agent_ids
from elasticsearch_dsl import Q
chat_api = Blueprint('chat_api', __name__, url_prefix='/api/chat')
logger = log.getLogger(__name__)
def validate_from_to(chat_from=None, chat_to=None, *args, **kwargs):
"""
This method validates the received from and to of chat and finds who is user and agent.
user's id contains the string 'USER' and agent's id contains the string 'AGENT'.
:chat_from param: str
:chat_to param: str
:return dict: {user: str, agent: str, success: bool}
"""
if chat_from and not chat_to:
if chat_from.count('-') == 10:
if 'USER' in chat_from:
if len(chat_from) == 78:
return {'user': chat_from, 'agent': None, 'success': True}
return {'user': None, 'agent': None, 'success': False}
elif 'AGENT' in chat_from:
if len(chat_from) == 79:
return {'user': None, 'agent': chat_from, 'success': True}
return {'user': None, 'agent': None, 'success': False}
return {'user': None, 'agent': None, 'success': False}
return {'user': None, 'agent': None, 'success': False}
elif not chat_from and chat_to:
if chat_to.count('-') == 10:
if 'USER' in chat_to:
if len(chat_from) == 78:
return {'user': chat_to, 'agent': None, 'success': True}
return {'user': None, 'agent': None, 'success': False}
elif 'AGENT' in chat_to:
if len(chat_from) == 79:
return {'user': None, 'agent': chat_to, 'success': True}
return {'user': None, 'agent': None, 'success': False}
return {'user': None, 'agent': None, 'success': False}
return {'user': None, 'agent': None, 'success': False}
elif chat_from and chat_to:
if chat_from.count('-') == 10 and chat_to.count('-') == 10:
user = chat_from if 'USER' in chat_from else chat_to
agent = chat_from if 'AGENT' in chat_from else chat_to
if 'USER' in user and 'AGENT' in agent:
if len(user) == 78 and len(agent) == 79:
return {'user': user, 'agent': agent, 'success': True}
return {'user': None, 'agent': None, 'success': False}
return {'user': None, 'agent': None, 'success': False}
return {'user': None, 'agent': None, 'success': False}
return {'user': None, 'agent': None, 'success': False}
def create_task(received=None):
""" Create a task for agent """
if not received:
received = request.get_json()
if received:
task_type = received.get('type', 'CUSTOM_TASK_FOLLOW_UP')
agents = received.get('agents', [])
partnership_sid = received.get('partnershipId', None)
partnership_account_sid = received.get('partnershipAccountId', None)
interaction = received.get('interaction', None)
action_user_sid = current_user.sid
# action_user_sid = '8ce3921e-3744-4fbd-af82-bcfe7653389a'
if partnership_sid and partnership_account_sid:
from buyercall.blueprints.partnership.models import Partnership
# Validate partnership
partnership = Partnership.query.filter(Partnership.sid == partnership_sid).first()
if not partnership:
return api_jsonify([], 422, "Invalid request parameters!", False)
# Validate users
from buyercall.blueprints.agents.models import Agent
log_state = flask_environment()
index_name = f'buyercall-interaction-task-{log_state}'
from buyercall.blueprints.user.tasks import put_to_elasticsearch
for agent in agents:
ag = Agent.query.filter(Agent.sid == agent).first()
if not ag:
return api_jsonify([], 422, "Invalid request parameters!", False)
# Insert to es
es_data = {
'task_id': uuid4(),
'is_viewed': False,
'task_type': task_type,
'created_at': datetime.utcnow(),
'updated_at': datetime.utcnow(),
'due_date': datetime.utcnow() + timedelta(days=3), # Defaulted to 3 days
'partnership_id': partnership_sid,
'partnership_account_id': str(partnership_account_sid),
'status': 'OPEN',
'user_id': agent,
'action_user': action_user_sid,
'interaction_id': interaction
}
es_resp = put_to_elasticsearch(es_data, es_client, index_name)
return api_jsonify([], 200, "Task added successfully!", True)
return api_jsonify([], 422, "Invalid request parameters!", False)
return api_jsonify([], 422, "Invalid request parameters!", False)
@authenticate
def interact():
""" Incoming first chat interaction """
received = request.get_json()
if received:
lead_from = received.get('from', None)
lead_id = received.get('leadId', None)
partnership_id = received.get('partnershipId', None)
lead_to = received.get('to', None)
payload = received.get('payload', {})
interaction_type = received.get('type', None)
widget_guid = received.get('widgetId', None)
message = ""
if payload:
message = payload.get('message', None)
widget = Widget.query.filter(Widget.guid == widget_guid).first()
from buyercall.blueprints.partnership.models import PartnershipAccount
partnership_account = PartnershipAccount.query.filter(
PartnershipAccount.id == widget.partnership_account_id).first()
partnership_account_id = partnership_account.sid
else:
return api_jsonify({}, 422, 'Missing parameters in the request.', False)
if lead_from and widget_guid and interaction_type:
who_is_who = validate_from_to(lead_from, lead_to)
if not who_is_who['success']:
return api_jsonify({}, 422, 'Invalid parameters in the request.', False)
is_lead_to_bc = True if 'USER' in lead_from else False
es_data = {
'interaction_id': str(uuid4()),
'created_at': datetime.utcnow(),
'customer_id': lead_from,
'lead_id': lead_id,
'partnership_id': partnership_id,
'partnership_account_id': str(partnership_account_id),
'type': interaction_type,
'interaction_object': {
'type': interaction_type,
'message': message,
'isLeadtoBC': is_lead_to_bc,
'from': lead_from
}
}
# Insert into es
log_state = flask_environment()
index_name = f'buyercall-lead-interaction-{log_state}'
from buyercall.blueprints.user.tasks import put_to_elasticsearch
es_response = put_to_elasticsearch(es_data, es_client, index_name)
# if interaction_type == "CALL":
# pass
# elif interaction_type == "TEXT_MESSAGE":
# pass
# elif interaction_type == "EMAIL_MESSAGE":
# pass
if interaction_type == "CHAT_MESSAGE":
is_rasa_enabled = widget._options.get('isRasaEnabled', True)
# is_rasa_enabled = True
rasa_reply = None
if is_rasa_enabled:
# Ask rasa
rasa_reply = ask_rasa(lead_from, message)
if rasa_reply:
rasa_replies = []
rasa_reply = rasa_reply.json()
for reply in rasa_reply:
es_data = {
'interaction_id': str(uuid4()),
'created_at': datetime.utcnow(),
'customer_id': lead_from,
'lead_id': lead_id,
'partnership_id': partnership_id,
'partnership_account_id': str(partnership_account_id),
'type': 'CHAT_MESSAGE',
'interaction_object': {
'type': 'CHAT_MESSAGE',
'message': reply.get("text", ""),
'isLeadtoBC': is_lead_to_bc,
'from': 'RASA'
}
}
es_response = put_to_elasticsearch(es_data, es_client, index_name)
rasa_replies.append(reply.get("text", ""))
return api_jsonify({
'from': "RASA",
'to': lead_from,
'payload': {
'message': rasa_replies
},
}, 200, 'Success', True)
else:
agent_ids = get_available_agent_ids(widget)
all_agents_sids = []
for agent in widget.agents:
all_agents_sids.append(agent.sid)
if agent_ids:
es_data = {
'interaction_id': str(uuid4()),
'created_at': datetime.utcnow(),
'customer_id': lead_from,
'lead_id': lead_id,
'partnership_id': partnership_id,
'partnership_account_id': str(partnership_account_id),
'type': 'INFO',
'interaction_object': {
'type': 'INFO',
'message': "Our representative has been notified of the request and will join the chat shortly.",
'isLeadtoBC': is_lead_to_bc,
'from': ""
}
}
es_response = put_to_elasticsearch(es_data, es_client, index_name)
if es_response.get('status'):
query = Q('term', **{'_id': es_response['meta']['_id']})
es_search_response = search_data(query, es_client, index_name)
if es_search_response['hits']['hits']:
interaction_id = es_search_response['hits']['hits'][0]['_source']['interaction_id']
task_payload = {
"type": f"NEW_{interaction_type}_FOLLOW_UP",
"agents": all_agents_sids,
"partnershipId": partnership_id,
'partnershipAccountId': str(partnership_account.sid),
'interaction': str(interaction_id)
}
task_resp = create_task(task_payload)
return api_jsonify({
'from': "",
'to': lead_from,
'payload': {
'message': "Our representative has been notified of their request and that they will chat to them shortly"
},
}, 200, 'Success', True)
else:
es_data = {
'interaction_id': str(uuid4()),
'created_at': datetime.utcnow(),
'customer_id': lead_from,
'lead_id': lead_id,
'partnership_id': partnership_id,
'partnership_account_id': str(partnership_account_id),
'type': 'INFO',
'interaction_object': {
'type': 'INFO',
'message': "__ERR_NO_AGENTS__",
'isLeadtoBC': is_lead_to_bc,
'from': ""
}
}
es_response = insert_data_by_index(es_data, es_client, index_name)
if es_response.get('status'):
query = Q('term', **{'_id': es_response['meta']['_id']})
es_search_response = search_data(query, es_client, index_name)
if es_search_response['hits']['hits']:
interaction_id = es_search_response['hits']['hits'][0]['_source']['interaction_id']
print('interaction_id : ', interaction_id)
# Add task for agents
task_payload = {
"type": f"MISSED_{interaction_type}_FOLLOW_UP",
"agents": all_agents_sids,
"partnershipId": partnership_id,
'partnershipAccountId': str(partnership_account.sid),
'interaction': str(interaction_id)
}
task_resp = create_task(task_payload)
return api_jsonify(
{
'from': "",
'to': lead_from,
'payload': {
'message': "__ERR_NO_AGENTS__"
}
}, 200, 'Success', True
)
else:
agent_ids = get_available_agent_ids(widget)
all_agents_sids = []
for agent in widget.agents:
all_agents_sids.append(agent.sid)
es_data = {
'interaction_id': str(uuid4()),
'created_at': datetime.utcnow(),
'customer_id': lead_from,
'lead_id': lead_id,
'partnership_id': partnership_id,
'partnership_account_id': str(partnership_account_id),
'type': interaction_type,
'interaction_object': {
'type': interaction_type,
'message': "",
'isLeadtoBC': is_lead_to_bc,
'from': lead_from
}
}
es_response = put_to_elasticsearch(es_data, es_client, index_name)
if es_response.get('status'):
query = Q('term', **{'_id': es_response['meta']['_id']})
es_search_response = search_data(query, es_client, index_name)
if es_search_response['hits']['hits']:
interaction_id = es_search_response['hits']['hits'][0]['_source']['interaction_id']
task_payload = {
"type": f"{interaction_type}_FOLLOW_UP",
"agents": all_agents_sids,
"partnershipId": partnership_id,
'partnershipAccountId': str(partnership_account.sid),
'interaction': str(interaction_id)
}
task_resp = create_task(task_payload)
return api_jsonify({
'from': "",
'to': lead_from,
'payload': {
'message': ""
},
}, 200, 'Success', True)
return api_jsonify({}, 422, 'Missing parameters in the request.', False)
@authenticate
def chat_log():
""" Log every chat to es """
received = request.get_json()
from buyercall.blueprints.partnership.models import Partnership, PartnershipAccount
if received:
chat_from = received.get('from', None)
chat_to = received.get('to', "")
lead_id = received.get('leadId', None)
partnership_id = received.get('partnershipId', None)
payload = received.get('payload', {})
widget_guid = received.get('widgetId', None)
widget = Widget.query.filter(Widget.guid == widget_guid).first()
partnership_account = PartnershipAccount.query.filter(PartnershipAccount.id == widget.partnership_account_id)
message = ""
if payload:
message = payload.get('message', None)
if chat_from and chat_to:
who_is_who = validate_from_to(chat_from, chat_to)
if not who_is_who['success']:
return api_jsonify({}, 422, 'Invalid parameters in the request.', False)
is_lead_to_bc = True if 'USER' in chat_from else False
user = who_is_who['user']
agent = who_is_who['agent']
es_data = {
'created_at': datetime.utcnow(),
'user': user,
'lead': lead_id,
'partnership': partnership_id,
'partnership_account_id': str(partnership_account.sid),
'type': 'LOG',
'interaction': {
'type': 'LOG',
'message': message,
'isLeadtoBC': is_lead_to_bc,
'from': chat_from,
'to': agent
}
}
# Insert into es
log_state = flask_environment()
index_name = f'buyercall-lead-interaction-{log_state}'
from buyercall.blueprints.user.tasks import put_to_elasticsearch
es_response = put_to_elasticsearch(es_data, es_client, index_name)
return api_jsonify({}, 200, 'Success', True)
return api_jsonify({}, 422, 'Invalid input parameters', False)
return api_jsonify({}, 422, 'Invalid input parameters', False)
@ authenticate
def get_tasks():
""" Get all tasks for an agent """
from buyercall.blueprints.partnership.models import Partnership, PartnershipAccount
agent_sid = current_user.agent.sid
# agent_sid = '56d21428-ba1e-4fda-8c73-5ef174510963'
partnership_sid = Partnership.query.filter(Partnership.id == current_user.partnership_id).first()
# partnership_sid = 'cb1386d5-16e0-4a5f-9e16-0fb8a87fc7d3'
if agent_sid and partnership_sid:
query = Q('bool', must=[
Q('term', **{'partnership_id.keyword': partnership_sid}),
Q('term', **{'user_id.keyword': agent_sid}),
])
flas_env = flask_environment()
index_name = f'buyercall-interaction-task-{flas_env}'
es_response = search_data(q=query, es_client=es_client, index=index_name, offset=0)
if es_response["hits"]["hits"]:
data = {
'totalRecordCount': es_response["hits"]["total"]["value"]
}
tasks = []
from buyercall.blueprints.leads.models import Lead
for hit in es_response["hits"]["hits"]:
_task = {}
_task['taskId'] = hit['_source']['task_id']
_task['taskType'] = hit['_source']['task_type']
_task['createdAt'] = hit['_source']['created_at']
_task['updatedAt'] = hit['_source']['updated_at']
_task['dueDate'] = hit['_source']['due_date']
_task['partnershipId'] = hit['_source']['partnership_id']
_task['partnershipAccountId'] = hit['_source']['partnership_account_id']
_task['status'] = hit['_source']['status']
_task['actionUserId'] = hit['_source']['action_user']
_task['interactionDetails'] = {}
query2 = Q('term', **{'_id': hit['_source']['interaction_id']})
index_name = f'buyercall-lead-interaction-{flas_env}'
es_interaction_response = search_data(q=query2, es_client=es_client, index=index_name)
_task_interaction = {}
if es_interaction_response['hits']['hits']:
interaction = es_interaction_response['hits']['hits'][0]['_source']
_task_interaction['createdAt'] = interaction['created_at'],
_task_interaction['interactionType'] = interaction['type'],
_task_interaction['interactionId'] = interaction['interaction_id'],
_task_interaction['customerId'] = interaction['customer_id'],
_task_interaction['payload'] = interaction['interaction_object'],
lead = Lead.query.filter(Lead.sid == interaction['lead_id']).first()
_lead_details = {}
if lead:
_lead_details['leadId'] = interaction['lead_id']
_lead_details['leadFirstName'] = lead.firstname
_lead_details['leadLastName'] = lead.lastname
_lead_details['leadEmail'] = lead.email
_lead_details['leadPhoneNumber'] = lead.phonenumber
_task_interaction['leadDetails'] = _lead_details
_task['interactionDetails'] = _task_interaction
tasks.append(_task)
data['tasks'] = tasks
return api_jsonify(data, 200, "Tasks fetched successfuly", True)
return api_jsonify([], 200, "Not tasks found!", True)
return api_jsonify([], 422, "Invalid request parameters!", False)
@ authenticate
def pick_task(task_id):
""" Pick a task """
if task_id:
from buyercall.blueprints.partnership.models import Partnership, PartnershipAccount
query = Q('bool', must=[Q('term', task_id=task_id)])
log_state = flask_environment()
index_name = f'buyercall-interaction-task-{log_state}'
es_response = search_data(q=query, es_client=es_client, index=index_name, offset=0)
if es_response:
if es_response["hits"]["total"]["value"] > 0:
update_query = {
"query": {"term": {"interaction_id.keyword": es_response["hits"]["hits"][0]['_source']['interaction_id']}}}
script = f"ctx._source.status='inprogress';ctx._source.updated_at={str(datetime.utcnow())};ctx._source.action_user={str(current_user.sid)}"
index_name = f'buyercall-interaction-task-{log_state}'
from buyercall.blueprints.user.tasks import update_to_elasticsearch
resp = update_to_elasticsearch(update_query, es_client, index_name=index_name, script=script)
if not resp['status']:
return api_jsonify([], 422, resp['message'], False)
# Notify the users
partnership = Partnership.query.filter(Partnership.id == current_user.partnership_id).first()
if not partnership:
partnership = Partnership.query.get(1)
# get tasks having same interaction id for the task
assigned_agent_sids = []
es_tasks_response = search_data(q=update_query, es_client=es_client, index=index_name, offset=0)
if es_tasks_response:
if es_tasks_response["hits"]["total"]["value"] > 0:
for hit in es_tasks_response["hits"]["hits"]:
assigned_agent_sids.append(hit['_source']['user_id'])
if assigned_agent_sids:
es_data = {
'user_id': current_user.sid,
'notify_message_type': 'TASK_PICKED',
'user_related_entities': "You've",
'other_user_related_entities': f'{current_user.firstname} {current_user.lastname}',
'hyperlink': f'{partnership.partner_url}/tasks',
'additional_notify_users': assigned_agent_sids
}
from buyercall.blueprints.notification.utilities import send_notifications
es_response = send_notifications(**es_data)
return api_jsonify([], 200, "Successfully picked the task!", True)
return api_jsonify([], 422, "Invalid request parameters!", False)
return api_jsonify([], 422, "Invalid request parameters!", False)
return api_jsonify([], 422, "Invalid request parameters!", False)
@ authenticate
def get_task_by_id(task_id):
""" Pick a task """
if task_id:
query = Q('bool', must=[Q('term', task_id=task_id)])
sort_string = '-created_at'
flas_env = flask_environment()
index_name = f'buyercall-interaction-task-{flas_env}'
es_response = search_data(q=query, es_client=es_client, index=index_name, offset=0, sort=sort_string)
if es_response:
if es_response["hits"]["hits"]:
hit = es_response["hits"]["hits"][0]
data = {}
from buyercall.blueprints.leads.models import Lead
_task = {}
_task['taskId'] = hit['_source']['task_id']
_task['taskType'] = hit['_source']['task_type']
_task['createdAt'] = hit['_source']['created_at']
_task['updatedAt'] = hit['_source']['updated_at']
_task['dueDate'] = hit['_source']['due_date']
_task['partnershipId'] = hit['_source']['partnership_id']
_task['partnershipAccountId'] = hit['_source']['partnership_account_id']
_task['status'] = hit['_source']['status']
_task['actionUserId'] = hit['_source']['action_user']
_task['interactionDetails'] = {}
query2 = Q('term', **{'_id': hit['_source']['interaction_id']})
index_name = f'buyercall-lead-interaction-{flas_env}'
es_interaction_response = search_data(q=query2, es_client=es_client, index=index_name)
_task_interaction = {}
if es_interaction_response['hits']['hits']:
interaction = es_interaction_response['hits']['hits'][0]['_source']
_task_interaction['createdAt'] = interaction['created_at'],
_task_interaction['interactionType'] = interaction['type'],
_task_interaction['interactionId'] = interaction['interaction_id'],
_task_interaction['customerId'] = interaction['customer_id'],
_task_interaction['payload'] = interaction['interaction_object'],
lead = Lead.query.filter(Lead.sid == interaction['lead_id']).first()
_lead_details = {}
if lead:
_lead_details['leadId'] = interaction['lead_id']
_lead_details['leadFirstName'] = lead.firstname
_lead_details['leadLastName'] = lead.lastname
_lead_details['leadEmail'] = lead.email
_lead_details['leadPhoneNumber'] = lead.phonenumber
_task_interaction['leadDetails'] = _lead_details
_task['interactionDetails'] = _task_interaction
data['task'] = _task
return api_jsonify(data, 422, "Invalid request parameters!", False)
return api_jsonify([], 200, "Task with the given id not found!", True)
return api_jsonify([], 422, "Invalid request parameters!", False)
return api_jsonify([], 422, "Invalid request parameters!", False)
# @authenticate
def get_tasks_meta():
query = Q('bool', must=[Q("term", **{"is_viewed": False})])
query2 = Q()
sort_string = '-created_at'
flas_env = flask_environment()
index_name = f'buyercall-interaction-task-{flas_env}'
es_response1 = search_data(q=query, es_client=es_client, index=index_name, count_only=True, sort=sort_string)
es_response2 = search_data(q=query2, es_client=es_client, index=index_name, limit=1, offset=0, sort=sort_string)
data = {"unViewedCount": 0}
if es_response1:
data["unViewedCount"] = es_response1
if es_response2:
if es_response2["hits"]["hits"]:
hit = es_response2["hits"]["hits"][0]
data["latestTaskCreatedAt"] = hit['_source']['created_at']
return api_jsonify(data, 200, "Task meta feteched successfully!", True)
# @authenticate
def update_task_viewed():
received = request.get_json()
task_id = received.get('task_id', None)
query = Q('bool', must=[Q("term", **{"task_id": task_id})])
flas_env = flask_environment()
index_name = f'buyercall-interaction-task-{flas_env}'
script = f"ctx._source.is_viewed=true"
from buyercall.blueprints.user.tasks import update_to_elasticsearch
es_response = update_to_elasticsearch(query, es_client, index_name, script)
if not es_response['status']:
return api_jsonify([], 422, es_response['message'], False)
return api_jsonify({}, 200, "Task View status updated successfully!", True)
# @authenticate
def search_task():
received = request.get_json()
search_query = received.get('search_query', None)
limit = received.get('limit', None)
offset = received.get('offset', None)
if search_query:
query = Q('bool', must=[Q('multi_match', **{"query": search_query, "fields":
['task_id', 'task_type', 'status', 'user_id', 'action_user', 'interaction_id',
'partnership_id', 'partnership_account_id']})])
sort_string = '-created_at'
flas_env = flask_environment()
index_name = f'buyercall-interaction-task-{flas_env}'
es_response = search_data(q=query, es_client=es_client, limit=limit,
offset=offset, index=index_name, sort=sort_string)
print(es_response.aggregations)
print(es_response.aggs)
# Get aggreggations
# format the output for response
return api_jsonify(es_response.to_dict(), 200, "Task List Fetched Successfully", True)
@authenticate
def interaction_task():
received = request.get_json()
interaction_id = received.get('interaction_id', None)
widget_id = received.get('widget_id', None)
interaction_type = received.get('type', None)
log_state = flask_environment()
index_name = f'buyercall-lead-interaction-{log_state}'
widget = Widget.query.filter(Widget.sid == widget_id).first()
all_agents_sids = []
for agent in widget.agents:
all_agents_sids.append(agent.sid)
from buyercall.blueprints.partnership.models import Partnership, PartnershipAccount
partnership_account = PartnershipAccount.query.filter(
PartnershipAccount.id == widget.partnership_account_id).first()
partnership = Partnership.query.filter(Partnership.id == partnership_account.partnership_id).first()
if interaction_id:
query = Q('term', **{'interaction_id': interaction_id})
es_search_response = search_data(query, es_client, index_name)
if es_search_response['hits']['hits']:
interaction_id = es_search_response['hits']['hits'][0]['_source']['interaction_id']
task_payload = {
"type": f"{interaction_type}_FOLLOW_UP",
"agents": all_agents_sids,
"partnershipId": partnership.sid,
'partnershipAccountId': str(partnership_account.sid),
'interaction': str(interaction_id)
}
task_resp = create_task(task_payload)
return api_jsonify({}, 200, "Task send successfully!", True)
@authenticate
def task_interactions():
received = request.get_json()
lead_id = received.get('lead_id', None)
if lead_id:
query = Q('bool', must=[Q('term', lead_id=lead_id)])
sort_string = '-created_at'
flas_env = flask_environment()
index_name = f'buyercall-lead-interaction-{flas_env}'
es_response = search_data(q=query, es_client=es_client, index=index_name, limit=20, offset=0, sort=sort_string)
if es_response:
data = []
for hit in es_response["hits"]["hits"]:
_interaction = {
'interaction_ID': hit['_source']['interaction_id'],
'createdAt': hit['_source']['created_at'],
'interaction_type': hit['_source']['type'],
'user_id': hit['_source']['customer_id'],
'lead_ID': hit['_source']['lead_id'],
'payload': {
'fromLead': hit['_source']['from'],
'message': hit['_source']['message'],
}
}
data.append(_interaction)
# Add Aggregations here
return api_jsonify(data, 200, "Interactions Fetched Successfully!", True)