Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 15371 | Rev 16766 | Ir a la última revisión | 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\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\Form\RecruitmentSelection\RecruitmentSelectionVacancyForm;
use LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\RecruitmentSelectionVacancyMapper;
use LeadersLinked\Model\RecruitmentSelectionVacancy;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Model\Location;
use LeadersLinked\Mapper\LocationMapper;
use LeadersLinked\Mapper\IndustryMapper;
use LeadersLinked\Mapper\JobDescriptionMapper;
use LeadersLinked\Mapper\JobCategoryMapper;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use LeadersLinked\Mapper\QueryMapper;
use Laminas\Hydrator\ArraySerializableHydrator;
use Laminas\Db\ResultSet\HydratingResultSet;

class RecruitmentSelectionVacancyController extends AbstractActionController
{

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

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

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

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

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

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


        $request = $this->getRequest();
        if ($request->isGet()) {
            $sandbox = $this->config['leaderslinked.runmode.sandbox'];
            if ($sandbox) {
                $google_map_key  = $this->config['leaderslinked.google_map.sandbox_api_key'];
            } else {
                $google_map_key  = $this->config['leaderslinked.google_map.production_api_key'];
            }


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

                $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' : strtoupper(filter_var($order[0]['dir'], FILTER_SANITIZE_STRING));

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

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

                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/vacancies/delete');
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'recruitment-and-selection/vacancies/edit');


                $queryMapper = QueryMapper::getInstance($this->adapter);
                $select = $queryMapper->getSql()->select();
                $select->from(['tb1' => RecruitmentSelectionVacancyMapper::_TABLE]);
                $select->columns(['uuid', 'name', 'last_date', 'status']);
                $select->join(['tb2' => JobDescriptionMapper::_TABLE], 'tb1.job_description_id = tb2.id AND tb1.company_id = tb2.company_id', ['job_description' => 'name']);
                
                $select->where->equalTo('tb1.company_id', $currentCompany->network_id);
                
                if($search) {
                    $select->where->like('tb1.name', '%' . $search . '%');
                }
                $select->order($order_field . ' ' . $order_direction);
                
                //echo $select->getSqlString($this->adapter->platform); exit;
                
                $hydrator   = new ArraySerializableHydrator();
                $resultset  = new HydratingResultSet($hydrator);
                
                $adapter = new DbSelect($select, $queryMapper->getSql(), $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']);
                    
                    switch($record['status'])
                    {
                        case RecruitmentSelectionVacancy::STATUS_ACTIVE : 
                            $status = 'LABEL_ACTIVE';
                            break;
                            
                        case RecruitmentSelectionVacancy::STATUS_INACTIVE : 
                            $status = 'LABEL_INACTIVE';
                            break;
                            
                        case RecruitmentSelectionVacancy::STATUS_EXPIRED : 
                            $status = 'LABEL_EXPIRED';
                            break;
                            
                        case RecruitmentSelectionVacancy::STATUS_COMPLETED :
                            $status = 'LABEL_COMPLETED';
                            break;
                            
                        default :   
                            $status = 'LABEL_UNKNOWN';
                            break;
                            
                    }
                    
                    $item = [
                      'name' => $record['name'],
                      'job_description' => $record['job_description'],
                      'last_date' => $dt->format('d/m/Y'),
                      'status' => $record->status,
                      'actions' => [
                            'link_edit' => $allowEdit ? $this->url()->fromRoute('recruitment-and-selection/vacancies/edit', ['id' => $record['uuid']]) : '',
                            'link_delete' => $allowDelete ? $this->url()->fromRoute('recruitment-and-selection/vacancies/delete', ['id' => $record['uuid']]) : ''
                       ]
                    ];
      

                    array_push($items, $item);
                }

                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'items' => $items,
                        'total' => $paginator->getTotalItemCount(),
                    ]
                ]);
            } else {

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

                $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
                $industryMapper = industryMapper::getInstance($this->adapter);
                $jobCategoryMapper = JobCategoryMapper::getInstance($this->adapter);

                $jobDescritions = [];
                $industries = [];
                $jobCategories = [];

                $records = $jobCategoryMapper->fetchAllActive();

                foreach ($records as $record) {
                    $jobCategories[$record->uuid] = $record->name;
                }

                $records = $industryMapper->fetchAllActive();

                foreach ($records as $record) {
                    $industries[$record->uuid] = $record->name;
                }

                $records = $currentCompany ?
                    $jobDescriptionMapper->fetchAllActiveByCompanyId($currentCompany->id) :
                    $jobDescriptionMapper->fetchAllActiveByDefault();
                
                foreach ($records as $record) {
                    $jobDescritions[$record->uuid] = $record->name;
                }

                
                //print_r($jobDescritions); exit;
                
                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/recruitment-and-selection-vacancies/index.phtml');
                $viewModel->setVariable('form', $form);
                $viewModel->setVariable('google_map_key', $google_map_key);
                $viewModel->setVariable('jobDescritions', $jobDescritions);
                $viewModel->setVariable('industries', $industries);
                $viewModel->setVariable('jobCategories', $jobCategories);

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

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

        $request = $this->getRequest();


        if ($request->isPost()) {
            $form = new RecruitmentSelectionVacancyForm($this->adapter, $currentCompany->id);
            $dataPost = $request->getPost()->toArray();

            


            $dataPost['status'] = isset($dataPost['status']) ? $dataPost['status'] : RecruitmentSelectionVacancy::STATUS_INACTIVE;

            $form->setData($dataPost);

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

                
                $hydrator = new ObjectPropertyHydrator();

                $location = new Location();
                $hydrator->hydrate($dataPost, $location);

                $locationMapper = LocationMapper::getInstance($this->adapter);
                $result = $locationMapper->insert($location);


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

                $vacancy = new RecruitmentSelectionVacancy();
                $hydrator->hydrate($dataPost, $vacancy);

                $vacancy->location_id = $location->id;
                $vacancy->company_id = $currentCompany->id;

                $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
                $jobDescription = $jobDescriptionMapper->fetchOneByUuid($dataPost['job_description_id']);
                $vacancy->job_description_id = $jobDescription->id;

                $jobCategoryMapper = JobCategoryMapper::getInstance($this->adapter);
                $jobCategory = $jobCategoryMapper->fetchOneByUuid($dataPost['job_category_id']);
                $vacancy->job_category_id = $jobCategory->id;

                $industryMapper = IndustryMapper::getInstance($this->adapter);
                $industry = $industryMapper->fetchOneByUuid($dataPost['industry_id']);
                $vacancy->industry_id = $industry->id;

                $vacancy->description = $dataPost['description'];
                $vacancy->last_date = $dataPost['last_date'];

                $dt = \DateTime::createFromFormat('m/d/Y', $vacancy->last_date);
                if ($dt) {
                    $vacancy->last_date = $dt->format('Y-m-d');
                    
                    
                    
                }


                $recruitmentSelectionVacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);

                $result = $recruitmentSelectionVacancyMapper->insert($vacancy);

                if ($result) {
                    $this->logger->info('Se agrego el proceso de reclutamiento' . $vacancy->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    $data = [
                        'success' => true,
                        'data' => 'LABEL_RECORD_ADDED'
                    ];
                } else {
                    $data = [
                        'success' => false,
                        'data' => $recruitmentSelectionVacancyMapper->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 editAction()
    {
        $request = $this->getRequest();
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();

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


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

            return new JsonModel($data);
        }

        $recruitmentSelectionVacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancy = $recruitmentSelectionVacancyMapper->fetchOneByUuid($uuid);
        if (!$vacancy) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];

            return new JsonModel($data);
        }

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


        if ($request->isPost()) {
            $form = new RecruitmentSelectionVacancyForm($this->adapter, $currentCompany->id);
            $dataPost = $request->getPost()->toArray();
            $dataPost['status'] = isset($dataPost['status']) ? $dataPost['status'] : RecruitmentSelectionVacancy::STATUS_INACTIVE;

            $form->setData($dataPost);

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

                $hydrator = new ObjectPropertyHydrator();
                $hydrator->hydrate($dataPost, $vacancy);

                if (!$vacancy->status) {
                    $vacancy->status = RecruitmentSelectionVacancy::STATUS_INACTIVE;
                }
                
                $dt = \DateTime::createFromFormat('m/d/Y', $vacancy->last_date);
                if ($dt) {
                    $vacancy->last_date = $dt->format('Y-m-d');
                }

                $locationMapper = LocationMapper::getInstance($this->adapter);
                $location = $locationMapper->fetchOne($vacancy->location_id);
                $hydrator->hydrate($dataPost, $location);
                $locationMapper->update($location);

                $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
                $jobDescription = $jobDescriptionMapper->fetchOneByUuid($dataPost['job_description_id']);
                $vacancy->job_description_id = $jobDescription->id;

                $jobCategoryMapper = JobCategoryMapper::getInstance($this->adapter);
                $jobCategory = $jobCategoryMapper->fetchOneByUuid($dataPost['job_category_id']);
                $vacancy->job_category_id = $jobCategory->id;

                $industryMapper = IndustryMapper::getInstance($this->adapter);
                $industry = $industryMapper->fetchOneByUuid($dataPost['industry_id']);
                $vacancy->industry_id = $industry->id;

                $vacancy->job_description_id = $jobDescription->id;
                $vacancy->job_category_id = $jobCategory->id;
                $vacancy->industry_id = $industry->id;

                $result = $recruitmentSelectionVacancyMapper->update($vacancy);


                if ($result) {
                    $this->logger->info('Se agrego el proceso de reclutamiento' . $vacancy->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    $data = [
                        'success' => true,
                        'data' => 'LABEL_RECORD_UPDATED'
                    ];
                } else {
                    $data = [
                        'success' => false,
                        'data' => $recruitmentSelectionVacancyMapper->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 if ($request->isGet()) {
            $hydrator = new ObjectPropertyHydrator();

            $locationMapper = LocationMapper::getInstance($this->adapter);
            $location = $locationMapper->fetchOne($vacancy->location_id);

            $jobDescriptionMapper = JobDescriptionMapper::getInstance($this->adapter);
            $jobDescription = $jobDescriptionMapper->fetchOne($vacancy->job_description_id);
            $jobDescritions = [];

            $records = $currentCompany ?
                $jobDescriptionMapper->fetchAllActiveByCompanyId($currentCompany->id) :
                $jobDescriptionMapper->fetchAllByDefault();

            foreach ($records as $record) {
                $jobDescritions[$record->uuid] = $record->name;
            }

            $jobCategoryMapper = JobCategoryMapper::getInstance($this->adapter);
            $jobCategory = $jobCategoryMapper->fetchOne($vacancy->job_category_id);
            $jobCategories = [];

            $records = $jobCategoryMapper->fetchAllActive();

            foreach ($records as $record) {
                $jobCategories[$record->uuid] = $record->name;
            }

            $industryMapper = IndustryMapper::getInstance($this->adapter);
            $industry = $industryMapper->fetchOne($vacancy->industry_id);
            $industries = [];

            $records = $industryMapper->fetchAllActive();

            foreach ($records as $record) {
                $industries[$record->uuid] = $record->name;
            }


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

                return new JsonModel($data);
            }
            

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

            $data = [
                'success' => true,
                'data' => [
                    'id' => $vacancy->uuid,
                    'name' => $vacancy->name,
                    'job_description' => [
                        'description_options' => $jobDescritions,
                        'current_description' => [
                            'description_id' => $jobDescription->uuid,
                            'description_name' => $jobDescription->name
                        ]
                    ],
                    'location_search' => $location->formatted_address,
                    'formatted_address' => $location->formatted_address,
                    'address1' => $location->address1,
                    'address2' => $location->address2,
                    'country' => $location->country,
                    'state' => $location->state,
                    'city1' => $location->city1,
                    'city2' => $location->city2,
                    'postal_code' => $location->postal_code,
                    'latitude' => $location->latitude,
                    'longitude' => $location->longitude,
                    'job_category' => [
                        'category_options' => $jobCategories,
                        'current_category' => [
                            'job_category_id' => $jobCategory->uuid,
                            'job_category_name' => $jobCategory->name,
                        ]
                    ],
                    'description' => $vacancy->description,
                    'industry' => [
                        'industry_options' => $industries,
                        'current_industry' => [
                            'industry_id' => $industry->uuid,
                            'industry_name' => $industry->name,
                        ]
                    ],
                    'last_date' => $last_date,
                    'status' => $vacancy->status,
                    // 'content' => $vacancy->content ? json_decode($vacancy->content) : [],
                ]
            ];

            return new JsonModel($data);
        } 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();
        $uuid = $this->params()->fromRoute('id');

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

            return new JsonModel($data);
        }

        $recruitmentSelectionVacancyMapper = RecruitmentSelectionVacancyMapper::getInstance($this->adapter);
        $vacancyMapper = $recruitmentSelectionVacancyMapper->fetchOneByUuid($uuid);
        if (!$vacancyMapper) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];

            return new JsonModel($data);
        }

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

        if ($request->isPost()) {


            $result = $recruitmentSelectionVacancyMapper->delete($vacancyMapper->id);
            if ($result) {
                $this->logger->info('Se borro el formulario de reclutamiento ' . $vacancyMapper->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                $data = [
                    'success' => true,
                    'data' => 'LABEL_RECORD_DELETED'
                ];
            } else {

                $data = [
                    'success' => false,
                    'data' => $recruitmentSelectionVacancyMapper->getError()
                ];

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }
}