Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 630 | Rev 6849 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php

/**
 * 
 * Controlador: Autoevaluación 
 * 
 */
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\Model\Notification;
use LeadersLinked\Mapper\SelfEvaluationTestMapper;
use LeadersLinked\Mapper\NotificationMapper;
use LeadersLinked\Mapper\QueryMapper;
use LeadersLinked\Model\SelfEvaluationForm;
use LeadersLinked\Mapper\SelfEvaluationFormMapper;
use LeadersLinked\Model\SelfEvaluationTest;
use Laminas\Db\Sql\Select;
use LeadersLinked\Library\SelfEvaluationPDF;
use LeadersLinked\Mapper\SelfEvaluationFormUserMapper;
use LeadersLinked\Form\SelfEvaluation\SelfEvaluationTestForm;
use LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\UserMapper;

class SelfEvaluationController 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;
    }

    /**
     * 
     * Generación del listado de evaluaciones
     * {@inheritDoc}
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction() {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $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 = trim(filter_var($this->params()->fromQuery('search', ''), FILTER_SANITIZE_STRING));


                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowTakeATest = $acl->isAllowed($currentUser->usertype_id, 'profile/self-evaluation/take-a-test');
                $allowReport = $acl->isAllowed($currentUser->usertype_id, 'profile/self-evaluation/report');




                $queryMapper = QueryMapper::getInstance($this->adapter);

                $select = $queryMapper->getSql()->select();
                $select->columns(['uuid', 'name', 'description', 'text', 'language']);
                $select->from(['f' => SelfEvaluationFormMapper::_TABLE]);
                $select->join(['fu' => SelfEvaluationFormUserMapper::_TABLE], 'f.id = fu.form_id', []);
                $select->join(['t' => SelfEvaluationTestMapper::_TABLE], 'fu.form_id = t.form_id AND fu.user_id = t.user_id', ['status'], Select::JOIN_LEFT_OUTER);
                $select->where->equalTo('f.status', SelfEvaluationForm::STATUS_ACTIVE);
                $select->where->equalTo('fu.user_id', $currentUser->id);


                if ($search) {
                    $select->where->NEST->like('name', '%' . $search . '%');
                }
                $select->order('name ASC, language ASC');

                $records = $queryMapper->fetchAll($select);
                $items = [];
                foreach ($records as $record) {
                    switch ($record['language']) {
                        case SelfEvaluationForm::LANGUAGE_ENGLISH :
                            $language = 'LABEL_ENGLISH';
                            break;

                        case SelfEvaluationForm::LANGUAGE_SPANISH :
                            $language = 'LABEL_SPANISH';
                            break;

                        default :
                            $language = '';
                            break;
                    }

                    switch ($record['status']) {

                        case SelfEvaluationTest::STATUS_DRAFT :
                            $status = 'LABEL_DRAFT';
                            break;

                        case SelfEvaluationTest::STATUS_COMPLETED :
                            $status = 'LABEL_COMPLETED';
                            break;

                        case SelfEvaluationTest::STATUS_PENDING :
                            $status = 'LABEL_PENDING';
                            break;

                        case SelfEvaluationTest::STATUS_REVIEW :
                            $status = 'LABEL_REVIEW';
                            break;


                        default :
                            $status = 'LABEL_AVAILABLE';
                            break;
                    }


                    $item = [
                        'name' => $record['name'],
                        'description' => $record['description'],
                        'text' => $record['text'],
                        'language' => $language,
                        'status' => $status,
                        'link_take_a_test' => $allowTakeATest && ( empty($record['status']) || $record['status'] == SelfEvaluationTest::STATUS_DRAFT) ? $this->url()->fromRoute('profile/self-evaluation/take-a-test', ['id' => $record['uuid']]) : '',
                        'link_report' => $allowReport && $record['status'] == SelfEvaluationTest::STATUS_COMPLETED ? $this->url()->fromRoute('profile/self-evaluation/report', ['id' => $record['uuid']]) : '',
                    ];



                    array_push($items, $item);
                }




                $response = [
                    'success' => true,
                    'data' => $items
                ];

                return new JsonModel($response);
            } else {

                $notificationMapper = NotificationMapper::getInstance($this->adapter);
                $notificationMapper->markAllNotificationsAsReadByTypeAndUserId(Notification::TYPE_ACCEPT_MY_REQUEST_CONNECTION, $currentUser->id);

                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/self-evaluation/index.phtml');
                return $viewModel;
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }

    public function takeaTestAction() {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $uuid = $this->params()->fromRoute('id');

        $companySelfEvaluationFormMapper = SelfEvaluationFormMapper::getInstance($this->adapter);
        $companySelfEvaluationForm = $companySelfEvaluationFormMapper->fetchOneByUuid($uuid);

        if (!$companySelfEvaluationForm) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_NOT_FOUND'
            ]);
        }

        if ($companySelfEvaluationForm->status == SelfEvaluationForm::STATUS_INACTIVE) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_IS_INACTIVE'
            ]);
        }


        $companySelfEvaluationFormUserMapper = SelfEvaluationFormUserMapper::getInstance($this->adapter);
        $companySelfEvaluationFormUser = $companySelfEvaluationFormUserMapper->fetchOneByFormIdAndUserId($companySelfEvaluationForm->id, $currentUser->id);
        if (!$companySelfEvaluationFormUser) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_YOU_CAN_NOT_TAKE'
            ]);
        }


        $companySelfEvaluationTestMapper = SelfEvaluationTestMapper::getInstance($this->adapter);
        $companySelfEvaluationTest = $companySelfEvaluationTestMapper->fetchOneBy($companySelfEvaluationForm->id, $currentUser->id);

        if ($companySelfEvaluationTest && $companySelfEvaluationTest->status != SelfEvaluationTest::STATUS_DRAFT) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_ALREADY_YOUR_APPLICATION_IN_THIS_TEST'
            ]);
        }


        $request = $this->getRequest();
        if ($request->isGet()) {
            return new JsonModel([
                'success' => true,
                'data' => [
                    'name' => $companySelfEvaluationForm->name,
                    'description' => $companySelfEvaluationForm->description,
                    'text' => $companySelfEvaluationForm->text,
                    'content' => $companySelfEvaluationTest && $companySelfEvaluationTest->status == SelfEvaluationTest::STATUS_DRAFT ?
                    json_decode($companySelfEvaluationTest->content) :
                    json_decode($companySelfEvaluationForm->content),
                ]
            ]);
        }

        if ($request->isPost()) {
            $form = new SelfEvaluationTestForm();
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

            if ($form->isValid()) {
                $dataPost = (array) $form->getData();

                $selfEvaluationTest = new SelfEvaluationTest();
                $selfEvaluationTest->company_id = $companySelfEvaluationForm->company_id;
                $selfEvaluationTest->form_id = $companySelfEvaluationForm->id;
                $selfEvaluationTest->user_id = $currentUser->id;
                $selfEvaluationTest->status = $dataPost['status'];
                $selfEvaluationTest->content = $dataPost['content'];


                //Check if the form is already registered
                $companySelfEvaluationTest = $companySelfEvaluationTestMapper->fetchOneBy($companySelfEvaluationForm->id, $currentUser->id);

                $result = $companySelfEvaluationTest ?
                        $companySelfEvaluationTestMapper->update($selfEvaluationTest, $companySelfEvaluationTest->id) :
                        $companySelfEvaluationTestMapper->insert($selfEvaluationTest);


                if ($result) {
                    $this->logger->info('Se agrego un nuevo test de auto-evaluación : ' . $companySelfEvaluationForm->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    $data = [
                        'success' => true,
                        'data' => $companySelfEvaluationTest ? 'LABEL_RECORD_UPDATED' : 'LABEL_RECORD_ADDED'
                    ];
                } else {
                    $data = [
                        'success' => false,
                        'data' => $companySelfEvaluationTestMapper->getError()
                    ];
                }

                return new JsonModel($data);
            } else {
                $messages = [];
                $form_messages = (array) $form->getMessages();
                foreach ($form_messages as $fieldname => $field_messages) {

                    $messages[$fieldname] = array_values($field_messages);
                }

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

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

    public function reportAction() {

        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();

        $uuid = $this->params()->fromRoute('id');

        $companySelfEvaluationFormMapper = SelfEvaluationFormMapper::getInstance($this->adapter);
        $companySelfEvaluationForm = $companySelfEvaluationFormMapper->fetchOneByUuid($uuid);

        if (!$companySelfEvaluationForm) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_NOT_FOUND'
            ]);
        }

        if ($companySelfEvaluationForm->status == SelfEvaluationForm::STATUS_INACTIVE) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_IS_INACTIVE'
            ]);
        }


        $companySelfEvaluationFormUserMapper = SelfEvaluationFormUserMapper::getInstance($this->adapter);
        $companySelfEvaluationFormUser = $companySelfEvaluationFormUserMapper->fetchOneByFormIdAndUserId($companySelfEvaluationForm->id, $currentUser->id);
        if (!$companySelfEvaluationFormUser) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_YOU_CAN_NOT_TAKE'
            ]);
        }


        $companySelfEvaluationTestMapper = SelfEvaluationTestMapper::getInstance($this->adapter);
        $companySelfEvaluationTest = $companySelfEvaluationTestMapper->fetchOneBy($companySelfEvaluationForm->id, $currentUser->id);

        if (!$companySelfEvaluationTest) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_TEST_NOT_FOUND'
            ]);
        }

        if ($companySelfEvaluationTest->status != SelfEvaluationTest::STATUS_COMPLETED) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_FORM_EVALUATION_TEST_IS_INCOPLETE'
            ]);
        }


        $request = $this->getRequest();

        if ($request->isGet()) {

            return $this->renderPDF($companySelfEvaluationForm, $companySelfEvaluationTest, $currentUser);
        }

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

    /**
     * Render Pdf document
     * @param SelfEvaluationForm $companySelfEvaluationForm
     * @param SelfEvaluationTest $companySelfEvaluationTest
     * @param UserMapper $userMapper
     * @return mixed
     */
    public function renderPDF($companySelfEvaluationForm, $companySelfEvaluationTest, $userMapper) {

        // Set Data
        $headerFormName = utf8_decode($companySelfEvaluationForm->name);
        $headerUserName = utf8_decode('Informe de Auto-evaluación: ' . trim($userMapper->first_name . ' ' . $userMapper->last_name) . ' al ' . date("m-d-Y H:i:s", strtotime($companySelfEvaluationTest->added_on)));
        $sections = json_decode($companySelfEvaluationTest->content, true);
        $labels = ['Total', 'Logrado'];


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

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

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

        $valueFormSections = 0;
        $valueFormQuestions = 0;

        $countSection = 0;

        for ($i = 0; $i < count($sections); $i++) {
            if ($countSection > 1) {
                $countSection = 0;
                $pdf->AddPage();
                $pdf->customHeader($headerFormName, $headerUserName);
            }

            $pdf->SetY(70 + (92 * $countSection));
            $totalQuestion = 0;

            $valueSection = floatval($sections[$i]['value']);
            $valueFormSections = $valueFormSections + $valueSection;

            for ($j = 0; $j < count($sections[$i]['questions']); $j++) {
                $totalQuestion = $totalQuestion + $this->getPtosAnswer($sections[$i]['questions'][$j]);
            }

            $values = [$valueSection, $totalQuestion];
            $valueFormQuestions = $valueFormQuestions + $totalQuestion;


            $filename = 'data' . DIRECTORY_SEPARATOR . 'self-evaluation' . $sections[$i]['slug_section'] . '.png';
            $pdf->PieChart($labels, $values, '', $filename);
            $pdf->SetFont('Arial', '', 8);
            $pdf->Cell(190, 10, utf8_decode($sections[$i]['name']), 0, 0, 'C');
            $pdf->setY($pdf->getY() + 10);
            // Salto de línea
            $pdf->Image($filename, 60, $pdf->getY(), 90);
            $pdf->setY($pdf->getY() + 60);

            $countSection++;
        }

        $pdf->AddPage();
        $pdf->customHeader($headerFormName, $headerUserName);

        $pdf->SetFont('Arial', 'B', 10);
        $pdf->Cell(190, 10, utf8_decode('Desempeño General'), 0, 0, 'C');
        $pdf->setY($pdf->getY() + 10);


        $values = [$valueFormSections, $valueFormQuestions];

        $filenameGeneral = 'data' . DIRECTORY_SEPARATOR . 'self-evaluation' . uniqid() . '.png';
        $pdf->PieChart($labels, $values, '', $filenameGeneral);
        $pdf->Image($filenameGeneral, 60, $pdf->getY(), 90);
        $pdf->setY($pdf->getY() + 60);


        if ($companySelfEvaluationTest->comments) {

            $pdf->SetFont('Arial', 'B', 10);
            $pdf->Cell(190, 10, utf8_decode('Comentarios finales'), 0, 0, 'C');
            $pdf->setY($pdf->getY() + 10);

            $pdf->SetFont('Arial', '', 8);
            $pdf->MultiCell(180, 8, utf8_decode($companySelfEvaluationTest->comments));
            $pdf->setY(60);
        }

        return $pdf->Output();
    }

    /**
     * get total ptos Answer
     * @param array $question
     * @return int
     */
    public function getPtosAnswer($question) {

        $ptos = 0;

        if ($question['type'] == "open" || $question['type'] == "rating-open" || $question['type'] == "rating-range") {

            $ptos = isset($question['question_value']) ? $question['question_value'] : 0;
        } else {
            if ($question['type'] == 'multiple') {

                for ($o = 0; $o < count($question['options']); $o++) {
                    if (in_array($question['options'][$o]['slug_option'], $question['answer'])) {
                        $ptos = $ptos + $question['options'][$o]['value'];
                    }
                }
            } else {

                for ($o = 0; $o < count($question['options']); $o++) {
                    if ($question['options'][$o]['slug_option'] == $question['answer']) {
                        $ptos = $question['options'][$o]['value'];
                    }
                }
            }
        }
        return $ptos;
    }

}