Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 15371 | Rev 16768 | 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\Library\Functions;
use LeadersLinked\Mapper\SelfEvaluationFormMapper;
use LeadersLinked\Form\SelfEvaluationFormForm;
use LeadersLinked\Model\SelfEvaluationForm;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Mapper\SelfEvaluationFormUserMapper;

class SelfEvaluationFormController 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()) {

            $headers = $request->getHeaders();

            $isJson = false;
            if ($headers->has('Accept')) {
                $accept = $headers->get('Accept');

                $prioritized = $accept->getPrioritized();

                foreach ($prioritized as $key => $value) {
                    $raw = trim($value->getRaw());

                    if (!$isJson) {
                        $isJson = strpos($raw, 'json');
                    }
                }
            }

            if ($isJson) {
                $search = $this->params()->fromQuery('search', []);
                $search = empty($search['value']) ? '' : filter_var($search['value'], 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';
                }

                $companySelfEvaluationMapper = SelfEvaluationFormMapper::getInstance($this->adapter);
                $paginator = $companySelfEvaluationMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);

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

                    if ($record->language == SelfEvaluationForm::LANGUAGE_SPANISH) {
                        $language = 'LABEL_SPANISH';
                    } else if ($record->language == SelfEvaluationForm::LANGUAGE_ENGLISH) {
                        $language = 'LABEL_ENGLISH';
                    } else {
                        $language = '';
                    }

                    $item = [
                        'id' => $record->id,
                        'name' => $record->name,
                        'language' => $language,
                        'status' => $record->status,
                        'actions' => [
                            'link_edit' => $this->url()->fromRoute('self-evaluation/forms/edit', ['id' => $record->uuid]),
                            'link_delete' => $this->url()->fromRoute('self-evaluation/forms/delete', ['id' => $record->uuid])
                        ]
                    ];

                    array_push($items, $item);
                }

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

                $form = new SelfEvaluationFormForm();

                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/self-evaluation-forms/index.phtml');
                $viewModel->setVariable('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');
        $currentCompany = $currentUserPlugin->getCompany();
        $currentUser = $currentUserPlugin->getUser();

        $request = $this->getRequest();


        if ($request->isPost()) {
            $form = new SelfEvaluationFormForm();
            $dataPost = $request->getPost()->toArray();
            $dataPost['status'] = isset($dataPost['status']) ? $dataPost['status'] : SelfEvaluationForm::STATUS_INACTIVE;

            $form->setData($dataPost);

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

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

                if (!$companySelfEvaluation->status) {
                    $companySelfEvaluation->status = SelfEvaluationForm::STATUS_INACTIVE;
                }
                $companySelfEvaluation->company_id = $currentCompany->id;


                $companySelfEvaluationMapper = SelfEvaluationFormMapper::getInstance($this->adapter);
                $result = $companySelfEvaluationMapper->insert($companySelfEvaluation);

                if ($result) {
                    $this->logger->info('Se agrego el tamaño de empresa ' . $companySelfEvaluation->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    // Get record by id
                    $record = $companySelfEvaluationMapper->fetchOne($companySelfEvaluation->id);

                    if ($record) {

                        $data = [
                            'success' => true,
                            'id' => $record->id,
                            'action_edit' => $this->url()->fromRoute('self-evaluation/forms/edit', ['id' => $record->uuid]),
                            'data' => 'LABEL_RECORD_ADDED'
                        ];
                    } else {

                        $data = [
                            'success' => false,
                            'data' => 'ERROR_RECORD_NOT_FOUND'
                        ];
                    }
                } else {
                    $data = [
                        'success' => false,
                        'data' => $companySelfEvaluationMapper->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);
        }

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

            return new JsonModel($data);
        }

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


        if ($request->isPost()) {
            $form = new SelfEvaluationFormForm();
            $dataPost = $request->getPost()->toArray();
            $dataPost['status'] = isset($dataPost['status']) ? $dataPost['status'] : SelfEvaluationForm::STATUS_INACTIVE;

            $form->setData($dataPost);

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

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

                if (!$companySelfEvaluation->status) {
                    $companySelfEvaluation->status = SelfEvaluationForm::STATUS_INACTIVE;
                }

                $result = $companySelfEvaluationMapper->update($companySelfEvaluation);

                if ($result) {
                    $this->logger->info('Se actualizo el tamaño de empresa ' . $companySelfEvaluation->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                    $data = [
                        'success' => true,
                        'id' => $companySelfEvaluation->id,
                        'action_edit' => $this->url()->fromRoute('self-evaluation/forms/edit', ['id' => $companySelfEvaluation->uuid]),
                        'data' => 'LABEL_RECORD_UPDATED'
                    ];
                } else {
                    $data = [
                        'success' => false,
                        'data' => $companySelfEvaluationMapper->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();

            $data = [
                'success' => true,
                'data' => [
                    'id' => $companySelfEvaluation->uuid,
                    'name' => $companySelfEvaluation->name,
                    'description' => $companySelfEvaluation->description,
                    'text' => $companySelfEvaluation->text,
                    'language' => $companySelfEvaluation->language,
                    'status' => $companySelfEvaluation->status,
                    'content' => $companySelfEvaluation->content ? json_decode($companySelfEvaluation->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);
        }

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

            return new JsonModel($data);
        }

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

        if ($request->isPost()) {

            //Falta borrar los test  primeramente
            $selfEvaluationFormUserMapper = SelfEvaluationFormUserMapper::getInstance($this->adapter);
            $selfEvaluationFormUserMapper->deleteAllByFormId($companySelfEvaluation->id);


            $result = $companySelfEvaluationMapper->delete($companySelfEvaluation->id);
            if ($result) {
                $this->logger->info('Se borro el formulario de auto-evaluación ' . $companySelfEvaluation->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

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

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

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

}