Proyectos de Subversion LeadersLinked - Backend

Rev

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

<?php

declare(strict_types=1);

namespace LeadersLinked\Controller;

use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
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;

class SurveyReportController extends AbstractActionController {

    /**
     *
     * @var AdapterInterface
     */
    private $adapter;

    /**
     *
     * @var AbstractAdapter
     */
    private $cache;

    /**
     *
     * @var  LoggerInterface
     */
    private $logger;

    /**
     *
     * @var array
     */
    private $config;

    /**
     *
     * @param AdapterInterface $adapter
     * @param AbstractAdapter $cache
     * @param LoggerInterface $logger
     * @param array $config
     */
    public function __construct($adapter, $cache, $logger, $config) {
        $this->adapter = $adapter;
        $this->cache = $cache;
        $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']) ? '' : filter_var($search['value'], FILTER_SANITIZE_STRING);

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

                $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_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);

        $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()) {
            $hydrator = new ObjectPropertyHydrator();

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

            if ($surveyForm) {

                return $this->renderPDF($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($surveyForm, $surveyTests, $survey) {

        $target_path = $this->config['leaderslinked.fullpath.company'] . DIRECTORY_SEPARATOR . $survey->uuid;
        
        
        if(file_exists($target_path)) {
            Functions::deleteFiles($target_path);
        } else {
            @mkdir($target_path, 0755, true);
        }
        
        // Set Data
        $headerFormName = utf8_decode($surveyForm->name);
        $headerSurveyName = utf8_decode('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;

                }
            }
        }

        //Generate New PDF
        $pdf = new SurveyReport();

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

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

        for ($i = 0; $i < count($sections); $i++) {
            if ($i != 0 && $i % 2 == 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) {
                            $labels []= strip_tags($option['text']) . "\n(%.1f%%)";
                            
                            $values []= $averages[$question['slug_question']][$option['slug_option']];
                        }
                        
                        $filename = $target_path . DIRECTORY_SEPARATOR .  $question['slug_question'] . '.png';
                        $pdf->Cell(0,10,strip_tags($question['text']),0,1);
                        $pdf->pieChart($labels, $values, '', $filename);
                        $pdf->SetFont('Arial', '', 12);
                        $pdf->Image($filename, 45, $pdf->getY(), 120);
                        $pdf->setY($pdf->getY() + 90);

                        break;
                        
                    case 'multiple':
                        $labels = [];
                        $values = [];
                        
                        foreach($question['options'] as $option) {
                            $labels []= strip_tags($option['text']);
                            
                            $values []= $averages[$question['slug_question']][$option['slug_option']];
                        }
                        
                        $filename = $target_path . DIRECTORY_SEPARATOR .  $question['slug_question'] . '.png';
                        $pdf->Cell(0,10,strip_tags($question['text']),0,1);
                        $pdf->barChart($labels, $values, '', $filename);
                        $pdf->SetFont('Arial', '', 12);
                        $pdf->Image($filename, 12, $pdf->getY());
                        $pdf->setY($pdf->getY() + (count($values) * 13) + 10);

                        break;
                }
            }
        }

        return $pdf->Output();
    }

}