Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 16749 | 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\FastSurveyMapper;
use LeadersLinked\Form\FastSurvey\FastSurveyForm;
use LeadersLinked\Model\FastSurvey;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Model\Feed;
use LeadersLinked\Mapper\CompanyUserMapper;
use LeadersLinked\Mapper\FeedMapper;

class FastSurveyController 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();
        
        $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) {
                
                
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'fast-survey/edit');
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'fast-survey/delete');
                $allowResult = $acl->isAllowed($currentUser->usertype_id, 'fast-survey/result');
                $allowDownload = $acl->isAllowed($currentUser->usertype_id, 'fast-survey/download');

                
                
                $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 =  ['added_on'];
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'added_on';
                
                if(!in_array($order_direction, ['ASC', 'DESC'])) {
                    $order_direction = 'DESC';
                }
                
                $fastSurveyMapper = FastSurveyMapper::getInstance($this->adapter);
                
                $paginator = $fastSurveyMapper->fetchAllDataTable($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);

                
                $items = [];
                $records = $paginator->getCurrentItems();
                foreach($records as $record)
                {
                    $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
                    $added_on = $dt->format('d/m/Y h:i a');
                    
                    $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->expire_on);
                    $expire_on = $dt->format('d/m/Y h:i a');
                    
                    $votes = $record->votes1 
                        + $record->votes2
                        + $record->votes3
                        + $record->votes4
                        + $record->votes5;
                    
                    switch($record->status)
                    {
                        case FastSurvey::STATUS_ACTIVE : 
                            $status = 'LABEL_ACTIVE';
                            break;
                       
                        default :     
                            $status = 'LABEL_INACTIVE';
                            break;
                            
                    }
                    
                    
                    $item = [
                        'question' => $record->question,
                        'details' => [
                            'status' => $status,
                            'added_on' => $added_on,
                            'expire_on' => $expire_on,
                        ],
                        'votes' => $votes,
                        'actions' => [
                            'link_edit' => $allowEdit && !$votes ?   $this->url()->fromRoute('fast-survey/edit', ['id' => $record->uuid ]) : '',
                            'link_delete' => $allowDelete && !$votes ? $this->url()->fromRoute('fast-survey/delete', ['id' => $record->uuid ]) : '',
                            'link_result' => $allowResult ? $this->url()->fromRoute('fast-survey/result', ['id' => $record->uuid ]) : '',
                            'link_download' => $allowDownload ? $this->url()->fromRoute('fast-survey/download', ['id' => $record->uuid ]) : '',
                        ],
              
                    ];
                    
                    array_push($items, $item);
                }
                
                return new JsonModel([
                    'success' => true,
                    'data' => [
                        'items' => $items,
                        'total' => $paginator->getTotalItemCount(),
                    ]
                ]);
            } else  {
                $form = new FastSurveyForm();
                
                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/fast-survey/index.phtml');
                $viewModel->setVariables([
                    'form' => $form
                ]);
                return $viewModel ;
            }
            
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);;
        }
    }

    public function addAction() 
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork = $currentNetworkPlugin->getNetwork();
        
        $currentCompany = $currentUserPlugin->getCompany();

        $request = $this->getRequest();


        if ($request->isPost()) {
           
            
            $form = new FastSurveyForm();
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);
            if ($form->isValid()) {

                $dataPost = (array) $form->getData();
               
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
                $companyUser = $companyUserMapper->fetchOwnerByCompanyId($currentCompany->id);
                
                
                

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

                $fastSurvey->network_id = $currentNetwork->id;
                $fastSurvey->company_id = $currentCompany->id;
                $fastSurvey->user_id = $companyUser->id;
                $fastSurvey->status = FastSurvey::STATUS_ACTIVE;
                
                $fastSurveyMapper = FastSurveyMapper::getInstance($this->adapter);
                $result = $fastSurveyMapper->insert($fastSurvey);
                if ($result) {
                    $feed = new Feed();
                    $feed->company_id = $currentCompany->id;
                    $feed->network_id = $currentNetwork->id;
                    $feed->user_id = $companyUser->id;
                    $feed->fast_survey_id = $fastSurvey->id;
                    $feed->type = Feed::TYPE_COMPANY;
                    $feed->file_type = Feed::FILE_TYPE_FAST_SURVEY;
                    $feed->posted_or_shared = Feed::POSTED;
                    $feed->status = Feed::STATUS_PUBLISHED;
                    $feed->title = '';
                    $feed->description = '';
                    $feed->total_comments   = 0;
                    $feed->total_shared     = 0;
                    
                    $feed->shared_with      = Feed::SHARE_WITH_CONNECTIONS;
                    
                    $feedMapper = FeedMapper::getInstance($this->adapter);
                    $feedMapper->insert($feed);
                    
                    $response = [
                        'success' => true,
                        'data' => 'LABEL_RECORD_ADDED',
                    ];
                        
                    $this->logger->info('Se agrego la encuesta rápida : ' . $fastSurvey->question, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                        
                } else {
                    $response = [
                        'success' => false,
                        'data' => $fastSurveyMapper->getError()
                    ];
                }

                return new JsonModel($response);
            } 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() 
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        $currentCompany = $currentUserPlugin->getCompany();

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


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

            return new JsonModel($data);
        }

        $fastSurveyMapper = FastSurveyMapper::getInstance($this->adapter);
        $fastSurvey = $fastSurveyMapper->fetchOneByUuid($id);
        if (!$fastSurvey) {
            $data = [
                'success' => false,
                'data' => 'ERROR_RECORD_NOT_FOUND'
            ];

            return new JsonModel($data);
        }
        
        if($fastSurvey->company_id != $currentCompany->id) {
            $response = [
                'success' => false,
                'data' =>  'ERROR_UNAUTHORIZED'
            ];
                
            return new JsonModel($response);
        }
        
        if($fastSurvey->votes1 > 0 || $fastSurvey->votes2 > 0|| $fastSurvey->votes3 > 0|| $fastSurvey->votes4 > 0|| $fastSurvey->votes5 > 0) {
            $response = [
                'success' => false,
                'data' =>  'ERROR_FAST_SURVEY_THERE_ARE_VOTES'
            ];
            
            return new JsonModel($response);
        }

        if ($request->isPost()) {
            $form = new FastSurveyForm();
            $dataPost = $request->getPost()->toArray();

            $form->setData($dataPost);

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

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

                $result = $fastSurveyMapper->update($fastSurvey);
                if ($result) {
                    $this->logger->info('Se actualizo la encuesta : ' . $fastSurvey->question, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

                    $data = [
                        'success' => true,
                        'data' => 'LABEL_RECORD_UPDATED'
                    ];
                } else {
                    $data = [
                        'success' => false,
                        'data' => $fastSurveyMapper->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' => [
                    'question' => $fastSurvey->question,
                    'number_of_answers' => $fastSurvey->number_of_answers, 
                    'answer1' => $fastSurvey->answer1, 
                    'answer2' => $fastSurvey->answer2, 
                    'answer3' => $fastSurvey->answer3, 
                    'answer4' => $fastSurvey->answer4, 
                    'answer5' => $fastSurvey->answer5, 
                    'duration_days' => $fastSurvey->duration_days, 
                    'duration_hours' => $fastSurvey->duration_hours, 
                    'duration_minutes' => $fastSurvey->duration_minutes, 
                    'status' => $fastSurvey->status, 
                    'privacy' => $fastSurvey->privacy, 
                    'result_type' => $fastSurvey->result_type, 
                ]
            ];

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

            return new JsonModel($data);
        }

        return new JsonModel($data);
    }

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

        $request = $this->getRequest();
        if ($request->isPost()) {
            
            $id = $this->params()->fromRoute('id');
            if (!$id) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_INVALID_PARAMETER'
                ];
    
                return new JsonModel($response);
            }
    
            
            
            $fastSurveyMapper = FastSurveyMapper::getInstance($this->adapter);
            $fastSurvey = $fastSurveyMapper->fetchOneByUuid($id);
            if (!$fastSurvey) {
                $data = [
                    'success' => false,
                    'data' => 'ERROR_RECORD_NOT_FOUND'
                ];
                
                return new JsonModel($data);
            }
            
            if($fastSurvey->company_id != $currentCompany->id) {
                $response = [
                    'success' => false,
                    'data' =>  'ERROR_UNAUTHORIZED'
                ];
                
                return new JsonModel($response);
            }
            
            if($fastSurvey->votes1 > 0 || $fastSurvey->votes2 > 0|| $fastSurvey->votes3 > 0|| $fastSurvey->votes4 > 0|| $fastSurvey->votes5 > 0) {
                $response = [
                    'success' => false,
                    'data' =>  'ERROR_FAST_SURVEY_THERE_ARE_VOTES'
                ];
                
                return new JsonModel($response);
            }

            
            $feedMapper = FeedMapper::getInstance($this->adapter);
            $feedMapper->deleteByFastSurvey($fastSurvey);
        
            $result = $fastSurveyMapper->delete($fastSurvey);
            if ($result) {
                
                
                
                $this->logger->info('Se borro la encuesta : ' . $fastSurvey->question, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);

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

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

            }
        } else {
            $response = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];

        }

        return new JsonModel($response);
    }
    
    
    
    
   

}