Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17162 | Rev 17185 | 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\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\JsonModel;
use LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\MicrolearningTopicMapper;
use LeadersLinked\Mapper\MicrolearningCapsuleMapper;
use LeadersLinked\Model\MicrolearningTopic;
use LeadersLinked\Form\Microlearning\TopicAddForm;
use LeadersLinked\Form\Microlearning\TopicEditForm;
use LeadersLinked\Library\Storage;
use LeadersLinked\Model\MicrolearningTopicCapsule;
use LeadersLinked\Mapper\MicrolearningTopicCapsuleMapper;
use LeadersLinked\Mapper\MicrolearningUserProgressMapper;

class MicrolearningTopicController 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;
    }
    
    /**
     * 
     * Generación del listado de tópicos
     * {@inheritDoc}
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
     * @return JsonModel
     */
    public function indexAction()
    {
        try {
            $request = $this->getRequest();

            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentCompany = $currentUserPlugin->getCompany();
            $currentUser    = $currentUserPlugin->getUser();
            
            if (!$request->isGet()) {
                return $this->createErrorResponse('ERROR_METHOD_NOT_ALLOWED');
            }

            if(!$currentCompany) {
                return $this->createErrorResponse('ERROR_COMPANY_NOT_FOUND');
            }

            if(!$currentUser) {
                return $this->createErrorResponse('ERROR_USER_NOT_FOUND');
            }
                
            if($this->isJsonRequest($request)) {
                return $this->handleJsonRequest($currentUser, $currentCompany);
            }

            return $this->handleHtmlRequest($currentCompany);
        } catch (\Exception $e) {
            $this->logger->err('Error in indexAction: ' . $e->getMessage());
            return $this->createErrorResponse('ERROR_INTERNAL_SERVER_ERROR');
        }
    }

    /**
     * 
     * Agregar un tópico
     * {@inheritDoc}
     * @see \Laminas\Mvc\Controller\AbstractActionController::addAction()
     * @return JsonModel
     */
    public function addAction()
    {
        try {
            $request    = $this->getRequest();

            $currentUserPlugin  = $this->plugin('currentUserPlugin');
            $currentCompany     = $currentUserPlugin->getCompany(); 
            $currentUser        = $currentUserPlugin->getUser();

            if(!$currentCompany) {
                return $this->createErrorResponse('ERROR_COMPANY_NOT_FOUND');
            }

            if(!$currentUser) {
                return $this->createErrorResponse('ERROR_USER_NOT_FOUND');
            }

            if(!$request->isPost() && !$request->isGet()) {
                return $this->createErrorResponse('ERROR_METHOD_NOT_ALLOWED');
            }

            if($request->isGet()) {        
                $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
                $records =  $capsuleMapper->fetchAllByCompanyId($currentCompany->id);
                
                $capsules = [];

                foreach($records as $record) {
                    array_push($capsules, [
                        'id' => $record->uuid,
                        'name' => $record->name,
                    ]);
                }

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

            if($request->isPost()) {
                $form = new TopicAddForm($this->adapter, $currentCompany->id);
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
                
                $form->setData($dataPost);
                
                if(!$form->isValid()) {
                    $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
                    ]);
                }

                $dataPost = (array) $form->getData();

                $topic = new MicrolearningTopic();
                $topic->name = $dataPost['name'];
                $topic->description = $dataPost['description'];
                $topic->order = $dataPost['order'];
                $topic->status = $dataPost['status'];        
                $topic->privacy = $dataPost['privacy'];
                $topic->type = $dataPost['type'];
                $topic->cost = $dataPost['cost'];
                $topic->company_id = $currentCompany->id;
                $topic->image = '';
                $topic->marketplace = '';
                
                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);

                if(!$topicMapper->insert($topic)) {
                    return $this->createErrorResponse($topicMapper->getError());
                }

                $topic = $topicMapper->fetchOne($topic->id);
                
                $capsuleUuids = $dataPost['capsule_id'];
                $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
                $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
                
                foreach ($capsuleUuids as $capsuleUuid) {
                    $capsule = $capsuleMapper->fetchOneByUuid($capsuleUuid);
                    
                    if ($capsule) {
                        $topicCapsule = new MicrolearningTopicCapsule();
                        $topicCapsule->topic_id = $topic->id;
                        $topicCapsule->capsule_id = $capsule->id;
                        $topicCapsule->company_id = $currentCompany->id;
                        $topicCapsuleMapper->insert($topicCapsule);
                    }
                }
                
                $storage = Storage::getInstance($this->config, $this->adapter);
                $storage->setFiles($request->getFiles()->toArray());
        
                if (!$storage->setCurrentFilename('file')) {
                    return $this->createErrorResponse('ERROR_UPLOAD_IMAGE');
                }

                $target_size = $this->config['leaderslinked.image_sizes.microlearning_image_size'];
                list($target_width, $target_height) = explode('x', $target_size);

                $image_source_filename = $storage->getTmpFilename();
                $image_filename = 'topic-' . uniqid() . '.png';
                $image_target_filename = $storage->composePathToFilename(
                    Storage::TYPE_MICROLEARNING_TOPIC,
                    $topic->uuid,
                    $image_filename
                );

                if (!$storage->uploadImageCrop($image_source_filename, $image_target_filename, $target_width, $target_height)) {
                    return $this->createErrorResponse('ERROR_UPLOAD_IMAGE');
                }

                if(!$storage->setCurrentFilename('marketplace')) {
                    return $this->createErrorResponse('ERROR_UPLOAD_IMAGE');
                }

                $marketplace_source_filename = $storage->getTmpFilename();
                $marketplace_filename = 'marketplace-' . uniqid() . '.png';
                $marketplace_target_filename = $storage->composePathToFilename(
                    Storage::TYPE_MICROLEARNING_TOPIC,
                    $topic->uuid,
                    $marketplace_filename
                );

                if (!$storage->uploadImageCrop($marketplace_source_filename, $marketplace_target_filename, $target_width, $target_height)) {
                    return $this->createErrorResponse('ERROR_UPLOAD_IMAGE');
                }

                $topic->image = $image_filename;
                $topic->marketplace = $marketplace_filename;

                if(!$topicMapper->update($topic)) {
                    return $this->createErrorResponse($topicMapper->getError());
                }
                
                $this->logger->info('Se agrego el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                return new JsonModel([
                    'success'   => true,
                    'data'   => 'LABEL_RECORD_ADDED'
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->err('Error in addAction: ' . $e->getMessage());
            return $this->createErrorResponse('ERROR_INTERNAL_SERVER_ERROR');
        }
    }
    
    /**
     * 
     * Borrar un tópico
     * {@inheritDoc}
     * @see \Laminas\Mvc\Controller\AbstractActionController::deleteAction()
     * @return JsonModel
     */
    public function deleteAction()
    {
        try {
            $request = $this->getRequest();

            $currentUserPlugin  = $this->plugin('currentUserPlugin');
            $currentCompany     = $currentUserPlugin->getCompany();
            $currentUser        = $currentUserPlugin->getUser();
            
            $id   = $this->params()->fromRoute('id');

            if(!$currentCompany) {
                return $this->createErrorResponse('ERROR_COMPANY_NOT_FOUND');
            }

            if(!$currentUser) {
                return $this->createErrorResponse('ERROR_USER_NOT_FOUND');
            }

            if(!$request->isPost()) {
                return $this->createErrorResponse('ERROR_METHOD_NOT_ALLOWED');
            }

            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
            $topic = $topicMapper->fetchOneByUuid($id);
        
            if(!$topic) {
                return $this->createErrorResponse('ERROR_TOPIC_NOT_FOUND');
            }
        
            if($topic->company_id != $currentCompany->id) {
                return $this->createErrorResponse('ERROR_UNAUTHORIZED');
            }

            // Eliminar las relaciones con cápsulas primero
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
            
            if(!$topicCapsuleMapper->deleteByTopicId($topic->id)) {
                return $this->createErrorResponse($topicCapsuleMapper->getError());
            }

            // Eliminar el progreso de los usuarios
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);

            if(!$userProgressMapper->deleteAllTopicProgressByTopicId($topic->id)) {
                return $this->createErrorResponse($userProgressMapper->getError());
            }

            // Eliminar archivos de almacenamiento
            $storage = Storage::getInstance($this->config, $this->adapter);
            $target_path = $storage->getPathMicrolearningTopic();
            
            if($topic->image) {
                if(!$storage->deleteFile($target_path, $topic->uuid, $topic->image)) {
                    return $this->createErrorResponse('ERROR_DELETING_FILE');
                }
            }

            if(!$topicMapper->delete($topic)) {
                return $this->createErrorResponse($topicMapper->getError());
            }

            if($topic->marketplace) {
                if(!$storage->deleteFile($target_path, $topic->uuid, $topic->marketplace)) {
                    return $this->createErrorResponse('ERROR_DELETING_FILE');
                }
            }

            // Registrar la acción en el log
            $this->logger->info('Se borro el tópico : ' . $topic->name, [
            'user_id' => $currentUser->id, 
            'ip' => Functions::getUserIP()
            ]);
        
            return new JsonModel([
                'success' => true,
                'data' => 'LABEL_RECORD_DELETED'
            ]);
        } catch (\Exception $e) {
            $this->logger->err('Error in deleteAction: ' . $e->getMessage());
            return $this->createErrorResponse('ERROR_INTERNAL_SERVER_ERROR');
        }
    }
    
    /**
     * 
     * Editar un tópico
     * {@inheritDoc}
     * @see \Laminas\Mvc\Controller\AbstractActionController::editAction()
     * @return JsonModel
     */
    public function editAction()
    {
        try {
            $request = $this->getRequest();

            $currentUserPlugin  = $this->plugin('currentUserPlugin');
            $currentCompany     = $currentUserPlugin->getCompany();
            $currentUser        = $currentUserPlugin->getUser();
            
            $id   = $this->params()->fromRoute('id');

            if(!$currentCompany) {
                return $this->createErrorResponse('ERROR_COMPANY_NOT_FOUND');
            }

            if(!$currentUser) {
                return $this->createErrorResponse('ERROR_USER_NOT_FOUND');
            }

            if(!$request->isPost() && !$request->isGet()) {
                return $this->createErrorResponse('ERROR_METHOD_NOT_ALLOWED');
            }

            if($request->isGet()) {
                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
                $topic = $topicMapper->fetchOneByUuid($id);
    
                if(!$topic) {
                    return $this->createErrorResponse('ERROR_TOPIC_NOT_FOUND');
                }
        
                if($topic->company_id != $currentCompany->id) {
                    return $this->createErrorResponse('ERROR_UNAUTHORIZED');
                }
                
                $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
                $records =  $capsuleMapper->fetchAllByCompanyId($currentCompany->id);
                
                $capsules = [];

                foreach($records as $record) {
                    array_push($capsules, [
                        'id' => $record->uuid,
                        'name' => $record->name,
                    ]);
                }

                $storage = Storage::getInstance($this->config, $this->adapter);
                $path = $storage->getPathMicrolearningTopic();
                
                $data = [
                    'success' => true,
                    'data' => [
                        'capsules' => $capsules,
                        'name' => $topic->name,
                        'description' => $topic->description,
                        'order' => $topic->order,
                        'status' => $topic->status,
                        'privacy' => $topic->privacy,
                        'type' => $topic->type,
                        'cost' => $topic->cost,
                        'image'=> $storage->getGenericImage($path, $topic->uuid, $topic->image),
                        'marketplace'=> $storage->getGenericImage($path, $topic->uuid, $topic->marketplace)
                    ]
                ];
                
                return new JsonModel($data);
            }

            if($request->isPost()) {
                $form = new  TopicEditForm($this->adapter, $currentCompany->id, $currentCompany->internal);
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
                
                $form->setData($dataPost);
                
                if(!$form->isValid()) {
                    $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
                    ]);
                }

                $dataPost = (array) $form->getData();

                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
                $topic = $topicMapper->fetchOneByUuid($id);

                if(!$topic) {
                    return $this->createErrorResponse('ERROR_TOPIC_NOT_FOUND');
                }

                if($topic->company_id != $currentCompany->id) {
                    return $this->createErrorResponse('ERROR_UNAUTHORIZED');
                }

                $topic->name = $dataPost['name'];
                $topic->description = $dataPost['description'];
                $topic->order = $dataPost['order'];
                $topic->status = $dataPost['status'];
                $topic->privacy = $dataPost['privacy'];
                $topic->type = $dataPost['type'];
                $topic->cost = $dataPost['cost'];
                $topic->image = $dataPost['image'];
                $topic->marketplace = $dataPost['marketplace'];
          
                if(!$topicMapper->update($topic)) {
                    return $this->createErrorResponse($topicMapper->getError());
                }
                
                $storage = Storage::getInstance($this->config, $this->adapter);
                $target_path = $storage->getPathMicrolearningTopic();
                
                $storage->setFiles($request->getFiles()->toArray());

                if(!$storage->setCurrentFilename('file')) {
                    return $this->createErrorResponse('ERROR_UPLOAD_IMAGE');
                }

                list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
                $image_source_filename = $storage->getTmpFilename();
                $image_filename = 'topic-' . uniqid() . '.png';
                $image_target_filename = $storage->composePathToFilename(
                    Storage::TYPE_MICROLEARNING_TOPIC,
                    $topic->uuid,
                    $image_filename
                );

                if (!$storage->uploadImageCrop($image_source_filename, $image_target_filename, $target_width, $target_height)) {
                    return $this->createErrorResponse('ERROR_UPLOAD_IMAGE');
                }

                if(!$storage->setCurrentFilename('marketplace')) {
                    return $this->createErrorResponse('ERROR_UPLOAD_IMAGE');
                }

                $marketplace_source_filename = $storage->getTmpFilename();
                $marketplace_filename = 'marketplace-' . uniqid() . '.png';
                $marketplace_target_filename = $storage->composePathToFilename(
                    Storage::TYPE_MICROLEARNING_TOPIC,
                    $topic->uuid,
                    $marketplace_filename
                );

                if (!$storage->uploadImageCrop($marketplace_source_filename, $marketplace_target_filename, $target_width, $target_height)) {
                    return $this->createErrorResponse('ERROR_UPLOAD_IMAGE');
                }

                if($topic->image) {
                    if(!$storage->deleteFile($target_path, $topic->uuid, $topic->image)) {
                        return $this->createErrorResponse('ERROR_DELETING_FILE');
                    }
                }

                if($topic->marketplace) {
                    if(!$storage->deleteFile($target_path, $topic->uuid, $topic->marketplace)) {
                        return $this->createErrorResponse('ERROR_DELETING_FILE');
                    }
                }

                $topic->image = $image_filename;
                $topic->marketplace = $marketplace_filename;

                if(!$topicMapper->update($topic)) {
                    return $this->createErrorResponse($topicMapper->getError());
                }
                
                $this->logger->info('Se edito el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                
                return new JsonModel([
                    'success'   => true,
                    'data'   => 'LABEL_RECORD_UPDATED'
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->err('Error in editAction: ' . $e->getMessage());
            return $this->createErrorResponse('ERROR_INTERNAL_SERVER_ERROR');
        }
    }

     /**
     * Check if request is JSON
     * @param \Laminas\Http\Request $request
     * @return bool
     */
    private function isJsonRequest($request)
    {
        $headers = $request->getHeaders();
        if (!$headers->has('Accept')) {
            return false;
        }

        $accept = $headers->get('Accept');
        $prioritized = $accept->getPrioritized();
        
        foreach ($prioritized as $value) {
            if (strpos(trim($value->getRaw()), 'json') !== false) {
                return true;
            }
        }
        
        return false;
    }

    /**
     * Handle JSON request for datatable
     * @param \LeadersLinked\Model\User $currentUser
     * @param \LeadersLinked\Model\Company $currentCompany
     * @return \Laminas\View\Model\JsonModel
     */
    private function handleJsonRequest($currentUser, $currentCompany)
    {
        try {
            $search = $this->params()->fromQuery('search', []);
            $search = empty($search['value']) ? '' : Functions::sanitizeFilterString($search['value']);
            
            $recordsPerPage = intval($this->params()->fromQuery('length', 10), 10);
            $page = (intval($this->params()->fromQuery('start', 1), 10) / $recordsPerPage) + 1;
            
            $order = $this->params()->fromQuery('order', []);
            $orderField = empty($order[0]['column']) ? 99 : intval($order[0]['column'], 10);
            $orderDirection = empty($order[0]['dir']) ? 'ASC' : strtoupper(Functions::sanitizeFilterString($order[0]['dir']));
            
            $fields = ['name'];
            $orderField = isset($fields[$orderField]) ? $fields[$orderField] : 'name';
            
            if (!in_array($orderDirection, ['ASC', 'DESC'])) {
                $orderDirection = 'ASC';
            }

            $acl = $this->getEvent()->getViewModel()->getVariable('acl');
            $permissions = $this->getUserPermissions($acl, $currentUser);
            
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
            $paginator = $topicMapper->fetchAllDataTableByCompanyId(
                $currentCompany->id, 
                $search, 
                $page, 
                $recordsPerPage, 
                $orderField, 
                $orderDirection
            );

            $items = $this->prepareTopicItems($paginator->getCurrentItems(), $currentCompany, $permissions);

            $response = [
                'success' => true,
                'data' => [
                    'link_add' => $permissions['allowAdd'] ? $this->url()->fromRoute('microlearning/content/topics/add') : '',
                    'items' => $items,
                    'total' => $paginator->getTotalItemCount(),
                ]
            ];

            return new JsonModel($response);

        } catch (\Exception $e) {
            $this->logger->err('Error in handleJsonRequest: ' . $e->getMessage());
            return $this->createErrorResponse('ERROR_INTERNAL_SERVER_ERROR');
        }
    }

    /**
     * Handle HTML request for view
     * @param \LeadersLinked\Model\Company $currentCompany
     * @return \Laminas\View\Model\ViewModel
     */
    private function handleHtmlRequest($currentCompany)
    {
        $imageSize = $this->config['leaderslinked.image_sizes.microlearning_image_upload'];
        $marketplaceSize = $this->config['leaderslinked.image_sizes.marketplace'];
        
        $formAdd = new TopicAddForm($this->adapter, $currentCompany->id, $currentCompany->internal);
        $formEdit = new TopicEditForm($this->adapter, $currentCompany->id, $currentCompany->internal);

        $this->layout()->setTemplate('layout/layout-backend.phtml');
        $viewModel = new ViewModel();
        $viewModel->setTemplate('leaders-linked/microlearning-topics/index.phtml');
        $viewModel->setVariables([
            'formAdd' => $formAdd,
            'formEdit' => $formEdit,
            'company_uuid' => $currentCompany->uuid,
            'image_size' => $imageSize,
            'marketplace_size' => $marketplaceSize,
        ]);
        
        return $viewModel;
    }

    /**
     * Get user permissions for topic actions
     * @param \Laminas\Permissions\Acl\Acl $acl
     * @param \LeadersLinked\Model\User $currentUser
     * @return array
     */
    private function getUserPermissions($acl, $currentUser)
    {
        return [
            'allowAdd' => $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/add'),
            'allowEdit' => $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/edit'),
            'allowDelete' => $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/delete'),
            'allowUsers' => $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/users')
        ];
    }

    /**
     * Create error response
     * @param string $message
     * @return \Laminas\View\Model\JsonModel
     */
    private function createErrorResponse($message)
    {
        return new JsonModel([
            'success' => false,
            'data' => $message
        ]);
    }

     /**
     * Prepare topic items for datatable
     * @param array $records
     * @param \LeadersLinked\Model\Company $currentCompany
     * @param array $permissions
     * @return array
     */
    private function prepareTopicItems($records, $currentCompany, $permissions)
    {
        $items = [];
        $microlearningTopicUserMapper = MicrolearningTopicUserMapper::getInstance($this->adapter);
        $storage = Storage::getInstance($this->config, $this->adapter);
        $path = $storage->getPathMicrolearningTopic();

        foreach ($records as $record) {
            $totalUsers = $microlearningTopicUserMapper->fetchCountUsersByCompanyIdAndTopicId($currentCompany->id, $record->id);
            $totalUsersActive = $microlearningTopicUserMapper->fetchCountUsersActiveByCompanyIdAndTopicId($currentCompany->id, $record->id);

            $status = $this->getTopicStatus($record->status);
            $privacy = $this->getTopicPrivacy($record->privacy);
            $type = $this->getTopicType($record->type);

            $params = ['capsule_uuid' => $record->uuid];

            $items[] = [
                'name' => $record->name,
                'details' => [
                    'status' => $status,
                    'privacy' => $privacy,
                    'type' => $type,
                    'cost' => $record->cost,
                    'total_users' => $totalUsers,
                    'total_users_active' => $totalUsersActive,
                ],
                'images' => [
                    'image' => $storage->getGenericImage($path, $record->uuid, $record->image),
                ],
                'actions' => $this->prepareTopicActions($record, $permissions, $totalUsers, $totalUsersActive)
            ];
        }

        return $items;
    }

        /**
     * Get topic status label
     * @param int $status
     * @return string
     */
    private function getTopicStatus($status)
    {
        switch ($status) {
            case MicrolearningTopic::STATUS_ACTIVE:
                return 'LABEL_ACTIVE';
            case MicrolearningTopic::STATUS_INACTIVE:
                return 'LABEL_INACTIVE';
            default:
                return '';
        }
    }

    /**
     * Get topic privacy label
     * @param int $privacy
     * @return string
     */
    private function getTopicPrivacy($privacy)
    {
        switch ($privacy) {
            case MicrolearningTopic::PRIVACY_PUBLIC:
                return 'LABEL_PUBLIC';
            case MicrolearningTopic::PRIVACY_PRIVATE:
                return 'LABEL_PRIVATE';
            default:
                return '';
        }
    }

    /**
     * Get topic type label
     * @param int $type
     * @return string
     */
    private function getTopicType($type)
    {
        switch ($type) {
            case MicrolearningTopic::TYPE_FREE:
                return 'LABEL_FREE';
            case MicrolearningTopic::TYPE_PRIVATE:
                return 'LABEL_PRIVATE';
            case MicrolearningTopic::TYPE_SELLING:
                return 'LABEL_SELLING';
            default:
                return '';
        }
    }

     /**
     * Prepare topic actions
     * @param \LeadersLinked\Model\MicrolearningTopic $record
     * @param array $permissions
     * @param int $totalUsers
     * @param int $totalUsersActive
     * @return array
     */
    private function prepareTopicActions($record, $permissions, $totalUsers, $totalUsersActive)
    {
        $params = ['topic_uuid' => $record->uuid];

        return [
            'link_edit' => $permissions['allowEdit'] ? $this->url()->fromRoute('microlearning/content/topics/edit', $params) : '',
            'link_delete' => $permissions['allowDelete'] ? $this->url()->fromRoute('microlearning/content/topics/delete', $params) : '',
            'link_total_users' => $permissions['allowUsers'] && $totalUsers ? 
                $this->url()->fromRoute('microlearning/content/topics/users', [
                    'topic_uuid' => $record->uuid,
                    'type' => 'all'
                ]) : '',
            'link_total_users_actives' => $permissions['allowUsers'] && $totalUsersActive ? 
                $this->url()->fromRoute('microlearning/content/topics/users', [
                    'topic_uuid' => $record->uuid,
                    'type' => 'active'
                ]) : ''
        ];
    }
}