function listar_oportunidades_por_puntaje($fecha = array(), $dashboard = NULL) { $dataset = array(); $results = array(); $fields = array("opp.id_oportunidad", "opp.nombre", "HEX(opp.uuid_oportunidad) AS uuid_oportunidad", "HEX(cl.uuid_cliente) AS uuid_cliente", "HEX(opp.uuid_sociedad) AS uuid_sociedad", "HEX(opp.uuid_contacto) AS uuid_contacto", "ccat.etiqueta AS tipo_cliente", "cl.nombre AS nombre_cliente", "clso.nombre_comercial", "ocat.id_cat AS id_etapa", "ocat.etiqueta AS etapa", "opp.fecha_cierre", "opp.fecha_creacion", "prop.valor_alquiler", "CONCAT_WS(' ', IF(usr.nombre != '', usr.nombre, ''), IF(usr.apellido != '', usr.apellido, '')) AS usuario_asignado", "CONCAT_WS(' ', IF(con.nombre != '', con.nombre, ''), IF(con.apellido != '', con.apellido, '')) AS nombre_contacto"); /** * Permiso Default: ver las asignadas o las que ha creado */ $clause = array("ocat.valor NOT IN('vendido','venta_perdida')" => NULL); if (!empty($fecha)) { $replace = Grafica_usuario::condicion_fecha($fecha); $str = str_replace("fecha_creacion", "opp.fecha_creacion", $replace); $clause[$str] = NULL; } else { $clause["MONTH(opp.fecha_creacion) = '" . date('n') . "'"] = NULL; } /** * Array con los uuid de usuarios * que el usario actual puede ver. */ if (empty($dashboard)) { $ver_usuarios = @CRM_Controller::andrea_ACL(); } else { $ver_usuarios = @CRM_Controller::andrea_ACL('dashboard'); } $this->db->select($fields)->distinct()->from('opp_oportunidades AS opp')->join('cl_clientes AS cl', 'cl.uuid_cliente = opp.uuid_cliente', 'LEFT')->join('cl_cliente_sociedades_contactos AS clcon', 'clcon.uuid_cliente = cl.uuid_cliente', 'LEFT')->join('con_contactos AS con', 'con.uuid_contacto = clcon.uuid_contacto', 'LEFT')->join('opp_oportunidades_cat AS ocat', 'ocat.id_cat = opp.id_etapa_venta', 'LEFT')->join('usuarios AS usr', 'usr.uuid_usuario = opp.id_asignado', 'LEFT')->join('cl_clientes_cat AS ccat', 'ccat.id_cat = cl.id_tipo_cliente', 'LEFT')->join('rpo_propiedades AS prop', 'prop.uuid_propiedad = opp.uuid_propiedad', 'LEFT')->join('cl_clientes_sociedades AS clso', 'clso.uuid_sociedad = opp.uuid_sociedad', 'LEFT'); /** * verificar array $ver_usuarios */ if (!empty($ver_usuarios["uuid_usuario"])) { $usuarios = $ver_usuarios["uuid_usuario"]; $usuarios = !empty($usuarios) ? implode(", ", array_map(function ($usuarios) { return "'" . $usuarios . "'"; }, $usuarios)) : ""; $clause["HEX(opp.id_asignado) IN(" . $usuarios . ")"] = NULL; } $this->db->where($clause); $oportunidades = $this->db->group_by('opp.id_oportunidad', 'DESC')->get()->result_array(); if (!empty($oportunidades)) { $i = 0; foreach ($oportunidades as $oportunidad) { $uuid_oportunidad = !empty($oportunidad["uuid_oportunidad"]) ? $oportunidad["uuid_oportunidad"] : ""; $results[$i]["id_oportunidad"] = !empty($oportunidad["id_oportunidad"]) ? $oportunidad["id_oportunidad"] : ""; $results[$i]["uuid_oportunidad"] = !empty($oportunidad["uuid_oportunidad"]) ? $oportunidad["uuid_oportunidad"] : ""; $results[$i]["nombre"] = !empty($oportunidad["nombre"]) ? $oportunidad["nombre"] : ""; $results[$i]["nombre_comercial"] = !empty($oportunidad["nombre_comercial"]) ? $oportunidad["nombre_comercial"] : ""; $results[$i]["tipo_cliente"] = !empty($oportunidad["tipo_cliente"]) ? $oportunidad["tipo_cliente"] : ""; $results[$i]["nombre_cliente"] = !empty($oportunidad["nombre_cliente"]) ? $oportunidad["nombre_cliente"] : ""; $results[$i]["fecha_creacion"] = !empty($oportunidad["fecha_creacion"]) ? $oportunidad["fecha_creacion"] : ""; //------------------------- // Seleccionar la suma total // de las actividades completadas // de esta oportunidad. //------------------------- $fields = array("COALESCE(SUM(actta.puntaje), 0) AS puntaje_total"); $clause = array("actcat1.valor" => "oportunidades", "act.uuid_oportunidad = UNHEX('{$uuid_oportunidad}')" => NULL, "act.completada" => 1); $actividad = $this->db->select($fields)->distinct()->from('act_actividades AS act')->join("act_actividades_cat AS actcat1", "actcat1.id_cat = act.relacionado_con", 'LEFT')->join("act_tipo_actividades AS actta", "actta.uuid_tipo_actividad = act.uuid_tipo_actividad", 'LEFT')->where($clause)->get()->result_array(); $results[$i]["puntaje_total"] = 0; if (!empty($actividad[0]["puntaje_total"]) && $actividad[0]["puntaje_total"] > 0) { $results[$i]["puntaje_total"] = !empty($actividad[0]["puntaje_total"]) ? (int) $actividad[0]["puntaje_total"] : 0; $dataset[$i] = (int) $actividad[0]["puntaje_total"]; $i++; } else { unset($results[$i]); unset($dataset[$i]); } } //Si no tiene actividad retornar false /*if(@Util::is_array_empty($hasActividades)){ return false; }*/ /** * Hack: para que la funcion PHPExcel_Calculation_Statistical::PERCENTRANK * No envie el siguiente error, si el array $dataset contiene un solo valor: * * A PHP Error was encountered * Severity: Warning * Message: Division by zero * Filename: Calculation/Statistical.php */ if (count($dataset) == 1) { $dataset[] = 0; } //ordenar los puntajes //de menor a mayor ksort($dataset); //Recorrer los resultados y calcular el PERCENTRANK //Usando una clase de la libreria PHPEXcel y introducir //el resultado en el array de $results $j = 0; $percentagerank = ""; foreach ($results as $result) { /*if(empty($result) || empty($result["puntaje_total"]) && $result["puntaje_total"] == "" || empty($result["puntaje_total"]) && $result["puntaje_total"] <= 0 || !empty($result["puntaje_total"]) && count($dataset) == 1 && $dataset[0] == $result["puntaje_total"]){ continue; }*/ if (!empty($result["puntaje_total"]) && $result["puntaje_total"] != "" && $result["puntaje_total"] > 0) { $percentagerank = PHPExcel_Calculation_Statistical::PERCENTRANK($dataset, $result["puntaje_total"], 2) * 100; //$percentagerank = PHPExcel_Calculation_Statistical::PERCENTRANK($dataset, $result["puntaje_total"], 1); $results[$j]["percentagerank"] = !empty($percentagerank) ? $percentagerank : 0; } else { unset($result); } $j++; } } //Ordenar el arreglo segun los valores de porcentaje. (mayor -> menor) usort($results, function ($a, $b) { $array_a = !empty($a['percentagerank']) ? $a['percentagerank'] : 0; $array_b = !empty($b['percentagerank']) ? $b['percentagerank'] : 0; if ($array_a == $array_b) { return 0; } else { if ($array_a > $array_b) { return -1; } else { return 1; } } }); return $results; }
function ajax_score_clientes() { if ($this->input->is_ajax_request()) { CRM_Controller::$user_role; $fecha = $this->input->post('fecha', true); $fecha_opciones = date_options($fecha); $key = key($fecha_opciones); $fecha_actual = $fecha_opciones[$key][0]; $actual = array($key => $fecha_actual); $usuario_categoria = CRM_Controller::$categoria_usuario_key; $subordinados = array(); if ($usuario_categoria != 'admin') { //$subordinados = CRM_Controller::seleccionar_subordinados(); $subordinados = $this->andrea_ACL(); } $datos = Grafica_usuario::clientes_total_average($actual, $subordinados); $json = '{"results":[' . json_encode($datos) . ']}'; echo $json; exit; } }
/** * The method that is actually run. */ public function perform() { try { //Si el arreglo de usuarios no es vacio if (isset(self::$usuarios)) { $grafica = new Grafica_usuario(); $excel = new SimpleExcel('csv'); $excel->writer->setDelimiter(","); /** * Filtro de Reporte Default Semanal */ $fecha["esta_semana"] = date('Y-m-d h:i:s'); foreach (self::$usuarios as $usuario) { $subordinados = Subordinados::andrea_ACL($usuario["uuid_usuario"]); $uuid_subordinados = !empty($subordinados) ? implode(", ", array_map(function ($subordinados) { return "'" . $subordinados . "'"; }, $subordinados)) : ""; echo "ID JOB: " . $usuario["id_job"] . "." . PHP_EOL; if ($usuario["id_job"] == 6) { echo "Ejecutando Reporte de Oportunidades." . PHP_EOL; /** * REPORTE PUNTAJE DE OPORTUNIDAD */ $puntaje_oportunidad = $grafica->listar_oportunidades_por_puntaje($fecha, $subordinados); if (!empty($puntaje_oportunidad)) { $headers = array("Usuario", "Nombre Oportunidad", "Puntaje"); /** * Armar contenido/valores del CSV */ $j = 0; foreach ($puntaje_oportunidad as $puntaje) { $contentarray[$j][] = $grafica->limpiar_cadena_texto($puntaje["usuario_asignado"]); $contentarray[$j][] = $grafica->limpiar_cadena_texto($puntaje["nombre"]); $contentarray[$j][] = $puntaje["percentagerank"] . "%"; $j++; } $csv = array_merge(array($headers), $contentarray); /** * GENERAR ARCHIVO CSV */ $excel->writer->setData($csv); $excel->writer->saveFile('reporte-puntaje-oportunidades-semana-' . date('W'), '/var/www/clientes/crm_corcione/public/uploads/reportes/reporte-puntaje-oportunidades-semana-' . date('W') . '.csv'); $filename = '/var/www/clientes/crm_corcione/public/uploads/reportes/reporte-puntaje-oportunidades-semana-' . date('W') . '.csv'; $mail = new PHPMailer(); $mail->setFrom('*****@*****.**', 'Corcione'); $mail->addAddress($usuario["email"], $usuario["nombre_completo"]); $mail->addAttachment($filename); $mail->isHTML(true); $mail->Subject = 'Reporte de Puntaje de Oportunidades - Corcione CRM'; $mail->Body = 'Adjunto reporte'; if (!$mail->send()) { echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo . PHP_EOL; } else { echo 'Message has been sent \\n' . PHP_EOL; } if (file_exists($filename)) { unlink($filename); } } } else { if ($usuario["id_job"] == 4) { /** * REPORTE DE ACTIVIDAD SEMANAL */ $actividades = $grafica->usuarios_actividades($fecha, $subordinados); if (!empty($actividades)) { /** * Armar Headers */ $headers = array_keys($actividades[0]); $headers = array_map(function ($headers) { $key = ucwords(str_replace("_", " ", $headers)); $key = str_replace(" De ", " de ", $key); $key = str_replace(" Al ", " al ", $key); $key = str_replace(" Con ", " con ", $key); $key = str_replace(" La ", " la ", $key); $key = str_replace(" En ", " en ", $key); return $key; }, $headers); $contentarray = array(); /** * Armar contenido/valores del CSV */ $j = 0; foreach ($actividades as $actividad) { foreach ($actividad as $key => $descripcion) { $contentarray[$j][] = $descripcion; } $j++; } $csv = array_merge(array($headers), $contentarray); /** * GENERAR ARCHIVO CSV */ $excel->writer->setData($csv); $excel->writer->saveFile('reporte-actividades-semana-' . date('W'), '/var/www/clientes/crm_corcione/public/uploads/reportes/reporte-actividades-semana-' . date('W') . '.csv'); $filename = '/var/www/clientes/crm_corcione/public/uploads/reportes/reporte-actividades-semana-' . date('W') . '.csv'; $mail = new PHPMailer(); $mail->setFrom('*****@*****.**', 'Corcione'); $mail->addAddress($usuario["email"], $usuario["nombre_completo"]); $mail->addAttachment($filename); $mail->isHTML(true); $mail->Subject = 'Reporte de Actividad Semanal - Corcione CRM'; $mail->Body = 'Adjunto reporte'; if (!$mail->send()) { echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo . PHP_EOL; } else { echo 'Message has been sent \\n' . PHP_EOL; } if (file_exists($filename)) { unlink($filename); } } } else { if ($usuario["id_job"] == 5) { /** * REPORTE DE CLIENT SCORE */ $client_scores = $grafica->clienteScoreUsuario(date('Y-m-d h:i:s'), $uuid_subordinados); if (!empty($client_scores)) { /** * Armar Headers */ $headers = array("Usuario", "Clientes de Semana", "Clientes de Mes", "Clientes de Año", "Todos los Clientes"); $contentarray = array(); /** * Armar contenido/valores del CSV */ $j = 0; foreach ($client_scores as $score) { //foreach($scores AS $key => $score){ $contentarray[$j][] = $score["usuario_asignado"]; $contentarray[$j][] = $score["score_semana"]; $contentarray[$j][] = $score["score_mes"]; $contentarray[$j][] = $score["score_year"]; $contentarray[$j][] = $score["score_todo"]; //} $j++; } $csv = array_merge(array($headers), $contentarray); /** * GENERAR ARCHIVO CSV */ $excel->writer->setData($csv); $excel->writer->saveFile('reporte-clientscore-semana-' . date('W'), '/var/www/clientes/crm_corcione/public/uploads/reportes/reporte-clientscore-semana-' . date('W') . '.csv'); $filename = '/var/www/clientes/crm_corcione/public/uploads/reportes/reporte-clientscore-semana-' . date('W') . '.csv'; $mail = new PHPMailer(); $mail->setFrom('*****@*****.**', 'Corcione'); $mail->addAddress($usuario["email"], $usuario["nombre_completo"]); $mail->addAttachment($filename); $mail->isHTML(true); $mail->Subject = 'Reporte de Client Score - Corcione CRM'; $mail->Body = 'Adjunto reporte'; if (!$mail->send()) { echo 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo . PHP_EOL; } else { echo 'Message has been sent \\n' . PHP_EOL; } if (file_exists($filename)) { unlink($filename); } } } } } } } } catch (\Exception $e) { echo $e->getMessage() . PHP_EOL; } }
public function ajax_cliente_score_usuario() { if ($this->input->is_ajax_request()) { $fecha = $this->input->post('fecha', true); $fecha_opciones = date_options($fecha); $fecha_actual = $fecha_opciones[$fecha][0]; $actual = array($fecha => $fecha_actual); $uuid_usuario = CRM_Controller::$uuid_usuario; $score = Grafica_usuario::clienteScoreUsuario($actual, $uuid_usuario); $json = $score; echo $json; } }