Esempio n. 1
0
function listAgent($pDB, $smarty, $module_name, $local_templates_dir)
{
    global $arrLang;
    $oAgentes = new Agentes($pDB);
    // Operaciones de manipulación de agentes
    if (isset($_POST['reparar_db']) && ereg('^[[:digit:]]+$', $_POST['reparar_db'])) {
        // Hay que agregar el agente al archivo de configuración de Asterisk
        $infoAgente = $oAgentes->getAgents($_POST['reparar_db']);
        if (!is_array($infoAgente)) {
            $smarty->assign(array('mb_title' => 'DB Error', 'mb_message' => $oAgentes->errMsg));
        } elseif (count($infoAgente) == 0) {
            // Agente no existe en DB, no se hace nada
        } elseif (!$oAgentes->addAgentFile(array($infoAgente['number'], $infoAgente['password'], $infoAgente['name']))) {
            $smarty->assign(array('mb_title' => _tr("Error saving agent in file"), 'mb_message' => $oAgentes->errMsg));
        }
    } elseif (isset($_POST['reparar_file']) && ereg('^[[:digit:]]+$', $_POST['reparar_file'])) {
        // Hay que remover el agente del archivo de configuración de Asterisk
        if (!$oAgentes->deleteAgentFile($_POST['reparar_file'])) {
            $smarty->assign(array('mb_title' => _tr("Error when deleting agent in file"), 'mb_message' => $oAgentes->errMsg));
        }
    } elseif (isset($_POST['delete']) && isset($_POST['agent_number']) && ereg('^[[:digit:]]+$', $_POST['agent_number'])) {
        // Borrar el agente indicado de la base de datos, y del archivo
        if (!$oAgentes->deleteAgent($_POST['agent_number'])) {
            $smarty->assign(array('mb_title' => _tr("Error Delete Agent"), 'mb_message' => $oAgentes->errMsg));
        }
    } elseif (isset($_POST['disconnect']) && isset($_POST['agent_number']) && ereg('^[[:digit:]]+$', $_POST['agent_number'])) {
        // Desconectar agentes. El código en Agentes.class.php puede desconectar
        // varios agentes a la vez, pero aquí sólo se desconecta uno.
        $arrAgentes = array($_POST['agent_number']);
        if (!$oAgentes->desconectarAgentes($arrAgentes)) {
            $smarty->assign(array('mb_title' => 'Unable to disconnect agent', 'mb_message' => $oAgentes->errMsg));
        }
    }
    // Estados posibles del agente
    $sEstadoAgente = 'All';
    $listaEstados = array("All" => _tr("All"), "Online" => _tr("Online"), "Offline" => _tr("Offline"), "Repair" => _tr("Repair"));
    if (isset($_GET['cbo_estado'])) {
        $sEstadoAgente = $_GET['cbo_estado'];
    }
    if (isset($_POST['cbo_estado'])) {
        $sEstadoAgente = $_POST['cbo_estado'];
    }
    if (!in_array($sEstadoAgente, array_keys($listaEstados))) {
        $sEstadoAgente = 'All';
    }
    // Leer los agentes activos y comparar contra la lista de Asterisk
    $listaAgentesCallCenter = $oAgentes->getAgents();
    function get_agente_num($t)
    {
        return $t['number'];
    }
    $listaNumAgentesCallCenter = array_map('get_agente_num', $listaAgentesCallCenter);
    $listaNumAgentesAsterisk = $oAgentes->getAgentsFile();
    $listaNumSobrantes = array_diff($listaNumAgentesAsterisk, $listaNumAgentesCallCenter);
    $listaNumFaltantes = array_diff($listaNumAgentesCallCenter, $listaNumAgentesAsterisk);
    /* La variable $listaNumSobrantes tiene ahora todos los IDs de agente que 
          constan en Asterisk y no en la tabla call_center.agent como activos.
          La variable $listaNumFaltantes tiene los agentes que constan en 
          call_center.agent y no en Asterisk. El código posterior asume que el 
          archivo de agentes de Asterisk debería cambiarse para que refleje la
          tabla call_center.agent .
       */
    // Campo sync debe ser OK, o ASTERISK si consta en Asterisk pero no en
    // CallCenter, o CC si consta en CallCenter pero no en Asterisk.
    foreach (array_keys($listaAgentesCallCenter) as $k) {
        $listaAgentesCallCenter[$k]['sync'] = in_array($listaAgentesCallCenter[$k]['number'], $listaNumFaltantes) ? 'CC' : 'OK';
    }
    // Lista de todos los agentes conocidos, incluyendo los sobrantes.
    $listaAgentes = $listaAgentesCallCenter;
    foreach ($listaNumSobrantes as $idSobrante) {
        $listaAgentes[] = array('id' => NULL, 'number' => $oAgentes->arrAgents[$idSobrante][0], 'name' => $oAgentes->arrAgents[$idSobrante][2], 'password' => $oAgentes->arrAgents[$idSobrante][1], 'estatus' => NULL, 'sync' => 'ASTERISK');
    }
    // Listar todos los agentes que están conectados
    $listaOnline = $oAgentes->getOnlineAgents();
    if (is_array($listaOnline)) {
        foreach (array_keys($listaAgentes) as $k) {
            $listaAgentes[$k]['online'] = in_array($listaAgentes[$k]['number'], $listaOnline);
        }
    } else {
        $smarty->assign("mb_title", 'Unable to read agent');
        $smarty->assign("mb_message", 'Cannot read agent - ' . $oAgentes->errMsg);
        foreach (array_keys($listaAgentes) as $k) {
            $listaAgentes[$k]['online'] = NULL;
        }
    }
    // Filtrar los agentes conocidos según el estado que se requiera
    function estado_Online($t)
    {
        return $t['sync'] == 'OK' && $t['online'];
    }
    function estado_Offline($t)
    {
        return $t['sync'] == 'OK' && !$t['online'];
    }
    function estado_Repair($t)
    {
        return $t['sync'] != 'OK';
    }
    if ($sEstadoAgente != 'All') {
        $listaAgentes = array_filter($listaAgentes, "estado_{$sEstadoAgente}");
    }
    $arrData = array();
    $sImgVisto = "<img src='modules/{$module_name}/themes/images/visto.gif' border='0' />";
    $sImgErrorCC = "<img src='modules/{$module_name}/themes/images/error_small.png' border='0' title=\"" . _tr("Agent doesn't exist in configuration file") . "\" />";
    $sImgErrorAst = "<img src='modules/{$module_name}/themes/images/error_small.png' border='0' title=\"" . _tr("Agent doesn't exist in database") . "\" />";
    $smarty->assign(array('PREGUNTA_BORRAR_AGENTE_CONF' => _tr("To rapair is necesary delete agent from configuration file. Do you want to continue?"), 'PREGUNTA_AGREGAR_AGENTE_CONF' => _tr("To rapair is necesary add an agent in configuration file. Do you want to continue?")));
    foreach ($listaAgentes as $tuplaAgente) {
        $tuplaData = array("<input class=\"button\" type=\"radio\" name=\"agent_number\" value=\"{$tuplaAgente["number"]}\" />", NULL, htmlentities($tuplaAgente['number'], ENT_COMPAT, 'UTF-8'), htmlentities($tuplaAgente['name'], ENT_COMPAT, 'UTF-8'), $tuplaAgente['sync'] != 'CC' ? $tuplaAgente['online'] ? _tr("Online") : _tr("Offline") : '&nbsp;', "<a href='?menu=agents&amp;action=edit_agent&amp;id_agent=" . $tuplaAgente["number"] . "'>[" . _tr("Edit") . "]</a>");
        switch ($tuplaAgente['sync']) {
            case 'OK':
                $tuplaData[1] = $sImgVisto;
                break;
            case 'ASTERISK':
                $tuplaData[1] = $sImgErrorAst . "&nbsp;<a href='javascript:preguntar_por_reparacion(\"" . $tuplaAgente['number'] . "\",\"reparar_file\", pregunta_borrar_agente_conf)'>" . _tr('Repair') . "</a>";
                $tuplaData[5] = '&nbsp;';
                // No mostrar opción de editar agente que no está en DB
                break;
            case 'CC':
                $tuplaData[1] = $sImgErrorCC . "&nbsp;<a href='javascript:preguntar_por_reparacion(\"" . $tuplaAgente['number'] . "\",\"reparar_db\", pregunta_agregar_agente_conf)'>" . _tr('Repair') . "</a>";
                break;
        }
        $arrData[] = $tuplaData;
    }
    $url = construirURL(array('menu' => $module_name, 'cbo_estado' => $sEstadoAgente), array('nav', 'start'));
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->setLimit(50);
    if (is_array($arrData)) {
        $oGrid->setTotal(count($arrData));
        $offset = $oGrid->calculateOffset();
        $arrData = array_slice($arrData, $offset, $oGrid->getLimit());
    }
    // Construir el reporte de los agentes activos
    $arrGrid = array("title" => "Số máy nhánh", "url" => $url, "icon" => "images/user.png", "width" => "99%", "columns" => array(0 => array("name" => '&nbsp;', "property1" => ""), 1 => array("name" => _tr("Configure"), "property1" => ""), 2 => array("name" => _tr("Number"), "property1" => ""), 3 => array("name" => _tr("Name"), "property1" => ""), 4 => array("name" => _tr("Status"), "property1" => ""), 5 => array("name" => _tr("Options"), "property1" => "")));
    $smarty->assign(array('LABEL_STATE' => _tr('Status'), 'LABEL_CREATE_AGENT' => _tr("New agent"), 'estados' => $listaEstados, 'estado_sel' => $sEstadoAgente, 'MODULE_NAME' => $module_name, 'LABEL_WITH_SELECTION' => _tr('With selection'), 'LABEL_DISCONNECT' => _tr('Disconnect'), 'LABEL_DELETE' => _tr('Delete'), 'MESSAGE_CONTINUE_DELETE' => _tr("Are you sure you wish to continue?")));
    $oGrid->showFilter($smarty->fetch("{$local_templates_dir}/filter-list-agents.tpl"));
    $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;
}
Esempio n. 2
0
function listCampaign($pDB, $smarty, $module_name, $local_templates_dir)
{
    global $arrLang;
    $arrData = '';
    $oCampaign = new paloSantoCampaignCC($pDB);
    // Recoger ID de campaña para operación
    $id_campaign = NULL;
    if (isset($_POST['id_campaign']) && ereg('^[[:digit:]]+$', $_POST['id_campaign'])) {
        $id_campaign = $_POST['id_campaign'];
    }
    // Revisar si se debe de borrar una campaña elegida
    if (isset($_POST['delete']) && !is_null($id_campaign)) {
        if ($oCampaign->delete_campaign($id_campaign)) {
            if ($oCampaign->errMsg != "") {
                $smarty->assign("mb_title", _tr('Validation Error'));
                $smarty->assign("mb_message", $oCampaign->errMsg);
            } else {
            }
        } else {
            $msg_error = $oCampaign->errMsg != "" ? "<br/>" . $oCampaign->errMsg : "";
            $smarty->assign("mb_title", _tr('Delete Error'));
            $smarty->assign("mb_message", _tr('Error when deleting the Campaign') . $msg_error);
        }
    }
    // Revisar si se debe activar una campaña elegida
    if (isset($_POST['activate']) && !is_null($id_campaign)) {
        if (!$oCampaign->activar_campaign($id_campaign, 'A')) {
            $smarty->assign("mb_title", _tr('Activate Error'));
            $smarty->assign("mb_message", _tr('Error when Activating the Campaign'));
        }
    }
    // Revisar si se debe desactivar una campaña elegida
    if (isset($_POST['deactivate']) && !is_null($id_campaign)) {
        if (!$oCampaign->activar_campaign($id_campaign, 'I')) {
            $smarty->assign("mb_title", _tr("Desactivate Error"));
            $smarty->assign("mb_message", _tr("Error when desactivating the Campaign"));
        }
    }
    // Validar el filtro por estado de actividad de la campaña
    $estados = array("all" => _tr("All"), "A" => _tr("Active"), "T" => _tr("Finish"), "I" => _tr("Inactive"));
    $sEstado = 'A';
    if (isset($_GET['cbo_estado']) && isset($estados[$_GET['cbo_estado']])) {
        $sEstado = $_GET['cbo_estado'];
    }
    if (isset($_POST['cbo_estado']) && isset($estados[$_POST['cbo_estado']])) {
        $sEstado = $_POST['cbo_estado'];
    }
    // para el pagineo
    $arrCampaign = $oCampaign->getCampaigns(NULL, NULL, NULL, $sEstado);
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->setLimit(50);
    $oGrid->setTotal(count($arrCampaign));
    $offset = $oGrid->calculateOffset();
    $arrCampaign = array_slice($arrCampaign, $offset, $oGrid->getLimit());
    $url = construirURL(array('menu' => $module_name, 'cbo_estado' => $sEstado), array('nav', 'start'));
    if (is_array($arrCampaign)) {
        foreach ($arrCampaign as $campaign) {
            $arrTmp = array();
            $arrTmp[0] = "<input class=\"button\" type=\"radio\" name=\"id_campaign\" value=\"{$campaign['id']}\" />";
            $arrTmp[1] = $campaign['name'];
            $arrTmp[2] = $campaign['datetime_init'] . ' - ' . $campaign['datetime_end'];
            $arrTmp[3] = $campaign['daytime_init'] . ' - ' . $campaign['daytime_end'];
            $arrTmp[4] = $campaign['retries'] != "" ? $campaign['retries'] : "&nbsp;";
            $arrTmp[5] = is_null($campaign['trunk']) ? '(Dialplan)' : $campaign['trunk'];
            $arrTmp[6] = $campaign['queue'];
            $arrTmp[7] = $campaign['num_completadas'] != "" ? $campaign['num_completadas'] : "N/A";
            $arrTmp[8] = $campaign['promedio'] != "" ? number_format($campaign['promedio'], 0) : "N/A";
            $csv_data = "&nbsp;<a href='?menu={$module_name}&amp;action=csv_data&amp;id_campaign=" . $campaign['id'] . "&amp;rawmode=yes'>[" . _tr('CSV Data') . "]</a>";
            $ver_campania = "&nbsp;<a href='?menu={$module_name}&amp;action=edit_campaign&amp;id_campaign=" . $campaign['id'] . "'>[" . _tr('Edit') . "]</a>";
            if ($campaign['estatus'] == 'I') {
                $arrTmp[9] = _tr('Inactive');
                $arrTmp[10] = $ver_campania . $csv_data;
            } elseif ($campaign['estatus'] == 'A') {
                $arrTmp[9] = _tr('Active');
                $arrTmp[10] = $ver_campania . $csv_data;
            } elseif ($campaign['estatus'] == 'T') {
                $arrTmp[9] = _tr('Finish');
                $arrTmp[10] = $ver_campania . $csv_data;
            }
            $arrData[] = $arrTmp;
        }
    }
    // Definición de la tabla de las campañas
    $arrGrid = array("title" => _tr("Campaigns List"), "url" => $url, "icon" => "images/list.png", "width" => "99%", "columns" => array(0 => array("name" => ''), 1 => array("name" => _tr("Name Campaign")), 2 => array("name" => _tr("Range Date")), 3 => array("name" => _tr("Schedule per Day")), 4 => array("name" => _tr("Retries")), 5 => array("name" => _tr("Trunk")), 6 => array("name" => _tr("Queue")), 7 => array("name" => _tr("Completed Calls")), 8 => array("name" => _tr("Average Time")), 9 => array("name" => _tr("Status")), 10 => array("name" => _tr("Options"))));
    // Construir el HTML del filtro
    $smarty->assign(array('MODULE_NAME' => $module_name, 'LABEL_CAMPAIGN_STATE' => _tr('Campaign state'), 'estados' => $estados, 'estado_sel' => $sEstado, 'LABEL_CREATE_CAMPAIGN' => _tr('Create New Campaign'), 'LABEL_WITH_SELECTION' => _tr('With selection'), 'LABEL_ACTIVATE' => _tr('Activate'), 'LABEL_DEACTIVATE' => _tr('Desactivate'), 'LABEL_DELETE' => _tr('Delete'), 'MESSAGE_CONTINUE_DEACTIVATE' => _tr("Are you sure you wish to continue?"), 'MESSAGE_CONTINUE_DELETE' => _tr("Are you sure you wish to delete campaign?")));
    $oGrid->showFilter($smarty->fetch("{$local_templates_dir}/filter-list-campaign.tpl"));
    $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;
}
Esempio n. 3
0
function listCalls($pDB, $smarty, $module_name, $local_templates_dir)
{
    global $arrLang;
    $arrCalls = array();
    $oCalls = new PaloSantoDontCalls($pDB);
    $arrCalls = $oCalls->getCalls();
    $end = count($arrCalls);
    if (is_array($arrCalls) && count($arrCalls) > 0) {
        foreach ($arrCalls as $call) {
            $arrTmp = array();
            $arrTmp[0] = construirCheck($call['id']);
            $arrTmp[1] = $call['caller_id'];
            $arrTmp[2] = $call['date_income'];
            if ($call['status'] == 'I') {
                $arrTmp[3] = _tr('Inactive');
            } else {
                $arrTmp[3] = _tr('Active');
            }
            $arrData[] = $arrTmp;
        }
    } else {
        $arrData = array();
    }
    $button_delete = "<input class='button' type='submit' name='submit_delete'" . " value='" . _tr('Remove') . "'>";
    $url = construirURL(array('menu' => $module_name), array('nav', 'start'));
    $arrGrid = array("title" => _tr('Phone List'), "url" => $url, "icon" => "images/list.png", "width" => "99%", "start" => $end == 0 ? 0 : 1, "end" => $end, "total" => $end, "columns" => array(0 => array("name" => $button_delete, "property1" => ""), 1 => array("name" => _tr("Number Phone's"), "property1" => ""), 2 => array("name" => _tr('Date Income'), "property1" => ""), 3 => array("name" => _tr('Status'), "property1" => "")));
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->showFilter("<input type='submit' name='submit_Add_Call' value='" . _tr('Add') . "' class='button' />&nbsp&nbsp&nbsp&nbsp" . "<input type='submit' name='submit_Apply' value='" . _tr('Apply') . "' class='button' />");
    $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;
}
Esempio n. 4
0
function reportReportsBreak($smarty, $module_name, $local_templates_dir, &$pDB)
{
    // Obtener rango de fechas de consulta. Si no existe, se asume día de hoy
    $sFechaInicio = date('d M Y');
    if (isset($_GET['txt_fecha_init'])) {
        $sFechaInicio = $_GET['txt_fecha_init'];
    }
    if (isset($_POST['txt_fecha_init'])) {
        $sFechaInicio = $_POST['txt_fecha_init'];
    }
    $sFechaFinal = date('d M Y');
    if (isset($_GET['txt_fecha_end'])) {
        $sFechaFinal = $_GET['txt_fecha_end'];
    }
    if (isset($_POST['txt_fecha_end'])) {
        $sFechaFinal = $_POST['txt_fecha_end'];
    }
    $arrFilterExtraVars = array("txt_fecha_init" => $sFechaInicio, "txt_fecha_end" => $sFechaFinal);
    $arrFormElements = createFieldFilter();
    $oFilterForm = new paloForm($smarty, $arrFormElements);
    // Validación de las fechas recogidas
    if (!$oFilterForm->validateForm($arrFilterExtraVars)) {
        $smarty->assign("mb_title", _tr("Validation Error"));
        $arrErrores = $oFilterForm->arrErroresValidacion;
        $strErrorMsg = '<b>' . _tr('The following fields contain errors') . '</b><br/>';
        foreach ($arrErrores as $k => $v) {
            $strErrorMsg .= "{$k}, ";
        }
        $smarty->assign("mb_message", $strErrorMsg);
        $arrFilterExtraVars = array("txt_fecha_init" => date('d M Y'), "txt_fecha_end" => date('d M Y'));
    }
    $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $arrFilterExtraVars);
    // Obtener fechas en formato yyyy-mm-dd
    $sFechaInicio = translateDate($arrFilterExtraVars['txt_fecha_init']);
    $sFechaFinal = translateDate($arrFilterExtraVars['txt_fecha_end']);
    $oReportsBreak = new paloSantoReportsBreak($pDB);
    //begin grid parameters
    $bElastixNuevo = method_exists('paloSantoGrid', 'setURL');
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->enableExport();
    // enable export.
    $oGrid->showFilter($htmlFilter);
    $arrColumnas = array(_tr('Agent Number'), _tr('Agent Name'));
    $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes' || isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' || isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes';
    $datosBreaks = $oReportsBreak->getReportesBreak($sFechaInicio, $sFechaFinal);
    $mapa = array();
    // Columna del break dado su ID
    $sTagInicio = !$bExportando ? '<b>' : '';
    $sTagFinal = $sTagInicio != '' ? '</b>' : '';
    $filaTotales = array($sTagInicio . _tr('Total') . $sTagFinal, '');
    foreach ($datosBreaks['breaks'] as $idBreak => $sNombreBreak) {
        $mapa[$idBreak] = count($arrColumnas);
        $arrColumnas[] = $sNombreBreak;
        $filaTotales[] = 0;
        // Total de segundos usado por todos los agentes en este break
    }
    $mapa['TOTAL'] = count($arrColumnas);
    $filaTotales[] = 0;
    // Total de segundos usado por todos los agentes en todos los breaks
    $arrColumnas[] = _tr('Total');
    $arrData = array();
    foreach ($datosBreaks['reporte'] as $infoAgente) {
        $filaAgente = array($infoAgente['numero_agente'], $infoAgente['nombre_agente']);
        $iTotalAgente = 0;
        // Total de segundos usados por agente en breaks
        // Valor inicial de todos los breaks es 0 segundos
        foreach (array_keys($datosBreaks['breaks']) as $idBreak) {
            $filaAgente[$mapa[$idBreak]] = '00:00:00';
        }
        // Asignar duración del break para este agente y break
        foreach ($infoAgente['breaks'] as $tuplaBreak) {
            $sTagInicio = !$bExportando && $tuplaBreak['duracion'] > 0 ? '<font color="green">' : '';
            $sTagFinal = $sTagInicio != '' ? '</font>' : '';
            $filaAgente[$mapa[$tuplaBreak['id_break']]] = $sTagInicio . formatoSegundos($tuplaBreak['duracion']) . $sTagFinal;
            $iTotalAgente += $tuplaBreak['duracion'];
            $filaTotales[$mapa[$tuplaBreak['id_break']]] += $tuplaBreak['duracion'];
            $filaTotales[$mapa['TOTAL']] += $tuplaBreak['duracion'];
        }
        // Total para todos los breaks de este agente
        $filaAgente[$mapa['TOTAL']] = formatoSegundos($iTotalAgente);
        $arrData[] = $filaAgente;
    }
    $sTagInicio = !$bExportando ? '<b>' : '';
    $sTagFinal = $sTagInicio != '' ? '</b>' : '';
    foreach ($mapa as $iPos) {
        $filaTotales[$iPos] = $sTagInicio . formatoSegundos($filaTotales[$iPos]) . $sTagFinal;
    }
    $arrData[] = $filaTotales;
    if ($bElastixNuevo) {
        $oGrid->setURL(construirURL($arrFilterExtraVars));
        $oGrid->setData($arrData);
        $oGrid->setColumns($arrColumnas);
        $oGrid->setTitle(_tr("Reports Break"));
        $oGrid->pagingShow(false);
        $oGrid->setNameFile_Export(_tr("Reports Break"));
        $smarty->assign("SHOW", _tr("Show"));
        return $oGrid->fetchGrid();
    } else {
        $url = construirURL($arrFilterExtraVars);
        $offset = 0;
        $total = count($datosBreaks['reporte']) + 1;
        $limit = $total;
        function _map_name($s)
        {
            return array('name' => $s);
        }
        $arrGrid = array("title" => _tr('Reports Break'), "url" => $url, "icon" => "images/list.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $offset + $limit <= $total ? $offset + $limit : $total, "total" => $total, "columns" => array_map('_map_name', $arrColumnas));
        if (isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes' && method_exists($oGrid, 'fetchGridPDF')) {
            return $oGrid->fetchGridPDF($arrGrid, $arrData);
        }
        if (isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' && method_exists($oGrid, 'fetchGridXLS')) {
            return $oGrid->fetchGridXLS($arrGrid, $arrData);
        }
        if ($bExportando) {
            $title = $sFechaInicio . "-" . $sFechaFinal;
            header("Cache-Control: private");
            header("Pragma: cache");
            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);
        if (strpos($sContenido, '<form') === FALSE) {
            $sContenido = "<form  method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>";
        }
        return $sContenido;
    }
}
 function fetchGrid($arrGrid = array(), $arrData = array(), $arrLang = array())
 {
     if (isset($arrGrid["title"])) {
         $this->title = $arrGrid["title"];
     }
     if (isset($arrGrid["icon"])) {
         $this->icon = $arrGrid["icon"];
     }
     if (isset($arrGrid["width"])) {
         $this->width = $arrGrid["width"];
     }
     if (isset($arrGrid["start"])) {
         $this->start = $arrGrid["start"];
     }
     if (isset($arrGrid["end"])) {
         $this->end = $arrGrid["end"];
     }
     if (isset($arrGrid["total"])) {
         $this->total = $arrGrid["total"];
     }
     if (isset($arrGrid['url'])) {
         if (is_array($arrGrid['url'])) {
             $this->url = construirURL($arrGrid['url'], array('nav', 'start', 'logout', 'name_delete_filters'));
         } else {
             $this->url = $arrGrid["url"];
         }
     }
     if (isset($arrGrid["columns"]) && count($arrGrid["columns"]) > 0) {
         $this->arrHeaders = $arrGrid["columns"];
     }
     if (isset($arrData) && count($arrData) > 0) {
         $this->arrData = $arrData;
     }
     $export = $this->exportType();
     switch ($export) {
         case "csv":
             $content = $this->fetchGridCSV($arrGrid, $arrData);
             break;
         case "pdf":
             $content = $this->fetchGridPDF();
             break;
         case "xls":
             $content = $this->fetchGridXLS();
             break;
         default:
             //html
             $content = $this->fetchGridHTML();
             break;
     }
     return $content;
 }
Esempio n. 6
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;
    }
}
Esempio n. 7
0
function listadoHoldTime($pDB, $smarty, $module_name, $local_templates_dir, &$oGrid, &$arrGrid, &$arrData)
{
    $arrData = array();
    $oCalls = new paloSantoHoldTime($pDB);
    $fecha_init = date("d M Y");
    $fecha_end = date("d M Y");
    // preguntamos por el TIPO del filtro (Entrante/Saliente)
    if (!isset($_POST['cbo_tipos']) || $_POST['cbo_tipos'] == "") {
        $_POST['cbo_tipos'] = "E";
        //por defecto las consultas seran de Llamadas Entrantes
    }
    $tipo = 'E';
    $entrantes = 'T';
    $salientes = 'T';
    if (isset($_POST['cbo_tipos'])) {
        $tipo = $_POST['cbo_tipos'];
    }
    if (isset($_POST['cbo_estado_entrantes'])) {
        $entrantes = $_POST['cbo_estado_entrantes'];
    }
    if (isset($_POST['cbo_estado_salientes'])) {
        $salientes = $_POST['cbo_estado_salientes'];
    }
    //validamos la fecha
    if (isset($_POST['txt_fecha_init']) && isset($_POST['txt_fecha_end'])) {
        $fecha_init_actual = $_POST['txt_fecha_init'];
        $fecha_end_actual = $_POST['txt_fecha_end'];
    } elseif (isset($_GET['txt_fecha_init']) && isset($_GET['txt_fecha_end'])) {
        $fecha_init_actual = $_GET['txt_fecha_init'];
        $fecha_end_actual = $_GET['txt_fecha_end'];
    } else {
        $fecha_init_actual = $fecha_init;
        $fecha_end_actual = $fecha_end;
    }
    $sValidacion = "^[[:digit:]]{1,2}[[:space:]]+[[:alnum:]]{3}[[:space:]]+[[:digit:]]{4}\$";
    if (isset($_POST['submit_fecha']) || isset($_POST['cbo_tipos'])) {
        // si se ha presionado el boton pregunto si hay una fecha de inicio elegida
        if (isset($_POST['txt_fecha_init']) && $_POST['txt_fecha_init'] != "" && isset($_POST['txt_fecha_end']) && $_POST['txt_fecha_end'] != "") {
            // sihay una fecha de inicio pregunto si es valido el formato de la fecha
            if (ereg($sValidacion, $_POST['txt_fecha_init'])) {
                // si el formato es valido procedo a convertir la fecha en un arreglo que contiene
                // el anio , mes y dia seleccionados
                $fecha_init = $fecha_init_actual;
                //$_POST['txt_fecha_init'];
                $arrFecha_init = explode('-', translateDate($fecha_init));
            } else {
                // si la fecha esta en un formato no valido se envia un mensaje de error
                $smarty->assign("mb_title", _tr("Error"));
                $smarty->assign("mb_message", _tr("Debe ingresar una fecha valida"));
            }
            // pregunto si es valido el formato de la fecha final
            if (ereg($sValidacion, $_POST['txt_fecha_end'])) {
                // si el formato es valido procedo a convertir la fecha en un arreglo que contiene
                // el anio , mes y dia seleccionados
                $fecha_end = $fecha_end_actual;
                //$_POST['txt_fecha_end'];
                $arrFecha_end = explode('-', translateDate($fecha_end));
            } else {
                // si la fecha esta en un formato no valido se envia un mensaje de error
                $smarty->assign("mb_title", _tr("Error"));
                $smarty->assign("mb_message", _tr("Debe ingresar una fecha valida"));
            }
            //PRUEBA
            $arrFilterExtraVars = array("cbo_tipos" => $tipo, "cbo_estado_entrantes" => $entrantes, "cbo_estado_salientes" => $salientes, "txt_fecha_init" => $_POST['txt_fecha_init'], "txt_fecha_end" => $_POST['txt_fecha_end']);
            //PRUEBA
        } elseif (isset($_GET['txt_fecha_init']) && $_GET['txt_fecha_init'] != "" && isset($_GET['txt_fecha_end']) && $_GET['txt_fecha_end'] != "") {
            if (ereg($sValidacion, $_GET['txt_fecha_init'])) {
                // si el formato es valido procedo a convertir la fecha en un arreglo que contiene
                // el anio , mes y dia seleccionados
                $fecha_init = $fecha_init_actual;
                //$_POST['txt_fecha_init'];
                $arrFecha_init = explode('-', translateDate($fecha_init));
            } else {
                // si la fecha esta en un formato no valido se envia un mensaje de error
                $smarty->assign("mb_title", _tr("Error"));
                $smarty->assign("mb_message", _tr("Debe ingresar una fecha valida"));
            }
            // pregunto si es valido el formato de la fecha final
            if (ereg($sValidacion, $_GET['txt_fecha_end'])) {
                // si el formato es valido procedo a convertir la fecha en un arreglo que contiene
                // el anio , mes y dia seleccionados
                $fecha_end = $fecha_end_actual;
                //$_POST['txt_fecha_end'];
                $arrFecha_end = explode('-', translateDate($fecha_end));
            } else {
                // si la fecha esta en un formato no valido se envia un mensaje de error
                $smarty->assign("mb_title", _tr("Error"));
                $smarty->assign("mb_message", _tr("Debe ingresar una fecha valida"));
            }
            $tipo = $_GET['cbo_tipos'];
            $entrantes = $_GET['cbo_estado_entrantes'];
            $salientes = $_GET['cbo_estado_salientes'];
            $arrFilterExtraVars = array("cbo_tipos" => $_GET['cbo_tipos'], "cbo_estado_entrantes" => $_GET['cbo_estado_entrantes'], "cbo_estado_salientes" => $_GET['cbo_estado_salientes'], "txt_fecha_init" => $_GET['txt_fecha_init'], "txt_fecha_end" => $_GET['txt_fecha_end']);
        } elseif (!isset($fecha_init) && !isset($fecha_end)) {
            // si se ha presionado el boton para listar por fechas, y no se ha ingresado una fecha
            // se le muestra al usuario un mensaje de error
            $smarty->assign("mb_title", _tr("Error"));
            $smarty->assign("mb_message", _tr("Debe ingresar una fecha inicio/fin"));
        }
    }
    $bElastixNuevo = method_exists('paloSantoGrid', 'setURL');
    $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes' || isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' || isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes';
    //para el pagineo
    // LISTADO
    $limit = 50;
    $offset = 0;
    //numero de registros
    $arrCallsTmp = $oCalls->getHoldTime($tipo, $entrantes, $salientes, translateDate($fecha_init), translateDate($fecha_end), $limit, $offset);
    $totalCalls = $arrCallsTmp['NumRecords'];
    if ($bElastixNuevo) {
        $oGrid->setLimit($limit);
        $oGrid->setTotal($totalCalls);
        $offset = $oGrid->calculateOffset();
    } else {
        // Si se quiere avanzar a la sgte. pagina
        if (isset($_GET['nav']) && $_GET['nav'] == "end") {
            // Mejorar el sgte. bloque.
            if ($totalCalls % $limit == 0) {
                $offset = $totalCalls - $limit;
            } else {
                $offset = $totalCalls - $totalCalls % $limit;
            }
        }
        // Si se quiere avanzar a la sgte. pagina
        if (isset($_GET['nav']) && $_GET['nav'] == "next") {
            $offset = $_GET['start'] + $limit - 1;
        }
        // Si se quiere retroceder
        if (isset($_GET['nav']) && $_GET['nav'] == "previous") {
            $offset = $_GET['start'] - $limit - 1;
        }
    }
    // Construyo el URL base
    $url = array('menu' => $module_name);
    if (isset($arrFilterExtraVars) && is_array($arrFilterExtraVars) && count($arrFilterExtraVars) > 0) {
        $url = array_merge($url, $arrFilterExtraVars);
    }
    //fin de pagineo
    //llamamos  a la función que hace la consulta  a la base según los criterios de búsqueda
    $arrCalls = $oCalls->getHoldTime($tipo, $entrantes, $salientes, translateDate($fecha_init), translateDate($fecha_end), $limit, $offset);
    //Llenamos el contenido de las columnas
    $arrTmp = array();
    $sTagInicio = !$bExportando ? '<b>' : '';
    $sTagFinal = $sTagInicio != '' ? '</b>' : '';
    if (is_array($arrCalls)) {
        $end = $arrCalls['NumRecords'];
        foreach ($arrCalls['Data'] as $calls) {
            $arrTmp[0] = $calls['cola'];
            //primeramente enceramos los valores de horas
            $arrTmp[1] = "";
            $arrTmp[2] = "";
            $arrTmp[3] = "";
            $arrTmp[4] = "";
            $arrTmp[5] = "";
            $arrTmp[6] = "";
            $arrTmp[7] = "";
            $arrTmp[8] = "";
            $arrTmp[9] = "";
            foreach ($calls as $intervalo => $num_veces) {
                if ($intervalo == '0') {
                    $arrTmp[1] = $num_veces;
                } elseif ($intervalo == '1') {
                    $arrTmp[2] = $num_veces;
                } elseif ($intervalo == '2') {
                    $arrTmp[3] = $num_veces;
                } elseif ($intervalo == '3') {
                    $arrTmp[4] = $num_veces;
                } elseif ($intervalo == '4') {
                    $arrTmp[5] = $num_veces;
                } elseif ($intervalo == '5') {
                    $arrTmp[6] = $num_veces;
                } elseif ($intervalo == "6") {
                    $arrTmp[7] = $num_veces;
                } elseif ($intervalo == 'tiempo_promedio') {
                    //tiempo promedio de espera en segundos
                    $arrTmp[8] = number_format($num_veces, 0);
                } elseif ($intervalo == 'nuevo_valor_maximo') {
                    //valor mayor en segundos
                    $arrTmp[9] = $num_veces;
                }
                $arrTmp[10] = sumNumCalls($arrTmp);
            }
            $arrData[] = $arrTmp;
        }
        $arrTmp[0] = $sTagInicio . _tr("Total") . $sTagFinal;
        for ($j = 1; $j <= 8; $j++) {
            $sum = 0;
            for ($i = 0; $i < count($arrData); $i++) {
                $sum = $sum + $arrData[$i][$j];
            }
            $arrTmp[$j] = $sTagInicio . $sum . $sTagFinal;
        }
        $sumTotalCalls = $maxTimeWait = 0;
        for ($i = 0; $i < count($arrData); $i++) {
            $maxTimeWait = $oCalls->getMaxWait($maxTimeWait, $arrData[$i][9]);
            $sumTotalCalls = $sumTotalCalls + $arrData[$i][10];
        }
        $arrTmp[10] = $sTagInicio . $sumTotalCalls . $sTagFinal;
        $arrTmp[9] = $sTagInicio . $maxTimeWait . $sTagFinal;
        $arrData[] = $arrTmp;
    }
    //Para el combo de tipos
    $tipos = array("E" => _tr("Ingoing"), "S" => _tr("Outgoing"));
    $combo_tipos = "<select name='cbo_tipos' id='cbo_tipos' onChange='submit();'>" . combo($tipos, $_POST['cbo_tipos']) . "</select>";
    //para el combo de entrantes
    if (isset($_POST['cbo_estado_entrantes'])) {
        $cbo_estado_entrates = $_POST['cbo_estado_entrantes'];
    } elseif (isset($_GET['cbo_estado_entrantes'])) {
        $cbo_estado_entrates = $_GET['cbo_estado_entrantes'];
    } else {
        $cbo_estado_entrates = 'T';
    }
    $estados_entrantes = array("T" => _tr("Todas"), "E" => _tr("Exitosas"), "A" => _tr("Abandonadas"));
    $combo_estados_entrantes = "<select name='cbo_estado_entrantes' id='cbo_estado_entrantes' >" . combo($estados_entrantes, $cbo_estado_entrates) . "</select>";
    //para el combo de salientes
    if (isset($_POST['cbo_estado_salientes'])) {
        $cbo_estado_salientes = $_POST['cbo_estado_salientes'];
    } elseif (isset($_GET['cbo_estado_salientes'])) {
        $cbo_estado_salientes = $_GET['cbo_estado_salientes'];
    } else {
        $cbo_estado_salientes = 'T';
    }
    $estados_salientes = array("T" => _tr("Todas"), "E" => _tr("Exitosas"), "N" => _tr("No Realizadas"), "A" => _tr("Abandonadas"));
    $combo_estados_salientes = "<select name='cbo_estado_salientes' id='cbo_estado_salientes' >" . combo($estados_salientes, $cbo_estado_salientes) . "</select>";
    //validamos que combo se cargará segun lo electo en combo TIPO, al principio le seteamos por defecto el de ENTRANTES
    $td = "<td class='letra12' align='right'>" . _tr("Estado") . "</td><td>{$combo_estados_entrantes}</td>";
    if (isset($_POST['cbo_tipos']) && $_POST['cbo_tipos'] == "E") {
        $td = "<td class='letra12' align='left'>" . _tr("Estado") . "</td><td>{$combo_estados_entrantes}</td>";
    } elseif (isset($_POST['cbo_tipos']) && $_POST['cbo_tipos'] == "S") {
        $td = "<td class='letra12' align='left'>" . _tr("Estado") . "</td><td>{$combo_estados_salientes}</td>";
    }
    $oGrid->showFilter(insertarCabeceraCalendario() . "\n\n            <table width='100%' border='0'>\n                <tr>\n                    <td align='left'>\n                        <table>\n                        <tr>\n                            <td class='letra12'>\n                                " . _tr("Date Init") . "\n                                <span  class='required'>*</span>\n                            </td>\n                            <td>\n                                " . insertarDateInit($fecha_init_actual) . "\n                            </td>\n                            <td class='letra12'>\n                                &nbsp;\n                            </td>\n                            <td class='letra12'>\n                                " . _tr("Date End") . "\n                                <span  class='required'>*</span>\n                            </td>\n                            <td>\n                                " . insertarDateEnd($fecha_end_actual) . "\n                            </td>\n\n                        </tr>\n\n                        <tr>\n                            <td class='letra12' align='left'>" . _tr("Tipo") . "</td>\n                            <td>{$combo_tipos}</td>\n                            <td class='letra12'>\n                                &nbsp;\n                            </td>\n                            " . $td . "\n                            <td>\n                                <input type='submit' name='submit_fecha' value=" . _tr("Find") . " class='button'>\n                            </td>\n                        </tr>\n                        </table>\n                    </td>\n                </tr>\n            </table>\n\n        ");
    $oGrid->enableExport();
    if ($bElastixNuevo) {
        $oGrid->setURL($url);
        $oGrid->setData($arrData);
        $arrColumnas = array(_tr("Cola"), "0 - 10", "11 - 20", "21 - 30", "31 - 40", "41 - 50", "51 - 60", "61 >", _tr("Tiempo Promedio Espera(Seg)"), _tr("Espera Mayor(seg)"), _tr("Total Calls"));
        $oGrid->setColumns($arrColumnas);
        $oGrid->setTitle(_tr("Hold Time"));
        $oGrid->pagingShow(true);
        $oGrid->setNameFile_Export(_tr("Hold Time"));
        $smarty->assign("SHOW", _tr("Show"));
        return $oGrid->fetchGrid();
    } else {
        global $arrLang;
        $offset = 0;
        $limit = $totalCalls;
        //Llenamos las cabeceras
        $url = construirURL($url, array("nav", "start"));
        $arrGrid = array("title" => _tr("Hold Time"), "url" => $url, "icon" => "images/list.png", "width" => "99%", "start" => $end == 0 ? 0 : $offset + 1, "end" => $offset + $limit <= $end ? $offset + $limit : $end, "total" => $end, "columns" => array(0 => array("name" => _tr("Cola"), "property1" => ""), 1 => array("name" => "0 - 10", "property1" => ""), 2 => array("name" => "11 - 20", "property1" => ""), 3 => array("name" => "21 - 30", "property1" => ""), 4 => array("name" => "31 - 40", "property1" => ""), 5 => array("name" => "41 - 50", "property1" => ""), 6 => array("name" => "51 - 60", "property1" => ""), 7 => array("name" => "61 >", "property1" => ""), 8 => array("name" => _tr("Tiempo Promedio Espera(Seg)"), "property1" => ""), 9 => array("name" => _tr("Espera Mayor(seg)"), "property1" => ""), 10 => array("name" => _tr("Total Calls"), "property1" => "")));
        if (isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes' && method_exists($oGrid, 'fetchGridPDF')) {
            return $oGrid->fetchGridPDF($arrGrid, $arrData);
        }
        if (isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' && method_exists($oGrid, 'fetchGridXLS')) {
            return $oGrid->fetchGridXLS($arrGrid, $arrData);
        }
        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;
    }
}
Esempio n. 8
0
function graphLinks($smarty, $module_name, $local_templates_dir)
{
    $getParams = array('ext', 'dini', 'dfin');
    foreach ($getParams as $k) {
        if (!isset($_GET[$k])) {
            $_GET[$k] = '';
        }
    }
    $urlEntrantes = construirURL(array('module' => $module_name, 'rawmode' => 'yes', 'action' => 'imageTop10Entrantes', 'ext' => $_GET['ext'], 'dini' => $_GET['dini'], 'dfin' => $_GET['dfin']));
    $urlSalientes = construirURL(array('module' => $module_name, 'rawmode' => 'yes', 'action' => 'imageTop10Salientes', 'ext' => $_GET['ext'], 'dini' => $_GET['dini'], 'dfin' => $_GET['dfin']));
    $sPlantilla = <<<PLANTILLA_GRAPH
<html>
<head><title>Top 10</title></head>
<body>
<table width='100%' border='0' cellspacing='0' cellpadding='0' align='center'>
<tr><td align='center'><img alt='imageTop10Entrantes' src='{$urlEntrantes}' /></td></tr>
<tr><td align='center'><img alt='imageTop10Salientes' src='{$urlSalientes}' /></td></tr>
</table>
</body>
</html>
PLANTILLA_GRAPH;
    return $sPlantilla;
}
Esempio n. 9
0
function reportTransfer_List($smarty, $module_name, $local_templates_dir, &$pDB, $enable = true)
{
    $pTransfer_List = new paloSantoTransfer_List($pDB);
    $oGrid = new paloSantoGrid($smarty);
    // get filter parameters
    $paramFilter = array();
    foreach (array('firstname', 'lastname', 'department', 'phone') as $k) {
        $paramFilter[$k] = getFilterParam($k);
    }
    //get filter field and value
    $search_key = "";
    $search_value = "";
    foreach ($paramFilter as $k => $v) {
        if ($paramFilter[$k] != NULL) {
            $search_key = $k;
            $search_value = $v;
            break;
        }
    }
    //arrange columns
    $arrCols = array(_tr("Tên"), _tr("Họ"), _tr("Phòng - Công ty"), _tr("Ghi chú"), _tr("Số điện thoại"), _tr("Chức năng"));
    //Paginacion
    $total = $pTransfer_List->countTransferList($search_key, $search_value);
    $limit = 15;
    $oGrid->setLimit($limit);
    $oGrid->setTotal($total);
    $offset = $oGrid->calculateOffset();
    $inicio = $total == 0 ? 0 : $offset + 1;
    $end1 = $offset + $limit <= $total ? $offset + $limit : $total;
    //Fin Paginacion
    // get list with filter
    $arrResult = $pTransfer_List->getTransfer_List($search_key, $search_value, $limit, $offset);
    if (!is_array($arrResult)) {
        $smarty->assign("mb_title", _tr("ERROR"));
        $smarty->assign("mb_message", _tr("Lỗi khi lấy dữ liệu") . "<br/>" . $pDB->errMsg);
        $arrResult = array();
    }
    if (!function_exists('listTransfer_formatHTML')) {
        function listTransfer_formatHTML($transfer, $param)
        {
            $img_dir = "/modules/agent_console/images/";
            return array(htmlentities($transfer['firstname'], ENT_COMPAT, "UTF-8"), htmlentities($transfer['lastname'], ENT_COMPAT, "UTF-8"), htmlentities($transfer['department'], ENT_COMPAT, "UTF-8"), htmlentities($transfer['note'], ENT_COMPAT, "UTF-8"), htmlentities($transfer['phone'], ENT_COMPAT, "UTF-8"), '<a onclick="do_transfer_param(\'' . $transfer['phone'] . '\',\'true\')" href="#"><img src="' . $img_dir . 'btn-chuyencuocgoi.png" alt="ATTENDDED XFER" title="Chuyển gián tiếp"></a>' . '&nbsp;&nbsp;&nbsp;' . '<a onclick="do_transfer_param(	\'' . $transfer['phone'] . '\',\'false\')" href="#"><img src="' . $img_dir . 'btn-chuyenhuonggoi.png" alt="ATTENDDED XFER" title="Chuyển trực tiếp"></a>');
        }
    }
    $arrData = array();
    if (count($arrResult) > 0) {
        $arrData = array_map('listTransfer_formatHTML', $arrResult, array_fill(0, count($arrResult), array('module_name' => $module_name)));
    }
    // Grid construction view
    if (!function_exists('listTransfer_formatCols')) {
        function listTransfer_formatCols($x)
        {
            return array('name' => $x);
        }
    }
    global $arrLang;
    $end = count($arrResult);
    $start = $end == 0 ? 0 : 1;
    //begin section filter
    $oFilterForm = new paloForm($smarty, createFieldFilter());
    $smarty->assign("SHOW", _tr("Tìm kiếm"));
    $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST);
    $oGrid->showFilter(trim($htmlFilter));
    $url = construirURL(array('menu' => $module_name), array('nav', 'start'));
    $content = $oGrid->fetchGrid(array("url" => array('menu' => $module_name), "icon" => "images/list.png", "width" => "99%", "start" => $inicio, "end" => $end1, "total" => $total, "columns" => array_map('listTransfer_formatCols', $arrCols)), $arrData, $arrLang);
    if (strpos($content, '<form') === FALSE) {
        $content = "<form  method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$content}</form>";
    }
    return $content;
}
Esempio n. 10
0
function _moduleContent(&$smarty, $module_name)
{
    require_once "modules/{$module_name}/configs/default.config.php";
    require_once "modules/{$module_name}/libs/paloSantoReportsCalls.class.php";
    // obtengo la ruta del template a utilizar para generar el filtro.
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $templates_dir = isset($config['templates_dir']) ? $config['templates_dir'] : 'themes';
    $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $config['theme'];
    load_language_module($module_name);
    // se crea el objeto conexion a la base de datos
    $pDB = new paloDB($cadena_dsn);
    // valido lacreacion del objeto conexion, presentando un mensaje deerror si es invalido.
    $bElastixNuevo = method_exists('paloSantoGrid', 'setURL');
    $url = array('menu' => $module_name);
    $htmlFilter = "";
    $oGrid = new paloSantoGrid($smarty);
    $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes';
    if (!is_object($pDB->conn) || $pDB->errMsg != "") {
        $smarty->assign("mb_title", _tr("Error"));
        $smarty->assign("mb_message", _tr("Error when connecting to database") . " " . $pDB->errMsg);
        // sio el objeto coenxion a la base no tiene problemas, consulto si se han seteado las variables GET.
    } elseif ($bExportando) {
        if (empty($_GET['txt_fecha_init'])) {
            $fecha_actual_init = date("d M Y");
        } else {
            $fecha_actual_init = $_GET['txt_fecha_init'];
        }
        if (empty($_GET['txt_fecha_end'])) {
            $fecha_actual_end = date("d M Y");
        } else {
            $fecha_actual_end = $_GET['txt_fecha_end'];
        }
        // sino hay variables GET seteadas....
    } else {
        // creo un arreglo con la informacion necesario para el filtro que se desea definir.
        $arrFormElements = createFieldFilter();
        // obtengo la fecha actual del sistema.
        $fecha_actual_init = date("d M Y");
        $fecha_actual_end = date("d M Y");
        // nombre del boton que me permitira enviar los valores del formulario.
        $smarty->assign("btn_consultar", _tr('Find'));
        // nombre del modulo actual.
        $smarty->assign("module_name", $module_name);
        // creo un objeto paloForm para crear el filtro del formulario.
        $oFilterForm = new paloForm($smarty, $arrFormElements);
        // valido si se ha presionado el boton "Consultar", cuyo name es "submit_fecha".
        if (isset($_POST['submit_fecha'])) {
            // valido la informacion obtenida del formulario.
            if ($oFilterForm->validateForm($_POST)) {
                // si la informacion es correcta  procedo a procesar los datos,
                // en este caso la fecha del reporte deseado es asignada a una variable.
                $fecha_actual_init = $_POST['txt_fecha_init'];
                $fecha_actual_end = $_POST['txt_fecha_end'];
                // Envio al arreglo la fecha obtenida del formulario.
                // txt_fecha es el nombre del campo de texto en el quese guarda la fecha
                $arrFilterExtraVars = array("txt_fecha_init" => $fecha_actual_init, "txt_fecha_end" => $fecha_actual_end);
            } else {
                // si la informacion es invalida presento un mensaje de error con la cadena "Error de validacion"
                // dependiendo del idioma.
                $smarty->assign("mb_title", _tr("Validation Error"));
                // en este arreglo se guarada los posibles errores de validacion generados.
                $arrErrores = $oFilterForm->arrErroresValidacion;
                // cadena que almacena el mensaje de error a mostrarse en la pantalla.
                $strErrorMsg = "<b>" . _tr('The following fields contain errors') . ":</b><br>";
                // se recorre el arreglo para revisar todos los errores encontrados en la informacion del formulario
                foreach ($arrErrores as $k => $v) {
                    // se concatena los mensajes de error encontrados.
                    $strErrorMsg .= "{$k}, ";
                }
                $strErrorMsg .= "";
                // se presenta la cadena de error en la pantalla.
                $smarty->assign("mb_message", $strErrorMsg);
            }
            // se asigna el template elegido , asi como tambien la variable super global $_POST, al filtro.
            $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/form.tpl", "", $_POST);
            // si existe una fecha en el GET...
        } else {
            if (isset($_GET['txt_fecha_init']) && isset($_GET['txt_fecha_end'])) {
                // se toma la fecha del GET
                $fecha_actual_init = $_GET['txt_fecha_init'];
                $fecha_actual_end = $_GET['txt_fecha_end'];
                // envio la fecha obtenida.  txt_fecha es el nombre del campo de texto en el quese guarda la fecha
                $arrFilterExtraVars = array("txt_fecha_init" => $_GET['txt_fecha_init'], "txt_fecha_end" => $_GET['txt_fecha_end']);
                // seteo el template elegido junto con la variable GET que contine los datos del formulario(txt_fecha).
                $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/form.tpl", "", $_GET);
                // sino se ha presionado el boton Consultar y no se ha clickado en el enlace "Export".
            } else {
                // asigno el template deseado, y obtengo la fecha actual del sistema, y se la envio junto al template
                // en un array asociativo .
                // txt_fecha es el nombre del campo de texto en el quese guarda la fecha.
                $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/form.tpl", "", array('txt_fecha_init' => date("d M Y"), 'txt_fecha_end' => date("d M Y")));
            }
        }
        // genero la url
        if (isset($arrFilterExtraVars) && is_array($arrFilterExtraVars) and count($arrFilterExtraVars) > 0) {
            // esta url contiene la informacion de lso campos del formulario pasados como GET,
            // a traves de un enlace.
            $url = array_merge($url, $arrFilterExtraVars);
        }
    }
    $url = construirURL($url, array("nav", "start"));
    // creo el objeto $oReportsBreak, que me ayudara a construir el reporte.
    $oReportsCalls = new paloSantoReportsCalls($pDB);
    // valido la creacion del objeto
    if (!$oReportsCalls) {
        $smarty->assign("mb_title", _tr("Error"));
        $smarty->assign("mb_message", _tr("Error when creating object paloSantoReportsCalls"));
    } else {
        // creo un arreglo para el grid
        $arrGrid = array();
        // envio el arreglo por referencia a la funcion para que esta se encargue de defnirlo. La funcion
        // me retorna un arreglo con la informacion del reporte y ha generado el grid,
        // el cual es devuelto por referencia.
        $oGrid = new paloSantoGrid($smarty);
        $contenido = generarReporte($smarty, $fecha_actual_init, $fecha_actual_end, $oReportsCalls, $arrGrid, $bElastixNuevo, $bExportando, $oGrid, $url, $htmlFilter);
        // creo el objeto GRID
        // habilito la opcion Export con la que se procedera a exportar la data a un archivo.
        // evaluo si se ha dado click en el enlace Export para generar el archivo
        return $contenido;
    }
}
Esempio n. 11
0
function listarUsuarios($pDB, $smarty, $module_name, $local_templates_dir)
{
    global $arrLang;
    $oUsuarios = new UsuariosECCP($pDB);
    $smarty->assign(array('MODULE_NAME' => $module_name, 'LABEL_CREATE_USER' => _tr('New ECCP User')));
    // Manejar posible borrado de agentes
    if (isset($_POST['delete']) && isset($_POST['id']) && ctype_digit($_POST['id'])) {
        $bExito = $oUsuarios->borrarUsuario($_POST['id']);
        if (!$bExito) {
            $smarty->assign(array('mb_title' => _tr('Error when deleting user'), 'mb_message' => $oUsuarios->errMsg));
        }
    }
    // Listar todos los agentes
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->setLimit(50);
    $oGrid->setTotal($oUsuarios->contarUsuarios());
    $offset = $oGrid->calculateOffset();
    $listaAgentes = $oUsuarios->listarUsuarios(NULL, $offset, $oGrid->getLimit());
    $arrData = array();
    foreach ($listaAgentes as $t) {
        $arrData[] = array('<input type="radio" name="id" value="' . $t['id'] . '" />', htmlentities($t['username'], ENT_COMPAT, 'UTF-8'), '<a href="?menu=' . $module_name . '&amp;action=edit_user&amp;id=' . $t['id'] . '">[' . _tr('Edit') . ']</a>');
    }
    $url = construirURL(array('menu' => $module_name), array('nav', 'start'));
    $arrGrid = array("title" => _tr('ECCP User List'), "url" => $url, "icon" => 'images/user.png', "width" => "99%", "columns" => array(0 => array("name" => '<input type="submit" class="button" name="delete" value="' . htmlentities(_tr('Delete'), ENT_COMPAT, 'UTF-8') . '" onclick="return confirmSubmit(' . "'" . htmlentities(_tr('Are you sure to delete this user?'), ENT_COMPAT, 'UTF-8') . "'" . ')" />'), 1 => array("name" => _tr('Name')), 2 => array("name" => _tr('Options'))));
    $oGrid->showFilter($smarty->fetch("{$local_templates_dir}/filter-list-users.tpl"));
    $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;
}
Esempio n. 12
0
function _moduleContent(&$smarty, $module_name)
{
    include_once "libs/paloSantoGrid.class.php";
    include_once "libs/paloSantoDB.class.php";
    include_once "libs/paloSantoForm.class.php";
    include_once "libs/paloSantoConfig.class.php";
    require_once "libs/misc.lib.php";
    //Incluir librería de lenguaje
    load_language_module($module_name);
    //include module files
    include_once "modules/{$module_name}/configs/default.conf.php";
    include_once "modules/{$module_name}/libs/paloSantoCallPerAgent.class.php";
    global $arrConf;
    global $arrLang;
    $arrCallsAgentTmp = 0;
    //folder path for custom templates
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $templates_dir = isset($arrConfig['templates_dir']) ? $arrConfig['templates_dir'] : 'themes';
    $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConf['theme'];
    $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*");
    $arrConfig = $pConfig->leer_configuracion(false);
    $pDB = new paloDB($cadena_dsn);
    $arrData = array();
    $oCallsAgent = new paloSantoCallsAgent($pDB);
    $urlVars = array('menu' => $module_name);
    $smarty->assign("menu", "calls_per_agent");
    $smarty->assign("Filter", _tr('Query'));
    $arrFormElements = createFieldFilter();
    $oFilterForm = new paloForm($smarty, $arrFormElements);
    // Por omision las fechas toman el sgte. valor (la fecha de hoy)
    $date_start = date("Y-m-d") . " 00:00:00";
    $date_end = date("Y-m-d") . " 23:59:59";
    $arrFilterExtraVars = null;
    $fieldPat = array();
    if (isset($_POST['filter'])) {
        if ($oFilterForm->validateForm($_POST)) {
            // Exito, puedo procesar los datos ahora.
            $date_start = translateDate($_POST['date_start']) . " 00:00:00";
            $date_end = translateDate($_POST['date_end']) . " 23:59:59";
            if (!empty($_POST['field_pattern'])) {
                $fieldPat[$_POST['field_name']][] = $_POST['field_pattern'];
            }
            if (!empty($_POST['field_pattern_1'])) {
                $fieldPat[$_POST['field_name_1']][] = $_POST['field_pattern_1'];
            }
            $arrFilterExtraVars = array("date_start" => $_POST['date_start'], "date_end" => $_POST['date_end'], "field_name" => $_POST['field_name'], "field_pattern" => $_POST['field_pattern'], "field_name_1" => $_POST['field_name_1'], "field_pattern_1" => $_POST['field_pattern_1']);
        } else {
            // Error
            $smarty->assign("mb_title", _tr("Validation Error"));
            $arrErrores = $oFilterForm->arrErroresValidacion;
            $strErrorMsg = "<b>" . _tr('The following fields contain errors') . ":</b><br>";
            foreach ($arrErrores as $k => $v) {
                $strErrorMsg .= "{$k}, ";
            }
            $strErrorMsg .= "";
            $smarty->assign("mb_message", $strErrorMsg);
        }
        $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_POST);
    } else {
        if (isset($_GET['date_start']) and isset($_GET['date_end'])) {
            $date_start = translateDate($_GET['date_start']) . " 00:00:00";
            $date_end = translateDate($_GET['date_end']) . " 23:59:59";
            if (!empty($_GET['field_pattern'])) {
                $fieldPat[$_GET['field_name']][] = $_GET['field_pattern'];
            }
            if (!empty($_GET['field_pattern_1'])) {
                $fieldPat[$_GET['field_name_1']][] = $_GET['field_pattern_1'];
            }
            $arrFilterExtraVars = array("date_start" => $_GET['date_start'], "date_end" => $_GET['date_end']);
            $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $_GET);
        } else {
            $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", array('date_start' => date("d M Y"), 'date_end' => date("d M Y"), 'field_name' => 'agent', 'field_pattern' => '', 'field_name_1' => 'agent', 'field_pattern_1' => ''));
        }
    }
    $bElastixNuevo = method_exists('paloSantoGrid', 'setURL');
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->enableExport();
    // enable export.
    $oGrid->showFilter($htmlFilter);
    $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes' || isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' || isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes';
    $offset = 0;
    $limit = 20;
    if (isset($fieldPat['type'])) {
        $fieldPat['type'] = array_map('strtoupper', $fieldPat['type']);
    }
    $arrCallsAgentTmp = $oCallsAgent->obtenerCallsAgent($date_start, $date_end, $fieldPat);
    if (!is_array($arrCallsAgentTmp)) {
        $smarty->assign(array('mb_title' => _tr('ERROR'), 'mb_message' => $oCallsAgent->errMsg));
        $arrCallsAgentTmp = array();
    }
    $totalCallsAgents = count($arrCallsAgentTmp);
    // Si se quiere avanzar a la sgte. pagina
    if ($bElastixNuevo) {
        $oGrid->setLimit($limit);
        $oGrid->setTotal($totalCallsAgents + 1);
        $offset = $oGrid->calculateOffset();
    } else {
        if (isset($_GET['nav']) && $_GET['nav'] == "end") {
            // Mejorar el sgte. bloque.
            if ($totalCallsAgents % $limit == 0) {
                $offset = $totalCallsAgents - $limit;
            } else {
                $offset = $totalCallsAgents - $totalCallsAgents % $limit;
            }
        }
        // Si se quiere avanzar a la sgte. pagina
        if (isset($_GET['nav']) && $_GET['nav'] == "next") {
            $offset = $_GET['start'] + $limit - 1;
        }
        // Si se quiere retroceder
        if (isset($_GET['nav']) && $_GET['nav'] == "previous") {
            $offset = $_GET['start'] - $limit - 1;
        }
    }
    // Bloque comun
    $arrCallsAgent = array_slice($arrCallsAgentTmp, $offset, $limit);
    $arrData = array();
    $sumCallAnswered = $sumDuration = $timeMayor = 0;
    foreach ($arrCallsAgent as $cdr) {
        $arrData[] = array($cdr['agent_number'], htmlentities($cdr['agent_name'], ENT_COMPAT, 'UTF-8'), $cdr['type'], $cdr['queue'], $cdr['num_answered'], formatoSegundos($cdr['sum_duration']), formatoSegundos($cdr['avg_duration']), formatoSegundos($cdr['max_duration']));
        $sumCallAnswered += $cdr['num_answered'];
        // Total de llamadas contestadas
        $sumDuration += $cdr['sum_duration'];
        // Total de segundos en llamadas
        $timeMayor = $timeMayor < $cdr['max_duration'] ? $cdr['max_duration'] : $timeMayor;
    }
    $sTagInicio = !$bExportando ? '<b>' : '';
    $sTagFinal = $sTagInicio != '' ? '</b>' : '';
    $arrData[] = array($sTagInicio . _tr('Total') . $sTagFinal, '', '', '', $sTagInicio . $sumCallAnswered . $sTagFinal, $sTagInicio . formatoSegundos($sumDuration) . $sTagFinal, $sTagInicio . formatoSegundos($sumCallAnswered > 0 ? $sumDuration / $sumCallAnswered : 0) . $sTagFinal, $sTagInicio . formatoSegundos($timeMayor) . $sTagFinal);
    // Construyo el URL base
    if (isset($arrFilterExtraVars) && is_array($arrFilterExtraVars) && count($arrFilterExtraVars) > 0) {
        $urlVars = array_merge($urlVars, $arrFilterExtraVars);
    }
    if ($bElastixNuevo) {
        $oGrid->setURL(construirURL($urlVars, array("nav", "start")));
        $oGrid->setData($arrData);
        $arrColumnas = array(_tr("No.Agent"), _tr("Agent"), _tr("Type"), _tr("Queue"), _tr("Calls answered"), _tr("Duration"), _tr("Average"), _tr("Call longest"));
        $oGrid->setColumns($arrColumnas);
        $oGrid->setTitle(_tr("Calls per Agent"));
        $oGrid->pagingShow(true);
        $oGrid->setNameFile_Export(_tr("Calls per Agent"));
        $smarty->assign("SHOW", _tr("Show"));
        return $oGrid->fetchGrid();
    } else {
        $url = construirURL($urlVars, array("nav", "start"));
        $offset = 0;
        $total = count($arrData);
        $limit = $total;
        $arrGrid = array("title" => _tr("Calls per Agent"), "url" => $url, "icon" => "images/user.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $offset + $limit <= $total ? $offset + $limit : $total, "total" => $total, "columns" => array(0 => array("name" => _tr("No.Agent"), "property" => ""), 1 => array("name" => _tr("Agent"), "property" => ""), 2 => array("name" => _tr("Type"), "property" => ""), 3 => array("name" => _tr("Queue"), "property" => ""), 4 => array("name" => _tr("Calls answered"), "property" => ""), 5 => array("name" => _tr("Duration"), "property" => ""), 6 => array("name" => _tr("Average"), "property" => ""), 7 => array("name" => _tr("Call longest"), "property" => "")));
        if (isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes' && method_exists($oGrid, 'fetchGridPDF')) {
            return $oGrid->fetchGridPDF($arrGrid, $arrData);
        }
        if (isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' && method_exists($oGrid, 'fetchGridXLS')) {
            return $oGrid->fetchGridXLS($arrGrid, $arrData);
        }
        if ($bExportando) {
            header("Cache-Control: private");
            header("Pragma: cache");
            header('Content-Type: application/octet-stream');
            header('Content-disposition: inline; filename="calls_per_agent.csv"');
            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;
    }
}
Esempio n. 13
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;
    }
}
Esempio n. 14
0
function listBreaks(&$smarty, $module_name, &$pDB, $local_templates_dir)
{
    $oBreaks = new PaloSantoBreaks($pDB);
    // Procesamiento de la activación/desactivación de breaks
    $r = TRUE;
    if (isset($_POST['activate']) && isset($_POST['id_break'])) {
        $r = $oBreaks->activateBreak($_POST['id_break'], 'A');
        if (!$r) {
            $smarty->assign("mb_title", _tr('Activate Error'));
            $smarty->assign("mb_message", _tr('Error when Activating the Break'));
        }
    } elseif (isset($_POST['deactivate']) && isset($_POST['id_break'])) {
        $r = $oBreaks->activateBreak($_POST['id_break'], 'I');
        if (!$r) {
            $respuesta->addAssign("mb_title", "innerHTML", _tr("Desactivate Error"));
            $respuesta->addAssign("mb_message", "innerHTML", _tr("Error when desactivating the Break"));
        }
    }
    // Procesamiento de la visualización de breaks
    $arrBreaks = $oBreaks->getBreaks();
    // Todos los breaks en todos los estados
    if (!is_array($arrBreaks)) {
        $smarty->assign("mb_title", _tr("ERROR"));
        $smarty->assign("mb_message", _tr("Failed to fetch breaks") . "<br/>" . $pDB->errMsg);
        $arrBreaks = array();
    }
    $arrCols = array("<input type=\"submit\" class=\"button\" name=\"activate\" value=\"" . _tr('Activate') . "\" /> " . "<input type=\"submit\" class=\"button\" name=\"deactivate\" value=\"" . _tr('Desactivate') . "\" />", _tr("Name Break"), _tr("Description Break"), _tr("Status"), _tr("Options"));
    function listBreaks_formatHTML($break, $param)
    {
        return array("<input class=\"input\" type=\"radio\" name=\"id_break\" value=\"{$break['id']}\"/>", htmlentities($break['name'], ENT_COMPAT, "UTF-8"), htmlentities($break['description'], ENT_COMPAT, "UTF-8") . '&nbsp;', $break['status'] == 'A' ? _tr('Active') : _tr('Inactive'), $break['status'] == 'A' ? "<a href=\"?menu={$param['module_name']}&amp;action=edit&amp;id_break={$break['id']}\">[" . _tr('Edit Break') . ']</a>' : '&nbsp;');
    }
    $arrData = array();
    if (count($arrBreaks) > 0) {
        $arrData = array_map('listBreaks_formatHTML', $arrBreaks, array_fill(0, count($arrBreaks), array('module_name' => $module_name)));
    }
    // Construcción de la rejilla de vista
    function listBreaks_formatCols($x)
    {
        return array('name' => $x);
    }
    global $arrLang;
    $end = count($arrBreaks);
    $start = $end == 0 ? 0 : 1;
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->showFilter("<a href=\"?menu={$module_name}&amp;action=new\"><b>" . _tr('Create New Break') . '&nbsp;&raquo;</b></a>');
    $url = construirURL(array('menu' => $module_name), array('nav', 'start'));
    $sContenido = $oGrid->fetchGrid(array("title" => _tr("Breaks List"), "url" => $url, "icon" => "images/list.png", "width" => "99%", "start" => $end == 0 ? 0 : 1, "end" => $end, "total" => $end, "columns" => array_map('listBreaks_formatCols', $arrCols)), $arrData, $arrLang);
    if (strpos($sContenido, '<form') === FALSE) {
        $sContenido = "<form  method=\"POST\" style=\"margin-bottom:0;\" action=\"{$url}\">{$sContenido}</form>";
    }
    return $sContenido;
}
Esempio n. 15
0
 function genericImage($sGraph, $extraParam = array(), $w = NULL, $h = NULL)
 {
     return sprintf('<img alt="%s" src="%s" %s %s />', $sGraph, construirURL(array_merge(array('menu' => $this->module_name, 'action' => 'image', 'rawmode' => 'yes', 'image' => $sGraph), $extraParam)), is_null($w) ? '' : "width=\"{$w}\"", is_null($h) ? '' : "height=\"{$w}\"");
 }
Esempio n. 16
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;
    }
}
Esempio n. 17
0
function listAgent($pDB, $smarty, $module_name, $local_templates_dir)
{
    global $arrLang;
    $oAgentes = new Agentes($pDB);
    // Operaciones de manipulación de agentes
    if (isset($_POST['delete']) && isset($_POST['agent_number']) && ereg('^[[:digit:]]+$', $_POST['agent_number'])) {
        // Borrar el agente indicado de la base de datos, y del archivo
        if (!$oAgentes->deleteAgent($_POST['agent_number'])) {
            $smarty->assign(array('mb_title' => _tr("Error Delete Agent"), 'mb_message' => $oAgentes->errMsg));
        }
    } elseif (isset($_POST['disconnect']) && isset($_POST['agent_number']) && ereg('^[[:digit:]]+$', $_POST['agent_number'])) {
        // Desconectar agentes. El código en Agentes.class.php puede desconectar
        // varios agentes a la vez, pero aquí sólo se desconecta uno.
        $infoAgent = $oAgentes->getAgents($_POST['agent_number']);
        $arrAgentes = array($infoAgent['type'] . '/' . $infoAgent['number']);
        if (!$oAgentes->desconectarAgentes($arrAgentes)) {
            $smarty->assign(array('mb_title' => 'Unable to disconnect agent', 'mb_message' => $oAgentes->errMsg));
        }
    }
    // Estados posibles del agente
    $sEstadoAgente = 'All';
    $listaEstados = array("All" => _tr("All"), "Online" => _tr("Online"), "Offline" => _tr("Offline"));
    if (isset($_GET['cbo_estado'])) {
        $sEstadoAgente = $_GET['cbo_estado'];
    }
    if (isset($_POST['cbo_estado'])) {
        $sEstadoAgente = $_POST['cbo_estado'];
    }
    if (!in_array($sEstadoAgente, array_keys($listaEstados))) {
        $sEstadoAgente = 'All';
    }
    $listaAgentes = $oAgentes->getAgents();
    // Listar todos los agentes que están conectados
    $listaOnline = $oAgentes->getOnlineAgents();
    if (is_array($listaOnline)) {
        foreach (array_keys($listaAgentes) as $k) {
            $listaAgentes[$k]['online'] = in_array($listaAgentes[$k]['type'] . '/' . $listaAgentes[$k]['number'], $listaOnline);
        }
    } else {
        $smarty->assign("mb_title", 'Unable to read agent');
        $smarty->assign("mb_message", 'Cannot read agent - ' . $oAgentes->errMsg);
        foreach (array_keys($listaAgentes) as $k) {
            $listaAgentes[$k]['online'] = NULL;
        }
    }
    // Filtrar los agentes conocidos según el estado que se requiera
    function estado_Online($t)
    {
        return $t['online'];
    }
    function estado_Offline($t)
    {
        return !$t['online'];
    }
    if ($sEstadoAgente != 'All') {
        $listaAgentes = array_filter($listaAgentes, "estado_{$sEstadoAgente}");
    }
    $arrData = array();
    $sImgVisto = "<img src='modules/{$module_name}/themes/images/visto.gif' border='0' />";
    $sImgErrorCC = "<img src='modules/{$module_name}/themes/images/error_small.png' border='0' title=\"" . _tr("Agent doesn't exist in configuration file") . "\" />";
    $sImgErrorAst = "<img src='modules/{$module_name}/themes/images/error_small.png' border='0' title=\"" . _tr("Agent doesn't exist in database") . "\" />";
    $smarty->assign(array('PREGUNTA_BORRAR_AGENTE_CONF' => _tr("To rapair is necesary delete agent from configuration file. Do you want to continue?"), 'PREGUNTA_AGREGAR_AGENTE_CONF' => _tr("To rapair is necesary add an agent in configuration file. Do you want to continue?")));
    foreach ($listaAgentes as $tuplaAgente) {
        $tuplaData = array("<input class=\"button\" type=\"radio\" name=\"agent_number\" value=\"{$tuplaAgente["number"]}\" />", htmlentities($tuplaAgente['number'], ENT_COMPAT, 'UTF-8'), htmlentities($tuplaAgente['name'], ENT_COMPAT, 'UTF-8'), $tuplaAgente['online'] ? _tr("Online") : _tr("Offline"), htmlentities($tuplaAgente['office'], ENT_COMPAT, 'UTF-8'), "<a href='?menu={$module_name}&amp;action=edit_agent&amp;id_agent=" . $tuplaAgente["number"] . "'>[Sửa]</a>");
        /*
                switch ($tuplaAgente['sync']) {
                case 'OK':
                    $tuplaData[1] = $sImgVisto;
                    break;
        
                }
        */
        $arrData[] = $tuplaData;
    }
    $url = construirURL(array('menu' => $module_name, 'cbo_estado' => $sEstadoAgente), array('nav', 'start'));
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->setLimit(50);
    if (is_array($arrData)) {
        $oGrid->setTotal(count($arrData));
        $offset = $oGrid->calculateOffset();
        $arrData = array_slice($arrData, $offset, $oGrid->getLimit());
    }
    // Construir el reporte de los agentes activos
    $arrGrid = array("title" => "Số máy nhánh", "url" => $url, "url" => $url, "icon" => "images/user.png", "width" => "99%", "columns" => array(0 => array("name" => '&nbsp;', "property1" => ""), 1 => array("name" => _tr("Number"), "property1" => ""), 2 => array("name" => _tr("Name"), "property1" => ""), 3 => array("name" => _tr("Status"), "property1" => ""), 4 => array("name" => "Văn phòng", "property1" => ""), 5 => array("name" => _tr("Options"), "property1" => "")));
    $smarty->assign(array('LABEL_STATE' => _tr('Status'), 'LABEL_CREATE_AGENT' => "Thêm tổng đài viên", 'estados' => $listaEstados, 'estado_sel' => $sEstadoAgente, 'MODULE_NAME' => $module_name, 'LABEL_WITH_SELECTION' => _tr('With selection'), 'LABEL_DISCONNECT' => _tr('Disconnect'), 'LABEL_DELETE' => "Xóa", 'MESSAGE_CONTINUE_DELETE' => _tr("Are you sure you wish to continue?")));
    $oGrid->showFilter($smarty->fetch("{$local_templates_dir}/filter-list-agents.tpl"));
    $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;
}
Esempio n. 18
0
function _moduleContent(&$smarty, $module_name)
{
    //include module files
    include_once "modules/{$module_name}/configs/default.conf.php";
    include_once "modules/{$module_name}/libs/paloSantoCallsDetail.class.php";
    include_once "modules/agent_console/getinfo.php";
    global $arrConf;
    load_language_module($module_name);
    //folder path for custom templates
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $templates_dir = isset($arrConfig['templates_dir']) ? $arrConfig['templates_dir'] : 'themes';
    $local_templates_dir = "{$base_dir}/modules/{$module_name}/" . $templates_dir . '/' . $arrConf['theme'];
    // added by Tri Do
    $sAction = getParameter('action');
    switch ($sAction) {
        case 'viewNote':
            return viewNote();
            break;
        case 'viewDelivery':
            return view_delivery();
            break;
        default:
            break;
    }
    // Cadenas estáticas de Smarty
    $smarty->assign(array("Filter" => _tr('Filter'), "SHOW" => _tr("Show")));
    $bElastixNuevo = method_exists('paloSantoGrid', 'setURL');
    // Variables iniciales para posición de grid
    $offset = 0;
    $limit = 50;
    $total = 0;
    // Para poder consultar las colas activas
    $pConfig = new paloConfig("/etc", "amportal.conf", "=", "[[:space:]]*=[[:space:]]*");
    $ampconfig = $pConfig->leer_configuracion(false);
    $ampdsn = $ampconfig['AMPDBENGINE']['valor'] . "://" . $ampconfig['AMPDBUSER']['valor'] . ":" . $ampconfig['AMPDBPASS']['valor'] . "@" . $ampconfig['AMPDBHOST']['valor'] . "/asterisk";
    $oQueue = new paloQueue($ampdsn);
    $listaColas = $oQueue->getQueue();
    if (!is_array($listaColas)) {
        $smarty->assign("mb_title", _tr("Error when connecting to database"));
        $smarty->assign("mb_message", $oQueue->errMsg);
    }
    // Para poder consultar los agentes de campañas
    $pDB = new paloDB($cadena_dsn);
    $oCallsDetail = new paloSantoCallsDetail($pDB);
    $listaAgentes = $oCallsDetail->getAgents();
    // Para llenar el select de agentes
    $urlVars = array('menu' => $module_name);
    $arrFormElements = createFieldFilter($listaAgentes, $listaColas);
    $oFilterForm = new paloForm($smarty, $arrFormElements);
    // Validar y aplicar las variables de filtro
    $paramLista = NULL;
    $paramFiltro = array();
    foreach (array('date_start', 'date_end', 'calltype', 'agent', 'queue', 'phone') as $k) {
        $paramFiltro[$k] = getParameter($k);
    }
    if (!isset($paramFiltro['date_start'])) {
        $paramFiltro['date_start'] = date("d M Y");
    }
    if (!isset($paramFiltro['date_end'])) {
        $paramFiltro['date_end'] = date("d M Y");
    }
    if (!$oFilterForm->validateForm($paramFiltro)) {
        // Hay un error al validar las variables del filtro
        $smarty->assign("mb_title", _tr("Validation Error"));
        $arrErrores = $oFilterForm->arrErroresValidacion;
        $strErrorMsg = "<b>" . _tr('The following fields contain errors') . ":</b><br>";
        $strErrorMsg = implode(', ', array_keys($arrErrores));
        $smarty->assign("mb_message", $strErrorMsg);
    } else {
        $urlVars = array_merge($urlVars, $paramFiltro);
        $paramLista = $paramFiltro;
        $paramLista['date_start'] = translateDate($paramFiltro['date_start']) . " 00:00:00";
        $paramLista['date_end'] = translateDate($paramFiltro['date_end']) . " 23:59:59";
    }
    $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/filter.tpl", "", $paramFiltro);
    // Inicio de objeto grilla y asignación de filtro
    $oGrid = new paloSantoGrid($smarty);
    $oGrid->enableExport();
    // enable export.
    $oGrid->showFilter($htmlFilter);
    $bExportando = $bElastixNuevo ? $oGrid->isExportAction() : isset($_GET['exportcsv']) && $_GET['exportcsv'] == 'yes' || isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' || isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes';
    // Ejecutar la consulta con las variables ya validadas
    $arrData = array();
    $total = 0;
    if (is_array($paramLista)) {
        $total = $oCallsDetail->contarDetalleLlamadas($paramLista);
        if (is_null($total)) {
            $smarty->assign("mb_title", _tr("Error when connecting to database"));
            $smarty->assign("mb_message", $oCallsDetail->errMsg);
            $total = 0;
        } else {
            // Habilitar la exportación de todo el contenido consultado
            if ($bExportando) {
                $limit = $total;
            }
            // Calcular el offset de la petición de registros
            if ($bElastixNuevo) {
                $oGrid->setLimit($limit);
                $oGrid->setTotal($total);
                $offset = $oGrid->calculateOffset();
            } else {
                // Si se quiere avanzar a la sgte. pagina
                if (isset($_GET['nav']) && $_GET['nav'] == "end") {
                    // Mejorar el sgte. bloque.
                    if ($total % $limit == 0) {
                        $offset = $total - $limit;
                    } else {
                        $offset = $total - $total % $limit;
                    }
                }
                // Si se quiere avanzar a la sgte. pagina
                if (isset($_GET['nav']) && $_GET['nav'] == "next") {
                    $offset = $_GET['start'] + $limit - 1;
                }
                // Si se quiere retroceder
                if (isset($_GET['nav']) && $_GET['nav'] == "previous") {
                    $offset = $_GET['start'] - $limit - 1;
                }
            }
            // Ejecutar la consulta de los datos en el offset indicado
            $recordset = $oCallsDetail->leerDetalleLlamadas($paramLista, $limit, $offset);
            // add STT
            for ($i = 0; $i < count($recordset); $i++) {
                $recordset[$i]['stt'] = $i + 1;
            }
            if (!is_array($recordset)) {
                $smarty->assign("mb_title", _tr("Error when connecting to database"));
                $smarty->assign("mb_message", $oCallsDetail->errMsg);
                $total = 0;
            } else {
                function _calls_detail_map_recordset($cdr)
                {
                    $mapaEstados = array('abandonada' => 'Bỏ nhỡ', 'Abandoned' => 'Bỏ nhỡ', 'terminada' => 'Đã nghe', 'Success' => 'Đã nghe', 'fin-monitoreo' => _tr('End Monitor'), 'Failure' => _tr('Failure'), 'NoAnswer' => _tr('NoAnswer'), 'OnQueue' => _tr('OnQueue'), 'Placing' => _tr('Placing'), 'Ringing' => _tr('Ringing'), 'ShortCall' => _tr('ShortCall'), 'activa' => 'Đang gọi');
                    return array($cdr['stt'], $cdr[0], htmlentities($cdr[1], ENT_COMPAT, "UTF-8"), substr($cdr[2], 0, 10), substr($cdr[2], 11, 8), substr($cdr[3], 0, 10), substr($cdr[3], 11, 8), is_null($cdr[4]) ? '-' : formatoSegundos($cdr[4]), is_null($cdr[5]) ? '-' : formatoSegundos($cdr[5]), $cdr[6], $cdr[8], $cdr[9], isset($mapaEstados[$cdr[10]]) ? $mapaEstados[$cdr[10]] : _tr($cdr[10]), is_null($cdr[12]) || trim($cdr[12] == '') ? '' : '<a href="javascript:void(0)" onclick="view_note(\'' . $cdr[11] . '\')">Xem</a>');
                }
                $arrData = array_map('_calls_detail_map_recordset', $recordset);
            }
        }
    }
    $arrColumnas = array('STT', 'Số Agent', 'Nhân viên', _tr("Start Date"), _tr("Start Time"), _tr("End Date"), _tr("End Time"), "Thời lượng", _tr("Thời gian chờ"), _tr("Queue"), _tr("Số điện thoại"), _tr("Chuyển máy"), _tr("Status"), 'Nội dung');
    if ($bElastixNuevo) {
        $oGrid->setURL(construirURL($urlVars, array("nav", "start")));
        $oGrid->setData($arrData);
        $oGrid->setColumns($arrColumnas);
        $oGrid->setTitle('Chi tiết cuộc gọi Call Center');
        $oGrid->pagingShow(true);
        $oGrid->setNameFile_Export(_tr("Calls Detail"));
        return $oGrid->fetchGrid();
    } else {
        global $arrLang;
        $url = construirURL($urlVars, array("nav", "start"));
        function _map_name($s)
        {
            return array('name' => $s);
        }
        $arrGrid = array("title" => _tr("Calls Detail"), "url" => $url, "icon" => "images/user.png", "width" => "99%", "start" => $total == 0 ? 0 : $offset + 1, "end" => $offset + $limit <= $total ? $offset + $limit : $total, "total" => $total, "columns" => array_map('_map_name', $arrColumnas));
        if (isset($_GET['exportpdf']) && $_GET['exportpdf'] == 'yes' && method_exists($oGrid, 'fetchGridPDF')) {
            return $oGrid->fetchGridPDF($arrGrid, $arrData);
        }
        if (isset($_GET['exportspreadsheet']) && $_GET['exportspreadsheet'] == 'yes' && method_exists($oGrid, 'fetchGridXLS')) {
            return $oGrid->fetchGridXLS($arrGrid, $arrData);
        }
        if ($bExportando) {
            header("Cache-Control: private");
            header("Pragma: cache");
            // Se requiere para HTTPS bajo IE6
            header('Content-disposition: inline; filename="calls_detail.csv"');
            header("Content-Type: text/csv; charset=UTF-8");
        }
        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;
    }
}
Esempio n. 19
0
function _moduleContent(&$smarty, $module_name)
{
    include_once "libs/paloSantoGrid.class.php";
    include_once "libs/paloSantoDB.class.php";
    include_once "libs/paloSantoForm.class.php";
    include_once "libs/paloSantoConfig.class.php";
    include_once "libs/paloSantoCDR.class.php";
    require_once "libs/misc.lib.php";
    include_once "libs/paloSantoRate.class.php";
    include_once "libs/paloSantoTrunk.class.php";
    include_once "libs/paloSantoGraphImage.lib.php";
    //include module files
    include_once "modules/{$module_name}/configs/default.conf.php";
    $lang = get_language();
    $base_dir = dirname($_SERVER['SCRIPT_FILENAME']);
    $lang_file = "modules/{$module_name}/lang/{$lang}.lang";
    if (file_exists("{$base_dir}/{$lang_file}")) {
        include_once "{$lang_file}";
    } else {
        include_once "modules/{$module_name}/lang/en.lang";
    }
    //global variables
    global $arrConf;
    global $arrConfModule;
    global $arrLang;
    global $arrLangModule;
    $arrConf = array_merge($arrConf, $arrConfModule);
    $arrLang = array_merge($arrLang, $arrLangModule);
    //folder path for custom templates
    $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'];
    $MAX_DAYS = 60;
    $arrData = array();
    $smarty->assign("menu", "dest_distribution");
    $smarty->assign("Filter", $arrLang['Filter']);
    $arrFormElements = array("date_start" => array("LABEL" => $arrLang["Start Date"], "REQUIRED" => "yes", "INPUT_TYPE" => "DATE", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^[[:digit:]]{1,2}[[:space:]]+[[:alnum:]]{3}[[:space:]]+[[:digit:]]{4}\$"), "date_end" => array("LABEL" => $arrLang["End Date"], "REQUIRED" => "yes", "INPUT_TYPE" => "DATE", "INPUT_EXTRA_PARAM" => "", "VALIDATION_TYPE" => "ereg", "VALIDATION_EXTRA_PARAM" => "^[[:digit:]]{1,2}[[:space:]]+[[:alnum:]]{3}[[:space:]]+[[:digit:]]{4}\$"), "criteria" => array("LABEL" => $arrLang["Criteria"], "REQUIRED" => "yes", "INPUT_TYPE" => "SELECT", "INPUT_EXTRA_PARAM" => array("minutes" => $arrLang["Distribution by Time"], "num_calls" => $arrLang["Distribution by Number of Calls"], "charge" => $arrLang["Distribution by Cost"]), "VALIDATION_TYPE" => "text", "VALIDATION_EXTRA_PARAM" => ""));
    $oFilterForm = new paloForm($smarty, $arrFormElements);
    // Por omision las fechas toman el sgte. valor (la fecha de hoy)
    $date_start = date("Y-m-d") . " 00:00:00";
    $date_end = date("Y-m-d") . " 23:59:59";
    $value_criteria = "minutes";
    if (isset($_POST['filter'])) {
        if ($oFilterForm->validateForm($_POST)) {
            // Exito, puedo procesar los datos ahora.
            $date_start = translateDate($_POST['date_start']) . " 00:00:00";
            $date_end = translateDate($_POST['date_end']) . " 23:59:59";
            //valido que no exista diferencia mayor de 31 dias entre las fechas
            $inicio = strtotime($date_start);
            $fin = strtotime($date_end);
            $num_dias = ($fin - $inicio) / 86400;
            if ($num_dias > $MAX_DAYS) {
                $_POST['date_start'] = date("d M Y");
                $_POST['date_end'] = date("d M Y");
                $date_start = date("Y-m-d") . " 00:00:00";
                $date_end = date("Y-m-d") . " 23:59:59";
                $smarty->assign("mb_title", $arrLang["Validation Error"]);
                $smarty->assign("mb_message", "{$arrLang['Date Range spans maximum number of days']}:{$MAX_DAYS}");
            }
            $value_criteria = $_POST['criteria'];
            $arrFilterExtraVars = array("date_start" => $_POST['date_start'], "date_end" => $_POST['date_end'], "criteria" => $_POST['criteria']);
        } else {
            // Error
            $smarty->assign("mb_title", $arrLang["Validation Error"]);
            $arrErrores = $oFilterForm->arrErroresValidacion;
            $strErrorMsg = "<b>{$arrLang['The following fields contain errors']}:</b><br>";
            foreach ($arrErrores as $k => $v) {
                $strErrorMsg .= "{$k}, ";
            }
            $strErrorMsg .= "";
            $smarty->assign("mb_message", $strErrorMsg);
        }
        $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/dest_dist_filter.tpl", "", $_POST);
    } else {
        if (isset($_GET['date_start']) && isset($_GET['date_end'])) {
            //valido que no exista diferencia mayor de 31 dias entre las fechas
            $date_start = translateDate($_GET['date_start']) . " 00:00:00";
            $date_end = translateDate($_GET['date_end']) . " 23:59:59";
            $inicio = strtotime($date_start);
            $fin = strtotime($date_end);
            $num_dias = ($fin - $inicio) / 86400;
            if ($num_dias > $MAX_DAYS) {
                $_GET['date_start'] = date("d M Y");
                $_GET['date_end'] = date("d M Y");
                $date_start = date("Y-m-d") . " 00:00:00";
                $date_end = date("Y-m-d") . " 23:59:59";
                $smarty->assign("mb_title", $arrLang["Validation Error"]);
                $smarty->assign("mb_message", "{$arrLang['Date Range spans maximum number of days']}:{$MAX_DAYS}");
            }
            $value_criteria = $_GET['criteria'];
            $arrFilterExtraVars = array("date_start" => $_GET['date_start'], "date_end" => $_GET['date_end'], "criteria" => $_GET['criteria']);
            $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/dest_dist_filter.tpl", "", $_GET);
        } else {
            $date_start = date("Y-m-d") . " 00:00:00";
            $date_end = date("Y-m-d") . " 23:59:59";
            $htmlFilter = $contenidoModulo = $oFilterForm->fetchForm("{$local_templates_dir}/dest_dist_filter.tpl", "", array('date_start' => date("d M Y"), 'date_end' => date("d M Y"), 'criteria' => 'minutes'));
        }
    }
    if (isset($_GET['action']) && $_GET['action'] == 'image') {
        ejecutarGrafico($value_criteria, $date_start, $date_end);
        return '';
    }
    //obtener los datos a mostrar
    $type_graph = $value_criteria;
    //consulto cuales son los trunks de salida
    $data_graph = leerDatosGrafico($type_graph, $date_start, $date_end);
    $title_sumary = $data_graph['title_sumary'];
    //contruir la tabla de sumario
    $smarty->assign('URL_GRAPHIC', construirURL(array('module' => $module_name, 'rawmode' => 'yes', 'action' => 'image', 'criteria' => $value_criteria, 'date_start' => date('d M Y', strtotime($date_start)), 'date_end' => date('d M Y', strtotime($date_end)))));
    if (count($data_graph["values"]) > 0) {
        $mostrarSumario = TRUE;
        $total_valores = array_sum($data_graph["values"]);
        $resultados = $data_graph["values"];
        foreach ($resultados as $pos => $valor) {
            $results[] = array($data_graph['legend'][$pos], number_format($valor, 2), number_format($valor / $total_valores * 100, 2));
        }
        if (count($results) > 1) {
            $results[] = array("<b>Total<b>", "<b>" . number_format($total_valores, 2) . "<b>", "<b>" . number_format(100, 2) . "<b>");
        }
        $smarty->assign("Rate_Name", $arrLang["Rate Name"]);
        $smarty->assign("Title_Criteria", $title_sumary);
        $smarty->assign("results", $results);
    } else {
        $mostrarSumario = FALSE;
    }
    $smarty->assign("mostrarSumario", $mostrarSumario);
    $smarty->assign("contentFilter", $htmlFilter);
    $smarty->assign("title", $arrLang['Destination Distribution']);
    $smarty->assign("icon", "images/bardoc.png");
    return $smarty->fetch("file:{$local_templates_dir}/dest_distribution.tpl");
}
Esempio n. 20
0
function modificarArchivo($module_name, $smarty, $local_templates_dir, $sDirectorio, $sAccion)
{
    $sNombreArchivo = '';
    $sMensajeStatus = '';
    if (isset($_POST['Reload'])) {
        $parameters = array('Command' => "module reload");
        $result = AsteriskManagerAPI("Command", $parameters, true);
        if ($result) {
            $smarty->assign("mb_title", "MESSAGE");
            $smarty->assign("mb_message", _tr("Asterisk has been reloaded"));
        } else {
            $smarty->assign("mb_title", "ERROR");
            $smarty->assign("mb_message", _tr("Error when connecting to Asterisk Manager"));
        }
    }
    if ($sAccion == 'new') {
        $smarty->assign('LABEL_COMPLETADO', '.conf');
        if (isset($_POST['Guardar'])) {
            if (!isset($_POST['basename']) || trim($_POST['basename']) == '') {
                $sMensajeStatus .= _tr('Please write the file name') . '<br/>';
            } else {
                $sNombreArchivo = basename($_POST['basename'] . '.conf');
                /* Los datos del archivo se envían desde el navegador con líneas
                     separadas por CRLF que debe ser convertido a LF para estilo Unix
                   */
                if (file_put_contents($sDirectorio . $sNombreArchivo, str_replace("\r\n", "\n", $_POST['content'])) === FALSE) {
                    $sMensajeStatus .= _tr("This file doesn't have permisses to write") . '<br/>';
                } else {
                    $sMensajeStatus .= _tr("The changes was saved in the file") . '<br/>';
                }
            }
        }
    } elseif ($sAccion == 'edit') {
        $sNombreArchivo = basename(getParameter('file'));
        if (is_null($sNombreArchivo) || !file_exists($sDirectorio . $sNombreArchivo)) {
            Header("Location: ?menu={$module_name}");
            return '';
        }
        if (isset($_POST['Guardar'])) {
            /* Los datos del archivo se envían desde el navegador con líneas
                 separadas por CRLF que debe ser convertido a LF para estilo Unix
               */
            if (!is_writable($sDirectorio . $sNombreArchivo) || file_put_contents($sDirectorio . $sNombreArchivo, str_replace("\r\n", "\n", $_POST['content'])) === FALSE) {
                $sMensajeStatus .= _tr("This file doesn't have permisses to write") . '<br/>';
            } else {
                $sMensajeStatus .= _tr("The changes was saved in the file") . '<br/>';
            }
        } else {
            if (!is_writable($sDirectorio . $sNombreArchivo)) {
                $sMensajeStatus .= _tr("This file doesn't have permisses to write") . '<br/>';
            }
        }
        $sContenido = file_get_contents($sDirectorio . $sNombreArchivo);
        if ($sContenido === FALSE) {
            $sMensajeStatus .= _tr("This file doesn't have permisses to read") . '<br/>';
        }
        if (!isset($_POST['content'])) {
            $_POST['content'] = $sContenido;
        }
        $_POST['basename'] = basename($sNombreArchivo);
    }
    $oForm = new paloForm($smarty, array('basename' => array('LABEL' => _tr('File'), 'REQUIRED' => 'yes', 'INPUT_TYPE' => 'TEXT', 'INPUT_EXTRA_PARAM' => '', 'VALIDATION_TYPE' => 'text', 'VALIDATION_EXTRA_PARAM' => '', 'EDITABLE' => $sAccion == 'new' ? 'yes' : 'no'), 'content' => array('LABEL' => _tr('Content'), 'REQUIRED' => 'no', 'INPUT_TYPE' => 'TEXTAREA', 'INPUT_EXTRA_PARAM' => '', 'VALIDATION_TYPE' => 'text', 'VALIDATION_EXTRA_PARAM' => '', 'ROWS' => 25, 'COLS' => 100)));
    $oForm->setEditMode();
    $smarty->assign('url_edit', construirURL(array('menu' => $module_name, 'action' => $sAccion, 'file' => $sNombreArchivo)));
    $smarty->assign('url_back', construirURL(array('menu' => $module_name), array('action', 'file', 'nav' => getParameter('nav'), 'page' => getParameter('page'))));
    $smarty->assign('search', getParameter('search'));
    $smarty->assign('LABEL_SAVE', _tr('Save'));
    $smarty->assign('RELOAD_ASTERISK', _tr('Reload Asterisk'));
    $smarty->assign('LABEL_BACK', _tr('Back'));
    $smarty->assign('msg_status', $sMensajeStatus);
    $smarty->assign('icon', "images/user.png");
    return $oForm->fetchForm("{$local_templates_dir}/file_editor.tpl", _tr("File Editor"), $_POST);
}
Esempio n. 21
0
function viewMemberList($smarty, $module_name, $local_templates_dir, &$pDB, $arrConf)
{
    $pEmailList = new paloSantoEmailList($pDB);
    $id_list = getParameter("id");
    if (!$pEmailList->listExistsbyId($id_list)) {
        $smarty->assign("mb_title", _tr("Validation Error"));
        $smarty->assign("mb_message", _tr("The List entered does not exist"));
        return reportEmailList($smarty, $module_name, $local_templates_dir, $pDB, $arrConf);
    }
    $field_type = getParameter("filter_type");
    $field_pattern = getParameter("filter_txt");
    $smarty->assign("IDEMAILLIST", $id_list);
    $smarty->assign("SHOW", _tr("Show"));
    $smarty->assign("RETURN", _tr("Return"));
    $smarty->assign("LINK", "?menu={$module_name}&action=export&id={$id_list}&rawmode=yes");
    $smarty->assign("EXPORT", _tr("Export Members"));
    $totalMembers = $pEmailList->getTotalMembers($id_list);
    $oGrid = new paloSantoGrid($smarty);
    $limit = 20;
    $oGrid->setLimit($limit);
    $oGrid->setTotal($totalMembers);
    $oGrid->setTitle(_tr("List Members of") . " " . $pEmailList->getListName($id_list));
    $oGrid->setIcon("/modules/{$module_name}/images/email.png");
    $oGrid->pagingShow(true);
    $offset = $oGrid->calculateOffset();
    $url = array('menu' => $module_name, 'action' => 'view_memberlist', 'id' => $id_list, 'filter_type' => $field_type, 'filter_txt' => $field_pattern);
    $oGrid->setURL($url);
    $arrColumns = array(_tr("Member name"), _tr("Member email"));
    $oGrid->setColumns($arrColumns);
    $arrResult = $pEmailList->getMembers($limit, $offset, $id_list, $field_type, $field_pattern);
    $arrData = null;
    if (is_array($arrResult) && $totalMembers > 0) {
        foreach ($arrResult as $key => $value) {
            $arrTmp[0] = $value["namemember"];
            $arrTmp[1] = $value["mailmember"];
            $arrData[] = $arrTmp;
        }
    }
    $oGrid->setData($arrData);
    $arrFormFilterMembers = createFieldFilterViewMembers();
    $oFilterForm = new paloForm($smarty, $arrFormFilterMembers);
    $arrType = array("name" => _tr("Name"), "email" => _tr("Email"));
    if (!is_null($field_type)) {
        $nameField = $arrType[$field_type];
    } else {
        $nameField = "";
    }
    $oGrid->customAction("return", _tr("Return"));
    $oGrid->customAction("?menu={$module_name}&action=export&id={$id_list}&rawmode=yes", _tr("Export Members"), null, true);
    //$arrFiltro = array("filter_type"=>$field_type,"filter_txt"=>$field_pattern);
    $oGrid->addFilterControl(_tr("Filter applied: ") . $nameField . " = " . $field_pattern, $_POST, array("filter_type" => "name", "filter_txt" => ""));
    $htmlFilter = $oFilterForm->fetchForm("{$local_templates_dir}/view_members.tpl", "", $_POST);
    $oGrid->showFilter(trim($htmlFilter));
    $content = $oGrid->fetchGrid();
    if (strpos($content, '<form') === FALSE) {
        $content = "<form  method='POST' style='margin-bottom:0;' action=" . construirURL($url) . ">{$content}</form>";
    }
    return $content;
}