Proyectos de Subversion LeadersLinked - Backend

Rev

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

<?php

declare(strict_types=1);

namespace LeadersLinked\Controller;

use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Log\LoggerInterface;
use Laminas\View\Model\ViewModel;
use Laminas\View\Model\JsonModel;
use LeadersLinked\Mapper\CompanyMicrolearningTopicMapper;
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleMapper;
use LeadersLinked\Form\TopicCapsuleForm;
use LeadersLinked\Form\PushMicrolearningNotificationForm;
use LeadersLinked\Mapper\QueryMapper;
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleUserMapper;
use LeadersLinked\Mapper\UserMapper;
use Laminas\Hydrator\ArraySerializableHydrator;
use Laminas\Db\ResultSet\HydratingResultSet;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use LeadersLinked\Model\CompanyMicrolearningCapsuleUser;
use LeadersLinked\Mapper\ApplicationMapper;
use LeadersLinked\Mapper\PushMapper;
use LeadersLinked\Mapper\PushTemplateMapper;
use LeadersLinked\Mapper\DeviceHistoryMapper;
use LeadersLinked\Model\Push;
use LeadersLinked\Model\Application;
use LeadersLinked\Form\CapsuleCustomerUploadForm;
use PhpOffice\PhpSpreadsheet\IOFactory;
use LeadersLinked\Model\User;
use LeadersLinked\Model\UserType;
use LeadersLinked\Model\UserPassword;
use LeadersLinked\Model\PerformanceEvaluationForm;
use LeadersLinked\Factory\Controller\PerformanceEvaluationFormControllerFactory;
use LeadersLinked\Form\PerformanceEvaluationFormForm;
use LeadersLinked\Mapper\CompanyPerformanceEvaluationFormMapper;
use LeadersLinked\Mapper\CompanyUserMapper;
use LeadersLinked\Mapper\CompanyPerformanceEvaluationFormUserMapper;
use LeadersLinked\Model\CompanyPerformanceEvaluationFormUser;

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

            if ($isJson) {
                $form_uuid = filter_var($this->params()->fromQuery('form_uuid'), FILTER_SANITIZE_STRING);

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


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


                $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
                $form = $formMapper->fetchOneByUuid($form_uuid);
                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'
                    ]);
                }


                $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 = ['uuid', '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';
                }

                $formUsersMapper = CompanyPerformanceEvaluationFormUserMapper::getInstance($this->adapter);




                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowAdd = $acl->isAllowed($currentUser->usertype_id, 'performance-evaluation/users/add');
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'performance-evaluation/users/delete');

                $queryMapper = QueryMapper::getInstance($this->adapter);
                $sql = $queryMapper->getSql();
                $select = $sql->select();
                $select->columns(['id', 'uuid', 'first_name', 'last_name', 'email']);
                $select->from(['tb1' => UserMapper::_TABLE]);
                $select->join(['tb2' => CompanyUserMapper::_TABLE], 'tb1.id = tb2.user_id ', []);
                $select->where->equalTo('tb2.company_id', $form->company_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);

                $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) {
                    $params = [
                        'form_id' => $form->uuid,
                        'user_id' => $record['uuid'],
                    ];

                    $link_add = '';
                    $link_delete = '';
                    $formUser = $formUsersMapper->fetchAllByCompanyIdAndFormIdAndUserId($form->company_id, $form->id, $record['id']);

                    if ($formUser) {
                        $link_delete = $this->url()->fromRoute('performance-evaluation/users/delete', $params);
                    } else {
                        $link_add = $this->url()->fromRoute('performance-evaluation/users/add', $params);
                    }

                    $item = [
                        'uuid' => $record['uuid'],
                        'first_name' => $record['first_name'],
                        'last_name' => $record['last_name'],
                        'email' => $record['email'],
                        'actions' => [
                            'link_add' => $allowAdd ? $link_add : '',
                            'link_delete' => $allowDelete ? $link_delete : '',
                        ]
                    ];


                    array_push($items, $item);
                }

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


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


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



                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/performance-evaluation-users/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();
        $form_uuid = $this->params()->fromRoute('form_id');
        $user_uuid = $this->params()->fromRoute('user_id');
        $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);
        $form = $formMapper->fetchOneByUuid($form_uuid);
        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_uuid);

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

        if ($request->isPost()) {

            $formUserMapper = CompanyPerformanceEvaluationFormUserMapper::getInstance($this->adapter);
            $formUser = $formUserMapper->fetchAllByCompanyIdAndFormIdAndUserId($form->company_id, $form->id, $user->id);

            if ($formUser) {
                return new JsonModel([
                    'success' => false,
                    'data' => 'ERROR_ALREADY_USER_ACCESS_TO_FORM'
                ]);
            }

            $formUser = new CompanyPerformanceEvaluationFormUser();
            $formUser->company_id = $form->company_id;
            $formUser->form_id = $form->id;
            $formUser->user_id = $user->id;

            $result = $formUserMapper->insert($formUser);

            if ($result) {

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

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

        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();
        $form_uuid = $this->params()->fromRoute('form_id');
        $user_uuid = $this->params()->fromRoute('user_id');
        $formMapper = CompanyPerformanceEvaluationFormMapper::getInstance($this->adapter);

        $form = $formMapper->fetchOneByUuid($form_uuid);
        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_uuid);

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

        if ($request->isPost()) {

            $formUserMapper = CompanyPerformanceEvaluationFormUserMapper::getInstance($this->adapter);
            $formUser = $formUserMapper->fetchAllByCompanyIdAndFormIdAndUserId($form->company_id, $form->id, $user->id);



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


            $result = $formUserMapper->delete($formUser->id);

            if ($result) {

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

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

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

}