Proyectos de Subversion LeadersLinked - Backend

Rev

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\Library\Functions;
use LeadersLinked\Mapper\QueryMapper;
use LeadersLinked\Mapper\UserMapper;
use Laminas\Hydrator\ArraySerializableHydrator;
use Laminas\Db\ResultSet\HydratingResultSet;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use LeadersLinked\Mapper\CompanyPerformanceEvaluationFormMapper;
use LeadersLinked\Mapper\CompanyUserMapper;
use LeadersLinked\Form\PerformanceEvaluationEvaluationForm;
use LeadersLinked\Mapper\CompanyPerformanceEvaluationTestMapper;
use LeadersLinked\Model\CompanyPerformanceEvaluationTest;
use LeadersLinked\Model\CompanyPerformanceEvaluationForm;

class PerformanceEvaluationEvaluationController 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() {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();

        $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');
                    }
                }
            }

            //$isJson = true;
            if ($isJson) {


                $data = [
                    'items' => [],
                    'total' => 0,
                ];


                $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 = ['max_date'];
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'first_name';

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


                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'performance-evaluation/evaluations/edit');
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'performance-evaluation/evaluations/delete');
                $allowUsers = $acl->isAllowed($currentUser->usertype_id, 'performance-evaluation/evaluations/users');
                
                $queryMapper = QueryMapper::getInstance($this->adapter);
                $sql = $queryMapper->getSql();
                $select = $sql->select();
                $select->columns(['uuid', 'last_date']);
                $select->from(['tb1' => CompanyPerformanceEvaluationTestMapper::_TABLE]);
                $select->join(['tb2' => CompanyPerformanceEvaluationFormMapper::_TABLE], 'tb1.form_id = tb2.id ', ['form' =>'name']);
                $select->join(['tb3' => UserMapper::_TABLE], 'tb1.supervisor_id = tb3.id ', ['first_name', 'last_name', 'email']);
                $select->where->equalTo('tb1.company_id', $currentCompany->id);

                if ($search) {
                    $select->where->nest()
                            ->like('tb1.last_date', '%' . $search . '%')
                            ->like('tb2.name', '%' . $search . '%')
                            ->like('tb3.first_name', '%' . $search . '%')
                            ->or->like('tb3.last_name', '%' . $search . '%')
                            ->or->like('tb3.email', '%' . $search . '%')
                            ->unnest();
                }


                $select->order($order_field . ' ' . $order_direction);

                $hydrator = new ArraySerializableHydrator();
                $resultset = new HydratingResultSet($hydrator);

                $adapter = new DbSelect($select, $sql, $resultset);
                $paginator = new Paginator($adapter);
                $paginator->setItemCountPerPage($records_x_page);
                $paginator->setCurrentPageNumber($page);


                $items = [];
                $records = $paginator->getCurrentItems();
                foreach ($records as $record) 
                {

                    $dt = \DateTime::createFromFormat('Y-m-d', $record['last_date']);
                    $last_date = $dt->format('d/m/Y');

                    $link_edit = $this->url()->fromRoute('performance-evaluation/forms/report', ['id' => $record['uuid'] ]);
                    $link_delete = $this->url()->fromRoute('performance-evaluation/forms/report', ['id' => $record['uuid'] ]);
                    $link_users = $this->url()->fromRoute('performance-evaluation/forms/report', ['id' => $record['uuid'] ]);
                    
                    $item = [
                        'last_date' => $last_date,
                        'form' => $record['form'],
                        'supervisor' => trim(trim($record['first_name']) . ' ' . trim($record['last_name'])) . ' (' . trim($record['email']) . ')',
                        'actions' => [
 
                            'link_edit' => $allowEdit ? $link_edit : '',
                            'link_delete' => $allowDelete ? $link_delete : '',
                            'link_users' => $allowUsers ? $link_users : '',
                        ]
                    ];


                    array_push($items, $item);
                }

                $data['items'] = $items;
                $data['total'] = $paginator->getTotalItemCount();


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


                $form = new PerformanceEvaluationEvaluationForm($this->adapter, $currentCompany->id);



                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/performance-evaluation-evaluations/index.phtml');
                $viewModel->setVariables([
                    'form' => $form,
                ]);

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

    public function addAction() {
        $request = $this->getRequest();

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

        $request = $this->getRequest();


        if ($request->isPost()) {
            $dataPost = $request->getPost()->toArray();
            $form = new  PerformanceEvaluationEvaluationForm($this->adapter, $currentCompany->id);
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $form_id = $dataPost['form_id'];
                $user_id = $dataPost['supervisor_id'];
                $dt = \DateTime::createFromFormat('d/m/Y', $dataPost['last_date']);
                $last_date = $dt->format('Y-m-d');
                
                $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
                $form = $formMapper->fetchOneByUuid($form_id);
                if (!$form) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_FORM_NOT_FOUND'
                    ]);
                }
                
                if ($form->company_id != $currentCompany->id) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ]);
                }
                
                
                $userMapper = UserMapper::getInstance($this->adapter);
                $user = $userMapper->fetchOneByUuid($user_id);
                
                if (!$user) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_USER_NOT_FOUND'
                    ]);
                }
                
                
                
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($form->company_id, $user->id);
                if (!$companyUser) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ]);
                }
                
                
                $test = new CompanyPerformanceEvaluationTest();
                $test->company_id = $form->company_id;
                $test->form_id = $form->id;
                $test->supervisor_id = $user->id;
                $test->last_date = $last_date;

                
                $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
                $result = $testMapper->insert($test);
                
                if($result) {
                    $this->logger->info('Se agrego el Test de Performance ' . $form->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_ADDED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $testMapper->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 editAction() {
        $request = $this->getRequest();
        
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();
        
        $request = $this->getRequest();
        $id = $this->params()->fromRoute('id');
        
        $formTestMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
        $formTest =  $formTestMapper->fetchOneByUuid($id);
        if (!$formTest) {
            return new JsonModel([
                'success' => true,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ]);
        }
        
        if ($formTest->company_id != $currentCompany->id) {
            return new JsonModel([
                'success' => true,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        
        
        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($formTest->company_id, $currentUser->id);
        if (!$companyUser) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        
        if ($request->isGet()) {
            
            $dt = \DateTime::createFromFormat('Y-m-d', $formTest->last_date);
            
            $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
            $form = $formMapper->fetchOne($formTest->form_id);
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOne($currentUser->id);
            
            $data = [
                'success'   => true,
                'data'   => [
                    'last_date' => $dt->format('d/m/Y'),
                    'form' => $form->uuid,
                    'supervisor' => $user->uuid,
                ]
            ];
        
            return new JsonModel($data);
            
            
        
        } else if ($request->isPost()) {
            
            
            $dataPost = $request->getPost()->toArray();
            $form = new  PerformanceEvaluationEvaluationForm($this->adapter, $currentCompany->id);
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $form_id = $dataPost['form_id'];
                $user_id = $dataPost['supervisor_id'];
                $dt = \DateTime::createFromFormat('d/m/Y', $dataPost['last_date']);
                $last_date = $dt->format('Y-m-d');
                
                $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
                $form = $formMapper->fetchOneByUuid($form_id);
                if (!$form) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_FORM_NOT_FOUND'
                    ]);
                }
                
                if ($form->company_id != $currentCompany->id) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ]);
                }
                
                
                $userMapper = UserMapper::getInstance($this->adapter);
                $user = $userMapper->fetchOneByUuid($user_id);
                
                if (!$user) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_USER_NOT_FOUND'
                    ]);
                }
                
                
                
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($form->company_id, $user->id);
                if (!$companyUser) {
                    return new JsonModel([
                        'success' => false,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ]);
                }
                
                $formTest->supervisor_id = $user->id;
                $formTest->last_date = $last_date;
                
                $testMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
                $result = $testMapper->update($formTest);
                
                if($result) {
                    $this->logger->info('Se actualizo el Test de Performance ' . $form->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_UPDATED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $testMapper->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 deleteAction() {
        $request = $this->getRequest();

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

        $request = $this->getRequest();
        $id = $this->params()->fromRoute('id');
        
        $formTestMapper = CompanyPerformanceEvaluationTestMapper::getInstance($this->adapter);
        $formTest =  $formTestMapper->fetchOneByUuid($id);
        if (!$formTest) {
            return new JsonModel([
                'success' => true,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ]);
        }
        
        if ($formTest->company_id != $currentCompany->id) {
            return new JsonModel([
                'success' => true,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        

        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($formTest->company_id, $currentUser->id);
        if (!$companyUser) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }

        if ($request->isPost()) {


            $result = $formTestMapper->delete($formTest);

            if ($result) {

                return new JsonModel([
                    'success' => true,
                    'data' => 'LABEL_PERFORMANCE_TEST_DELETED',
                ]);
            } else {

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

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

}