HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/buyercall_new/buyercall/buyercall/blueprints/api/doc/endpoints/widgets.py
import logging

from flask import jsonify
from flask_restx import Resource
from sqlalchemy import and_

from buyercall.lib.util_rest import (rest_partnership_account, rest_partnership, requires_auth,
                                     rest_is_partnership_account, rest_is_partnership)

from buyercall.blueprints.api.restplus import api
from buyercall.blueprints.widgets.rest_api import call as widget_call
from buyercall.blueprints.widgets.rest_api import save_lead as widget_save_lead
from buyercall.blueprints.widgets.models import Widget
from buyercall.extensions import db


log = logging.getLogger(__name__)
ns = api.namespace('widgets', description='Operations related to widgets.')


@ns.route('/<string:guid>')
@api.doc(responses={200: 'OK',
                    400: 'Error performing operation.',
                    401: 'Unauthorized request.',
                    404: 'Widget not found.'},
         params={'guid': 'The widget GUID.'})
class ApiWidget(Resource):
    @requires_auth
    def get(self, guid):
        """
        Retrieves widget details.

        Use this method to view the details of a widget.

        """
        if rest_is_partnership_account and rest_partnership_account:
            result_widget = ''
            widgets = db.session.query(Widget) \
                .filter(and_(Widget.partnership_account_id == rest_partnership_account.id, Widget.guid == guid)) \
                .distinct() \
                .all()

            if widgets:
                widget = widgets[0]

                result_widget = {
                    'guid': widget.guid,
                    'name': widget.name,
                    'options': widget.options
                }

            return jsonify(
                result_widget
            )
        elif rest_is_partnership and rest_partnership:
            partnership_accounts = rest_partnership.get_partnership_accounts()
            pa_list = list()

            if partnership_accounts:
                for pa in partnership_accounts:
                    pa_widget_list = list()
                    pa_widgets = db.session.query(Widget) \
                        .filter(and_(Widget.partnership_account_id == pa.id, Widget.guid == guid)) \
                        .distinct() \
                        .all()

                    if pa_widgets:
                        widget = pa_widgets[0]

                        result_widget = {
                            'guid': widget.guid,
                            'name': widget.name,
                            'options': widget.options
                        }
                        pa_widget_list.append(result_widget)

                    add_pa = {
                        'name': pa.name,
                        'widgets': pa_widget_list
                    }
                    pa_list.append(add_pa)

                return jsonify(
                    accounts=pa_list
                )
        else:
            return api.abort(401)

    @requires_auth
    @api.response(204, 'Widget successfully deleted.')
    def delete(self, guid):
        """
        Deletes widget details.

        Use this method to delete the details of a widget.

        """
        final_result = False

        if rest_is_partnership_account and rest_partnership_account:
            final_result = Widget.delete(None, guid, rest_partnership_account.partnership_account_id)

            if final_result:
                return final_result, 204
            else:
                api.abort(code=400, message="Error deleting widget.")
        elif rest_is_partnership and rest_partnership:
            partnership_accounts = rest_partnership.get_partnership_accounts()

            if partnership_accounts:
                widget = db.session.query(Widget).filter(
                    and_(Widget.partnership_account_id.in_(partnership_accounts), Widget.guid == guid))\
                    .distinct()\
                    .first()
                if widget:
                    final_result = Widget.delete(None, guid, widget.partnership_account_id)

            if final_result:
                return final_result, 204
            else:
                api.abort(code=400, message="Error deleting widget.")
        else:
            return api.abort(401)


@ns.route('/disable/<string:guid>')
class ApiWidgetDisable(Resource):
    @requires_auth
    @api.response(204, 'Widget successfully disabled.')
    def put(self, guid):
        """
        Disables a widget.

        Use this method to disable a widget.

        """
        final_result = False

        if rest_is_partnership_account and rest_partnership_account:
            final_result = Widget.disable(None, guid, rest_partnership_account.partnership_account_id)

            if final_result:
                return final_result, 204
            else:
                api.abort(code=400, message="Error disabling widget.")
        elif rest_is_partnership and rest_partnership:
            partnership_accounts = rest_partnership.get_partnership_accounts()

            if partnership_accounts:
                widget = db.session.query(Widget).filter(
                    and_(Widget.partnership_account_id.in_(partnership_accounts), Widget.guid == guid))\
                    .distinct()\
                    .first()
                if widget:
                    final_result = Widget.disable(None, guid, widget.partnership_account_id)

            if final_result:
                return final_result, 204
            else:
                api.abort(code=400, message="Error disabling widget.")
        else:
            return api.abort(401)


@ns.route('/enable/<string:guid>')
class ApiWidgetEnable(Resource):
    @requires_auth
    @api.response(204, 'Widget successfully enabled.')
    def put(self, guid):
        """
        Enables a widget.

        Use this method to enable a widget.

        """
        final_result = False

        if rest_is_partnership_account and rest_partnership_account:
            final_result = Widget.enable(None, guid, rest_partnership_account.partnership_account_id)

            if final_result:
                return final_result, 204
            else:
                api.abort(code=400, message="Error enabling widget.")
        elif rest_is_partnership and rest_partnership:
            partnership_accounts = rest_partnership.get_partnership_accounts()

            if partnership_accounts:
                widget = db.session.query(Widget).filter(
                    and_(Widget.partnership_account_id.in_(partnership_accounts), Widget.guid == guid))\
                    .distinct()\
                    .first()
                if widget:
                    final_result = Widget.enable(None, guid, widget.partnership_account_id)

            if final_result:
                return final_result, 204
            else:
                api.abort(code=400, message="Error enabling widget.")
        else:
            return api.abort(401)


@ns.route('/settings/<string:guid>')
class ApiWidgetSettings(Resource):
    @requires_auth
    @api.response(204, 'Widget settings successfully retrieved.')
    def get(self, guid):
        """
        Retrieves widget settings.

        Use this method to retrieve widget settings.

        """
        widget = None

        if rest_is_partnership_account and rest_partnership_account:
            widget = db.session.query(Widget).filter(
                and_(Widget.partnership_account_id == rest_partnership_account.id, Widget.guid == guid)) \
                .distinct() \
                .first()
        elif rest_is_partnership and rest_partnership:
            partnership_accounts = rest_partnership.get_partnership_accounts()

            if partnership_accounts:
                widget = db.session.query(Widget).filter(
                    and_(Widget.partnership_account_id.in_(partnership_accounts), Widget.guid == guid))\
                    .distinct()\
                    .first()

        if widget:
            result = dict(widget.options)
            result['agentsAvailable'] = widget.agents_available

            for key in [
                'agents', 'scheduleTimezone', 'days', 'availableFrom',
                'availableTo', 'recordCalls', 'retryRouting', 'routeInSequence',
                'routeRandomly', 'routeSimultaneously', 'voicemail',
                'voicemailMessage', 'whisperMessage'
            ]:
                if key in result:
                    del result[key]

            return jsonify(result), 204
        else:
            return api.abort(401)


@ns.route('/call/')
class ApiWidgetCall(Resource):
    @requires_auth
    def post(self):
        """ The endpoint that gets called when the lead presses 'Talk!' on the
        widget. Saves the lead information in the database and routes the call to
        the agents.

        Receives the widget GUID as a query string parameter, and the user's data
        in the JSON body.
        """
        authenticated = False

        if rest_is_partnership_account and rest_partnership_account:
            authenticated = True
        elif rest_is_partnership and rest_partnership:
            authenticated = True

        if authenticated:
            widget_call()
        else:
            return api.abort(401)


@ns.route('/save_lead/')
class ApiWidgetSaveLead(Resource):
    @requires_auth
    def post(self):
        """ The endpoint that gets called when the lead chooses to send us his
        information when the agents are unavailable. Saves the lead information in
        the database.

        Receives the widget GUID as a query string parameter, and the user's data
        in the JSON body.
        """
        authenticated = False

        if rest_is_partnership_account and rest_partnership_account:
            authenticated = True
        elif rest_is_partnership and rest_partnership:
            authenticated = True

        if authenticated:
            widget_save_lead()
        else:
            return api.abort(401)


@ns.route('/')
@api.doc(responses={200: 'OK',
                    400: 'Error performing operation.',
                    401: 'Unauthorized request.'})
class ApiWidgetCollection(Resource):
    @requires_auth
    def get(self):
        """
        Retrieves widgets of a partnership account.

        Use this method to view the details of a partnership account's widgets.

        """
        if rest_is_partnership_account and rest_partnership_account:
            widget_list = list()
            widgets = db.session.query(Widget) \
                .filter(Widget.partnership_account_id == rest_partnership_account.id) \
                .distinct() \
                .all()

            if widgets:
                for widget in widgets:
                    add_widget = {
                        'guid': widget.guid,
                        'name': widget.name,
                        'options': widget.options
                    }
                    widget_list.append(add_widget)
            return jsonify(
                widgets=widget_list
            )
        elif rest_is_partnership and rest_partnership:
            partnership_accounts = rest_partnership.get_partnership_accounts()
            pa_list = list()

            if partnership_accounts:
                for pa in partnership_accounts:
                    pa_widget_list = list()
                    pa_widgets = db.session.query(Widget) \
                        .filter(Widget.partnership_account_id == pa.id) \
                        .distinct() \
                        .all()

                    if pa_widgets:
                        for pa_widget in pa_widgets:
                            add_pa_widget = {
                                'name': pa_widget.name,
                                'guid': pa_widget.guid,
                                'options': pa_widget.options
                            }
                            pa_widget_list.append(add_pa_widget)

                    add_pa = {
                        'name': pa.name,
                        'agents': pa_widget_list
                    }
                    pa_list.append(add_pa)
            return jsonify(
                accounts=pa_list
            )
        else:
            return api.abort(401)