Exemplo n.º 1
0
function reportReportedeTroncalesusadasporHoraeneldia($smarty, $module_name, $local_templates_dir, &$pDB, $arrConf, &$pDB_asterisk)
{
    $pReportedeTroncalesusadasporHoraeneldia = new paloSantoReportedeTroncalesusadasporHoraeneldia($pDB);
    // PS se obtiene el arreglo con las trunks para mostrarlas en el filtro
    //$arrTrunk1 = getTrunk($pDB, $pDB_asterisk);//Trunks
    //diana
    //llamamos  funcion nueva
    $arrTrunk = obtener_nuevas_trunks($pDB, $pDB_asterisk);
    // valores del filtro
    $filter_field = getParameter("filter_field");
    $filter_value = getParameter("filter_value");
    $date_from = getParameter("date_from");
    $date_to = getParameter("date_to");
    // si la fecha no está seteada en el filtro
    $_POST["date_from"] = isset($date_from) ? $date_from : date("d M Y");
    $_POST["date_to"] = isset($date_to) ? $date_to : date("d M Y");
    $date_from = isset($date_from) ? date('Y-m-d', strtotime($date_from)) : date("Y-m-d");
    $date_to = isset($date_to) ? date('Y-m-d', strtotime($date_to)) : date("Y-m-d");
    // para setear la trunk la primera vez
    $filter_value = getParameter("filter_value");
    if (!isset($filter_value)) {
        $trunk = array_shift(array_keys($arrTrunk));
        //Trunks
        $_POST["filter_value"] = $trunk;
        $filter_value = $trunk;
    }
    //validacion para que los filtros se queden seteados con el valor correcto, correccion de bug que se estaba dando en caso de pagineo
    $_POST["filter_value"] = $filter_value;
    $bElastixNuevo = method_exists('paloSantoGrid', 'setURL');
    // begin grid parameters
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->enableExport();
    $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes';
    $limit = 50;
    $offset = 0;
    // se obtienen los datos que se van a mostrar
    $arrData = null;
    $filter_value = trim($filter_value);
    $recordset = $pReportedeTroncalesusadasporHoraeneldia->listarTraficoLlamadasHora($date_from, $date_to, empty($filter_value) ? NULL : $filter_value);
    if (!is_array($recordset)) {
        $smarty->assign(array('mb_title' => _tr('Query Error'), 'mb_message' => $oCalls->errMsg));
        $recordset = array();
    }
    $total = count($recordset);
    $oGrid->setLimit($limit);
    $oGrid->setTotal($total);
    if ($bElastixNuevo) {
        $offset = $oGrid->calculateOffset();
    } else {
        $action = getParameter("nav");
        $start = getParameter("start");
        $oGrid->calculatePagination($action, $start);
        $end = $oGrid->getEnd();
    }
    $url = array("menu" => $module_name, "filter_field" => $filter_field, "filter_value" => $filter_value, "date_from" => $date_from, "date_to" => $date_to);
    // se guarda la data en un arreglo que luego es enviado como parámetro para crear el reporte
    if (is_array($recordset)) {
        $arrData = array();
        $total = array('entered' => 0, 'terminada' => 0, 'abandonada' => 0, 'en-cola' => 0, 'fin-monitoreo' => 0);
        foreach ($recordset as $iHora => $tupla) {
            $arrData[] = array(sprintf('%02d:00:00 - %02d:00:00', $iHora, $iHora + 1), $tupla['entered'], $tupla['terminada'], $tupla['abandonada'], $tupla['en-cola'], $tupla['fin-monitoreo']);
            foreach (array_keys($total) as $k) {
                $total[$k] += $tupla[$k];
            }
        }
        $sTagInicio = !$bExportando ? '<b>' : '';
        $sTagFinal = $sTagInicio != '' ? '</b>' : '';
        $arrData[] = array($sTagInicio . _tr('TOTAL') . $sTagFinal, $sTagInicio . $total['entered'] . $sTagFinal, $sTagInicio . $total['terminada'] . $sTagFinal, $sTagInicio . $total['abandonada'] . $sTagFinal, $sTagInicio . $total['en-cola'] . $sTagFinal, $sTagInicio . $total['fin-monitoreo'] . $sTagFinal);
    }
    //begin section filter
    $arrFormFilterReportedeTroncalesusadasporHoraeneldia = createFieldFilter($arrTrunk);
    $smarty->assign("SHOW", _tr("Show"));
    $oFilterForm = new paloForm($smarty, $arrFormFilterReportedeTroncalesusadasporHoraeneldia);
    $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST, $_GET);
    //end section filter
    $oGrid->showFilter($htmlFilter);
    if ($bElastixNuevo) {
        $oGrid->setURL($url);
        $oGrid->setData($arrData);
        $arrColumnas = array(_tr("Time Period "), _tr("Entered"), _tr("Answered"), _tr("Abandoned"), _tr("In queue"), _tr("Without monitoring "));
        $oGrid->setColumns($arrColumnas);
        $oGrid->setTitle(_tr("Reporte de Troncales usadas por Hora en el dia"));
        $oGrid->pagingShow(true);
        $oGrid->setNameFile_Export(_tr("Reporte de Troncales usadas por Hora en el dia"));
        return $oGrid->fetchGrid();
    } else {
        global $arrLang;
        $url = construirURL($url, array('nav', 'start'));
        $offset = 0;
        $limit = $total + 1;
        // se crea el grid
        $arrGrid = array("title" => _tr("Reporte de Troncales usadas por Hora en el dia"), "url" => $url, "icon" => "images/list.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $end, "total" => $total, "columns" => array(0 => array("name" => _tr("Time Period "), "property1" => ""), 1 => array("name" => _tr("Entered"), "property1" => ""), 2 => array("name" => _tr("Answered"), "property1" => ""), 3 => array("name" => _tr("Abandoned"), "property1" => ""), 4 => array("name" => _tr("In queue"), "property1" => ""), 5 => array("name" => _tr("Without monitoring "), "property1" => "")));
        if ($bExportando) {
            $fechaActual = date("d M Y");
            header("Cache-Control: private");
            header("Pragma: cache");
            header('Content-Type: application/octec-stream');
            $title = "\"" . $fechaActual . ".csv\"";
            header("Content-disposition: inline; filename={$title}");
            header('Content-Type: application/force-download');
        }
        if ($bExportando) {
            return $oGrid->fetchGridCSV($arrGrid, $arrData);
        }
        $sContenido = $oGrid->fetchGrid($arrGrid, $arrData, $arrLang);
        if (strpos($sContenido, '<form') === FALSE) {
            $sContenido = "<form  method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>";
        }
        return $sContenido;
    }
}
Exemplo n.º 2
0
function listHistogram($pDB, $smarty, $module_name, $local_templates_dir)
{
    global $arrLang;
    // Tipo de llamada
    $comboTipos = array("E" => _tr("Ingoing"), "S" => _tr("Outgoing"));
    $sTipoLlamada = 'E';
    if (isset($_GET['tipo'])) {
        $sTipoLlamada = $_GET['tipo'];
    }
    if (isset($_POST['tipo'])) {
        $sTipoLlamada = $_POST['tipo'];
    }
    if (!in_array($sTipoLlamada, array_keys($comboTipos))) {
        $sTipoLlamada = 'E';
    }
    $_POST['tipo'] = $sTipoLlamada;
    // Para llenar el formulario
    $smarty->assign('TIPO', $_POST['tipo']);
    // Estado de la llamada
    $comboEstados = array('T' => _tr('All'), 'E' => _tr('Completed'), 'A' => _tr('Abandoned'));
    if ($sTipoLlamada == 'S') {
        $comboEstados['N'] = _tr('No answer/Short call');
    }
    $sEstadoLlamada = 'T';
    if (isset($_GET['estado'])) {
        $sEstadoLlamada = $_GET['estado'];
    }
    if (isset($_POST['estado'])) {
        $sEstadoLlamada = $_POST['estado'];
    }
    if (!in_array($sEstadoLlamada, array_keys($comboEstados))) {
        $sEstadoLlamada = 'E';
    }
    $_POST['estado'] = $sEstadoLlamada;
    // Para llenar el formulario
    $smarty->assign('ESTADO', $_POST['estado']);
    // Rango de fechas
    $sFechaInicial = $sFechaFinal = date('Y-m-d');
    if (isset($_GET['fecha_ini'])) {
        $sFechaInicial = date('Y-m-d', strtotime($_GET['fecha_ini']));
    }
    if (isset($_POST['fecha_ini'])) {
        $sFechaInicial = date('Y-m-d', strtotime($_POST['fecha_ini']));
    }
    if (isset($_GET['fecha_fin'])) {
        $sFechaFinal = date('Y-m-d', strtotime($_GET['fecha_fin']));
    }
    if (isset($_POST['fecha_fin'])) {
        $sFechaFinal = date('Y-m-d', strtotime($_POST['fecha_fin']));
    }
    $_POST['fecha_ini'] = date('d M Y', strtotime($sFechaInicial));
    $_POST['fecha_fin'] = date('d M Y', strtotime($sFechaFinal));
    $smarty->assign('FECHA_INI', $sFechaInicial);
    $smarty->assign('FECHA_FIN', $sFechaFinal);
    // Recuperar la lista de llamadas
    $oCalls = new paloSantoCallsHour($pDB);
    $arrCalls = $oCalls->getCalls($sTipoLlamada, $sEstadoLlamada, $sFechaInicial, $sFechaFinal);
    // TODO: manejar error al obtener llamadas
    if (!is_array($arrCalls)) {
        $smarty->assign("mb_title", _tr("Validation Error"));
        $smarty->assign("mb_message", $oCalls->errMsg);
        $arrCalls = array();
    }
    // Lista de colas a elegir para gráfico. Sólo se elige de las colas devueltas
    // por la lista de datos.
    $listaColas = array_keys($arrCalls);
    $comboColas = array('' => _tr('All'));
    if (count($listaColas) > 0) {
        $comboColas += array_combine($listaColas, $listaColas);
    }
    $sColaElegida = NULL;
    if (isset($_GET['queue'])) {
        $sColaElegida = $_GET['queue'];
    }
    if (isset($_POST['queue'])) {
        $sColaElegida = $_POST['queue'];
    }
    if (!in_array($sColaElegida, $listaColas)) {
        $sColaElegida = '';
    }
    $_POST['queue'] = $sColaElegida;
    // Para llenar el formulario
    $smarty->assign('QUEUE', $_POST['queue']);
    $url = construirURL(array('menu' => $module_name, 'tipo' => $sTipoLlamada, 'estado' => $sEstadoLlamada, 'queue' => $sColaElegida, 'fecha_ini' => $sFechaInicial, 'fecha_fin' => $sFechaFinal), array('nav', 'start'));
    $smarty->assign('url', $url);
    // Construir el arreglo como debe mostrarse en la tabla desglose
    $arrData = array();
    for ($i = 0; $i < 24; $i++) {
        $arrData[$i] = array(sprintf('%02d:00', $i));
    }
    $arrData[24] = array(_tr('Total Calls'));
    $arrCols = array(0 => array('name' => _tr('Hour')));
    $arrTodos = array_fill(0, 24, 0);
    foreach ($arrCalls as $sQueue => $hist) {
        if (empty($sColaElegida) || $sColaElegida == $sQueue) {
            $arrCols[] = array('name' => $sQueue);
            $iTotalCola = 0;
            foreach ($hist as $i => $iNumCalls) {
                $arrData[$i][] = $iNumCalls;
                $arrTodos[$i] += $iNumCalls;
                $iTotalCola += $iNumCalls;
            }
            $arrData[24][] = $iTotalCola;
        }
    }
    $arrCols[] = array('name' => _tr('All'));
    $iTotalCola = 0;
    foreach ($arrTodos as $i => $iNumCalls) {
        $arrData[$i][] = $iNumCalls;
        $iTotalCola += $iNumCalls;
    }
    $arrData[24][] = $iTotalCola;
    $smarty->assign('MODULE_NAME', $module_name);
    $smarty->assign('LABEL_FIND', _tr('Find'));
    $formFilter = getFormFilter($comboTipos, $comboEstados, $comboColas);
    $oForm = new paloForm($smarty, $formFilter);
    //Llenamos las cabeceras
    $arrGrid = array("title" => _tr("Graphic Calls per hour"), "url" => $url, "icon" => "images/list.png", "width" => "99%", "start" => 0, "end" => 0, "total" => 0, "columns" => $arrCols);
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->showFilter($oForm->fetchForm("{$local_templates_dir}/filter-graphic-calls.tpl", NULL, $_POST));
    $oGrid->enableExport();
    if (isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes') {
        $fechaActual = date("Y-m-d");
        header("Cache-Control: private");
        header("Pragma: cache");
        header('Content-Type: text/csv; charset=UTF-8; header=present');
        $title = "\"calls-per-hour-" . $fechaActual . ".csv\"";
        header("Content-disposition: attachment; filename={$title}");
        return $oGrid->fetchGridCSV($arrGrid, $arrData);
    } else {
        $bExportando = isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes' || isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' || isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes';
        $sContenido = $oGrid->fetchGrid($arrGrid, $arrData, $arrLang);
        if (!$bExportando) {
            if (strpos($sContenido, '<form') === FALSE) {
                $sContenido = "<form  method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>";
            }
        }
        return $sContenido;
    }
}
Exemplo n.º 3
0
function _moduleContent(&$smarty, $module_name)
{
    global $arrConf;
    global $arrConfModule;
    //include module files
    include_once "modules/{$module_name}/configs/default.conf.php";
    include_once "modules/{$module_name}/libs/paloSantoTiempoConexiondeAgentes.class.php";
    include_once "libs/paloSantoConfig.class.php";
    $arrConf = array_merge($arrConf, $arrConfModule);
    // Obtengo la ruta del template a utilizar para generar el filtro.
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $templates_dir = isset($arrConf['templates_dir']) ? $arrConf['templates_dir'] : 'themes';
    $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConf['theme'];
    load_language_module($module_name);
    //conexion resource
    $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*");
    $arrConfig = $pConfig->leer_configuracion(false);
    $dsnAsteriskCdr = $arrConfig['AMPDBENGINE']['valor'] . "://" . $arrConfig['AMPDBUSER']['valor'] . ":" . $arrConfig['AMPDBPASS']['valor'] . "@" . $arrConfig['AMPDBHOST']['valor'] . "/asterisk";
    $pDB = new paloDB($arrConf['dsn_conn_database']);
    $pDB_asterisk = new paloDB($dsnAsteriskCdr);
    $oCallsAgent = new paloSantoTiempoConexiondeAgentes($pDB);
    // Variables estáticas asignadas vía Smarty
    $smarty->assign(array("Filter" => _tr('Show')));
    $bElastixNuevo = method_exists('paloSantoGrid', 'setURL');
    $oGrid = new paloSantoGrid($smarty);
    $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes';
    // Estas son las colas entrantes disponibles en el sistema
    $arrQueue = leerColasEntrantes($pDB, $pDB_asterisk);
    $t = array_keys($arrQueue);
    if (count($t) <= 0) {
        // TODO: internacionalizar y poner en plantilla
        return <<<NO_QUEUE_END
<p><b>No queues have been defined for incoming calls.</b></p>
<p>For proper operation and reporting, it is necessary to configure at least one queue. You can add queues <a href="?menu=pbxconfig&amp;display=queues">here</a>. 
In addition, the queue must be registered for use by incoming calls by clicking <a href="?menu=queues">here</a>.</p>
NO_QUEUE_END;
    }
    $sColaOmision = $t[0];
    //Esto es para validar cuando recien se entra al modulo, para q aparezca seteado un numero de agente en el textbox
    // TODO: reemplazar con lista desplegable de agentes en cola elegida
    $sAgenteOmision = $oCallsAgent->obtener_agente();
    $arrFormElements = createFieldFilter($arrQueue);
    $oFilterForm = new paloForm($smarty, $arrFormElements);
    // Valores iniciales de las variables
    $paramConsulta = array('date_start' => date('d M Y'), 'date_end' => date('d M Y'), 'queue' => $sColaOmision, 'agent' => $sAgenteOmision);
    foreach (array_keys($paramConsulta) as $k) {
        if (isset($_GET[$k])) {
            $paramConsulta[$k] = $_GET[$k];
        }
        if (isset($_POST[$k])) {
            $paramConsulta[$k] = $_POST[$k];
        }
    }
    if ($oFilterForm->validateForm($paramConsulta)) {
        // Exito, puedo procesar los datos ahora.
    } else {
        // Error
        $smarty->assign("mb_title", _tr("Validation Error"));
        $arrErrores = $oFilterForm->arrErroresValidacion;
        $strErrorMsg = "<b>" . _tr('Required field') . ":</b><br/>";
        foreach ($arrErrores as $k => $v) {
            $strErrorMsg .= "{$k}, ";
        }
        $strErrorMsg .= "";
        $smarty->assign("mb_message", $strErrorMsg);
        $paramConsulta = array('date_start' => date('d M Y'), 'date_end' => date('d M Y'), 'queue' => $sColaOmision, 'agent' => $sAgenteOmision);
    }
    // Se genera el filtro con las variables ya validadas
    $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $paramConsulta);
    // Consultar los datos y generar la matriz del reporte
    $sFechaInicial = translateDate($paramConsulta['date_start']);
    $sFechaFinal = translateDate($paramConsulta['date_end']);
    $r = $oCallsAgent->reportarBreaksAgente($paramConsulta['agent'], $paramConsulta['queue'], $sFechaInicial, $sFechaFinal);
    $b = $bExportando ? array('', '') : array('<b>', '</b>');
    $ub = $bExportando ? array('', '') : array('<u><b>', '</b></u>');
    $arrData = array();
    if (is_array($r) && count($r) > 0) {
        $tempTiempos = array('monitoreadas' => 0, 'llamadas_por_hora' => 0, 'duracion_llamadas' => 0, 'promedio_duracion' => 0, 'total_llamadas' => 0);
        foreach ($r['tiempos_llamadas'] as $tupla) {
            $tempTiempos['llamadas_por_hora'] = $tempTiempos['total_llamadas'] += $tupla['N'];
            $tempTiempos['duracion_llamadas'] += $tupla['tiempo_llamadas_entrantes'];
            if ($tupla['status'] == 'terminada') {
                $tempTiempos['monitoreadas'] = $tupla['N'];
                $tempTiempos['promedio_duracion'] = $tupla['promedio_sobre_monitoreadas'];
            }
        }
        if ($r['tiempo_conexion'] > 0) {
            $tempTiempos['llamadas_por_hora'] /= $r['tiempo_conexion'] / 3600;
        }
        $sFormatoMonitoreadas = sprintf('%d %s(s) (%d %s, %d %s)', $tempTiempos['total_llamadas'], _tr('Call'), $tempTiempos['monitoreadas'], _tr('Monitored'), $tempTiempos['total_llamadas'] - $tempTiempos['monitoreadas'], _tr('Unmonitored'));
        $arrData = array(array($b[0] . strtoupper(_tr('Agent name')) . $b[1], $r['name'], "", ""), array($b[0] . strtoupper(_tr('Conecction Data')) . $b[1], "", "", ""), array(_tr('First Conecction'), $r['primera_conexion'], "", ""), array(_tr('Last Conecction'), $r['ultima_conexion'], "", ""), array(_tr('Time Conecction'), formatoSegundos($r['tiempo_conexion']), "", ""), array(_tr('Count Conecction'), $r['conteo_conexion'], "", ""), array($b[0] . strtoupper(_tr('Calls Entry')) . $b[1], "", "", ""), array(_tr('Count Calls Entry'), $sFormatoMonitoreadas, "", ""), array(_tr('Calls/h'), number_format($tempTiempos['llamadas_por_hora'], 2), "", ""), array(_tr('Time Call Entry'), formatoSegundos($tempTiempos['duracion_llamadas']), "", ""), array(_tr('Average Calls Entry'), $tempTiempos['promedio_duracion'] . "    (" . _tr('Monitored only') . ')', "", ""), array($b[0] . strtoupper(_tr('Reason No Ready')) . $b[1], "", "", ""), array($ub[0] . _tr('Break') . $ub[1], $ub[0] . _tr('Count') . $ub[1], $ub[0] . _tr('Hour') . $ub[1], $ub[0] . _tr('Porcent compare whit time not ready') . $ub[1]));
        $tempBreaks = array();
        $iTotalSeg = 0;
        foreach ($r['tiempos_breaks'] as $tupla) {
            $tempBreaks[] = array($tupla['name'], $tupla['N'], formatoSegundos($tupla['total_break']), $tupla['total_break']);
            $iTotalSeg += $tupla['total_break'];
        }
        for ($i = 0; $i < count($tempBreaks); $i++) {
            $tempBreaks[$i][3] = number_format(100.0 * ($tempBreaks[$i][3] / $iTotalSeg), 2) . ' %';
            $arrData[] = $tempBreaks[$i];
        }
    } else {
        if (!is_array($r)) {
            $smarty->assign("mb_title", _tr("Database Error"));
            $smarty->assign("mb_message", $oCallsAgent->errMsg);
        }
        $arrData[] = array($b[0] . _tr("There aren't records to show") . $b[1], '', '', '');
    }
    // Creo objeto de grid
    $oGrid->enableExport();
    $oGrid->showFilter($htmlFilter);
    // La definición del grid
    $paramConsulta['menu'] = $module_name;
    if ($bElastixNuevo) {
        $oGrid->setURL(construirURL($paramConsulta));
        $oGrid->setData($arrData);
        $arrColumnas = array("", "", "", "");
        $oGrid->setColumns($arrColumnas);
        $oGrid->setTitle(_tr("Agent Information"));
        $oGrid->pagingShow(false);
        $oGrid->setNameFile_Export(_tr("Agent Information"));
        $smarty->assign("SHOW", _tr("Show"));
        return $oGrid->fetchGrid();
    } else {
        global $arrLang;
        $total = $end = count($arrData);
        $offset = 0;
        $url = construirUrl($paramConsulta);
        $arrGrid = array("title" => _tr("Time conecction of agents"), "icon" => "images/list.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $end, "total" => $total, "url" => $url, "columns" => array(0 => array("name" => "", "property" => ""), 1 => array("name" => "", "property" => ""), 2 => array("name" => "", "property" => ""), 3 => array("name" => "", "property" => "")));
        if ($bExportando) {
            $fechaActual = date("d M Y");
            header("Cache-Control: private");
            header("Pragma: cache");
            $title = $fechaActual;
            header('Content-Type: text/csv; charset=utf-8; header=present');
            header("Content-disposition: attachment; filename=\"" . $title . ".csv\"");
        }
        if ($bExportando) {
            return $oGrid->fetchGridCSV($arrGrid, $arrData);
        }
        $sContenido = $oGrid->fetchGrid($arrGrid, $arrData, $arrLang);
        if (strpos($sContenido, '<form') === FALSE) {
            $sContenido = "<form  method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>";
        }
        return $sContenido;
    }
}