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_forms/buyercall/buyercall/blueprints/api/doc/endpoints/agents.py
import logging

from flask import jsonify, request
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.doc import serializers
from buyercall.blueprints.api.restplus import api
from buyercall.blueprints.billing.models.subscription import Subscription
from buyercall.blueprints.agents.models import Agent, AgentSchedule
from buyercall.extensions import db


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


def getboolean(param):
    if param == 'true' or param == 'True':
        return True
    else:
        return False


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

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

        """
        if rest_is_partnership_account and rest_partnership_account:
            agent_list = list()
            agents = db.session.query(Agent) \
                .filter(and_(Agent.partnership_account_id == rest_partnership_account.id, Agent.is_group == False)) \
                .distinct() \
                .all()

            if agents:
                for agent in agents:
                    add_agent = {
                        'id': agent.id,
                        'firstname': agent.firstname,
                        'lastname': agent.lastname,
                        'email': agent.email,
                        'phonenumber': agent.phonenumber,
                        'mobile': agent.mobile,
                        'department': agent.department,
                        'description': agent.description,
                        'extension': agent.extension,
                        'title': agent.title,
                        'available': agent.available_now
                    }
                    agent_list.append(add_agent)
            return jsonify(
                agents=agent_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_agent_list = list()
                    pa_agents = db.session.query(Agent) \
                        .filter(and_(Agent.partnership_account_id == pa.id, Agent.is_group == False)) \
                        .distinct() \
                        .all()

                    if pa_agents:
                        for pa_agent in pa_agents:
                            add_pa_agent = {
                                'firstname': pa_agent.firstname,
                                'lastname': pa_agent.lastname,
                                'email': pa_agent.email,
                                'phonenumber': pa_agent.phonenumber,
                                'mobile': pa_agent.mobile,
                                'department': pa_agent.department,
                                'description': pa_agent.description,
                                'extension': pa_agent.extension,
                                'title': pa_agent.title,
                                'available': pa_agent.available_now
                            }
                            pa_agent_list.append(add_pa_agent)

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

    @api.response(204, 'Agent successfully added.')
    @api.expect(serializers.agent_row, validate=True)
    @requires_auth
    def post(self):
        """
        Adds a partnership account agent.

        Use this method to add an agent to a partnership account.

        NB: If "ALL HOURS" is true, agents will be set to active 24/7.
        Otherwise, agents will be added by default as active between 8AM and 5PM during week days.

        """
        if rest_is_partnership_account and rest_partnership_account:
            result = request.json

            if result:
                total_agents = Agent.query.filter(rest_partnership_account.id == Agent.partnership_account_id).count()
                subscription = (db.session.query(Subscription))\
                    .filter(Subscription.id == rest_partnership_account.subscription_id)\
                    .first()

                if total_agents and subscription:
                    if total_agents >= subscription.agent_limit:
                        api.abort(code=400, message="Error creating agent. Agent limit exceeded.")
                    else:
                        params = {
                            'user_id': None,
                            'firstname': result['firstname'],
                            'lastname': result['lastname'],
                            'title': result['title'],
                            'email': result['email'],
                            'phonenumber': result['phonenumber'],
                            'mobile': result['mobile'],
                            'extension': int(result['extension']) if result['extension'] else None,
                            'department': result['department'],
                            'description': result['description'],
                            'partnership_account_id': rest_partnership_account.id,
                            'all_hours': getboolean(result['all_hours'])
                        }

                        agent_added = Agent.create(params)

                        if agent_added > 0:
                            day1param = {
                                'day': 0,
                                'available_from': '08:00 AM',
                                'available_to': '17:00 PM',
                                'is_active': False,
                                'partnership_account_id': rest_partnership_account.id,
                                'agent_id': int(agent_added)
                            }

                            day2param = {
                                'day': 1,
                                'available_from': '08:00 AM',
                                'available_to': '17:00 PM',
                                'is_active': True,
                                'partnership_account_id': rest_partnership_account.id,
                                'agent_id': int(agent_added)
                            }

                            day3param = {
                                'day': 2,
                                'available_from': '08:00 AM',
                                'available_to': '17:00 PM',
                                'is_active': True,
                                'partnership_account_id': rest_partnership_account.id,
                                'agent_id': int(agent_added)
                            }

                            day4param = {
                                'day': 3,
                                'available_from': '08:00 AM',
                                'available_to': '17:00 PM',
                                'is_active': True,
                                'partnership_account_id': rest_partnership_account.id,
                                'agent_id': int(agent_added)
                            }

                            day5param = {
                                'day': 4,
                                'available_from': '08:00 AM',
                                'available_to': '17:00 PM',
                                'is_active': True,
                                'partnership_account_id': rest_partnership_account.id,
                                'agent_id': int(agent_added)
                            }

                            day6param = {
                                'day': 5,
                                'available_from': '08:00 AM',
                                'available_to': '17:00 PM',
                                'is_active': True,
                                'partnership_account_id': rest_partnership_account.id,
                                'agent_id': int(agent_added)
                            }

                            day7param = {
                                'day': 6,
                                'available_from': '08:00 AM',
                                'available_to': '17:00 PM',
                                'is_active': False,
                                'partnership_account_id': rest_partnership_account.id,
                                'agent_id': int(agent_added)
                            }

                            day_result = AgentSchedule.create(day1param,
                                                              day2param,
                                                              day3param,
                                                              day4param,
                                                              day5param,
                                                              day6param,
                                                              day7param)

                            if day_result:
                                return True, 204
                            else:
                                api.abort(code=400, message="Error creating agent.")
                        else:
                            api.abort(code=400, message="Error creating agent.")
                else:
                    api.abort(code=400, message="Error creating agent.")
            else:
                api.abort(code=400, message="Error creating agent.")
        else:
            api.abort(code=401)


@ns.route('/<int:aid>')
@api.doc(responses={200: 'OK',
                    400: 'Error performing operation.',
                    401: 'Unauthorized request.',
                    404: 'Agent not found.'},
         params={'aid': 'The agent ID.'})
class ApiAgent(Resource):
    @api.response(204, 'Agent successfully updated.')
    @api.expect(serializers.agent_row, validate=True)
    @requires_auth
    def put(self, aid):
        """
        Update a partnership account's agent.

        Use this method to update an agent of a partnership account.

        """
        if rest_is_partnership_account and rest_partnership_account:
            result = request.json

            if result:

                final_result = Agent.api_update(
                    rest_partnership_account.id,
                    aid,
                    result['title'],
                    result['firstname'],
                    result['lastname'],
                    result['phonenumber'],
                    result['mobile'],
                    result['extension'],
                    result['email'],
                    result['department'],
                    result['description'],
                    getboolean(result['all_hours'])
                )
                if final_result:
                    return final_result, 204
                else:
                    api.abort(code=400, message="Error updating agent.")
            else:
                return api.abort(code=404)
        else:
            return api.abort(code=401)

    @api.response(204, 'Agent successfully deactivated.')
    @requires_auth
    def delete(self, aid):
        """
        Deactivate a partnership account agent.

        Use this method to deactivate an agent of a partnership account.

        """
        if rest_is_partnership_account and rest_partnership_account:
            agent = Agent.query.filter(and_(
                Agent.id == aid, Agent.partnership_account_id == rest_partnership_account.id)
            ).first()

            if agent:
                return agent.deactivate(aid, rest_partnership_account.id), 204
            else:
                return api.abort(code=404)
        else:
            return api.abort(code=401)


@ns.route('/schedule/<int:aid>')
@api.doc(responses={200: 'OK',
                    401: 'Unauthorized request.',
                    404: 'Agent not found.'},
         params={'aid': 'The agent ID.'})
class ApiAgentSchedule(Resource):
    @requires_auth
    def get(self, aid):
        """
        Retrieves agent schedule of an agent.

        Use this method to view the schedule details of an agents.

        * Specify the ID of the of the agent in the request URL path.
        """
        if rest_is_partnership_account and rest_partnership_account:
            agent = (db.session.query(Agent))\
                .filter(Agent.partnership_account_id == rest_partnership_account.id)\
                .filter(Agent.id == aid)\
                .first()
            schedules = list()

            if agent:
                for sched in agent.schedules:
                    day_name = ''

                    if sched.day == 0:
                        day_name = 'Sunday'
                    elif sched.day == 1:
                        day_name = 'Monday'
                    elif sched.day == 2:
                        day_name = 'Tuesday'
                    elif sched.day == 3:
                        day_name = 'Wednesday'
                    elif sched.day == 4:
                        day_name = 'Thursday'
                    elif sched.day == 5:
                        day_name = 'Friday'
                    elif sched.day == 6:
                        day_name = 'Saturday'

                    day = {
                        'day': day_name,
                        'available_from': sched.available_from,
                        'available_to': sched.available_to,
                        'is_active': sched.is_active
                    }
                    schedules.append(day)

                return jsonify(
                    firstname=agent.firstname,
                    lastname=agent.lastname,
                    email=agent.email,
                    phonenumber=agent.phonenumber,
                    mobile=agent.mobile,
                    department=agent.department,
                    description=agent.description,
                    extension=agent.extension,
                    title=agent.title,
                    all_hours=agent.all_hours,
                    available=agent.available_now,
                    schedule=schedules
                )
            else:
                api.abort(code=404)
        else:
            return api.abort(code=401)