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
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
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
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
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), }
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
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)
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
def calcular_tiempo_pausa_tipo(self, agentes, fecha_inferior, fecha_superior): """ Calcula el tiempo por tipo de pausa de los agentes en el periodo evaluado :return: un listado de agentes con el tiempo de pausa """ eventos_pausa = ['PAUSEALL', 'UNPAUSEALL', 'REMOVEMEMBER'] agentes_tiempo = [] # iterar por agente evaluando los eventos de pausa agentes_id = [agente.id for agente in agentes] logs_time = ActividadAgenteLog.objects.obtener_tiempos_event_agentes( eventos_pausa, fecha_inferior, fecha_superior, agentes_id) # Establezco un limite hasta al cual calcular la ultima pausa no finalizada hora_limite = now() hora_maxima = datetime_hora_maxima_dia(fecha_superior) if hora_maxima < hora_limite: hora_limite = hora_maxima TIME = 1 EVENT = 2 ID_PAUSA = 3 for agente in agentes: time_actual = hora_limite tiempos_pausa = {} logs_agente = self._filter_query_por_agente(logs_time, agente.id) # Iterar los logs (del último al primero) y contabiliza pausas cada vez que encuentra # un PAUSEALL seguido de otro evento PAUSEALL, UNPAUSEALL o REMOVEMEMBER for log in logs_agente: # Asumo que si la pausa no esta finalizada, es porque el agente esta online if log[EVENT] == 'PAUSEALL': resta = time_actual - log[TIME] id_pausa = log[ID_PAUSA] if id_pausa in tiempos_pausa.keys(): tiempos_pausa[id_pausa] += resta else: tiempos_pausa.update({id_pausa: resta}) time_actual = log[TIME] if log[EVENT] == 'UNPAUSEALL' or log[EVENT] == 'REMOVEMEMBER': time_actual = log[TIME] for id_pausa in tiempos_pausa: datos_de_pausa = self._obtener_datos_de_pausa(id_pausa) tiempo = str(timedelta(seconds=tiempos_pausa[id_pausa].seconds)) tiempo_agente = { 'id': agente.id, 'nombre_agente': agente.user.get_full_name(), 'pausa': datos_de_pausa['nombre'], 'tipo_de_pausa': datos_de_pausa['tipo'], 'tiempo': tiempo, 'pausa_id': id_pausa } agentes_tiempo.append(tiempo_agente) return agentes_tiempo
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 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'))
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 ")))
def calcular_tiempo_pausa_tipo_fecha(self, agente, fecha_inferior, fecha_superior, pausa_id): """ Calcula el tiempo de pausa de los agentes en el periodo evaluado :return: un listado de agentes con el tiempo de pausa """ agentes_tiempo = [] # iterar por agente evaluando los eventos de pausa logs_time = ActividadAgenteLog.objects.obtener_pausas_por_agente_fechas_pausa( fecha_inferior, fecha_superior, agente.id) # Establezco un limite hasta al cual calcular la ultima pausa no finalizada hora_limite = now() hora_maxima = datetime_hora_maxima_dia(fecha_superior) if hora_maxima < hora_limite: hora_limite = hora_maxima time_actual = hora_limite tiempos_pausa = {} # iterar los log teniendo en cuenta que si encuentra un evento # UNPAUSEALL/REMOVEMEMBER y luego un PAUSEALL calcula el tiempo de session for log in logs_time: # Descarto otras Pausas, pero las tengo en cuenta para contabilizar finalizaciones if log.event == 'PAUSEALL' and log.pausa_id != pausa_id: time_actual = log.time # Descarto Pausas sin log de finalización elif log.event == 'PAUSEALL': resta = time_actual - log.time fecha_pausa = fecha_local(time_actual) if fecha_pausa in tiempos_pausa.keys(): tiempos_pausa[fecha_pausa] += resta else: tiempos_pausa.update({fecha_pausa: resta}) time_actual = log.time if log.event == 'UNPAUSEALL' or log.event == 'REMOVEMEMBER': time_actual = log.time datos_de_pausa = self._obtener_datos_de_pausa(str(pausa_id)) for item in tiempos_pausa: tiempo = str(timedelta(seconds=tiempos_pausa[item].seconds)) tiempo_agente = { 'fecha': item, 'pausa': datos_de_pausa['nombre'], 'tipo_de_pausa': datos_de_pausa['tipo'], 'tiempo': tiempo, } agentes_tiempo.append(tiempo_agente) return agentes_tiempo
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()
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()
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
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 ")))
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 ")))
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
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')
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()
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
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_pausa_fecha_agente(self, agente, fecha_inferior, fecha_superior, agente_fecha): """ Calcula el tiempo de pausa teniendo en cuenta los eventos PAUSEALL, UNPAUSEALL y REMOVEMEMBER por fecha dia a dia para el agente""" eventos_pausa = ['PAUSEALL', 'UNPAUSEALL', 'REMOVEMEMBER'] logs_time = ActividadAgenteLog.objects.obtener_tiempos_event_agentes( eventos_pausa, fecha_inferior, fecha_superior, [agente.id]) # Establezco un limite hasta al cual calcular la ultima pausa no finalizada hora_limite = now() hora_maxima = datetime_hora_maxima_dia(fecha_superior) if hora_maxima < hora_limite: hora_limite = hora_maxima TIME = 1 EVENT = 2 time_actual = hora_limite for log in logs_time: agente_nuevo = None # Descarto Pausas sin log de finalización if log[EVENT] == 'PAUSEALL': resta = time_actual - log[TIME] date_time_actual = fecha_local(time_actual) agente_en_lista = list(filter(lambda x: x.agente == date_time_actual, agente_fecha)) if agente_en_lista: agente_nuevo = agente_en_lista[0] agente_nuevo._tiempo_pausa += resta else: agente_nuevo = AgenteTiemposReporte( fecha_local(time_actual), timedelta(0), resta, timedelta(0), 0, 0, 0, 0, timedelta(0), 0) agente_fecha.append(agente_nuevo) time_actual = log[TIME] if log[EVENT] == 'UNPAUSEALL' or log[EVENT] == 'REMOVEMEMBER': time_actual = log[TIME] return agente_fecha
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
def calcular_tiempo_pausa(self, agentes, fecha_inferior, fecha_superior): """ Calcula el tiempo de pausa teniendo en cuenta los eventos PAUSEALL, UNPAUSEALL y REMOVEMEMBER""" eventos_pausa = ['PAUSEALL', 'UNPAUSEALL', 'REMOVEMEMBER'] agentes_id = [agente.id for agente in agentes] logs_time = ActividadAgenteLog.objects.obtener_tiempos_event_agentes( eventos_pausa, fecha_inferior, fecha_superior, agentes_id) # Establezco un limite hasta al cual calcular la ultima pausa no finalizada hora_limite = now() hora_maxima = datetime_hora_maxima_dia(fecha_superior) if hora_maxima < hora_limite: hora_limite = hora_maxima TIME = 1 EVENT = 2 for agente in agentes: time_actual = hora_limite logs_agente = self._filter_query_por_agente(logs_time, agente.id) for log in logs_agente: # Asumo que si la pausa no esta finalizada, es porque el agente esta online if log[EVENT] == 'PAUSEALL': resta = time_actual - log[TIME] agente_en_lista = list(filter(lambda x: x.agente == agente, self.agentes_tiempo)) if agente_en_lista: agente_nuevo = agente_en_lista[0] agente_nuevo._tiempo_pausa += resta else: agente_nuevo = AgenteTiemposReporte( agente, timedelta(0), resta, timedelta(0), 0, 0, 0, 0) self.agentes_tiempo.append(agente_nuevo) time_actual = log[TIME] if log[EVENT] == 'UNPAUSEALL' or log[EVENT] == 'REMOVEMEMBER': time_actual = log[TIME]
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)
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()