input('year'); $month = $request->input('mes',Carbon::now()->format('m')); $operador_id = $request->input('operador_id', 0); $sucursal = $request->input('sucursal'); $empresarial = $this->empresarial($month, $year, $operador_id, $sucursal); $domestico = $this->domestico($month, $year, $operador_id, $sucursal); return response()->success(compact('domestico', 'empresarial')); } public function domestico($month, $year, $operador_id, $sucursal) { $servicios_det = ServicioDet::select('servicios_det.id') ->join('servicios_enc', 'servicios_det.servicio_enc_id', '=', 'servicios_enc.id') ->whereMonth('servicios_det.fecha_solicitud', $month) ->whereYear('servicios_det.fecha_solicitud', $year) ->where('requiere_encuesta', 1) ->where('servicios_enc.sucursal_id', $sucursal) ->where('tipo_servicio_id', DOMESTICO); if($operador_id){ $servicios_det->where(function($q) use ($operador_id){ $q->where('operador_id',$operador_id) ->orWhere('auxiliar_1',$operador_id) ->orWhere('auxiliar_2',$operador_id); }); } $id = $servicios_det->pluck('id'); $d = ServicioEncuestaDomestico::select('preguntas_domestico.nombre as pregunta', DB::raw('ROUND(AVG(coalesce(respuestas_domestico.puntuacion,0)), 2) as puntuacion')) ->join('respuestas_domestico', 'servicios_encuestas_domestico.respuesta_id', '=', 'respuestas_domestico.id') ->join('preguntas_domestico','servicios_encuestas_domestico.pregunta_id', '=','preguntas_domestico.id') ->whereIn('servicio_det_id', $id) ->whereNotNull('respuesta_id') ->groupBy('servicios_encuestas_domestico.pregunta_id', 'preguntas_domestico.nombre') ->get(); $salida = []; foreach ($d as $e){ $salida[] = [$e->pregunta, (float)$e->puntuacion]; } return $salida; } public function empresarial($month, $year, $operador_id, $sucursal){ $servicios_det = ServicioDet::select('servicios_det.id') ->join('servicios_enc', 'servicios_det.servicio_enc_id', '=', 'servicios_enc.id') ->whereMonth('servicios_det.fecha_solicitud', $month) ->whereYear('servicios_det.fecha_solicitud', $year) ->where('requiere_encuesta', 1) ->where('servicios_enc.sucursal_id', $sucursal) ->where('tipo_servicio_id', EMPRESARIAL); if($operador_id){ $servicios_det->where(function($q) use ($operador_id){ $q->where('operador_id',$operador_id) ->orWhere('auxiliar_1',$operador_id) ->orWhere('auxiliar_2',$operador_id); }); } $id = $servicios_det->pluck('id'); $e = ServicioEncuestaEmpresarial::select('preguntas_empresarial.nombre as pregunta', DB::raw('ROUND(AVG(coalesce(respuestas_empresarial.puntuacion,0)), 2) as puntuacion')) ->join('respuestas_empresarial', 'servicios_encuestas_empresarial.respuesta_id', '=', 'respuestas_empresarial.id') ->join('preguntas_empresarial','servicios_encuestas_empresarial.pregunta_id', '=','preguntas_empresarial.id') ->whereIn('servicio_det_id', $id) ->whereNotNull('respuesta_id') ->groupBy('servicios_encuestas_empresarial.pregunta_id', 'preguntas_empresarial.nombre') ->get(); $salida = []; foreach ($e as $l){ $salida[] = [$l->pregunta, (float)$l->puntuacion]; } return $salida; } public function generarExcel(EncuestasGeneralRequest $request) { $year = $request->input('year'); $month = $request->input('mes',Carbon::now()->format('m')); $operador_id = $request->input('operador_id', null); $sucursal = $request->input('sucursal', 1); /*$domestico = PreguntaDomestico::select('nombre') ->where('mostrar_numero', 1) ->get(); $preguntas_domestico = []; foreach ($domestico as $l){ $preguntas_domestico[] = [$l->nombre]; } $empresarial = PreguntaEmpresarial::select('nombre') ->where('mostrar_numero', 1) ->get(); $preguntas_empresarial = []; foreach ($empresarial as $z){ $preguntas_empresarial[] = [$z->nombre]; }*/ // Se va a calcular el promedio para domestico (int)$suma = 0; (int)$contador= 0; (double)$promedio_domestico = 0; $domestico = $this->domesticoExcel($year, $month, $operador_id, $sucursal); $dom = []; foreach ($domestico as $domestic) { $preg = []; foreach($domestic->preguntas as $detalle) { if($detalle->puntuacion){ $preg[] = $detalle->puntuacion; $suma += $detalle->puntuacion; $contador = $contador + 1; } } $det = [$domestic->servicio_id, $domestic->fecha_solicitud, $domestic->cliente, $domestic->operador, $domestic->fecha_nacimiento, $domestic->correo]; $dom[] = array_merge($det, $preg); } if($contador){ (double)$promedio_domestico = $suma / $contador; } //Cálculo del promedio de empresarial $empresarial = $this->empresarialExcel($year, $month, $operador_id, $sucursal); (int)$suma_e = 0; (int)$contador_e= 0; (double)$promedio_empresarial = 0; $empa = []; foreach ($empresarial as $empresa) { $preg = []; foreach($empresa->preguntas as $detalle) { if($detalle->puntuacion){ $preg[] = $detalle->puntuacion; $suma_e += $detalle->puntuacion; $contador_e = $contador_e + 1; } } $det = [$empresa->servicio_id, $empresa->fecha_solicitud, $empresa->cliente, $empresa->operador, $empresa->fecha_nacimiento, $empresa->correo]; $empa[] = array_merge($det, $preg); } if($contador_e){ (double)$promedio_empresarial = $suma_e / $contador_e; } //Información que va necesitar el excel nombre y titulos $total = $domestico->count(); //Transformar el número del mes por la información $mes = ''; $meses = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']; foreach ($meses as $key => $m){ if($key+1 == $month) { $mes = $m; } } if($operador_id){ $query = User::select(DB::raw("CONCAT(users.nombre,' ', users.apellido_paterno, ' ', users.apellido_materno) as operador")) ->where('id', $operador_id) ->first(); $operador_title = $query->operador; } $total_e = $empresarial->count(); $nombre = ($operador_id) ? "Reporte_encuestas_domestico_empresarial".'_'.$mes.'_'.$year.'_detalle'.'_'. str_replace(' ', '_', $operador_title) : "Reporte_encuestas_domestico_empresarial".'_'.$mes.'_'.$year.'_'.$operador_title; $titulo_domestico = ($operador_id) ? "Reporte encuestas doméstico".' '.$operador_title : "Reporte encuestas doméstico general"; $titulo_empresarial = ($operador_id) ? "Reporte encuestas empresarial".' '.$operador_title : "Reporte encuestas empresarial general"; //Generación del excel Excel::create($nombre, function ($excel) use($dom, $total, $titulo_domestico, $promedio_domestico, $promedio_empresarial, $titulo_empresarial, $empa, $total_e, $sucursal, $mes, $year) { // Set del título del documento $excel->setTitle('Reporte de Encuestas'); // Seters de la campañía $excel->setCreator('DRENAX') ->setCompany('DRENAX'); // Creación de la descripción $excel->setDescription('Reporte de Encuesta en servicios'); $excel->sheet('Reporte_encuestas_domestico', function ($sheet) use($dom, $titulo_domestico, $total, $promedio_domestico, $sucursal, $mes, $year){ $sheet->mergeCells('B2:D6'); //Mostrar el logo $objDrawing = new \PHPExcel_Worksheet_Drawing; $objDrawing->setPath(resource_path('assets/images/logos').'/logo_drenax.png'); $objDrawing->setWidth(95); $objDrawing->setHeight(80); $objDrawing->setCoordinates('B2'); $objDrawing->setOffsetX(9); $objDrawing->setOffsetY(9); $objDrawing->setWorksheet($sheet); //Mostrar el título de la hoja de excel $sheet->mergeCells('G2:J6'); $sheet->cell('G2', function($cell) use($titulo_domestico) { $cell->setFontFamily('Aharoni'); $cell->setFontWeight('bold'); $cell->setAlignment('center'); $cell->setValignment('center'); $cell->setFontSize(20); $cell->setValue($titulo_domestico); }); //Información entre el encabezado y la información $sheet->cell('N7', function($cell) { $cell->setFontFamily('Calibri'); $cell->setAlignment('left'); $cell->setFontSize(12); $cell->setValue('Fecha'); }); $sheet->cell('N8', function($cell) use($mes, $year) { $cell->setFontFamily('Calibri'); $cell->setAlignment('left'); $cell->setFontSize(12); $cell->setValue($mes.' '.$year); }); $sheet->cell('O7', function($cell) { $cell->setFontFamily('Calibri'); $cell->setAlignment('left'); $cell->setFontSize(12); $cell->setValue('Promedio General:'); }); $sheet->cell('O8', function($cell) use($promedio_domestico) { $cell->setFontFamily('Calibri'); $cell->setAlignment('left'); $cell->setFontSize(12); $cell->setValue($promedio_domestico.'%'); }); // Mostar valores de consulta $sheet->fromArray($dom, null, 'B9', true); //Formato en columnas de titulo $sheet->cells('B9:O9', function ($cells) { $cells->setBackground('#001870'); $cells->setFontColor('#ffffff'); $cells->setFontSize(13); $cells->setFontFamily('Calibri'); $cells->setAlignment('left'); $cells->setFontWeight('bold'); }); // Asignar el listado $sheet->getStyle('B9:O9' , $sheet->getHighestRow())->getAlignment()->setWrapText(true); //Titulos personalizados $titulos_cell = [ ['cell' => 'B9', 'titulo' => 'Número de servicio'], ['cell' => 'C9', 'titulo' => 'Fecha de solicitud'], ['cell' => 'D9', 'titulo' => 'Cliente'], ['cell' => 'E9', 'titulo' => 'Asesor asignado'], ['cell' => 'F9', 'titulo' => 'Fecha de nacimiento'], ['cell' => 'G9', 'titulo' => 'Correo'], ['cell' => 'H9', 'titulo' => '¿El personal se presentó y mostró la orden de trabajo previo a la realización de su servicio?'], ['cell' => 'I9', 'titulo' => '¿Cómo califica la puntualidad de nuestro personal?'], ['cell' => 'J9', 'titulo' => '¿Cómo califica la imagen de nuestro personal?'], ['cell' => 'K9', 'titulo' => '¿El asesor usó los instrumentos de seguridad e higiene para la correcta ejecución del servicio?'], ['cell' => 'L9', 'titulo' => '¿Cómo califica la atención y asesoría brindada por los asesores?'], ['cell' => 'M9', 'titulo' => '¿El servicio fue efectivo quedando conforme con lo que contrató?'], ['cell' => 'N9', 'titulo' => '¿Cómo califica la atención y asesoría telefonica?'], ['cell' => 'O9', 'titulo' => 'De acuerdo al servicio recibido, ¿usted nos recomendaría?'] ]; // Obtener los títulos de la tabla foreach ($titulos_cell as $t){ $sheet->cell($t['cell'], function($cell) use($t) { $cell->setValue($t['titulo']); }); } //Darle un tamaño a las celdas $columns_set = [ 'B9', 'C9', 'D9', 'K9', 'L9' ]; foreach ($columns_set as $c){ $set_column = [ $c => [ 'width' => ($c == 'D9' || $c == 'G9')? 25: 16, 'height' => 40 ] ]; $sheet->setSize($set_column); } $question_set = [ 'H9', 'I9', 'J9', 'K9', 'L9', 'M9', 'N9', 'O9' ]; foreach ($question_set as $q){ $question = [ $q => [ 'width' => 35, 'height' => 50 ] ]; $sheet->setSize($question); } //Tamaño automático en columnas indicadas $columns_auto= [ 'E','F','G' ]; foreach ($columns_auto as $c){ $sheet->getColumnDimension($c)->setAutoSize(true); } $sheet->setWidth(array( 'A' => 3, )); //Borde $columns_border= [ 'B','C','D','E','F','G','H','I','J','K','L', 'M', 'N', 'O' ]; for ($i=0; $i<= $total; $i++){ $row = 9 + $i; foreach ($columns_border as $cb){ $border = "$cb$row:$cb$row"; $sheet->cells($border, function ($cells) { $cells->setBorder('thin', 'thin', 'thin', 'thin'); }); if($row != 9 && ($cb == 'C' || $cb == 'F' || $cb == 'L')){ $sheet->cells("$cb$row", function ($cells) { $cells->setAlignment('right'); }); } } } }); $excel->sheet('Reporte_encuestas_empresarial', function ($sheet) use($promedio_domestico, $sucursal, $mes, $year, $titulo_empresarial, $promedio_empresarial, $empa, $total_e){ $sheet->mergeCells('B2:D6'); //Mostrar el logo $objDrawing = new \PHPExcel_Worksheet_Drawing; $objDrawing->setPath(resource_path('assets/images/logos').'/logo_drenax.png'); $objDrawing->setWidth(95); $objDrawing->setHeight(80); $objDrawing->setCoordinates('B2'); $objDrawing->setOffsetX(9); $objDrawing->setOffsetY(9); $objDrawing->setWorksheet($sheet); //Mostrar el título de la hoja de excel $sheet->mergeCells('G2:J6'); $sheet->cell('G2', function($cell) use($titulo_empresarial) { $cell->setFontFamily('Aharoni'); $cell->setFontWeight('bold'); $cell->setAlignment('center'); $cell->setValignment('center'); $cell->setFontSize(20); $cell->setValue($titulo_empresarial); }); //Información entre el encabezado y la información $sheet->cell('P7', function($cell) { $cell->setFontFamily('Calibri'); $cell->setAlignment('left'); $cell->setFontSize(12); $cell->setValue('Fecha'); }); $sheet->cell('P8', function($cell) use($mes, $year) { $cell->setFontFamily('Calibri'); $cell->setAlignment('left'); $cell->setFontSize(12); $cell->setValue($mes.' '.$year); }); $sheet->cell('Q7', function($cell) { $cell->setFontFamily('Calibri'); $cell->setAlignment('left'); $cell->setFontSize(12); $cell->setValue('Promedio General:'); }); $sheet->cell('Q8', function($cell) use($promedio_empresarial) { $cell->setFontFamily('Calibri'); $cell->setAlignment('left'); $cell->setFontSize(12); $cell->setValue($promedio_empresarial.'%'); }); // Mostar valores de consulta $sheet->fromArray($empa, null, 'B9', true); //Formato en columnas de titulo $sheet->cells('B9:Q9', function ($cells) { $cells->setBackground('#001870'); $cells->setFontColor('#ffffff'); $cells->setFontSize(13); $cells->setFontFamily('Calibri'); $cells->setAlignment('left'); $cells->setFontWeight('bold'); }); $sheet->getStyle('B9:Q9' , $sheet->getHighestRow())->getAlignment()->setWrapText(true); //Titulos personalizados $titulos_cell = [ ['cell' => 'B9', 'titulo' => 'Número de servicio'], ['cell' => 'C9', 'titulo' => 'Fecha de solicitud'], ['cell' => 'D9', 'titulo' => 'Cliente'], ['cell' => 'E9', 'titulo' => 'Asesor asignado'], ['cell' => 'F9', 'titulo' => 'Fecha de nacimiento'], ['cell' => 'G9', 'titulo' => 'Correo'], ['cell' => 'H9', 'titulo' => '¿Su servicio fue programado en tiempo y forma?'], ['cell' => 'I9', 'titulo' => '¿El asesor de operaciones realiza recibo de servicio, y es llenado correctamente hora de inicio y hora final?'], ['cell' => 'J9', 'titulo' => '¿Cómo califica la imagen del personal?'], ['cell' => 'K9', 'titulo' => '¿El asesor usó los instrumentos de seguridad e higiene para la correcta ejecución del servicio?'], ['cell' => 'L9', 'titulo' => '¿Cómo califica la atención y asesoría brindada por los asesores de operaciones?'], ['cell' => 'M9', 'titulo' => '¿Cómo califica la calidad del servicio contratado?'], ['cell' => 'N9', 'titulo' => '¿Cómo califica la atención y asesoría telefonica?'], ['cell' => 'O9', 'titulo' => '¿Recibió su factura del mes en tiempo y forma?'], ['cell' => 'P9', 'titulo' => '¿Cómo califica nuestra área de cobranza?'], ['cell' => 'Q9', 'titulo' => '¿Cómo califica en general a la empresa DRENAX?'] ]; // Obtener los títulos de la tabla foreach ($titulos_cell as $t){ $sheet->cell($t['cell'], function($cell) use($t) { $cell->setValue($t['titulo']); }); } //Darle un tamaño a las celdas $columns_set = [ 'B9', 'C9', 'D9', 'K9', 'L9' ]; foreach ($columns_set as $c){ $set_column = [ $c => [ 'width' => ($c == 'D9' || $c == 'G9')? 25: 16, 'height' => 40 ] ]; $sheet->setSize($set_column); } $question_set = [ 'H9', 'I9', 'J9', 'K9', 'L9', 'M9', 'N9', 'O9', 'P9', 'Q9' ]; foreach ($question_set as $q){ $question = [ $q => [ 'width' => 35, 'height' => 50 ] ]; $sheet->setSize($question); } //Tamaño automático en columnas indicadas $columns_auto= [ 'E','F','G' ]; foreach ($columns_auto as $c){ $sheet->getColumnDimension($c)->setAutoSize(true); } $sheet->setWidth(array( 'A' => 3, )); //Borde $columns_border= [ 'B','C','D','E','F','G','H','I','J','K','L', 'M', 'N', 'O', 'P', 'Q' ]; for ($i=0; $i<= $total_e; $i++){ $row = 9 + $i; foreach ($columns_border as $cb){ $border = "$cb$row:$cb$row"; $sheet->cells($border, function ($cells) { $cells->setBorder('thin', 'thin', 'thin', 'thin'); }); if($row != 9 && ($cb == 'C' || $cb == 'F' || $cb == 'L')){ $sheet->cells("$cb$row", function ($cells) { $cells->setAlignment('right'); }); } } } }); // Hoja de excel por defecto $excel->setActiveSheetIndex(0); })->store('xls', storage_path('app') . '/public/reportes/servicios_encuestas/'); return response()->success(['nombre_archivo' => $nombre.'.xls?micro='.$this->getMicroSeconds()]); } public function domesticoExcel($year, $month, $operador_id, $sucursal){ // Campos que se necesitan para mostrar en el reporte de excel $campos = [ 'servicios_det.id as servicio_id', DB::raw("DATE(servicios_det.fecha_solicitud) as 'fecha_solicitud'"), 'clientes.denominacion as cliente', DB::raw("CONCAT(users.nombre,' ', users.apellido_paterno, ' ', users.apellido_materno) as operador")]; //Consulta pra trae y filtrar la información para mostrar $servicios_det = ServicioDet::select($campos) ->join('users', 'servicios_det.operador_id', '=', 'users.id') ->join('servicios_enc', 'servicio_enc_id', '=', 'servicios_enc.id') ->join('clientes', 'servicios_enc.cliente_id', '=', 'clientes.id') ->whereMonth('servicios_det.fecha_solicitud', $month) ->whereYear('servicios_det.fecha_solicitud', $year) ->where('requiere_encuesta', 1) ->where('tipo_servicio_id', DOMESTICO) ->where('users.sucursal_id', $sucursal) ->orderBy('users.tipo_empleado_id', 'asc') ->orderBy('servicios_det.id', 'asc') ->orderBy('operador', 'asc'); // Validamos si está filtrado por asesor o bien auxiliar de operación if($operador_id){ $servicios_det->where(function($q) use ($operador_id){ $q->where('operador_id',$operador_id) ->orWhere('auxiliar_1',$operador_id) ->orWhere('auxiliar_2',$operador_id); }); } // Obtenemos los datos antes que se va a realizar la próxima consulta $servicios = $servicios_det->get(); foreach($servicios as $servicio){ // Esta consulta es para traer la cantidad de preguntas que vamos a mostrar en el excel $servicio->preguntas = ServicioEncuestaDomestico::select('respuestas_domestico.puntuacion as puntuacion') ->join('respuestas_domestico', 'respuesta_id','=','respuestas_domestico.id') ->where('servicio_det_id', $servicio->servicio_id) ->get(); // obtenemos la fecha de nacimiento del cliente en caso de haberla mandado $fecha = ServicioEncuestaDomestico::select('respuesta') ->where('servicio_det_id', $servicio->servicio_id) ->where('pregunta_id', 11) ->first(); $servicio->fecha_nacimiento = ($fecha)? $fecha->respuesta : null; //Obtenemos el correo del cliente en caso dde haberla aceptado $correo = ServicioEncuestaDomestico::select('respuesta') ->where('servicio_det_id', $servicio->servicio_id) ->where('pregunta_id', 10) ->first(); $servicio->correo = ($correo)? $correo->respuesta : null; } return $servicios; } // Esta funcion es para traer los datos que necesitamos para la hoja de servicios empresariales public function empresarialExcel($year, $month, $operador_id, $sucursal){ $campos = [ 'servicios_det.id as servicio_id', DB::raw("DATE(servicios_det.fecha_solicitud) as 'fecha_solicitud'"), 'clientes.denominacion as cliente', DB::raw("CONCAT(users.nombre,' ', users.apellido_paterno, ' ', users.apellido_materno) as operador")]; $servicios_det = ServicioDet::select($campos) ->join('users', 'servicios_det.operador_id', '=', 'users.id') ->join('servicios_enc', 'servicio_enc_id', '=', 'servicios_enc.id') ->join('clientes', 'servicios_enc.cliente_id', '=', 'clientes.id') ->whereMonth('servicios_det.fecha_solicitud', $month) ->whereYear('servicios_det.fecha_solicitud', $year) ->where('requiere_encuesta', 1) ->where('tipo_servicio_id', EMPRESARIAL) ->where('users.sucursal_id', $sucursal) ->orderBy('users.tipo_empleado_id', 'asc') ->orderBy('servicios_det.id', 'asc') ->orderBy('operador', 'asc'); if($operador_id){ $servicios_det->where(function($q) use ($operador_id){ $q->where('operador_id',$operador_id) ->orWhere('auxiliar_1',$operador_id) ->orWhere('auxiliar_2',$operador_id); }); } $servicios_emp = $servicios_det->get(); foreach($servicios_emp as $servicio_emp){ $servicio_emp->preguntas = ServicioEncuestaEmpresarial::select('respuestas_empresarial.puntuacion as puntuacion') ->join('respuestas_empresarial', 'respuesta_id','=','respuestas_empresarial.id') ->where('servicio_det_id', $servicio_emp->servicio_id) ->get(); $fecha = ServicioEncuestaEmpresarial::select('respuesta') ->where('servicio_det_id', $servicio_emp->servicio_id) ->where('pregunta_id', 11) ->first(); $servicio_emp->fecha_nacimiento = ($fecha)? $fecha->respuesta : null; $correo = ServicioEncuestaEmpresarial::select('respuesta') ->where('servicio_det_id', $servicio_emp->servicio_id) ->where('pregunta_id', 10) ->first(); $servicio_emp->correo = ($correo)? $correo->respuesta : null; } return $servicios_emp; } }