Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 6749 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php

declare(strict_types=1);

namespace LeadersLinked\Library;


use Laminas\Db\Adapter\AdapterInterface;

use Laminas\View\Renderer\PhpRenderer;
use Laminas\Log\LoggerInterface;
use Laminas\Authentication\AuthenticationService;
use LeadersLinked\Mapper\NotificationMapper;
use LeadersLinked\Mapper\MessageMapper;
use LeadersLinked\Mapper\ConnectionMapper;
use LeadersLinked\Mapper\QueryMapper;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Mapper\FeedMapper;
use LeadersLinked\Mapper\GroupMapper;
use LeadersLinked\Mapper\JobMapper;
use LeadersLinked\Mapper\CompanyMapper;
use Laminas\View\Model\ViewModel;
use LeadersLinked\Model\Message;
use LeadersLinked\Model\Connection;
use LeadersLinked\Model\Notification;
use LeadersLinked\Mapper\UserExperienceMapper;
use Laminas\Db\Sql\Select;


class UserNotification
{
    const NOTIFICATION_TYPE_UNREAD = 'unread';
    const NOTIFICATION_TYPE_REGULAR = 'regular';
    
    
    /**
     *
     * @var AdapterInterface
     */
    private $adapter;

    
    /**
     *
     * @var  LoggerInterface
     */
    private $logger;
    
    
    /**
     *
     * @var  PhpRenderer
     */
    private $phpRender;
    
    /**
     *
     * @var integer
     */
    private $session_user_id;
    
    /**
     *
     * @var integer
     */
    private $session_language_id;
    
    /**
     *
     * @param AdapterInterface $adapter
     * @param LoggerInterface $logger
     */
    public function __construct(AdapterInterface $adapter, LoggerInterface $logger, PhpRenderer $phpRender)
    {
        $this->adapter          = $adapter;
        $this->logger           = $logger;
        $this->phpRender        = $phpRender;
        
        $authService = new AuthenticationService();
        if($authService->hasIdentity()) {
            $identity = $authService->getIdentity();
            $this->session_user_id = (int) $identity['user_id'];
        } else {
            $this->session_user_id = 0;
        }
        
        $this->session_language_id = 1;
    }
    
    /**
     * 
     * @return int
     */
    public function getUnreadNotificationsCount() 
    {

    }
    /**
     * 
     * @return int
     */
    public function getUnreadMessagesCount() 
    {
        $messageMapper = MessageMapper::getInstance($this->adapter);
        return $messageMapper->fetchUnreadMessagesCount($this->session_user_id);
    }

    /**
     * 
     * @return int
     */
    public function getConnectionRequestCount() 
    {
        $connectionMapper = ConnectionMapper::getInstance($this->adapter);
        return $connectionMapper->fetchConnectionRequestCount($this->session_user_id);
    }

    /**
     * 
     * @return boolean
     */
    public function markNotificationsAsRead() 
    {
        $notificationMapper = NotificationMapper::getInstance($this->adapter);
        return $notificationMapper->markNotificationsAsRead($this->session_user_id);
    }
    
    /**
     * 
     * @param int $currentPage
     * @param string $notification_type
     * @return string
     */
    public function getNotifications($currentPage = 1, $notification_type = self::NOTIFICATION_TYPE_REGULAR) 
    {
        
       
        
        
        $content = '';

        $queryMapper = QueryMapper::getInstance($this->adapter);
        $now = $queryMapper->getDatebaseNow();
        
        $select = $queryMapper->getSql()->select(NotificationMapper::_TABLE);
        $select->where->equalTo('user_id', $this->session_user_id);
        if ($notification_type ==  self::NOTIFICATION_TYPE_UNREAD) {
            $select->where->and->equalTo('is_notified', UserNotification::IS_NOTIFIED_NO);
        }
        $select->order('id DESC');
        
        $dbSelect = new DbSelect($select, $this->adapter);
        $paginator = new Paginator($dbSelect);
        $paginator->setCurrentPageNumber($currentPage);
        $paginator->setItemCountPerPage(NO_OF_NOTIFICATIONS_PER_PAGE);

        $notifications = []; 
        $items = $paginator->getCurrentItems();
        
        
        if ($items) {
            $notificationMapper = NotificationMapper::getInstance($this->adapter);

            foreach ($items as $item) 
            {
                
                $time_ago               = Functions::timeAgo($item['added_on'],  $now);
                $type                   = $item['type'];
                $action_by_user_id      = (int) $item['action_by_user_id'];
                $action_by_user_name    = '';
                $action_by_user_picture = '';
                $feed_id                = (int) $item['feed_id'];
                $group_id               = (int) $item['group_id'];
                $job_id                 = (int) $item['job_id'];
                $company_id             = (int) $item['company_id'];
                $post_title             = '';
                $group_name             = '';
                $job_title              = '';
                $company_name           = '';
                
                if ($action_by_user_id) {
                    $userMapper = UserMapper::getInstance($this->adapter);
                    $user = $userMapper->fetchOne($action_by_user_id);
                    $action_by_user_picture = $user->avatar;
                    $action_by_user_name = $user->first_name . ' '.  $user->last_name;
                }
                if ($feed_id) {
                    $feedMapper = FeedMapper::getInstance($this->adapter);
                    $feed = $feedMapper->fetchOne($feed_id);
                    $post_title = $feed->post_title;
                }
                if ($group_id) {
                    $groupMapper = GroupMapper::getInstance($this->adapter);
                    $group = $groupMapper->fetchOne($group_id);
                    $group_name = $group->group_name;
                }
                if ($job_id) {
                    $jobMapper = JobMapper::getInstance($this->adapter);
                    $job = $jobMapper->fetchOne($job_id);
                    $job_title = $job->job_title;
                }
                if ($company_id) {
                    $companyMapper = CompanyMapper::getInstance($this->adapter);
                    $company = $companyMapper->fetchOne($company_id);
                    

                    $company_name = $company->company_name;
                }
                
                if($action_by_user_picture) {
                    $user_img = $this->url('storage', ['type' => 'user', 'filename' => 'th2_' . $action_by_user_picture, 'code' => Functions::encryptIt($action_by_user_id)]);
                    
                } else {
                    $user_img = URL_USER_DEFAULT_AVATAR;
                }
                
                switch ($type) {
                    case Notification::TYPE_CONNECTION_REQUEST_ACCEPTED : 
                        $notification_text  = LABEL_COM_DET_YOUR_CONNECTION_REQUEST_ACCEPTED .' '. $action_by_user_name;
                        $notification_url   = $this->url('user', ['user_id' =>  Functions::encryptIt($action_by_user_id)]);
                        $notification_title = LABEL_CONNECTION_REQUEST_ACCEPTED;
                        break;
                    
                    
                    case Notification::TYPE_LIKE : 
                        $notification_text  = $action_by_user_name .' '. LABEL_LIKED_YOUR_POST . $post_title;
                        $notification_url   = $this->url('feed', ['feed_id' =>  Functions::encryptIt($feed_id)]);
                        $notification_title = $action_by_user_name .' '. LABEL_LIKED_YOUR_POST. $post_title;
                        break;
                    
                    case Notification::TYPE_COMMENT :
                        $notification_text  = $action_by_user_name.' ' . LABEL_COMMENTED_ON_YOUR_POST.' ' . $post_title;
                        $notification_url   = $this->url('feed', ['feed_id' =>  Functions::encryptIt($feed_id)]);
                        $notification_title = $action_by_user_name.' ' . LABEL_COMMENTED_ON_YOUR_POST.' ' . $post_title;
                        break;
              
                    case Notification::TYPE_SHARE : 
                        $notification_text  = $action_by_user_name.' ' . LABEL_SHARED_YOUR_POST.' ' . $post_title;
                        $notification_url   = $this->url('feed', ['feed_id' =>  Functions::encryptIt($feed_id)]);
                        $notification_title = $action_by_user_name.' ' . LABEL_SHARED_YOUR_POST.' ' . $post_title;
                        break;
                    
                    case Notification::TYPE_RECEIVED_GROUP_JOINING_INVITATION : 
                        $notification_text  = $action_by_user_name.' ' .  LABEL_SENT_INVITATION.' ' . $group_name;
                        $notification_url   = $this->url('group', ['group_id' =>  Functions::encryptIt($group_id)]);
                        $notification_title = LABEL_GROUP_JOINING_INVITATION;
                        break;
                    
                    case Notification::TYPE_RECEIVED_GROUP_JOINING_REQUEST : 
                        $notification_text  = $action_by_user_name.' ' . LABEL_SENT_INVITATION.' ' . $group_name;
                        $notification_url   = $this->url('group-received-invitation', ['group_id' =>  Functions::encryptIt($group_id)]); //get_group_detail_url($group_id).'?received-invitation';
                        $notification_title = LABEL_GROUP_JOINING_INVITATION;
                        break;
                    
                    case Notification::TYPE_GROUP_JOINING_REQUEST_ACCEPTED : 
                        $notification_text  = $action_by_user_name.' ' .  LABEL_ACCEPTED_YOUR_REQUEST_FOR_JOINING_GROUP.' '  . $group_name;
                        $notification_url   = $this->url('group', ['group_id' =>  Functions::encryptIt($group_id)]);
                        $notification_title = LABEL_GROUP_JOINING_REQUEST_ACCEPTED;
                        break;
                    
                    case Notification::TYPE_APPLIED_ON_JOB : 
                        $notification_text  = $action_by_user_name.' ' .  LABEL_APPLIED_ON_JOB.' ' . $job_title;
                        $notification_url   = $this->url('job-applicants', ['job_id' =>  Functions::encryptIt($job_id)]);
                        $notification_title = LABEL_APPLIED_ON_JOB_CAPITAL;
                        break;
                    
                    case Notification::TYPE_FOLLOW_COMPANY : 
                        $notification_text  = $action_by_user_name.' ' . LABEL_FOLLOWED_COMPANY.' ' . $company_name;
                        $notification_url   = $this->url('company-followers', ['company_id' =>  Functions::encryptIt($company_id)]); //get_company_detail_url($company_id).'?company-followers';
                        $notification_title = LABEL_FOLLOW_COMPANY;
                        break;
                    
                    case Notification::TYPE_NEW_FEED_POSTED_IN_GROUP :
                        $notification_text  = $action_by_user_name.' ' . LABEL_POSTED_GROUP.' ' . $group_name;
                        $notification_url   = $this->url('group-feed', ['group_id' =>  Functions::encryptIt($group_id), 'feed-id' => Functions::encryptIt($feed_id)]); //get_group_detail_url($group_id).'?id='.encryptIt($feed_id).'#'.encryptIt($feed_id);
                        $notification_title = LABEL_NEW_POST;
                        break;
                    
                    case Notification::TYPE_ADD_MEMBER_IN_PRIVATE_GROUP : 
                        $notification_text  = $action_by_user_name.' ' .LABEL_ADDED_IN_GROUP.' '. $group_name;
                        $notification_url   = $this->url('group', ['group_id' =>  Functions::encryptIt($group_id)]);
                        $notification_title = LABEL_ADDED_MEMBER;
                        break;
                    
                }
                
                array_push($notifications, [
                    'text'  => $notification_text,
                    'url'   => $notification_url,
                    'title' => $notification_title,
                    'time'  => $time_ago,
                    'image' => $user_img
                ]);
                
                $notificationMapper->markNotificationsAsNotified((int) $item['id'], $this->session_user_id);
            }
            
            $viewModel = new ViewModel();
            $viewModel->setTerminal(true);
            $viewModel->setTemplate('leaders-linked/notifications/single-notification-header.phtml');
            $viewModel->setVariables([
               'notifications' => $notifications 
            ]);
            
            $content = $this->phpRender->render($viewModel);
            
            if($paginator->count() > 1) {
                $viewModel = new ViewModel();
                $viewModel->setTerminal(true);
                $viewModel->setTemplate('leaders-linked/notifications/view-all-notification.phtml');
                $viewModel->setVariables([
                    'view_all_notification_url' => $this->url('view-all-notification')
                ]);
                
                $content .= $this->phpRender->render($viewModel);
            }
            
        } else {
            $viewModel = new ViewModel();
            $viewModel->setTerminal(true);
            $viewModel->setTemplate('leaders-linked/notifications/no-result-found.phtml');
            
            $content = $this->phpRender->render($viewModel);
        }
        return $content;
    }
    
    /**
     * 
     * @param int $currentPage
     * @return array
     */
    public function getMessages(int $currentPage = 1) 
    {
       
        
        
        $queryMapper = QueryMapper::getInstance($this->adapter);
        $now = $queryMapper->getDatebaseNow();
        
        $select = $queryMapper->getSql()->select(MessageMapper::_TABLE);
        $select->where->equalTo('user_id', $this->session_user_id)->and->equalTo('receiver_status', Message::STATUS_NORMAL); 
        $select->group('conversation_id');
        $select->order('id DESC');
        
        $dbSelect = new DbSelect($select, $this->adapter);
        $paginator = new Paginator($dbSelect);
        $paginator->setCurrentPageNumber($currentPage);
        $paginator->setItemCountPerPage(NO_OF_NOTIFICATIONS_PER_PAGE);

        $content = '';
        $items = $paginator->getCurrentItems();
        if ($items) {
            
            $messages = [];
            foreach($items as $item) 
            {
                $action_by_user_id      = (int) $item['sender_id'];
                $action_by_user_name    = '';
                $user_img               = '';
                if ($action_by_user_id) {
                    $userMapper = UserMapper::getInstance($this->adapter);
                    $user = $userMapper->fetchOne($action_by_user_id);
                    
                    if($user->avatar) {
                        $user_img = $this->url('storage', ['type' => 'user', 'filename' => 'th2_' . $user->avatar,  'code' => Functions::encryptIt($user->id)]);
                    } else {
                        $user_img = URL_USER_DEFAULT_AVATAR;
                    }
                    $action_by_user_name = $user->first_name . ' ' . $user->last_name;
                }

                array_push($messages, [
                    'title'         => $action_by_user_name,
                    'text'          => $item['message'],
                    'url'           => $this->url('messaging/thread', ['conversation_id' => Functions::encryptIt($item['conversation_id'])] ).'/#message',
                    'time'          => Functions::timeAgo($item['sent_on'], $now),
                    'image'         => $user_img,
                    'active_class'  => $item['is_read'] == Message::YES ? 'active' : ''
                ]);
                
            }
            
            
            $viewModel = new ViewModel();
            $viewModel->setTerminal(true);
            $viewModel->setTemplate('leaders-linked/notification/single-message-header.phtml');
            $viewModel->setVariables([
                'messages' => $messages
            ]);
            
            $content = $this->phpRender->render($viewModel);
            
            if ($paginator->count() > 1) {
                $viewModel = new ViewModel();
                $viewModel->setTerminal(true);
                $viewModel->setTemplate('leaders-linked/common/load-more-li.phtml');
                $viewModel->setVariables([
                    'load_more_link' => $this->url('load-more-messages/page', ['page' => $paginator->getCurrentPageNumber() + 1 ])
                ]);
                
                $content .= $this->phpRender->render($viewModel);
            }
            $consersationFound = true;
        } else {
            $consersationFound = false;
            
            $viewModel = new ViewModel();
            $viewModel->setTerminal(true);
            $viewModel->setTemplate('leaders-linked/common/no-result-found.phtml');

            $content = $this->phpRender->render($viewModel);
            
        }

        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        $viewModel->setTemplate('leaders-linked/common/view-all-notification.phtml');
        $viewModel->setVariables([
            'view_all_notification_url' => $this->url('messaging')
        ]);
        
        
        $view_all_messages = $this->phpRender->render($viewModel);
        $response = [
            'consersationFound' => $consersationFound ? true : false,
            'content'           => $content,
            'view_all_messages' => $view_all_messages
        ];    
        return $response;
    }
    
    /**
     * 
     * @param int $currentPage
     * @param bool $invitation_pagination
     * @return string
     */
    public function getConnectionRequest(int $currentPage = 1, bool $invitation_pagination = true) 
    {
        $queryMapper = QueryMapper::getInstance($this->adapter);
        $select = $queryMapper->getSql()->select();
        $select->columns(['id', 'request_from', 'request_to']);
        $select->from(['c' => ConnectionMapper::_TABLE]);
        $select->join(['au' => UserMapper::_TABLE], 'u.id = c.request_from', ['first_name','last_name', 'avatar']);
        $select->join(['ue' => UserExperienceMapper::_TABLE], 'ue.company_id = com.id', ['job_title'], Select::JOIN_LEFT);
        $select->join(['com' => CompanyMapper::_TABLE], 'ue.company_id = com.id', ['company_name'], Select::JOIN_LEFT);
        $select->where->equalTo('c.request_to', $this->session_user_id)->and->equalTo('status', Connection::STATUS_SENT);
        $select->group(' c.id');
        $select->order('id DESC');
        
        $dbSelect = new DbSelect($select, $this->adapter);
        $paginator = new Paginator($dbSelect);
        $paginator->setCurrentPageNumber($currentPage);
        $paginator->setItemCountPerPage(NO_OF_NOTIFICATIONS_PER_PAGE);
        
        
        $items = $paginator->getCurrentItems();

        if ($items) {
            
            $connections = [];
            
            foreach($items as $item)
            {
                $action_by_user_id      = $item['request_from'];
                $action_by_user_name    = $item['first_name'] . ' ' . $item['last_name'];
                $message_text           = $action_by_user_name .' '. LABEL_SENT_CONNECTION_REQUEST;
                $message_title          = $action_by_user_name;
                if($item['avatar']) {
                    $user_img = $this->url('storage', ['type' => 'user', 'filename' => $item['avatar'], 'code' => Functions::encryptIt($action_by_user_id)]);
                } else {
                    $user_img = URL_USER_DEFAULT_AVATAR;
                }
                
                
                array_push($connections, [
                    'user_img' => $user_img,
                    'message_title' => $message_title,
                    'message_text' => $message_text,
                    'encrypted_user_id' => Functions::encryptIt($action_by_user_id)
                ]);

                
            }
            
            $viewModel = new ViewModel();
            $viewModel->setTerminal(true);
            $viewModel->setTemplate('leaders-linked/common/single-connection-header.phtml');
            $viewModel->setVariables([
                'connections' => $connections
            ]);
            
            $content = $this->phpRender->render($viewModel);;
            
        } else {
            $viewModel = new ViewModel();
            $viewModel->setTerminal(true);
            $viewModel->setTemplate('leaders-linked/common/no-connection-requests.phtml');
            $content = $this->phpRender->render($viewModel);;
        }

        return $content;
    }

    /**
     * 
     * @return string[]
     */
    public function getAllNotifications() 
    {
        $response = [];
        $response['general_notifications']      = $this->getNotifications();
        $response['job_notifications']          = '';
        $response['company_notifications']      = '';
        $response['group_notifications']        = '';
        
        $messages                               = $this->getMessages();
        $response['consersationFound']          = $messages['consersationFound'];
        $response['messages']                   = $messages['content'];
        $response['view_all_messages']          = $messages['view_all_messages'];

        $response['connection_request']         = $this->getConnectionRequest();
        $response['notifications_count']        = $this->getUnreadNotificationsCount();
        $response['messages_count']             = $this->getUnreadMessagesCount();
        $response['connection_request_count']   = $this->getConnectionRequestCount();
        return $response;
    }
}