예제 #1
0
 def _procesa_tiempo_hold(self, fecha_inicio, fecha_fin):
     fecha_superior = datetime_hora_maxima_dia(fecha_fin)
     fecha_inferior = datetime_hora_minima_dia(fecha_inicio)
     logs = [hold for hold in LlamadaLog.objects.filter(agente_id=self.agente.id, event='HOLD',
                                                        time__range=(fecha_inferior,
                                                                     fecha_superior))]
     for log in logs:
         inicio_hold = log.time
         callid = log.callid
         unholds = LlamadaLog.objects.filter(agente_id=self.agente.id, callid=callid,
                                             event='UNHOLD',
                                             time__range=(log.time, fecha_superior)
                                             ).order_by('time').first()
         if unholds:
             # Si existen varios unhold dentro de una llamada se elige el primero
             fin_hold = unholds.time
         else:
             # Si se corta la llamada sin haber podido hacer unhold o por otro motivo
             log_llamada = LlamadaLog.objects.filter(agente_id=self.agente.id, callid=callid,
                                                     time__range=(fecha_inferior, fecha_superior)
                                                     ).last()
             if log_llamada.event == 'HOLD':
                 fin_hold = now()
             else:
                 fin_hold = log_llamada.time
         self.tiempo_hold += fin_hold - inicio_hold
예제 #2
0
    def get(self, request, pk_campana):
        hoy_ahora = now()
        hoy_inicio = datetime_hora_minima_dia(hoy_ahora)
        try:
            reporte = ReporteTipoDeLlamadasDeCampana(hoy_inicio, hoy_ahora,
                                                     pk_campana)
            reporte.estadisticas.pop('nombre')
            data = {'status': 'OK', 'llamadas': []}
            for campo, nombre in self.TIPOS.iteritems():
                if campo in reporte.estadisticas:
                    data['llamadas'].append(
                        (nombre, reporte.estadisticas[campo]))
            for campo, nombre in self.TIPOS_MANUALES.iteritems():
                if campo in reporte.estadisticas:
                    if 'manuales' not in data:
                        data['manuales'] = []
                    data['manuales'].append(
                        (nombre, reporte.estadisticas[campo]))

        except Campana.DoesNotExist:
            data = {
                'status': 'Error',
                'error_message': _(u'No existe la campaña')
            }

        return JsonResponse(data=data)
예제 #3
0
 def obtener_llamadas_finalizadas_del_dia(self, agente_id, fecha):
     fecha_desde = datetime_hora_minima_dia(fecha)
     fecha_hasta = datetime_hora_maxima_dia(fecha)
     return self.filter(agente_id=agente_id,
                        time__gte=fecha_desde,
                        time__lte=fecha_hasta,
                        event__in=LlamadaLog.EVENTOS_FIN_CONEXION)
예제 #4
0
    def obtener_tiempos_event_agentes(self, eventos, fecha_desde, fecha_hasta,
                                      agentes):

        if fecha_desde and fecha_hasta:
            fecha_desde = datetime_hora_minima_dia(fecha_desde)
            fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)

        cursor = connection.cursor()
        sql = """select agente_id, time, event, pausa_id
                 from reportes_app_actividadagentelog where
                 time between %(fecha_desde)s and %(fecha_hasta)s and
                 event = ANY(%(eventos)s) and agente_id = ANY(%(agentes)s)
                 order by agente_id, time desc
        """
        params = {
            'fecha_desde': fecha_desde,
            'fecha_hasta': fecha_hasta,
            'eventos': eventos,
            'agentes': agentes,

        }

        cursor.execute(sql, params)
        values = cursor.fetchall()
        return values
예제 #5
0
    def obtener_agentes_campanas_total(self, eventos, fecha_desde, fecha_hasta, agentes,
                                       campanas):
        """
        Query que sumariza por agente y campaña la cantidad y duración de
        llamadas para los eventos indicados.
        """

        if fecha_desde and fecha_hasta:
            fecha_desde = datetime_hora_minima_dia(fecha_desde)
            fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)

        cursor = connection.cursor()
        sql = """select agente_id, campana_id, SUM(duracion_llamada::integer), Count(*)
                 from reportes_app_llamadalog where time between %(fecha_desde)s and
                 %(fecha_hasta)s and event = ANY(%(eventos)s) and agente_id = ANY(%(agentes)s)
                 and campana_id = ANY(%(campanas)s) GROUP BY agente_id, campana_id order by
                 agente_id, campana_id
        """
        params = {
            'fecha_desde': fecha_desde,
            'fecha_hasta': fecha_hasta,
            'eventos': eventos,
            'agentes': agentes,
            'campanas': [campana.id for campana in campanas],
        }

        cursor.execute(sql, params)
        values = cursor.fetchall()
        return values
예제 #6
0
    def calcular_cantidad_llamadas(self, campana, fecha_desde, fecha_hasta):
        """
        Obtiene las cantidades toteles detalladas como resultado de las llamadas
        :param campana: campana la cuales se obtendran el detalle de la llamada
        :param fecha_desde: fecha desde la cual se obtendran las llamadas
        :param fecha_hasta: fecha hasta la cual se obtendran las llamadas
        :return: los eventos de llamadas con sus cantidades totales
        """
        fecha_desde = datetime_hora_minima_dia(fecha_desde)
        fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)

        logs_llamadas_campana = LlamadaLog.objects.filter(
            campana_id=campana.pk, time__range=(fecha_desde, fecha_hasta))

        if campana.type == Campana.TYPE_ENTRANTE:
            reporte = self._obtener_detalle_llamadas_entrantes(
                logs_llamadas_campana)
        elif campana.type == Campana.TYPE_DIALER:
            reporte = self._obtener_detalle_llamadas_dialer(
                logs_llamadas_campana)
        elif campana.type == Campana.TYPE_MANUAL:
            reporte = self._obtener_detalle_llamadas_manuales(
                logs_llamadas_campana)
        else:
            reporte = self._obtener_detalle_llamadas_preview(
                logs_llamadas_campana)
        return reporte
예제 #7
0
    def devuelve_reporte_agentes(self, agentes, fecha_inicio, fecha_fin):
        fecha_inicio = datetime_hora_minima_dia(fecha_inicio)
        fecha_fin = datetime_hora_maxima_dia(fecha_fin)
        self.genera_tiempos_pausa(agentes, fecha_inicio, fecha_fin)
        self.genera_tiempos_campana_agentes(agentes, fecha_inicio, fecha_fin)
        self.calcula_total_intentos_fallidos(agentes, fecha_inicio, fecha_fin)
        self._genera_tiempos_totales_agentes()
        dict_agentes_llamadas = self._obtener_total_agentes_tipo_llamada(fecha_inicio, fecha_fin)
        return {
            'fecha_desde': fecha_inicio,
            'fecha_hasta': fecha_fin,
            'agentes_tiempos': self.tiempos,
            'agente_pausa': self.devuelve_pausas_agentes(),
            'count_llamada_campana': self._genera_tiempo_total_llamada_campana(),
            'dict_agente_counter': list(zip(dict_agentes_llamadas['nombres_agentes'],
                                            dict_agentes_llamadas['total_agentes'],
                                            dict_agentes_llamadas['total_agente_preview'],
                                            dict_agentes_llamadas['total_agente_dialer'],
                                            dict_agentes_llamadas['total_agente_inbound'],
                                            dict_agentes_llamadas['total_agente_manual'],
                                            dict_agentes_llamadas['total_transferidas_agente'],
                                            dict_agentes_llamadas['total_transferidas_campana'],
                                            dict_agentes_llamadas['total_agente_fuera_campana'])),
            'barra_agente_total': self._generar_grafico_agentes_llamadas(dict_agentes_llamadas),

        }
예제 #8
0
    def _obtener_llamadas_agente(self, agentes, fecha_inferior,
                                 fecha_superior):
        """
        Obtiene el totales de llamadas por agente
        :param fecha_inferior: fecha desde cual se contabilizaran las llamadas
        :param fecha_superior: fecha hasta el cual se contabilizaran las llamadas
        :return: queryset con las cantidades totales por agente
        """
        fecha_inferior = datetime_hora_minima_dia(fecha_inferior)
        fecha_superior = datetime_hora_maxima_dia(fecha_superior)
        agentes_id = [agente.id for agente in agentes]
        eventos_llamadas = list(LlamadaLog.EVENTOS_INICIO_CONEXION)
        dict_agentes = LlamadaLog.objects.obtener_count_agente().filter(
            time__range=(fecha_inferior, fecha_superior),
            agente_id__in=agentes_id,
            event__in=eventos_llamadas)

        agentes = []
        ids_agentes = []

        for agente_id in dict_agentes:
            ids_agentes.append(agente_id['agente_id'])
            try:
                agente = AgenteProfile.objects.get(pk=agente_id['agente_id'])
                agentes.append(agente.user.get_full_name())
            except AgenteProfile.DoesNotExist:
                agentes.append(agente_id['agente_id'])

        return dict_agentes, agentes, ids_agentes
예제 #9
0
    def obtener_count_evento_agente_agrupado_fecha(self, eventos, fecha_desde,
                                                   fecha_hasta, agente_id):
        if fecha_desde and fecha_hasta:
            fecha_desde = datetime_hora_minima_dia(fecha_desde)
            fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)

        return LlamadaLog.objects.filter(event__in=eventos, agente_id=agente_id,
                                         time__range=(fecha_desde, fecha_hasta)).annotate(
            fecha=TruncDate('time')).values('fecha').annotate(cantidad=Count('fecha'))
예제 #10
0
    def calcular_tiempo_session(self, agentes, fecha_inferior, fecha_superior):
        """ Calcula el tiempo de session teniendo en cuenta los eventos
        ADDMEMBER, REMOVEMEMBER"""

        eventos_sesion = ['ADDMEMBER', 'REMOVEMEMBER']
        agentes_id = [agente.id for agente in agentes]

        logs_time = ActividadAgenteLog.objects.obtener_tiempos_event_agentes(
            eventos_sesion, fecha_inferior, fecha_superior, agentes_id)

        for agente in agentes:
            agente_nuevo = None
            is_remove = False
            time_actual = None
            log_agente = self._filter_query_por_agente(logs_time, agente.id)
            len_log_agente = len(log_agente) - 1
            for logs in log_agente:
                calculo_ok = False
                # primer elemento addmember
                if log_agente.index(logs) == 0 and logs[2] == 'ADDMEMBER':
                    fecha_hoy = timezone.now()
                    time_actual = datetime_hora_maxima_dia(logs[1])
                    if cast_datetime_part_date(
                            logs[1]) == cast_datetime_part_date(fecha_hoy):
                        time_actual = fecha_hoy
                    resta = time_actual - logs[1]
                    calculo_ok = True
                # ultimo elemento removemember
                if len_log_agente == log_agente.index(
                        logs) and logs[2] == 'REMOVEMEMBER':
                    time_actual = datetime_hora_minima_dia(logs[1])
                    resta = logs[1] - time_actual
                    calculo_ok = True

                if is_remove and logs[2] == 'ADDMEMBER':
                    resta = time_actual - logs[1]
                    calculo_ok = True

                if logs[2] == 'REMOVEMEMBER':
                    time_actual = logs[1]
                    is_remove = True
                if calculo_ok:
                    agente_en_lista = filter(lambda x: x.agente == agente,
                                             self.agentes_tiempo)
                    if agente_en_lista:
                        agente_nuevo = agente_en_lista[0]
                        if agente_nuevo.tiempo_sesion:
                            agente_nuevo._tiempo_sesion += resta
                        else:
                            agente_nuevo._tiempo_sesion = resta
                    else:
                        agente_nuevo = AgenteTiemposReporte(
                            agente, resta, 0, 0, 0, 0, 0, 0)
                        self.agentes_tiempo.append(agente_nuevo)
                    agente_nuevo = None
                    is_remove = False
                    time_actual = None
    def calcular_tiempo_hold_tipo_fecha(self, agente, fecha_inferior,
                                        fecha_superior, agente_fecha):
        evento_hold = ['HOLD']
        evento_unhold = ['UNHOLD']
        tiempo_hold = timedelta(0)
        hold_fecha = [hold for hold in LlamadaLog.objects.obtener_evento_hold_fecha(
            evento_hold,
            fecha_inferior,
            fecha_superior,
            agente.id)]

        primer_unhold = LlamadaLog.objects.obtener_evento_hold_fecha(evento_unhold, fecha_inferior,
                                                                     fecha_superior, agente.id
                                                                     ).first()
        if hold_fecha:
            primer_hold = hold_fecha[0]
            if primer_unhold and primer_unhold.time < primer_hold.time:
                tiempo_hold += primer_unhold.time - fecha_inferior

        for log in hold_fecha:
            fecha_actual = fecha_local(log.time)
            agente_en_lista = list(filter(lambda x: x.agente == fecha_actual,
                                          agente_fecha))
            inicio_hold = log.time
            callid = log.callid
            fecha_desde = datetime_hora_minima_dia(fecha_actual)
            fecha_hasta = datetime_hora_maxima_dia(fecha_actual)
            unhold_fecha = LlamadaLog.objects.filter(agente_id=agente.id, callid=callid,
                                                     event='UNHOLD',
                                                     time__range=(log.time, fecha_hasta)
                                                     ).order_by('time').first()
            if unhold_fecha:
                # Si existen varios unhold dentro de una llamada se elige el primero
                fin_hold = unhold_fecha.time
            else:
                # Si se corta la llamada sin haber podido hacer unhold o por otro motivo
                log_llamada = LlamadaLog.objects.filter(agente_id=agente.id, callid=callid,
                                                        time__range=(fecha_desde, fecha_hasta)
                                                        ).last()
                if log_llamada and log_llamada.event != 'HOLD':
                    fin_hold = log_llamada.time
                else:
                    fin_hold = now() \
                        if datetime_hora_maxima_dia(fecha_superior) >= now() else fecha_superior

            tiempo_hold += fin_hold - inicio_hold

            if agente_en_lista:
                agente_nuevo = agente_en_lista[0]
                agente_nuevo._tiempo_hold = tiempo_hold
            else:

                agente_nuevo = AgenteTiemposReporte(fecha_local(fecha_inferior), timedelta(0),
                                                    timedelta(0), timedelta(0), 0, 0, 0, 0,
                                                    tiempo_hold, 0)
                agente_fecha.append(agente_nuevo)
        return agente_fecha
예제 #12
0
    def obtener_evento_hold_fecha(self, eventos, fecha_desde, fecha_hasta, agente_id):
        """devuelve el hold"""
        if fecha_desde and fecha_hasta:
            fecha_desde = datetime_hora_minima_dia(fecha_desde)
            fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)

        try:
            return self.filter(agente_id=agente_id, event__in=eventos,
                               time__range=(fecha_desde, fecha_hasta))
        except LlamadaLog.DoesNotExist:
            raise (SuspiciousOperation(_("No se encontraron holds ")))
예제 #13
0
 def get(self, request, *args, **kwargs):
     hoy_ahora = now()
     hoy_inicio = datetime_hora_minima_dia(hoy_ahora)
     reporte = ReporteDeLlamadas(hoy_inicio, hoy_ahora, False, request.user)
     return self.render_to_response(self.get_context_data(
         desde=hoy_inicio,
         hasta=hoy_ahora,
         estadisticas=reporte.estadisticas,
         graficos=reporte.graficos,
         estadisticas_por_fecha=reporte.estadisticas_por_fecha,
         estadisticas_json=json.dumps(reporte.estadisticas)))
    def __init__(self, user_supervisor):
        query_campanas = self._obtener_campanas(user_supervisor)
        self.campanas = {}
        for campana in query_campanas:
            self.campanas[campana.id] = campana

        hoy = datetime.now()
        self.desde = datetime_hora_minima_dia(hoy)
        self.hasta = datetime_hora_maxima_dia(hoy)

        self.estadisticas = {}
        self._contabilizar_estadisticas_de_llamadas()
        self._contabilizar_gestiones()
예제 #15
0
 def __init__(self):
     query_campanas = Campana.objects.obtener_all_dialplan_asterisk(
     ).filter(type__in=[Campana.TYPE_PREVIEW, Campana.TYPE_MANUAL])
     self.campanas = {}
     for campana in query_campanas:
         self.campanas[campana.id] = campana
     hoy = localtime(now())
     self.desde = datetime_hora_minima_dia(hoy)
     self.hasta = datetime_hora_maxima_dia(hoy)
     self.estadisticas = {}
     self._contabilizar_estadisticas_de_llamadas()
     self._contabilizar_gestiones()
     self._calcular_porcentaje_objetivo()
예제 #16
0
    def setUp(self):
        self.usuario_admin_supervisor = UserFactory(is_staff=True,
                                                    is_supervisor=True)
        self.usuario_admin_supervisor.set_password(self.PWD)
        self.usuario_admin_supervisor.save()
        self.client.login(username=self.usuario_admin_supervisor.username,
                          password=self.PWD)

        hasta = now()
        desde = datetime_hora_minima_dia(hasta)
        reporte = ReporteDeLlamadas(desde, hasta, True,
                                    self.usuario_admin_supervisor)
        self.estadisticas = reporte.estadisticas
예제 #17
0
    def obtener_tiempo_llamadas_agente(self, eventos, fecha_desde, fecha_hasta, agentes):
        if fecha_desde and fecha_hasta:
            fecha_desde = datetime_hora_minima_dia(fecha_desde)
            fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)

        result = LlamadaLog.objects.values_list('agente_id') \
                                   .annotate(sum=Sum('duracion_llamada')) \
                                   .filter(time__gte=fecha_desde, time__lte=fecha_hasta) \
                                   .filter(event__in=eventos) \
                                   .filter(agente_id__in=agentes) \
                                   .exclude(campana_id=0) \
                                   .order_by('agente_id')

        return result
예제 #18
0
    def obtener_pausas_por_agente_fechas_pausa(self, fecha_desde,
                                               fecha_hasta, agente_id):
        """Devuelve todas las pausas del agente por una pausa en particular"""
        if fecha_desde and fecha_hasta:
            fecha_desde = datetime_hora_minima_dia(fecha_desde)
            fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)
        try:
            es_evento_pausa = Q(event__in=['PAUSEALL', 'UNPAUSEALL'])
            es_evento_sesion = Q(event='REMOVEMEMBER')
            return self.filter(agente_id=agente_id, time__range=(fecha_desde, fecha_hasta)).filter(
                es_evento_pausa | es_evento_sesion).order_by('-time')

        except ActividadAgenteLog.DoesNotExist:
            raise (SuspiciousOperation(_("No se encontraron pausas ")))
예제 #19
0
    def obtener_tiempos_event_agentes(self, eventos, fecha_desde, fecha_hasta,
                                      agentes):

        if fecha_desde and fecha_hasta:
            fecha_desde = datetime_hora_minima_dia(fecha_desde)
            fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)

        result = ActividadAgenteLog.objects.values_list('agente_id', 'time', 'event', 'pausa_id') \
                                           .filter(time__gte=fecha_desde, time__lte=fecha_hasta) \
                                           .filter(event__in=eventos) \
                                           .filter(agente_id__in=agentes) \
                                           .order_by('agente_id', '-time')

        return result
예제 #20
0
    def obtener_grabaciones_by_fecha_intervalo_campanas(self, fecha_inicio, fecha_fin, campanas):
        fecha_inicio = datetime_hora_minima_dia(fecha_inicio)
        fecha_fin = datetime_hora_maxima_dia(fecha_fin)
        INCLUDED_EVENTS = ['COMPLETEAGENT', 'COMPLETEOUTNUM', 'BT-COMPLETE',
                           'COMPLETE-BT', 'CT-COMPLETE', 'COMPLETE-CT', 'CAMPT-COMPLETE',
                           'COMPLETE-CAMPT', 'BTOUT-COMPLETE', 'COMPLETE-BTOUT', 'CTOUT-COMPLETE',
                           'COMPLETE-CTOUT', 'CAMPT-FAIL', 'BT-BUSY', 'BTOUT-TRY', 'CT-ABANDON',
                           'CTOUT-TRY', 'BT-TRY']

        return self.filter(time__range=(fecha_inicio, fecha_fin),
                           campana_id__in=campanas, duracion_llamada__gt=0,
                           event__in=INCLUDED_EVENTS,
                           archivo_grabacion__isnull=False).order_by('-time').\
            exclude(archivo_grabacion='-1').exclude(event='ENTERQUEUE-TRANSFER')
예제 #21
0
    def __init__(self):
        query_campanas = Campana.objects.obtener_actuales().filter(
            type=Campana.TYPE_ENTRANTE)
        self.campanas = {}
        for campana in query_campanas:
            self.campanas[campana.id] = campana

        hoy = localtime(now())
        self.desde = datetime_hora_minima_dia(hoy)
        self.hasta = datetime_hora_maxima_dia(hoy)
        self.estadisticas = {}
        self._contabilizar_estadisticas_de_llamadas()
        self._contabilizar_gestiones()
        self._contabilizar_llamadas_en_espera_por_campana()
예제 #22
0
 def obtener_pausas_por_agente_fechas_pausa(self, eventos, fecha_desde,
                                            fecha_hasta, agente_id,
                                            pausa_id):
     """Devuelve todas las pausas del agente por una pausa en particular"""
     if fecha_desde and fecha_hasta:
         fecha_desde = datetime_hora_minima_dia(fecha_desde)
         fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)
     try:
         return self.filter(agente_id=agente_id,
                            event__in=eventos,
                            time__range=(fecha_desde, fecha_hasta),
                            pausa_id=pausa_id).order_by('-time')
     except ActividadAgenteLog.DoesNotExist:
         raise (SuspiciousOperation(_("No se encontraron pausas ")))
예제 #23
0
    def _calcular_estadisticas(self, campana, fecha_desde, fecha_hasta):
        fecha_desde = datetime_hora_minima_dia(fecha_desde)
        fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)

        # obtener cantidad de calificaciones por campana
        calificaciones_nombre, calificaciones_cantidad, total_asignados = \
            self.obtener_cantidad_calificacion(campana, fecha_desde,
                                               fecha_hasta)

        # obtiene detalle de llamados no atendidos
        resultado_nombre, resultado_cantidad, total_no_atendidos = \
            self.obtener_cantidad_no_atendidos(campana, fecha_desde,
                                               fecha_hasta)

        # obtiene el total de calificaciones por agente
        (agentes_venta, total_calificados, total_ventas,
         calificaciones) = self.obtener_total_calificacion_agente(
             campana, fecha_desde, fecha_hasta)

        # obtiene las llamadas pendientes y realizadas por campana
        (llamadas_pendientes, llamadas_realizadas, llamadas_recibidas,
         tiempo_promedio_espera,
         tiempo_promedio_abandono) = self.obtener_total_llamadas(campana)

        # obtiene las cantidades totales por evento de las llamadas
        reporte = self.calcular_cantidad_llamadas(campana, fecha_desde,
                                                  fecha_hasta)
        cantidad_llamadas = (list(reporte.keys()), list(reporte.values()))

        dic_estadisticas = {
            'agentes_venta': agentes_venta,
            'total_asignados': total_asignados,
            'total_ventas': total_ventas,
            'calificaciones_nombre': calificaciones_nombre,
            'calificaciones_cantidad': calificaciones_cantidad,
            'total_calificados': total_calificados,
            'resultado_nombre': resultado_nombre,
            'resultado_cantidad': resultado_cantidad,
            'total_no_atendidos': total_no_atendidos,
            'llamadas_pendientes': llamadas_pendientes,
            'llamadas_realizadas': llamadas_realizadas,
            'llamadas_recibidas': llamadas_recibidas,
            'tiempo_promedio_espera': tiempo_promedio_espera,
            'tiempo_promedio_abandono': tiempo_promedio_abandono,
            'calificaciones': calificaciones,
            'cantidad_llamadas': cantidad_llamadas,
        }
        return dic_estadisticas
예제 #24
0
    def _calcular_estadisticas(self, campana, fecha_desde, fecha_hasta, agente):
        fecha_desde = datetime_hora_minima_dia(fecha_desde)
        fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)

        calificaciones_nombre, calificaciones_cantidad, total_asignados = \
            self.obtener_cantidad_calificacion(campana, fecha_desde, fecha_hasta, agente)

        agente_tiempo = self.calcular_tiempo_agente(agente, fecha_desde, fecha_hasta, campana)

        dic_estadisticas = {
            'total_asignados': total_asignados,
            'calificaciones_nombre': calificaciones_nombre,
            'calificaciones_cantidad': calificaciones_cantidad,
            'agente_tiempo': agente_tiempo
        }
        return dic_estadisticas
    def __init__(self, user_supervisor=None):
        if user_supervisor:
            query_campanas = self._obtener_campanas(user_supervisor)
        else:
            query_campanas = self._obtener_campanas()
        self.campanas = {}
        for campana in query_campanas:
            self.campanas[campana.id] = campana

        hoy = localtime(now())
        self.desde = datetime_hora_minima_dia(hoy)
        self.hasta = datetime_hora_maxima_dia(hoy)

        self.estadisticas = {}
        self._contabilizar_estadisticas_de_llamadas()
        self._contabilizar_gestiones()
        self._calcular_porcentaje_objetivo()
    def calcular_tiempo_llamada_agente_fecha(self, agente, fecha_inferior,
                                             fecha_superior, agente_fecha):
        """ Calcula el tiempo de llamada teniendo en cuenta los eventos
        COMPLETECALLER y COMPLETEOUTNUM, por fecha dia a dia para el agente"""

        eventos_llamadas = list(LlamadaLog.EVENTOS_FIN_CONEXION)

        logs_time = LlamadaLog.objects.obtener_tiempo_llamada_agente(
            eventos_llamadas,
            fecha_inferior,
            fecha_superior,
            agente.id).exclude(campana_id=0)

        campanas_ids = set()
        for log in logs_time:
            campanas_ids.add(log.campana_id)
            date_time_actual = fecha_local(log.time)
            agente_en_lista = list(filter(lambda x: x.agente == date_time_actual,
                                          agente_fecha))
            duracion_llamada = timedelta(seconds=log.duracion_llamada)
            if agente_en_lista:
                agente_nuevo = agente_en_lista[0]
                agente_nuevo._tiempo_llamada += duracion_llamada
                agente_nuevo._cantidad_llamadas_procesadas += 1
            else:
                agente_nuevo = AgenteTiemposReporte(
                    date_time_actual, timedelta(0), timedelta(0), duracion_llamada, 1, 0, 0, 0,
                    timedelta(0), 0)
                agente_fecha.append(agente_nuevo)

        for datos_fecha in agente_fecha:
            fecha = datos_fecha.agente
            fecha_inicial = datetime_hora_minima_dia(fecha)
            fecha_final = datetime_hora_maxima_dia(fecha)
            transferencias = LlamadaLog.objects.obtener_cantidades_de_transferencias_recibidas(
                fecha_inicial, fecha_final, [agente.id], campanas_ids)
            cant_transfers = 0
            transferencias_por_camp = transferencias.get(agente.id, {})
            for cant in transferencias_por_camp.values():
                cant_transfers += cant
            datos_fecha._cantidad_llamadas_procesadas -= cant_transfers
            datos_fecha._transferidas_a_agente = cant_transfers

        return agente_fecha
예제 #27
0
    def obtener_count_evento_agente(self, eventos, fecha_desde, fecha_hasta, agentes):
        if fecha_desde and fecha_hasta:
            fecha_desde = datetime_hora_minima_dia(fecha_desde)
            fecha_hasta = datetime_hora_maxima_dia(fecha_hasta)

        cursor = connection.cursor()
        sql = """select agente_id, count(*)
                 from reportes_app_llamadalog where time between %(fecha_desde)s and
                 %(fecha_hasta)s and event = ANY(%(eventos)s) and agente_id = ANY(%(agentes)s)
                 GROUP BY agente_id order by agente_id
        """
        params = {
            'fecha_desde': fecha_desde,
            'fecha_hasta': fecha_hasta,
            'eventos': eventos,
            'agentes': agentes,
        }

        cursor.execute(sql, params)
        values = cursor.fetchall()
        return values
    def _computar_tiempo_session_fecha(self, tiempos_fechas, inicio, fin):
        """ Computa la duracion de la sesion en la lista de tiempos por fecha """
        fecha_inicio = fecha_local(inicio)
        fecha_fin = fecha_local(fin)

        if tiempos_fechas and tiempos_fechas[-1].agente == fecha_inicio:
            tiempos = tiempos_fechas[-1]
        else:
            tiempos = AgenteTiemposReporte(
                fecha_inicio, timedelta(0), timedelta(0), timedelta(0), 0, 0, 0, 0)
            tiempos_fechas.append(tiempos)

        if fecha_fin == tiempos.agente:
            tiempos._tiempo_sesion += fin - inicio
        else:
            fin_dia = datetime_hora_maxima_dia(fecha_inicio)
            tiempos._tiempo_sesion += fin_dia - inicio
            inicio_dia = datetime_hora_minima_dia(fecha_fin)
            duracion = fin - inicio_dia
            tiempos = AgenteTiemposReporte(
                fecha_fin, duracion, timedelta(0), timedelta(0), 0, 0, 0, 0)
            tiempos_fechas.append(tiempos)
예제 #29
0
 def __init__(self):
     self.calificaciones_dict = {}
     self.estadisticas_dict_base = {
         'conectadas': {
             'total': 0,
             'salientes': 0,
             'entrantes': 0
         },
         'venta': {
             'total': 0,
             'observadas': 0
         },
         'logs': [],
     }
     self.estadisticas = {}
     self.callids_entrantes = set()
     self.callids_salientes = set()
     hoy = localtime(now())
     self.desde = datetime_hora_minima_dia(hoy)
     self.hasta = datetime_hora_maxima_dia(hoy)
     self.inicializar_estadisticas()
     self.logs_llamadas = list(self._obtener_logs_de_llamadas())
     self.calificaciones = list(self._obtener_estadisticas_calificacion())
     self.calcular_estadisticas()
예제 #30
0
    def get(self, request, pk_campana):

        try:
            campana = Campana.objects.get(id=pk_campana)
        except Campana.DoesNotExist:
            return JsonResponse(data={
                'status': 'Error',
                'error_message': _(u'No existe la campaña')
            })

        data = {'status': 'OK'}
        for opcion in campana.opciones_calificacion.all():
            data[opcion.nombre] = 0
        calificaciones = CalificacionCliente.objects.filter(
            fecha__gt=datetime_hora_minima_dia(now()),
            opcion_calificacion__campana_id=pk_campana)
        cantidades = calificaciones.values(
            'opcion_calificacion__nombre').annotate(
                cantidad=Count('opcion_calificacion__nombre'))

        for opcion in cantidades:
            data[opcion['opcion_calificacion__nombre']] = opcion['cantidad']

        return JsonResponse(data=data)