Proyectos de Subversion LeadersLinked - Antes de SPA

Rev

Rev 4632 | Rev 6749 | 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\Model\Page;
use LeadersLinked\Mapper\NotificationMapper;
use LeadersLinked\Mapper\CompanyMapper;
use LeadersLinked\Mapper\CompanyUserMapper;
use LeadersLinked\Model\Company;
use LeadersLinked\Mapper\PageMapper;
use LeadersLinked\Mapper\MessageMapper;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Mapper\UserProfileMapper;
use LeadersLinked\Mapper\CompanyUserRoleMapper;
use LeadersLinked\Model\Role;
use LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\ConnectionMapper;
use LeadersLinked\Mapper\LocationMapper;
use LeadersLinked\Mapper\PostMapper;
use LeadersLinked\Mapper\ProfileVisitMapper;
use LeadersLinked\Model\Post;
use LeadersLinked\Mapper\UtilMapper;
use LeadersLinked\Model\Notification;

class NotificationController extends AbstractActionController
{
    /**
     *
     * @var AdapterInterface
     */
    private $adapter;


    /**
     *
     * @var AbstractAdapter
     */
    private $cache;

    /**
     *
     * @var  LoggerInterface
     */
    private $logger;


    /**
     *
     * @var array
     */
    private $config;

    /**
     *
     * @param AdapterInterface $adapter
     * @param AbstractAdapter $cache
     * @param LoggerInterface $logger
     * @param array $config
     */
    public function __construct($adapter, $cache, $logger,  $config)
    {
        $this->adapter      = $adapter;
        $this->cache        = $cache;
        $this->logger       = $logger;
        $this->config       = $config;
    }



    public function indexAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {

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

            $userMapper = UserMapper::getInstance($this->adapter);
            $user = $userMapper->fetchOne($currentUser->id);

            $userProfileMapper = UserProfileMapper::getInstance($this->adapter);
            $userProfile = $userProfileMapper->fetchOnePublicByUserId($currentUser->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) {

                $utilMapper = UtilMapper::getInstance($this->adapter);
                $now = $utilMapper->getDatebaseNow();


                $notificationMapper = NotificationMapper::getInstance($this->adapter);
                $records = $notificationMapper->fetchAllByUserId($currentUser->id);



                $items = [];
                foreach ($records as $record) {

                    /*
                    if($record->read == Notification::NO) {
                       $notificationMapper->markAsReadById($record->id);
                    }*/

                    array_push($items, [
                        'message' => $record->message,
                        'link' => $record->url,
                        'link_delete' => $this->url()->fromRoute('notifications/delete', ['id' => $record->uuid]),
                        'time_elapsed' => Functions::timeAgo($record->added_on, $now),
                        'time' => $record->added_on
                    ]);
                }

                usort($items, function ($a, $b) {

                    if ($a['time'] == $b['time']) {
                        return 0;
                    } else {
                        return $a['time'] < $b['time'] ? -1 : 1;
                    }
                });

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

                if ($user->location_id) {
                    $locationMapper = LocationMapper::getInstance($this->adapter);
                    $location = $locationMapper->fetchOne($user->location_id);

                    $country = $location->country;
                } else {
                    $country = '';
                }

                $profileVisitMapper = ProfileVisitMapper::getInstance($this->adapter);
                $visits = $profileVisitMapper->getTotalByVisitedId($currentUser->id);

                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
                $connections = $connectionMapper->fetchTotalConnectionByUser($currentUser->id);

                $this->layout()->setTemplate('layout/layout.phtml');
                $viewModel = new ViewModel();
                $viewModel->setVariables([
                    'image' => $this->url()->fromRoute('storage', ['type' => 'user', 'code' => $user->uuid, 'filename' => $user->image]),
                    'fullname' => trim($user->first_name . ' ' . $user->last_name),
                    'description' => empty($userProfile->description) ? '' :  trim($userProfile->description),
                    'country' => $country,
                    'visits' => $visits,
                    'connections' => $connections,
                    'uuid' => $user->uuid,
                ]);

                $viewModel->setTemplate('leaders-linked/notifications/index.phtml');
                return $viewModel;
            }
        } else {
            $response = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
        }

        return new JsonModel($response);
    }

    public function unreadsAction()
    {
        $request = $this->getRequest();
        if ($request->isGet()) {

            $utilMapper = UtilMapper::getInstance($this->adapter);
            $now = $utilMapper->getDatebaseNow();

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

            $notificationMapper = NotificationMapper::getInstance($this->adapter);
            $records = $notificationMapper->fetchAllsUnreadByUserId($currentUser->id);

            $items = [];
            foreach ($records as $record) {
                array_push($items, [
                    'message' => $record->message,
                    'link' => $record->url,
                    'link_mark_read' => $this->url()->fromRoute('notifications/mark-read', ['id' => $record->uuid]),
                    'link_delete' => $this->url()->fromRoute('notifications/delete', ['id' => $record->uuid]),
                    'time_elapsed' => Functions::timeAgo($record->added_on, $now),
                    'time' => $record->added_on
                ]);
            }

            usort($items, function ($a, $b) {

                if ($a['time'] == $b['time']) {
                    return 0;
                } else {
                    return $a['time'] < $b['time'] ? -1 : 1;
                }
            });

            $total = $notificationMapper->fetchUnreadNotificationsCount($currentUser->id);

            $response = [
                'success' => true,
                'data' => [
                    'notifications' =>  $items,
                    'total' => $total,
                ],

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

        return new JsonModel($response);
    }

    public function markAllReadAction()
    {

        $request = $this->getRequest();

        if ($request->isPost()) {



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


            $notificationMapper = NotificationMapper::getInstance($this->adapter);

            $result = $notificationMapper->markAllAsReadByUserId($currentUser->id);

            if ($result) {
                $this->logger->info('Se marco como leidas todas las notificaciones de usuario: ' . $currentUser->id, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                $response = [
                    'success' => true,
                    'data' => 'LABEL_RECORD_UPDATED'
                ];
            } else {
                $response = [
                    'success' => false,
                    'data' => $notificationMapper->getError()
                ];
            }
        } else {
            $response = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
        }

        return new JsonModel($response);
    }

    public function markReadAction()
    {

        $request = $this->getRequest();

        if ($request->isPost()) {

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

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


            $notificationMapper = NotificationMapper::getInstance($this->adapter);
            $notification = $notificationMapper->fetchOneByUuid($uuid);

            if (!$notification) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_NOTIFICATION_NOT_FOUND'
                ];

                return new JsonModel($response);
            }

            if ($currentUser->id != $notification->user_id) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_NOTIFICATION'
                ];

                return new JsonModel($response);
            }

            $result = $notificationMapper->markAsReadById($notification->id);
            if ($result) {
                $this->logger->info('Se marco una notificación del usuario: ' . $currentUser->id, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                $response = [
                    'success' => true,
                    'data' => 'LABEL_RECORD_UPDATED'
                ];
            } else {
                $response = [
                    'success' => false,
                    'data' => $notificationMapper->getError()
                ];
            }
        } else {
            $response = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
        }

        return new JsonModel($response);
    }

    public function deleteAction()
    {

        $request = $this->getRequest();

        if ($request->isPost()) {

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

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


            $notificationMapper = NotificationMapper::getInstance($this->adapter);
            $notification = $notificationMapper->fetchOneByUuid($uuid);

            if (!$notification) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_NOTIFICATION_NOT_FOUND'
                ];

                return new JsonModel($response);
            }

            if ($currentUser->id != $notification->user_id) {
                $response = [
                    'success' => false,
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_NOTIFICATION'
                ];

                return new JsonModel($response);
            }

            $result = $notificationMapper->deleteById($notification->id);
            if ($result) {
                $this->logger->info('Se borro una notificación del usuario: ' . $currentUser->id, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                $response = [
                    'success' => true,
                    'data' => 'LABEL_RECORD_DELETED'
                ];
            } else {
                $response = [
                    'success' => false,
                    'data' => $notificationMapper->getError()
                ];
            }
        } else {
            $response = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
        }

        return new JsonModel($response);
    }


    public function clearAction()
    {

        $request = $this->getRequest();

        if ($request->isPost()) {


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


            $notificationMapper = NotificationMapper::getInstance($this->adapter);

            $result = $notificationMapper->deleteAllByUserId($currentUser->id);
            if ($result) {
                $this->logger->info('Se borraron todas las notificaciones del usuario: ' . $currentUser->id, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
                $response = [
                    'success' => true,
                    'data' => 'LABEL_RECORD_DELETED'
                ];
            } else {
                $response = [
                    'success' => false,
                    'data' => $notificationMapper->getError()
                ];
            }
        } else {
            $response = [
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ];
        }

        return new JsonModel($response);
    }
}