Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 16963 | Autoría | Comparar con el anterior | 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\Library\Functions;
use LeadersLinked\Mapper\RecruitmentSelectionCandidateMapper;
use LeadersLinked\Model\RecruitmentSelectionCandidate;
use LeadersLinked\Mapper\RecruitmentSelectionVacancyMapper;
use LeadersLinked\Mapper\UserMapper;
use Laminas\Hydrator\ArraySerializableHydrator;
use Laminas\Db\ResultSet\HydratingResultSet;
use LeadersLinked\Mapper\QueryMapper;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use LeadersLinked\Form\RecruitmentSelection\RecruitmentSelectionApplicationVacancyForm;
use LeadersLinked\Mapper\RecruitmentSelectionApplicationMapper;
use LeadersLinked\Model\RecruitmentSelectionApplication;
use LeadersLinked\Form\RecruitmentSelection\RecruitmentSelectionApplicationCandidateForm;
use LeadersLinked\Mapper\LocationMapper;
use LeadersLinked\Mapper\JobCategoryMapper;
use LeadersLinked\Mapper\IndustryMapper;
use LeadersLinked\Mapper\JobDescriptionMapper;
use LeadersLinked\Mapper\RecruitmentSelectionFileMapper;
use LeadersLinked\Mapper\RecruitmentSelectionInterviewMapper;
use LeadersLinked\Model\RecruitmentSelectionInterview;
use LeadersLinked\Form\RecruitmentSelection\RecruitmentSelectionApplicationFileForm;
use LeadersLinked\Form\RecruitmentSelection\RecruitmentSelectionApplicationPointsAndCommentForm;
use LeadersLinked\Form\RecruitmentSelection\RecruitmentSelectionApplicationLevelForm;
use LeadersLinked\Form\RecruitmentSelection\RecruitmentSelectionApplicationStatusForm;
use LeadersLinked\Form\RecruitmentSelection\RecruitmentSelectionApplicationInterviewForm;

class RecruitmentSelectionApplicationController extends AbstractActionController{

    /**
     *
     * @var \Laminas\Db\Adapter\AdapterInterface
     */
    private $adapter;
    
    /**
     *
     * @var \LeadersLinked\Cache\CacheInterface
     */
    private $cache;
    
    
    /**
     *
     * @var \Laminas\Log\LoggerInterface
     */
    private $logger;
    
    /**
     *
     * @var array
     */
    private $config;
    
    
    /**
     *
     * @var \Laminas\Mvc\I18n\Translator
     */
    private $translator;
    
    
    /**
     *
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
     * @param \LeadersLinked\Cache\CacheInterface $cache
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
     * @param array $config
     * @param \Laminas\Mvc\I18n\Translator $translator
     */
    public function __construct($adapter, $cache, $logger, $config, $translator)
    {
        $this->adapter      = $adapter;
        $this->cache        = $cache;
        $this->logger       = $logger;
        $this->config       = $config;
        $this->translator   = $translator;
    }

    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) {

                $vacancy_uuid = $this->params()->fromQuery('vacancy_id');

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


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


                $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
                $vacancy = $vacancyMapper->fetchOneByUuid($vacancy_uuid);
                if (! $vacancy) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_VACANCY_NOT_FOUND'
                    ]);
                }

                if ( $vacancy->company_id != $currentCompany->id) {
                    return new JsonModel([
                        'success' => true,
                        'data' => 'ERROR_UNAUTHORIZED'
                    ]);
                }


                $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 = ['first_name', 'last_name', 'email'];
                $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');
                $allowAdd = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/add');
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/delete');
                $allowView = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/view');
                
                
                
                $queryMapper = QueryMapper::getInstance($this->adapter);
                $sql = $queryMapper->getSql();
                $select = $sql->select();
                $select->columns(['uuid', 'level', 'status']);
                $select->from(['tb1' => RecruitmentSelectionApplicationMapper::_TABLE]);
                $select->join(['tb2' => RecruitmentSelectionCandidateMapper::_TABLE], 'tb1.candidate_id  = tb2.id', ['first_name', 'last_name', 'email']);
                $select->where->equalTo('tb1.vacancy_id', $vacancy->id);
                
                
                if($search) {
                    $select->where->nest()
                    ->like('first_name', '%' . $search . '%')
                    ->or->like('last_name', '%' . $search . '%')
                    ->or->like('email', '%' . $search . '%')
                    ->unnest();
                }

                $select->order($order_field . ' ' . $order_direction);  
                
               // echo $select->getSqlString($this->adapter->platform); exit;

                $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) {

                    switch($record['status'])
                    {
                        case RecruitmentSelectionApplication::STATUS_ACTIVE : 
                            $status = 'LABEL_ACTIVE';
                            break;
                            
                            
                        case RecruitmentSelectionApplication::STATUS_INACTIVE :
                            $status = 'LABEL_INACTIVE';
                            break;
                            
                        case RecruitmentSelectionApplication::STATUS_SELECTED :
                            $status = 'LABEL_SELECTED';
                            break;
                            
                        case RecruitmentSelectionApplication::STATUS_REJECTED :
                            $status = 'LABEL_REJECTED';
                            break;
                            
                    }
                    
                    switch($record['level'])
                    {
                        case RecruitmentSelectionApplication::LEVEL_CAPTURE : 
                            $level = 'LABEL_CAPTURE';
                            break;
                            
                        case RecruitmentSelectionApplication::LEVEL_PRE_SELECTION :
                            $level =  'LABEL_PRE_SELECTION';
                            break;
                            
                        case RecruitmentSelectionApplication::LEVEL_HUMAN_RESOURCE_INTERVIEW : 
                            $level =  'LABEL_HUMAN_RESOURCE';
                            break;
                            
                        case RecruitmentSelectionApplication::LEVEL_BOSS_RESOURCE_INTERVIEW : 
                            $level =  'LABEL_BOSS_INTERVIEW';
                            break;
                            
                        case RecruitmentSelectionApplication::LEVEL_FINISHED :
                            $level =  'LABEL_FINISHED';
                            break;
                            
                        default : 
                            $level =  'LABEL_UNKNOWN';
                            break;
                        
                    }

                    $item = [
                        'first_name' => $record['first_name'],
                        'last_name' => $record['last_name'],
                        'email' => $record['email'],
                        'status' => $status,
                        'level' => $level,
                        'actions' => [
                            'link_delete' => $allowDelete ? $this->url()->fromRoute('recruitment-and-selection/applications/delete', ['vacancy_id' => $vacancy->uuid, 'application_id' => $record['uuid']] ) : '', 
                            'link_view' => $allowView ? $this->url()->fromRoute('recruitment-and-selection/applications/view', ['vacancy_id' => $vacancy->uuid, 'application_id' => $record['uuid']] ) : '', 
                        ]
                    ];

                    array_push($items, $item);
                }

                $data['items'] = $items;
                $data['total'] = $paginator->getTotalItemCount();
                $data['link_add'] =  $allowAdd ? $this->url()->fromRoute( 'recruitment-and-selection/applications/add', ['vacancy_id' => $vacancy->uuid ]) : '';


                return new JsonModel([
                    'success' => true,
                    'data' => $data
                ]);
            } else {
                $formFile = new RecruitmentSelectionApplicationFileForm();
                $formAdd = new RecruitmentSelectionApplicationCandidateForm($this->adapter);
                $formFilter = new RecruitmentSelectionApplicationVacancyForm($this->adapter, $currentCompany->id);
                $formComment = new RecruitmentSelectionApplicationPointsAndCommentForm();
                $formLevel = new RecruitmentSelectionApplicationLevelForm();
                $formStatus = new RecruitmentSelectionApplicationStatusForm();
                $formInterview = new RecruitmentSelectionApplicationInterviewForm($this->adapter, $currentCompany->id);
                
                
                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/recruitment-and-selection-applications/index.phtml');
                $viewModel->setVariables([
                    'formFilter' => $formFilter,
                    'formAdd' => $formAdd,
                    'formFile' => $formFile,
                    'formComment' => $formComment,
                    'formLevel' => $formLevel,
                    'formStatus' => $formStatus,
                    'formInterview' => $formInterview,
                ]);

                return $viewModel;
            }
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
            ;
        }
    }
    
    public function userByEmailAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany     = $currentUserPlugin->getCompany(); 

        
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork = $currentNetworkPlugin->getNetwork();
        
        $request = $this->getRequest();
        
        if ($request->isGet()) {
            

            
            $email = trim(filter_var($this->params()->fromQuery('email'), FILTER_SANITIZE_EMAIL));
            if($email) {
                
                $userMapper = UserMapper::getInstance($this->adapter);
                $user = $userMapper->fetchOneActiveByEmailAndNetworkId($email, $currentNetwork->id);
                if($user) {
                    $data = [
                        'success' => true,
                        'data' => [
                            'uuid' => $user->uuid, 
                            'first_name' => $user->first_name,
                            'last_name' => $user->last_name,
                            'email' => $user->email
                        ]
                    ];
                } else {
                    $recruitmentSelectionCandidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
                    $candidate = $recruitmentSelectionCandidateMapper->fetchOneActiveByEmailAndCompanyId($email, $currentCompany->id);
                    if($candidate) {
                        $data = [
                            'success' => true,
                            'data' => [
                                'uuid' => '',
                                'first_name' => $candidate->first_name,
                                'last_name' => $candidate->last_name,
                                'email' => $candidate->email
                            ]
                        ];
                    } else {
                    
                        $data = [
                            'success' => false,
                            'data' => 'ERROR_EMAIL_NOT_FOUND'
                        ];
                    }
                }
            } else {
                $data = [
                    'success' => false,
                    'data' => 'ERROR_EMAIL_NOT_FOUND'
                ];
            }
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
        }
        
        
        return new JsonModel($data);
        
    }
    

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

        $vacancy_uuid = $this->params()->fromRoute('vacancy_id');
        
        $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancy = $vacancyMapper->fetchOneByUuid($vacancy_uuid);
        
        if(!$vacancy) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        
        if($vacancy->company_id != $currentCompany->id) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_IS_OTHER_COMPANY',
            ];
            
            return new JsonModel($data);
        }
        
        
        
        

        if($request->isPost()) {
            $dataPost = $request->getPost()->toArray();
            
            $form = new  RecruitmentSelectionApplicationCandidateForm($this->adapter);
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
                $candidate = $candidateMapper->fetchOneByEmail($dataPost['email']);
                if($candidate) {
                    
                    
                    $candidate->first_name = $dataPost['first_name'];
                    $candidate->last_name = $dataPost['last_name'];
                    
                    $result = $candidateMapper->update($candidate);
                    
                } else {

                    $candidate = new RecruitmentSelectionCandidate();
                    $candidate->company_id = $currentCompany->id;
                    $candidate->email = strtolower($dataPost['email']);
                    $candidate->first_name = $dataPost['first_name'];
                    $candidate->last_name = $dataPost['last_name'];
                    
                    $result = $candidateMapper->insert($candidate);
                }
                
                
                if(!$result) {
                    $data = [
                        'success'   => false,
                        'data'      => $candidateMapper->getError()
                    ];
                    
                    return new JsonModel($data);
                }

                $applicationMapper = RecruitmentSelectionApplicationMapper::getInstance($this->adapter);
                $application = $applicationMapper->fetchOneByVancancyIdAndCandidateId($vacancy->id, $candidate->id);
                
                
                if($application) {
                    $data = [
                        'success'   => false,
                        'data'      => 'ERROR_VACANCY_CANDIDATE_HAS_BEEN_PREVIOUSLY_ADDED',
                    ];
                    
                    return new JsonModel($data);
                    
                }
                
                
                $application = new RecruitmentSelectionApplication();
                $application->candidate_id = $candidate->id;
                $application->company_id = $currentCompany->id;
                $application->level = RecruitmentSelectionApplication::LEVEL_CAPTURE;
                $application->status = RecruitmentSelectionApplication::STATUS_ACTIVE;
                $application->vacancy_id = $vacancy->id;
                


                if($applicationMapper->insert($application)) {
                    
                    $this->logger->info('Se agrego la aplicación del candidato : ' . $candidate->first_name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success'   => true,
                        'data'   => 'LABEL_RECORD_ADDED'
                    ];
                } else {
                    $data = [
                        'success'   => false,
                        'data'      => $applicationMapper->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
                ]);
                
            }
            
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
    
    
    public function commentAction()
    {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        $application_id = $this->params()->fromRoute('application_id');
        
        $vacancy_uuid = $this->params()->fromRoute('vacancy_id');
        
        $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancy = $vacancyMapper->fetchOneByUuid($vacancy_uuid);
        
        if(!$vacancy) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        
        if($vacancy->company_id != $currentCompany->id) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_IS_OTHER_COMPANY',
            ];
            
            return new JsonModel($data);
        }
        
        
        
        $applicationMapper = RecruitmentSelectionApplicationMapper::getInstance($this->adapter);
        $application = $applicationMapper->fetchOneByUuid($application_id);
        
        
        if (!$application) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        
        if ($application->vacancy_id != $vacancy->id) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        
        
        if ($request->isGet()) {
            
            $data = [
                'success' => true,
                'data' => [
                    'points' => $application->points ? intval($application->points, 10) : 0,
                    'comment' => $application->comment ? trim($application->comment) : '',
                ]
            ];
            
            return new JsonModel($data);
        
        
        
        } else if ($request->isPost()) {
            
            
            $dataPost = $request->getPost()->toArray();
            
            $form = new RecruitmentSelectionApplicationPointsAndCommentForm();
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $application->points    = $dataPost['points'];
                $application->comment   = $dataPost['comment'];
                
                $result =  $applicationMapper->update($application);
                if ($result) {
                    $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
                    $candidate = $candidateMapper->fetchOne($application->candidate_id);
                    
                    
                    $this->logger->info('Se actualizo los puntos y comentario de la aplicación : ' . $candidate->first_name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    $data = [
                        'success' => true,
                        'data' => [
                            'message' => 'LABEL_RECORD_UPDATED',
                            'points' => $application->points ? intval($application->points, 10) : 0,
                            'comment' => $application->comment ? trim($application->comment) : '',
                        ]
                    ];
                    

                } else {
                    
                    $data = [
                        'success' => false,
                        'data' => $applicationMapper->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
                ]);
            }
            
           
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
    
    
    public function statusAction()
    {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        $application_id = $this->params()->fromRoute('application_id');
        
        $vacancy_uuid = $this->params()->fromRoute('vacancy_id');
        
        $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancy = $vacancyMapper->fetchOneByUuid($vacancy_uuid);
        
        if(!$vacancy) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        
        if($vacancy->company_id != $currentCompany->id) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_IS_OTHER_COMPANY',
            ];
            
            return new JsonModel($data);
        }
        
        
        
        $applicationMapper = RecruitmentSelectionApplicationMapper::getInstance($this->adapter);
        $application = $applicationMapper->fetchOneByUuid($application_id);
        
        
        if (!$application) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        
        if ($application->vacancy_id != $vacancy->id) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        
        
        if ($request->isGet()) {
            
            $data = [
                'success' => true,
                'data' => [
                    'status' => $application->status
                ]
            ];
            
            return new JsonModel($data);
            
            
            
        } else if ($request->isPost()) {
            
            
            $dataPost = $request->getPost()->toArray();
            
            $form = new RecruitmentSelectionApplicationStatusForm();
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $application->status    = $dataPost['status'];
 
                $result =  $applicationMapper->update($application);
                if ($result) {
                    $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
                    $candidate = $candidateMapper->fetchOne($application->candidate_id);
                    
                    
                    $this->logger->info('Se actualizo el estado de la aplicación : ' . $candidate->first_name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    switch($application->status)
                    {
                        case RecruitmentSelectionApplication::STATUS_ACTIVE :
                            $status = 'LABEL_ACTIVE';
                            break;
                            
                            
                        case RecruitmentSelectionApplication::STATUS_INACTIVE :
                            $status = 'LABEL_INACTIVE';
                            break;
                            
                        case RecruitmentSelectionApplication::STATUS_SELECTED :
                            $status = 'LABEL_SELECTED';
                            break;
                            
                        case RecruitmentSelectionApplication::STATUS_REJECTED :
                            $status = 'LABEL_REJECTED';
                            break;
                            
                    }
                    
                    
                    $data = [
                        'success' => true,
                        'data' => [
                            'message' => 'LABEL_RECORD_UPDATED',
                            'status' => $status 
                        ]
                    ];
                    
                    

                } else {
                    
                    $data = [
                        'success' => false,
                        'data' => $applicationMapper->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
                ]);
            }
            
            
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
    
    
    public function levelAction()
    {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        $application_id = $this->params()->fromRoute('application_id');
        
        $vacancy_uuid = $this->params()->fromRoute('vacancy_id');
        
        $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancy = $vacancyMapper->fetchOneByUuid($vacancy_uuid);
        
        if(!$vacancy) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        
        if($vacancy->company_id != $currentCompany->id) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_IS_OTHER_COMPANY',
            ];
            
            return new JsonModel($data);
        }
        
        
        
        $applicationMapper = RecruitmentSelectionApplicationMapper::getInstance($this->adapter);
        $application = $applicationMapper->fetchOneByUuid($application_id);
        
        
        if (!$application) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        
        if ($application->vacancy_id != $vacancy->id) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        
        
        if ($request->isGet()) {
            
            $data = [
                'success' => true,
                'data' => [
                    'level' => $application->level
                ]
            ];
            
            return new JsonModel($data);
            
            
            
        } else if ($request->isPost()) {
            
            
            $dataPost = $request->getPost()->toArray();
            
            $form = new RecruitmentSelectionApplicationLevelForm();
            $form->setData($dataPost);
            
            if($form->isValid()) {
                $dataPost = (array) $form->getData();
                
                $application->level = $dataPost['level'];

                $result =  $applicationMapper->update($application);
                if ($result) {
                    $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
                    $candidate = $candidateMapper->fetchOne($application->candidate_id);
                    
                    
                    $this->logger->info('Se actualizo el nivel de la aplicación : ' . $candidate->first_name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    
                    
                    switch($application->level)
                    {
                        case RecruitmentSelectionApplication::LEVEL_CAPTURE :
                            $level = 'LABEL_CAPTURE';
                            break;
                            
                        case RecruitmentSelectionApplication::LEVEL_PRE_SELECTION :
                            $level =  'LABEL_PRE_SELECTION';
                            break;
                            
                        case RecruitmentSelectionApplication::LEVEL_HUMAN_RESOURCE_INTERVIEW :
                            $level =  'LABEL_HUMAN_RESOURCE';
                            break;
                            
                        case RecruitmentSelectionApplication::LEVEL_BOSS_RESOURCE_INTERVIEW :
                            $level =  'LABEL_BOSS_INTERVIEW';
                            break;
                            
                        case RecruitmentSelectionApplication::LEVEL_FINISHED :
                            $level =  'LABEL_FINISHED';
                            break;
                            
                        default :
                            $level =  'LABEL_UNKNOWN';
                            break;
                            
                    }
                    
                    $data = [
                        'success' => true,
                        'data' => [
                            'message' => 'LABEL_RECORD_UPDATED',
                            'level' => $level
                        ]
                    ];

                } else {
                    
                    $data = [
                        'success' => false,
                        'data' => $applicationMapper->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
                ]);
            }
            
            
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
    
    
    public function deleteAction() 
    {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        $application_id = $this->params()->fromRoute('application_id');
        
        $vacancy_uuid = $this->params()->fromRoute('vacancy_id');
        
        $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancy = $vacancyMapper->fetchOneByUuid($vacancy_uuid);
        
        if(!$vacancy) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        
        if($vacancy->company_id != $currentCompany->id) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_IS_OTHER_COMPANY',
            ];
            
            return new JsonModel($data);
        }
        
        
        
        $applicationMapper = RecruitmentSelectionApplicationMapper::getInstance($this->adapter);
        $application = $applicationMapper->fetchOneByUuid($application_id);

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

        if ($application->vacancy_id != $vacancy->id) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        

        
        if ($request->isPost()) {
            
            $result = $applicationMapper->delete($application->id);
            if ($result) {
                $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
                $candidate = $candidateMapper->fetchOne($application->candidate_id);
                
                
                
                $this->logger->info('Se borro la aplicación : ' . $candidate->first_name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                $data = [
                    'success' => true,
                    'data' => 'LABEL_RECORD_DELETED'
                ];
            } else {
                
                $data = [
                    'success' => false,
                    'data' => $candidateMapper->getError()
                ];
                
                return new JsonModel($data);
            }
        } else {
            $data = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
            
            return new JsonModel($data);
        }
        
        return new JsonModel($data);
    }
    
    public function viewAction() 
    {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();
        
        $request = $this->getRequest();
        $application_id = $this->params()->fromRoute('application_id');
        
        $vacancy_uuid = $this->params()->fromRoute('vacancy_id');
        
        $vacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancy = $vacancyMapper->fetchOneByUuid($vacancy_uuid);
        
        if(!$vacancy) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        
        if($vacancy->company_id != $currentCompany->id) {
            $data = [
                'success' => false,
                'data' => 'ERROR_VACANCY_IS_OTHER_COMPANY',
            ];
            
            return new JsonModel($data);
        }
        
        
        
        $applicationMapper = RecruitmentSelectionApplicationMapper::getInstance($this->adapter);
        $application = $applicationMapper->fetchOneByUuid($application_id);
        
        
        if (!$application) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];
            
            return new JsonModel($data);
        }
        
        
        if ($application->vacancy_id != $vacancy->id) {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_UNAUTHORIZED'
            ]);
        }
        
        
        
        if ($request->isGet()) {
            
            $acl = $this->getEvent()->getViewModel()->getVariable('acl');
            $allowFile = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/files');
            $allowFileAdd = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/files/add');
            $allowFileDelete = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/files/delete');
            $allowFileView = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/files/view');
            $allowInterview = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/interviews');
            $allowInterviewAdd = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/interviews/add');
            $allowComment = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/comment');
            $allowLevel = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/level');
            $allowStatus = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/applications/status');
            
            
            $candidateMapper = RecruitmentSelectionCandidateMapper::getInstance($this->adapter);
            $candidate = $candidateMapper->fetchOne($application->candidate_id);
            
            
            switch($application->status)
            {
                case RecruitmentSelectionApplication::STATUS_ACTIVE :
                    $status = 'LABEL_ACTIVE';
                    break;
                    
                    
                case RecruitmentSelectionApplication::STATUS_INACTIVE :
                    $status = 'LABEL_INACTIVE';
                    break;
                    
                case RecruitmentSelectionApplication::STATUS_SELECTED :
                    $status = 'LABEL_SELECTED';
                    break;
                    
                case RecruitmentSelectionApplication::STATUS_REJECT :
                    $status = 'LABEL_REJECTED';
                    break;
                    
            }
            
            switch($application->level)
            {
                case RecruitmentSelectionApplication::LEVEL_CAPTURE :
                    $level = 'LABEL_CAPTURE';
                    break;
                    
                case RecruitmentSelectionApplication::LEVEL_PRE_SELECTION :
                    $level =  'LABEL_PRE_SELECTION';
                    break;
                    
                case RecruitmentSelectionApplication::LEVEL_HUMAN_RESOURCE_INTERVIEW :
                    $level =  'LABEL_HUMAN_RESOURCE';
                    break;
                    
                case RecruitmentSelectionApplication::LEVEL_BOSS_RESOURCE_INTERVIEW :
                    $level =  'LABEL_BOSS_INTERVIEW';
                    break;
                    
                case RecruitmentSelectionApplication::LEVEL_FINISHED :
                    $level =  'LABEL_FINISHED';
                    break;
                    
                default :
                    $level =  'LABEL_UNKNOWN';
                    break;
                    
            }
            
            $jobCategoryMapper = JobCategoryMapper::getInstance($this->adapter);
            $jobCategory = $jobCategoryMapper->fetchOne($vacancy->job_category_id);
            
            $industryMapper = IndustryMapper::getInstance($this->adapter);
            $industry = $industryMapper->fetchOne($vacancy->industry_id);
            
            
            $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
            $jobDescription = $jobDescriptionMapper->fetchOne($vacancy->job_description_id);
            
            
            $locationMapper = LocationMapper::getInstance($this->adapter);
            $location = $locationMapper->fetchOne($vacancy->location_id);
            
            
            $dt = \DateTime::createFromFormat('Y-m-d', $vacancy->last_date);
            $last_date = $dt->format('d/m/Y');
            
           
            $recruitmentSelectionFileMapper = RecruitmentSelectionFileMapper::getInstance($this->adapter);
            
            
            $files = [];
            $records = $recruitmentSelectionFileMapper->fetchAllByVacancyIdAndApplicationId($vacancy->id, $application->id);
            foreach($records as $record)
            {
                array_push($files, [
                    'name' => $record->name,
                    'filename' => basename($record->file),
                    'link_view' => $allowFileView ? $this->url()->fromRoute('recruitment-and-selection/applications/files/view', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid, 'id' => $record->uuid]) : '',
                    'link_delete' => $allowFileDelete ? $this->url()->fromRoute('recruitment-and-selection/applications/files/delete', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid, 'id' => $record->uuid]) : '',
                ]);  
            }
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $interviewMapper = RecruitmentSelectionInterviewMapper::getInstance($this->adapter);
            
            
            
            
            $interviews = [];
            $records = $interviewMapper->fetchAllByVacancyIdAndApplicationId($vacancy->id, $application->id);
            foreach($records as $record)
            {
                $status = '';
                switch($record->status) 
                {
                    case RecruitmentSelectionInterview::STATUS_ACCEPTED : 
                        $status = 'LABEL_ACCEPTED';
                        $link_report = $this->url()->fromRoute('recruitment-and-selection/applications/interviews/report', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid, 'id' => $record->uuid]);
                        
                        break;
                        
                    case RecruitmentSelectionInterview::STATUS_PENDING :
                        $status = 'LABEL_PENDING';
                        $link_report = '';
                        break;
                        
                    case RecruitmentSelectionInterview::STATUS_REJECTED :
                        $status = 'LABEL_REJECTED';
                        
                        $link_report = $this->url()->fromRoute('recruitment-and-selection/applications/interviews/report', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid, 'id' => $record->uuid]);
                        
                        break;
                        
                    default : 
                        $status = 'LABEL_UNKNOWN';
                        $link_report = '';
                        break;
                        
                }
                
                $type = '';
                switch($record->type)
                {
                    case RecruitmentSelectionInterview::TYPE_BOSS :
                        $type = 'LABEL_BOSS_INTERVIEW';
                        break;
                        
                    case RecruitmentSelectionInterview::TYPE_HUMAN_RESOURCE :
                        $type = 'LABEL_HUMAN_RESOURCE';
                        break;
                        
                    default :
                        $type = 'LABEL_UNKNOWN';
                        break;
                        
                }
                
                $dt = \DateTime::createFromFormat('Y-m-d',  $record->last_date);
                $last_date = $dt->format('d/m/Y');
                
                
                if($record->actual_date) {
                    
                    $dt = \DateTime::createFromFormat('Y-m-d',  $record->actual_date);
                    $actual_date = $dt->format('d/m/Y');
                } else {
                    $actual_date = '';
                }
                
                $user = $userMapper->fetchOne($record->interviewer_id);
                $interviewer = $user->first_name . ' ' . $user->last_name  . '(' . $user->email . ')'; 
                
                
                
                
                array_push($interviews, [
                    'type' => $type, 
                    'status' => $status, 
                    'last_date' => $last_date,
                    'actual_date' => $actual_date, 
                    'interviewer' => $interviewer,
                    'points' => $record->points,
                    'link_edit' => $this->url()->fromRoute('recruitment-and-selection/applications/interviews/edit', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid, 'id' => $record->uuid]),
                    'link_report' => $link_report,
                    'link_delete' => $this->url()->fromRoute('recruitment-and-selection/applications/interviews/delete', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid, 'id' => $record->uuid]),
                    
                ]);
            }
            
            $data = [
                'success' => true,
                'data' => [
                    'application' => [
                        'first_name' => $candidate->first_name,
                        'last_name' => $candidate->last_name,
                        'email' => $candidate->email,
                        'level' => $level,
                        'status' => $status,
                        'points' => $application->points,
                        'comment' => $application->comment,
                    ], 
                    'vacancy' => [
                        'name' => $vacancy->name, 
                        'last_date' => $last_date,
                        'address' => $location->formatted_address,
                        'industry' => $industry->name, 
                        'job_category' => $jobCategory->name,
                        'job_description' => $jobDescription->name
                    ], 
                    'files' => $files, 
                    'interviews' => $interviews,
                    'link_files' => $allowFile ? $this->url()->fromRoute('recruitment-and-selection/applications/files', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid]) : '',
                    'link_files_add' =>  $allowFileAdd ?  $this->url()->fromRoute('recruitment-and-selection/applications/files/add', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid]) : '',
                    'interviews' =>  $interviews, 
                    'link_interviews' => $allowInterview ? $this->url()->fromRoute('recruitment-and-selection/applications/interviews', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid]) : '',
                    'link_interviews_add' => $allowInterviewAdd ? $this->url()->fromRoute('recruitment-and-selection/applications/interviews/add', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid]) : '',
                    'link_comment' => $allowComment ? $this->url()->fromRoute('recruitment-and-selection/applications/comment', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid]) : '',
                    'link_level' => $allowLevel ? $this->url()->fromRoute('recruitment-and-selection/applications/level', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid]) : '',
                    'link_status' => $allowStatus ? $this->url()->fromRoute('recruitment-and-selection/applications/status', ['vacancy_id' => $vacancy->uuid, 'application_id' => $application->uuid]) : '',
                    
       

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