Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 1292 | Rev 2729 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php
/**
 * 
 * Controlador: Mis Perfiles 
 * 
 */
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\UserProfileMapper;
use LeadersLinked\Mapper\CompanyFollowerMapper;
use LeadersLinked\Mapper\LocationMapper;
use LeadersLinked\Mapper\UserLanguageMapper;
use LeadersLinked\Mapper\UserSkillMapper;

use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Mapper\UserEducationMapper;
use LeadersLinked\Mapper\DegreeMapper;
use LeadersLinked\Mapper\UserExperienceMapper;
use LeadersLinked\Mapper\IndustryMapper;
use LeadersLinked\Mapper\CompanySizeMapper;
use LeadersLinked\Mapper\ConnectionMapper;
use LeadersLinked\Mapper\UserBlockedMapper;
use LeadersLinked\Model\Connection;
use LeadersLinked\Mapper\ProfileVisitMapper;
use LeadersLinked\Model\ProfileVisit;
use LeadersLinked\Mapper\QueryMapper;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use LeadersLinked\Model\User;
use Laminas\Db\Sql\Expression;
use LeadersLinked\Mapper\LanguageMapper;
use LeadersLinked\Mapper\SkillMapper;


class ProfileController 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;

    }
    
    /**
     * 
     * Generación del listado de perfiles
     * {@inheritDoc}
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
     */
    public function indexAction()
    {
        $this->layout()->setTemplate('layout/layout.phtml');
        $viewModel = new ViewModel();
        $viewModel->setTemplate('leaders-linked/profile/index.phtml');
        return $viewModel ;
        
    }
    
   
    /**
     * Presenta el perfil con las opciónes de edición de cada sección
     * @return \Laminas\Http\Response|\Laminas\View\Model\ViewModel|\Laminas\View\Model\JsonModel
     */
    public function viewAction()
    {
        
        $request = $this->getRequest();
        if($request->isGet()) {
        
            
            $flashMessenger = $this->plugin('FlashMessenger');
            
    
            $id = $this->params()->fromRoute('id');
            if(!$id) {
                $flashMessenger->addErrorMessage('ERROR_INVALID_PARAMETER');
                return $this->redirect()->toRoute('dashboard');
            }
            
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOneByUuid($id);
            
            $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
            if($user) {
                $userProfile = $userProfileMapper->fetchOnePublicByUserId($user->id);
            } else {    
                $userProfile = $userProfileMapper->fetchOneByUuid($id);
            }
            
            if(!$userProfile) {
                $flashMessenger->addErrorMessage('ERROR_RECORD_NOT_FOUND');
                return $this->redirect()->toRoute('dashboard');
            }
            
            $currentUserPlugin = $this->plugin('currentUserPlugin');
            $currentUser = $currentUserPlugin->getUser();
    
            $userBlockedMapper = UserBlockedMapper::getInstance($this->adapter);
            $userBlocked = $userBlockedMapper->fetchOneByUserIdAndBlockedId($userProfile->user_id, $currentUser->id);
            
            if($userBlocked) {
                $flashMessenger->addErrorMessage('ERROR_UNAUTHORIZED');
                return $this->redirect()->toRoute('dashboard');
            }
            
            if($currentUser->id != $userProfile->user_id) {
                
                $visited_on = date('Y-m-d');;
                $profileVisitMapper = ProfileVisitMapper::getInstance($this->adapter);
                $profileVisit = $profileVisitMapper->fetchOneByVisitorIdAndVisitedIdAndVisitedOn($currentUser->id, $userProfile->user_id, $visited_on);
                if(!$profileVisit) {
                    $profileVisit = new ProfileVisit();
                    $profileVisit->user_profile_id = $userProfile->id;
                    $profileVisit->visited_id = $userProfile->user_id;
                    $profileVisit->visitor_id = $currentUser->id;
                    $profileVisit->visited_on = date('Y-m-d');
                    $profileVisitMapper->insert($profileVisit);
                }
            }
    
            if($userProfile->location_id) {
                $locationMapper= LocationMapper::getInstance($this->adapter);
                $location = $locationMapper->fetchOne($userProfile->location_id);
                    
                $formattedAddress = $location->formatted_address;
                $country = $location->country;
            } else {
                $formattedAddress = '';
                $country = '';
            }
            
            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($currentUser->id, $userProfile->user_id);
            
            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOne($userProfile->user_id);
                
            $userLanguages = [];
            $languageMapper = LanguageMapper::getInstance($this->adapter);
            $userLanguageMapper = UserLanguageMapper::getInstance($this->adapter);
            $records = $userLanguageMapper->fetchAllByUserProfileId($userProfile->id);
            foreach($records as $record)
            {
                $language = $languageMapper->fetchOne($record->language_id);
                $userLanguages[$language->id] = $language->name;
            }
            
            
            $locationMapper = LocationMapper::getInstance($this->adapter);
            
            $degreeMapper = DegreeMapper::getInstance($this->adapter);
            $userEducationMapper = UserEducationMapper::getInstance($this->adapter);
            $userEducations = $userEducationMapper->fetchAllByUserProfileId($userProfile->id);
                
            foreach($userEducations  as &$userEducation)
            {
                $location = $locationMapper->fetchOne($userEducation->location_id);
                $degree = $degreeMapper->fetchOne($userEducation->degree_id)    ;
                
                
                $userEducation = [
                    'university' => $userEducation->university,
                    'degree' => $degree->name,
                    'field_of_study' => $userEducation->field_of_study,
                    'grade_or_percentage' => $userEducation->grade_or_percentage,
                    'formatted_address' => $location->formatted_address,
                    'from_year' => $userEducation->from_year,
                    'to_year' => $userEducation->to_year,
                    'description' => $userEducation->description,
                ];
            }
               
            /*
            $industries = [];
            $industryMapper = IndustryMapper::getInstance($this->adapter);
            $records = $industryMapper->fetchAllActives();
            foreach($records as $record)
            {
                $industries[$record->uuid] = $record->name;
            }
                
            $companySizes = [];
            $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
            $records = $companySizeMapper->fetchAllActives();
            foreach($records as $record)
            {
                $companySizes[$record->uuid] = $record->name . ' ('.$record->minimum_no_of_employee . '-' . $record->maximum_no_of_employee .')';
            }
            */    
            
            $industryMapper = IndustryMapper::getInstance($this->adapter);
            $companySizeMapper = CompanySizeMapper::getInstance($this->adapter);
            
            
            $userExperienceMapper = UserExperienceMapper::getInstance($this->adapter);
            $userExperiences = $userExperienceMapper->fetchAllByUserProfileId($userProfile->id);
                
            foreach($userExperiences  as &$userExperience)
            {
                $industry = $industryMapper->fetchOne($userExperience->industry_id);
                $companySize = $companySizeMapper->fetchOne($userExperience->company_size_id);
                
                
                $location = $locationMapper->fetchOne($userExperience->location_id);
                    
                $userExperience = [
                    'company' => $userExperience->company,
                    'industry' => $industry->name,
                    'size' => $companySize->name . ' (' . $companySize->minimum_no_of_employee . ' - ' . $companySize->maximum_no_of_employee . ' ) ',
                    'title' => $userExperience->title,
                    'formatted_address' => $location->formatted_address,
                    'from_year' => $userExperience->from_year,
                    'from_month' => $userExperience->from_month,
                    'to_year' => $userExperience->to_year,
                    'to_month' => $userExperience->to_month,
                    'description' => $userExperience->description,
                    'is_current' => $userExperience->is_current,
                ];
            }
                
            $userSkills = [];
            $skillMapper = SkillMapper::getInstance($this->adapter);
            $userSkillMapper = UserSkillMapper::getInstance($this->adapter);
            $records  = $userSkillMapper->fetchAllByUserProfileId($userProfile->id);
            foreach($records as $record)
            {
                $skill = $skillMapper->fetchOne($record->skill_id);
                $userSkills[$skill->uuid] = $skill->name;
            }
            
            
            $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
            $following = $companyFollowerMapper->getCountFollowing($user->id);
                
            $connectionMapper = ConnectionMapper::getInstance($this->adapter);
            $total_connections = $connectionMapper->fetchTotalConnectionByUser($user->id);
    
            $request_connection = true;
            if($connection) {
                if($connection->status == Connection::STATUS_SENT || $connection->status == Connection::STATUS_ACCEPTED) {
                    $request_connection = false;
                }
            }
            
            $common_connection = count($connectionMapper->fetchAllCommonConnectionsUserIdByUser1ReturnIds($currentUser->id, $userProfile->user_id));
            
            $profileVisitMapper = ProfileVisitMapper::getInstance($this->adapter);
            $views          = $profileVisitMapper->getTotalByVisitedId( $userProfile->user_id );
            

            
            
            $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) {
            
                $data = [
                    'following'         => $following ,
                    'total_connections' => $total_connections,
                    'user_id'           => $user->uuid,
                    'user_uuid'         => ($user->uuid),
                    'full_name'         => trim($userProfile->name),
                    //'full_name'         => trim($user->first_name . ' ' . $user->last_name),
                    'user_profile_id'   => $userProfile->id,
                    'user_profile_uuid' => $userProfile->uuid,
                    'image'             => $this->url()->fromRoute('storage',['id' => $userProfile->uuid, 'type' => 'user-profile', 'filename' => $user->image]),
                    'cover'             => $this->url()->fromRoute('storage',['id' => $userProfile->uuid, 'type' => 'user-cover', 'filename' => $userProfile->cover]),
                    'overview'          => $userProfile->description,
                    'facebook'          => $userProfile->facebook,
                    'instagram'         => $userProfile->instagram,
                    'twitter'           => $userProfile->twitter,
                    'formatted_address' => $formattedAddress,
                    'country'           => $country,
                    'user_skills'       => $userSkills,
                    'user_languages'    => $userLanguages,
                    'user_educations'   => $userEducations,
                    'user_experiences'  => $userExperiences,
                    'common_connection' => $common_connection,
                    'views'             => $views,
                    'show_contact'          => $user->id != $currentUser->id,
                    'request_connection'    => $request_connection,
                    'link_cancel'           => $connection && $connection->status == Connection::STATUS_SENT ? $this->url()->fromRoute('connection/delete',['id' => $user->uuid ]) :  $this->url()->fromRoute('connection/cancel',['id' => $user->uuid]),
                    'link_request'          => $this->url()->fromRoute('connection/request',['id' => $user->uuid ]),
                    'link_inmail'           => $this->url()->fromRoute('inmail',['id' => $user->uuid ]),
                    
                ];
                
                return new JsonModel($data);
                
            } else {
             
            
                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/profile/view.phtml');
                $viewModel->setVariables([
                    'following'         => $following ,
                    'total_connections' => $total_connections,
                    'user_id'           => $user->uuid,
                    'user_uuid' => ($user->uuid),
                    'full_name'         => trim($userProfile->name),
                    //'full_name'         => trim($user->first_name . ' ' . $user->last_name),
                    'user_profile_id'   => $userProfile->id,
                    'user_profile_uuid' => $userProfile->uuid,
                    'image'             => $userProfile->image,
                    'cover'             => $userProfile->cover,
                    'overview'          => $userProfile->description,
                    'facebook'          => $userProfile->facebook,
                    'instagram'         => $userProfile->instagram,
                    'twitter'           => $userProfile->twitter,
                    'formatted_address' => $formattedAddress,
                    'country'           => $country,
                    'user_skills'       => $userSkills,
                    'user_languages'    => $userLanguages,
                    'user_educations'   => $userEducations,
                    'user_experiences'  => $userExperiences,
                    'show_contact'          => $user->id != $currentUser->id,
                    'request_connection'    => $request_connection, 
                    'link_cancel'           => $connection && $connection->status == Connection::STATUS_SENT ? $this->url()->fromRoute('connection/delete',['id' => $user->uuid ]) :  $this->url()->fromRoute('connection/cancel',['id' => $user->uuid]),
                    'link_request'          => $this->url()->fromRoute('connection/request',['id' => $user->uuid ]),
                    'link_inmail'           => $this->url()->fromRoute('inmail',['id' => $user->uuid ]),
                    
                ]);
                return $viewModel ;
            }
        }
        
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
        
        
        
    }
    
    public function peopleViewedProfileAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $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) {
                $page = (int) $this->params()->fromQuery('page');
                $search = trim(filter_var($this->params()->fromQuery('search', ''), FILTER_SANITIZE_STRING));
                
                $mapper = QueryMapper::getInstance($this->adapter);
                $select = $mapper->getSql()->select();
                $select->columns(['visitor_id' => new Expression('DISTINCT(visitor_id)')]);
                $select->from(['p' => ProfileVisitMapper::_TABLE]);
                $select->join(['u' => UserMapper::_TABLE], 'p.visitor_id = u.id ', ['uuid', 'first_name', 'last_name', 'image']);
                $select->where->equalTo('p.visited_id', $currentUser->id)->and->equalTo('u.status', User::STATUS_ACTIVE);
                
                if($search) {
                    $select->where->NEST->like('first_name', '%' . $search . '%')->or->like('last_name', '%' . $search . '%')->UNNEST;
                }
                $select->order('first_name','last_name');
                
                //echo $select->getSqlString($this->adapter->platform); exit;
                
                $dbSelect = new DbSelect($select, $this->adapter);
                $paginator = new Paginator($dbSelect);
                $paginator->setCurrentPageNumber($page ? $page : 1);
                $paginator->setItemCountPerPage(10);
                
                $items = [];
                $records = $paginator->getCurrentItems();
                
                foreach($records as $record)
                {
                    
                    $item = [
                        'name' => trim($record['first_name'] . ' ' . $record['last_name']),
                        'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $record['uuid'], 'filename' => $record['image'] ]),
                        'link_view' => $this->url()->fromRoute('profile/view', ['id' => $record['uuid']  ]),
                        'link_inmail'   => $this->url()->fromRoute('inmail', ['id' => $record['uuid']  ]),
                    ];
                    
                    array_push($items, $item);
                }
                
                $response = [
                    'success' => true,
                    'data' => [
                        'total' => [
                            'count' => $paginator->getTotalItemCount(),
                            'pages' => $paginator->getPages()->pageCount,
                        ],
                        'current' => [
                            'items'    => $items,
                            'page'     => $paginator->getCurrentPageNumber(),
                            'count'    => $paginator->getCurrentItemCount(),
                        ]
                    ]
                ];
                
                
                
                return new JsonModel($response);
            } else {
                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/profile/people-viewed-profile.phtml');
                return $viewModel ;
            }
            
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    
}