Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 16766 | Autoría | Ultima modificación | Ver Log |

<?php

declare(strict_types=1);

namespace LeadersLinked\Controller;

use Laminas\Db\Adapter\AdapterInterface;

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Log\LoggerInterface;
use Laminas\View\Model\ViewModel;
use Laminas\View\Model\JsonModel;
use LeadersLinked\Mapper\QueryMapper;
use Laminas\Db\Sql\Select;
use LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\SurveyTestMapper;
use LeadersLinked\Mapper\SurveyMapper;
use LeadersLinked\Mapper\SurveyFormMapper;
use LeadersLinked\Form\SurveyTestForm;
use LeadersLinked\Model\SurveyTest;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Library\SurveyReport;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

class SurveyReportController extends AbstractActionController {

    /**
     *
     * @var AdapterInterface
     */
    private $adapter;
    
    /**
     *
     * @var  LoggerInterface
     */
    private $logger;
    
    /**
     *
     * @var array
     */
    private $config;
    
    /**
     *
     * @param AdapterInterface $adapter
     * @param LoggerInterface $logger
     * @param array $config
     */
    public function __construct($adapter, $logger, $config)
    {
        $this->adapter = $adapter;
        $this->logger = $logger;
        $this->config = $config;
    }

    public function indexAction() {

        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();

        try{
        $request = $this->getRequest();
        if ($request->isGet()) {

            $headers = $request->getHeaders();

            $isJson = false;
            if ($headers->has('Accept')) {
                $accept = $headers->get('Accept');

                $prioritized = $accept->getPrioritized();

                foreach ($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());

                    if (!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                }
            }

            if ($isJson) {

                $search = $this->params()->fromQuery('search', []);
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);

                $start = intval($this->params()->fromQuery('start', 0), 10);
                $records_x_page = intval($this->params()->fromQuery('length', 10), 10);
                $page =  intval($start / $records_x_page);
                $page++;
                
                $order = $this->params()->fromQuery('order', []);
                $order_field = empty($order[0]['column']) ? 99 : intval($order[0]['column'], 10);
                $order_direction = empty($order[0]['dir']) ? 'ASC' : Functions::sanitizeFilterString(filter_var($order[0]['dir']));

                $fields = ['name'];
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';

                if (!in_array($order_direction, ['ASC', 'DESC'])) {
                    $order_direction = 'ASC';
                }

                $surveyMapper = SurveyMapper::getInstance($this->adapter);
                $paginator = $surveyMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);
                
                $surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
                
                $items = [];
                $records = $paginator->getCurrentItems();
               
                foreach ($records as $record) {
                    $surveyForm = $surveyFormMapper->fetchOne($record->form_id);
                    $params = [
                        
                        'id' => $record->uuid,
                    ];
                    $item = [
                        'id' => $record->id,
                        'name' => $record->name,
                        'form' => $surveyForm->name,
                        'status' => $record->status,
                        'actions' => [
                            'link_report_all' => $this->url()->fromRoute('survey/report/all', ['survey_id' => $record->uuid]),
                            'link_report_excel' => $this->url()->fromRoute('survey/report/excel', ['survey_id' => $record->uuid]),
                            'link_overview' => $this->url()->fromRoute('survey/report/overview', ['survey_id' => $record->uuid])
                        ]
                    ];

                    array_push($items, $item);
                }

                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'items' => $items,
                        'total' => $paginator->getTotalItemCount(),
                    ]
                ]);
            } else {
                $surveyMapper = SurveyMapper::getInstance($this->adapter);
                $survies = $surveyMapper->fetchAllByCompanyId($currentCompany->id);
                
                $form = new SurveyTestForm($this->adapter, $currentCompany->id);

                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/survey-report/index.phtml');
                $viewModel->setVariables([
                    'form'      => $form,
                    'survies' => $survies
                ]);
                return $viewModel;
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
            
        } 
        } catch (\Throwable $e) {
            $e->getMessage();
            return new JsonModel([
                'success' => false,
                'data' => $e
            ]);
        }
        
    }

    public function overviewAction(){
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();
        $uuid = $this->params()->fromRoute('survey_id');

        if (!$uuid) {
            $data = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($data);
        }

        $surveyMapper = SurveyMapper::getInstance($this->adapter);
        $survey = $surveyMapper->fetchOneByUuid($uuid);

        $surveyMapper = SurveyMapper::getInstance($this->adapter);
        $survey = $surveyMapper->fetchOneByUuid($uuid);
       
        $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
        $surveyTests = $surveyTestMapper->fetchAllBySurveyId($survey->id);

        if (!$surveyTests) {
            $data = [
                'success' => false,
                'data' => 'No hay respuestas en esta encuesta'
            ];

            return new JsonModel($data);
        }

        $surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
        $surveyForm = $surveyFormMapper->fetchOne($survey->form_id);

        $sections = json_decode($surveyForm->content, true);

        $allTests = array_map(
            function($response) {
                return json_decode($response->content, true);
            },
            $surveyTests,
        );

        $averages = [];

        foreach($sections as $section) {
            foreach($section['questions'] as $question) {
                switch ($question['type']) {
                    case 'multiple':
                        $totals = [];

                        foreach($question['options'] as $option) {
                            $totals[$option['slug_option']] = 0;
                        }

                        foreach($question['options'] as $option) {
                            $totals[$option['slug_option']] = count(array_filter(
                                $allTests,
                                function ($test) use($option, $question) {
                                    return in_array($option['slug_option'], $test[$question['slug_question']]);
                                }
                            ));
                        }

                        $averages[$question['slug_question']] = $totals;

                        break;
                   
                    case 'simple':
                        $totals = [];

                        foreach($question['options'] as $option) {
                            $totals[$option['slug_option']] = 0;
                        }

                        foreach ($allTests as $test) {
                            $totals[$test[$question['slug_question']]]++;
                        }

                        foreach($totals as $slug => $amount) {
                            $totals[$slug] = ($amount / count($allTests)) * 100;
                        }

                        $averages[$question['slug_question']] = $totals;
                    break;

                }
            }
        }

        $this->layout()->setTemplate('layout/layout-backend.phtml');
        $viewModel = new ViewModel();
        $viewModel->setTemplate('leaders-linked/survey-report/overview.phtml');
        $viewModel->setVariables([  
            'sections' => $sections,
            'averages' => $averages,
        ]); 
        return $viewModel ;

    }

    public function allAction() {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();
        $uuid = $this->params()->fromRoute('survey_id');
        


        if (!$uuid) {
            $data = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($data);
        }

        $surveyMapper = SurveyMapper::getInstance($this->adapter);
        $survey = $surveyMapper->fetchOneByUuid($uuid);
       
        $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
        $surveyTests = $surveyTestMapper->fetchAllBySurveyId($survey->id);
       
        if (!$surveyTests) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];

            return new JsonModel($data);
        }


        if ($request->isGet()) {
     
            $surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
            $surveyForm = $surveyFormMapper->fetchOne($survey->form_id);

            if ($surveyForm) {

                return $this->renderPDF($currentCompany, $surveyForm, $surveyTests, $survey);
            } else {

                $data = [
                    'success' => false,
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
                ];

                return new JsonModel($data);
            }
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

    
    public function renderPDF($company, $surveyForm, $surveyTests, $survey) {


      
        
        
        $target_path = $this->config['leaderslinked.fullpath.company'] . DIRECTORY_SEPARATOR . $company->uuid;
        
        $header = $company->header ? $target_path . DIRECTORY_SEPARATOR . $company->header : '';
        if(empty($header) || !file_exists($header)) {
            $header = $this->config['leaderslinked.images_default.company_pdf_header'];
        }
        
        $footer = $company->footer ? $target_path . DIRECTORY_SEPARATOR . $company->footer : '';
        if(empty($footer) || !file_exists($footer)) {
            $footer = $this->config['leaderslinked.images_default.company_pdf_footer'];
        }
        
        
        //Generate New PDF
        $pdf = new SurveyReport();
        
        
        $pdf->header = $header;
        $pdf->footer = $footer;
        
        
        
        $target_path = $this->config[ 'leaderslinked.fullpath.survey'] . DIRECTORY_SEPARATOR . $survey->uuid;
        if(!file_exists($target_path)) {
            mkdir($target_path, 0755, true);
        } else {
            Functions::deleteFiles($target_path);
        }
        // Set Data
        $headerFormName = $this->cleanStringToPdf($surveyForm->name);
        $headerSurveyName = $this->cleanStringToPdf('Informe de Encuesta: ' . trim($survey->name) . ' al ' . date("m-d-Y H:i:s", strtotime($survey->added_on)));
        $sections = json_decode($surveyForm->content, true);

        $allTests = array_map(
            function($response) {
                return json_decode($response->content, true);
            },
            $surveyTests,
        );
        
 


        $averages = [];

        foreach($sections as $section) {
            foreach($section['questions'] as $question) {
                switch ($question['type']) {
                    case 'multiple':
                        $totals = [];

                        foreach($question['options'] as $option) {
                            $totals[$option['slug_option']] = 0;
                        }

                        foreach($question['options'] as $option) {
                            $totals[$option['slug_option']] = count(array_filter(
                                $allTests,
                                function ($test) use($option, $question) {
                                    return in_array($option['slug_option'], $test[$question['slug_question']]);
                                }
                            ));
                        }

                        $averages[$question['slug_question']] = $totals;

                        break;
                   
                    case 'simple':
                        $totals = [];

                        foreach($question['options'] as $option) {
                            $totals[$option['slug_option']] = 0;
                        }

                        foreach ($allTests as $test) {
                            $totals[$test[$question['slug_question']]]++;
                        }

                        foreach($totals as $slug => $amount) {
                            $totals[$slug] = ($amount / count($allTests)) * 100;
                        }

                        $averages[$question['slug_question']] = $totals;
                    break;

                }
            }
        }


        $pdf->AliasNbPages();
        $pdf->AddPage();

        // Set header secundary
        $pdf->customHeader($headerFormName, $headerSurveyName);

        $countSection = 0;

        for ($i = 0, $max = count($sections);  $i < $max ; $i++) {
            $headerUserName = '';
            
            if ($countSection > 1) {
                $countSection = 0;
                $pdf->AddPage();
                $pdf->customHeader($headerFormName, $headerUserName);
            }
            $section = $sections[$i];
        
            foreach ($section['questions'] as $question) {
                    
                    switch ($question['type']) {
                        case 'simple':
                            $labels = [];
                            $values = [];

                            foreach($question['options'] as $option) {
                                $label = $this->cleanStringToPdf($option['text']) . "\n(%.1f%%)";
                                $value = $averages[$question['slug_question']][$option['slug_option']];
                                if(empty($value)) {
                                    continue;
                                }
                                
                                array_push($labels, $label);
                                
                                array_push($values, $value);
                            }

                            $filename = $target_path . DIRECTORY_SEPARATOR .  $question['slug_question'] . '.png';
                            $pdf->Cell(0,10, $this->cleanStringToPdf($question['text'], false),0,1);
                            $pdf->pieChart($labels, $values, '', $filename);
                            $pdf->SetFont('Arial', '', 12);
                            $pdf->Image($filename, 10, $pdf->getY(), 190);
                            $pdf->setY($pdf->getY() + 90);
                           

                            break;

                        case 'multiple':
                            $labels = [];
                            $values = [];

                            foreach($question['options'] as $option) 
                            {
                                $label = $this->cleanStringToPdf($option['text']) . "\n(%.1f%%)";
                                $value = $averages[$question['slug_question']][$option['slug_option']];
                                if(empty($value)) {
                                    continue;
                                }
                                
                                array_push($labels, $label);

                                array_push($values, $value);
                            }

                            $filename = $target_path . DIRECTORY_SEPARATOR .  $question['slug_question'] . '.png';
                            $pdf->Cell(0,10,$this->cleanStringToPdf($question['text'], false),0,1);
                            $pdf->pieChart($labels, $values, '', $filename);
                            $pdf->SetFont('Arial', '', 12);
                            $pdf->Image($filename, 10, $pdf->getY(), 190);
                            $pdf->setY($pdf->getY() + (count($values) * 13) + 10);

                            break;
                    }
                $countSection++;   
            }

            
        }

        return $pdf->Output();
    }

    public function excelAction() {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();
        $uuid = $this->params()->fromRoute('survey_id');
        


        if (!$uuid) {
            $data = [
                'success' => false,
                'data' => 'ERROR_INVALID_PARAMETER'
            ];

            return new JsonModel($data);
        }

        $surveyMapper = SurveyMapper::getInstance($this->adapter);
        $survey = $surveyMapper->fetchOneByUuid($uuid);
       
        $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
        $surveyTests = $surveyTestMapper->fetchAllBySurveyId($survey->id);
       
        if (!$surveyTests) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];

            return new JsonModel($data);
        }


        if ($request->isGet()) {
         
            $surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
            $surveyForm = $surveyFormMapper->fetchOne($survey->form_id);

            if ($surveyForm) {

                $filename = $this->excelRender($surveyForm, $surveyTests, $survey);
                $content = file_get_contents($filename);
                
                
                $response = $this->getResponse();
                $headers = $response->getHeaders();
                $headers->clearHeaders();

                
                $headers->addHeaderLine('Content-Description: File Transfer');
                $headers->addHeaderLine('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                $headers->addHeaderLine('Content-Disposition: attachment; filename='.$survey->uuid.'.xls');
                $headers->addHeaderLine('Content-Transfer-Encoding: binary');
                $headers->addHeaderLine('Expires: 0');
                $headers->addHeaderLine('Cache-Control: must-revalidate');
                $headers->addHeaderLine('Pragma: public');
                
               
                $response->setStatusCode(200);
                $response->setContent($content);
                
                
                return $response;
            } else {

                $data = [
                    'success' => false,
                    'data' => 'ERROR_SURVEY_NOT_FOUND'
                ];

                return new JsonModel($data);
            }
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }


    public function excelRender($surveyForm, $surveyTests, $survey)
    {
        $sections = json_decode($surveyForm->content, true);

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $allTests = array_map(
            function($response) {
                return json_decode($response->content, true);
            },
            $surveyTests,
        );

        $averages = [];

        foreach($sections as $section) {
            foreach($section['questions'] as $question) {
                switch ($question['type']) {
                    case 'multiple':
                        $totals = [];

                        foreach($question['options'] as $option) {
                            $totals[$option['slug_option']] = 0;
                        }

                        foreach($question['options'] as $option) {
                            $totals[$option['slug_option']] = count(array_filter(
                                $allTests,
                                function ($test) use($option, $question) {
                                    return in_array($option['slug_option'], $test[$question['slug_question']]);
                                }
                            ));
                        }

                        $averages[$question['slug_question']] = $totals;

                        break;
                   
                    case 'simple':
                        $totals = [];

                        foreach($question['options'] as $option) {
                            $totals[$option['slug_option']] = 0;
                        }

                        foreach ($allTests as $test) {
                            $totals[$test[$question['slug_question']]]++;
                        }

                        foreach($totals as $slug => $amount) {
                            $totals[$slug] = ($amount / count($allTests)) * 100;
                        }

                        $averages[$question['slug_question']] = $totals;
                    break;

                }
            }
        }

        $row = 1;

        for ($i = 0; $i < count($sections); $i++) {
            $section = $sections[$i];
        
           for($j = 0; $j < count($section['questions']); $j++) {
                $question = $section['questions'][$j];

                if (!in_array($question['type'], ['simple', 'multiple'])){
                    continue;
                }
                
                $row++;
                $sheet->setCellValue('A' . $row , $this->cleanStringToExcel($question['text']));

                switch ($question['type']) {
                    case 'simple':
                        for($k = 0; $k < count($question['options']); $k++) {
                            $row++;
                            
                            $option = $question['options'][$k];

                            
                            $sheet->setCellValue('B' . $row , $this->cleanStringToExcel($option['text']));
                            $sheet->setCellValue('C' . $row , round($averages[$question['slug_question']][$option['slug_option']], 2) . '%');
                            
                        }

                        break;

                    case 'multiple':
                        for($k = 0; $k < count($question['options']); $k++) {
                            
                            $row++;
                            $option = $question['options'][$k];
                            $sheet->setCellValue('B' . $row , $this->cleanStringToExcel($option['text']));
                            $sheet->setCellValue('C' . $row , round($averages[$question['slug_question']][$option['slug_option']]));
                            
                        }

                        break;
                }
            }

            
        }

       
        
        $target_path = $this->config[ 'leaderslinked.fullpath.survey'] . DIRECTORY_SEPARATOR . $survey->uuid;
        if(!file_exists($target_path)) {
            mkdir($target_path, 0755, true);    
        }
        
        $filename = $target_path  . DIRECTORY_SEPARATOR . $survey->uuid . '.xls'; 
        
        $writer = new Xlsx($spreadsheet);
        $writer->save($filename);
        
        return $filename;
        
    }
    

    
    private function cleanStringToPdf($s, $mbConvert = true)
    {
        
        $s = html_entity_decode($s);
       
        
        if($mbConvert) {
            $detect = mb_detect_encoding($s);
            if(strtoupper($detect) != 'UTF8') {
                
                $s = mb_convert_encoding($s, 'UTF8', $detect);
                
            }
        } else {
            $s = Functions::utf8_decode($s);
        }
        
        
        return strip_tags($s);
    }
    
    private function cleanStringToExcel($s)
    {
        
        $s = html_entity_decode($s);
        return strip_tags($s);
    }
}