src/Controller/Licensor/DefaultController.php line 201

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Licensor;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use App\Entity\Module;
  7. use App\Util\AccessControl;
  8. use App\Controller\ParametersNormalizerController;
  9. use App\Controller\Licensor\ContainerController;
  10. use App\Util\WS\Util;
  11. use App\Util\Util AS Utiles;
  12. use App\Entity\BellNotificationSeenBy;
  13. use App\Entity\SecurityActivityUser;
  14. use App\Entity\Partner;
  15. use App\Entity\DocusignAuthorizationUser;
  16. use App\Entity\WebService;
  17. use App\Util\Util as Util2;
  18. use DateTime;
  19. /**
  20.  * DefaultController
  21.  */
  22. class DefaultController extends ParametersNormalizerController {
  23.     public function dashboard(Request $requestContainerController $cc) {
  24.         if ('anon.' == $this->get('security.token_storage')->getToken()->getUser()) {
  25.             return $this->redirect($this->generateUrl('level_licensor_logout'));
  26.         }
  27.         $em $this->getDoctrine()->getManager();
  28.         $idActivity $request->getSession()->get("activitySecurityId");
  29.         $checkActivity false;
  30.         if (isset($idActivity) && strlen($idActivity) == 36) {
  31.             $resultInfoActivity $em->getRepository('App\Entity\SecurityActivityUser')->findOneBy(["id" =>  $idActivity"sauIpAddress" => null ]);
  32.             $checkActivity = (isset($resultInfoActivity) ? true false );
  33.             
  34.         }
  35.         $session $request->getSession();
  36.         $userSession $this->get('security.token_storage')->getToken()->getUser();
  37.         $userId $userSession->getId();
  38.         $user $em->getRepository('App\Entity\User')->findOneBy(['id' => $userId]);
  39.         $em $this->getDoctrine()->getManager();
  40.         $partnerInformation $em->getRepository('App\Entity\Partner')->getAllPartnersWithoutRelationUser();
  41.         if(count($partnerInformation) > 0){
  42.             $lastId $partnerInformation[count($partnerInformation)-1]->getId();
  43.         }else{
  44.             $lastId 0;
  45.         }
  46.         $date Utiles::getCurrentDate();
  47.         $date date_format($date'm/d/Y');
  48.     
  49.         $tasksInformation $em->getRepository('App\Entity\PlanningTask')->getActiveTasksFromLast($userId,$date);
  50.         $partnerAsociation $em->getRepository('App\Entity\Partner')->getAllPartnersWithoutRelationUser($user);
  51.         $expiredTasks $em->getRepository('App\Entity\PlanningTask')->getExpiredTasks($userId,$date);
  52.         $partnerNotChecked $em->getRepository('App\Entity\Partner')->getPartnersNotChecked($user);
  53.         $container $cc->getContainer();
  54.         $translator $container->get('translator');
  55.         $lenguage = [];
  56.         for ($i=0$i <$i++) { 
  57.             $lenguage[$i] = $translator->trans('configuration.languages.'$i);
  58.         }
  59.         // dump($session);die();
  60.         return $this->render('Default\dashboard.html.twig', array(
  61.             'menu' => 'dashboard',
  62.             'checkActivity' => $checkActivity,
  63.             'partnerInformation' => $partnerInformation,
  64.             'tasksInformation' => $tasksInformation,
  65.             'partnerAsociation' => $partnerAsociation,
  66.             'partnerNotChecked' => $partnerNotChecked,
  67.             'expiredTasks' => $expiredTasks,
  68.             'userData' => $user,
  69.             'lastId' => $lastId,
  70.             'lenguage' => $lenguage
  71.         ));
  72.     }
  73.     public function updateLanguage(Request $reqContainerController $cc) {
  74.         $session $req->getSession();
  75.         $em $this->getDoctrine()->getManager();
  76.         $params $cc->getContentInRequest($req);
  77.         $userSession $this->get('security.token_storage')->getToken()->getUser();
  78.         $userId $userSession->getId();
  79.         $user $em->getRepository('App\Entity\User')->findOneBy(['id' => $userId]);
  80.         $user->setLanguage($params["data"]["application_language"]);
  81.         
  82.         $em->persist($user);
  83.         $em->flush();
  84.         $session->set('lenguage', ($user->getLanguage() == 0) ? 'en' 'es');
  85.         $container $cc->getContainer();
  86.         $translator $container->get('translator');
  87.         $this->addFlash('notice'$translator->trans('configuration.save_successful'));
  88.         return $this->redirect($this->generateUrl('level_licensor_homepage'));
  89.     }
  90.     /**
  91.      * @return type
  92.      */
  93.     public function getMyNotiesForTheBell() {
  94.         $theToken $this->get('security.token_storage')->getToken();
  95.         $em $this->getDoctrine()->getManager();
  96.         $actualDate Util::getCurrentDate();
  97.         $actualDate->modify('-1 day');
  98.         $numberOfNewNotifications 0;
  99.         $notificationsArrayToShowInBell = [];
  100.         if ($theToken) {
  101.             $user $theToken->getUser();
  102.             $littleBellNotiRepo $em->getRepository('App\Entity\BellNotificationSeenBy');
  103.             $numberOfNewNotifications $littleBellNotiRepo->searchAndCountAllNewNotificationsToBell($user$actualDate);
  104.             $notificationsToShowInBell $littleBellNotiRepo->searchAndGetAllNotificationsToBell($user$actualDate);
  105.             foreach ($notificationsToShowInBell as $index => $notiToSetAsReaded) {
  106.                 $notificationsArrayToShowInBell[$index] = $notiToSetAsReaded->showEverything();
  107.                 $notificationsArrayToShowInBell[$index]['userWhoSaw'] = $notiToSetAsReaded->getUserWhoSaw();
  108.                 $notificationsArrayToShowInBell[$index]['seenNotification'] = $notiToSetAsReaded->getSeenNotification();
  109.                 
  110.                 $codeAreReset explode('>'$notiToSetAsReaded->getSeenNotification()->getNotificationMsg());
  111.                 
  112.                 if (isset($codeAreReset[1])) {
  113.                     $codeAreReset explode('<'$codeAreReset[1]);
  114.                     if (isset($codeAreReset[0])) {
  115.                         $codesEntity $em->getRepository('App\Entity\FoundRaisePlansCode')->findBy(['frpcCode' => $codeAreReset[0], 'deletedAt' => null]);
  116.                     }
  117.                 }
  118.                 if (isset($codesEntity) && isset($codesEntity[0])) {
  119.                     $notificationsArrayToShowInBell[$index]['inFancy'] = true;
  120.                 }
  121.             }
  122.         } else {
  123.             $user null;
  124.         }
  125.         return $this->render('Default\defaultNotificationBell.html.twig', [
  126.             'user' => $user,
  127.             'numberOfNewNotifications' => $numberOfNewNotifications,
  128.             'notificationsToShowInBell' => $notificationsArrayToShowInBell
  129.         ]);
  130.     }
  131.     public function getTicketsForSupport(){
  132.         $em $this->getDoctrine()->getManager();
  133.         $tickets $em->getRepository('App\Entity\Ticket')->findTicketByOrder();
  134.         $numberOfTickets count($tickets);
  135.         return $this->render('Default\defaultTicketList.html.twig', [
  136.             'tickets' => $tickets,
  137.             'numberOfTickets' => $numberOfTickets
  138.         ]);
  139.     }
  140.     /**
  141.      * Esta funcion permite validar el acceso de los usuarios del backend al sistema
  142.      */
  143.     public function login(Request $request$id null$key null) {
  144.         $helper $this->get('symfony_security_authentication_utils');
  145.         $em $this->getDoctrine()->getManager();
  146.         
  147.         $msg $request->query->get('msg');
  148.         $csrfToken $this->get('security.csrf.token_manager')->getToken('authenticate')->getValue();
  149.         return $this->render('Default\login.html.twig', array(
  150.             'error' => $helper->getLastAuthenticationError(),
  151.             'last_username' => $helper->getLastUsername(),
  152.             'msg' => $msg,
  153.             'csrf_token' => $csrfToken
  154.         ));
  155.     }
  156.     /**
  157.      * Esta funcion se encarga de crear una variable de session que
  158.      * aumentara segun la cantidad de intentos de login que tenga el
  159.      * usuario
  160.      */
  161.     public function sessionByLoginCompany(Request $request) {
  162.         $response = [];
  163.         $session $request->getSession();
  164.         
  165.         if ($request->getMethod() == 'POST') {
  166.             $value $request->request->get('model');
  167.             $session->set(sha1('counterRequestAjaxPostCompany'), $value);
  168.             $response['result'] = '__OK__';
  169.         }
  170.         $r = new Response(json_encode($response));
  171.         $r->headers->set('Content-Type''application/html');
  172.         return $r;
  173.     }
  174.     /**
  175.      * Esta funcion permite validar los permisos del usuario logueado y guardarlos en un arreglo en session
  176.      * el cual se usara en toda la aplicacion para mostrar u ocultar iconos y enlaces a los modulos correctos
  177.      *
  178.      * @return \HttpRequest pagina de inicio de la aplicacion
  179.      */
  180.     public function accessControl(Request $request) {
  181.         $theToken $this->get('security.token_storage')->getToken();
  182.         $path Util::getValidActiveLogByBaseName($this->realContainer'securityActivity''securityActivity0.txt');
  183.         $em $this->getDoctrine()->getManager();
  184.         if (null != $theToken) {
  185.             $user $theToken->getUser();
  186.             $rolesArray $user->getRoles();
  187.             if (!empty($rolesArray) && $rolesArray[0] == 'ROLE_INACTIVE') {
  188.                 $request->getSession()->invalidate(1);
  189.                 sleep(1);
  190.                 return $this->redirect($this->generateUrl('level_licensor_login', ['msg' => 'User Inactive']));
  191.             }
  192.             
  193.             $search['only_active'] = true;
  194.             $modulesUserCompany $em->getRepository('App\Entity\UserModules')->findUserModulesToEdition($user->getId(), $search);
  195.             
  196.             $activeModules = [];
  197.             for ($i 0$i count($modulesUserCompany); $i++) {
  198.                 $activeModules[$i] = $modulesUserCompany[$i]->getUmModule()->getMoSlug();
  199.                 // dump( $activeModules[$i]);
  200.                 // die;
  201.             }
  202.             $session $request->getSession();
  203.             $session->set('activeModules'$activeModules);
  204.             $paramsAux = [
  205.                 "userAgent" => $request->headers->get('User-Agent'),
  206.                 "userId" => $user->getId(),
  207.                 "clientIp" => null,
  208.                 "date" => new DateTime("now"),
  209.                 "typeProject" => SecurityActivityUser::PROJECT_LICENSOR
  210.             ];
  211.             $this->createFileJson($path"\r" 'New Login: ' json_encode($paramsAux) . "\r"); 
  212.             $result Util::securityActivity($em$path$paramsAux);
  213.             $session->set("activitySecurityId"$result);
  214.             $session->set("superAgentManager"$user->getIsSuperAgentManager());
  215.         }
  216.         
  217.         $referer $request->getUri();
  218.         if (strpos($referer'readedNoty=')) {
  219.             $theNotyIdArray explode('#readedNoty='$referer);
  220.             $newSeenNoty $em->getRepository('App\Entity\BellNotificationSeenBy')->find($theNotyIdArray[1]);
  221.             if ($newSeenNoty) {
  222.                 $actualUnmodifiedDate Util::getCurrentDate();
  223.                 $newSeenNoty->setDateSeen($actualUnmodifiedDate);
  224.                 $newSeenNoty->setNotificationStatus(BellNotificationSeenBy::STATUS_NOTIFIED);
  225.                 $em->persist($newSeenNoty);
  226.                 $em->flush();
  227.             }
  228.         }
  229.         // CODIGO PARA REFRESCAR DOCUSIGN
  230.         $docusign $em->getRepository('App\Entity\DocusignAuthorizationUser')->find(1);
  231.         $authentication $this->realContainer->get('licensor_authentication');
  232.         $userInfo $authentication->getUserInfoDocusign($docusign->getTokenType(), $docusign->getAccessToken());
  233.         $docusignConsumerUrl $this->realContainer->getParameter('docusign_url_api_consumer');
  234.         $docusignConsumerUrl .= 'v2.1/accounts/'$userInfo['account_id'] .'/envelopes?from_date=' urlencode(date('Y-m-d\TH:i:s\Z'strtotime('-7 days')));
  235.         $headers = [
  236.             'Authorization: '$docusign->getTokenType() .' '$docusign->getAccessToken(),
  237.             'Content-Type: application/json'
  238.         ];
  239.         $authentication->docusingCosumerApi($docusignConsumerUrl$headers, [], WebService::REQUEST_METHOD_GET);
  240.         
  241.         return $this->redirect($this->generateUrl('level_licensor_homepage'));
  242.     }
  243.     public function autocompleteCitiesCountry(Request $request) {
  244.         $em $this->getDoctrine()->getManager();
  245.         $term mb_convert_case($request->get('term') . '%'MB_CASE_TITLE"UTF-8");
  246.         $search = [];
  247.         $search['term'] = $term;
  248.         $search['contry'] = $request->get('cId');
  249.         $country $em->getRepository('App\Entity\Country')->find($request->get('cId'));
  250.         $citiesx = [];
  251.         if (!$country) {
  252.             $citiesx['id'] = 0;
  253.             $citiesx['label'] = 'Error: Conutry Not Found!';
  254.             $citiesx['value'] = 'Error: Conutry Not Found!';
  255.             $cities[0] = $citiesx;
  256.         } else {
  257.             $cities $em->getRepository('App\Entity\City')->autocompleteCitiesByCountry($search['term'], $search['contry']);
  258.             if (empty($cities)) {
  259.                 $citiesx['id'] = 0;
  260.                 $citiesx['label'] = 'Not Matched Results!';
  261.                 $citiesx['value'] = 'Not Matched Results!';
  262.                 $cities[0] = $citiesx;
  263.             }
  264.         }
  265.         $r = new Response(json_encode($cities));
  266.         $r->headers->set('Content-Type''application/json');
  267.         return $r;
  268.     }
  269.     public function selectStateCountry(Request $request) {
  270.         $em $this->getDoctrine()->getManager();
  271.         if ($request->request->get('country_id') == NULL) {
  272.             $idCo $request->request->get('idco');
  273.             $idCi $request->request->get('idci');
  274.             $states $em->getRepository('App\Entity\State')->selectStateByCityCountry($idCo$idCi);
  275.             $response = [];
  276.             if (empty($states)) {
  277.                 $response['manual'] = '__YES__';
  278.             } else {
  279.                 $response['manual'] = '__NO__';
  280.             }
  281.             $html "<select id='stateBlock' name='state' class='form-control' required='required' readonly>";
  282.             foreach ($states as $state) {
  283.                 $html .= "<option value ='" $state['id'] . "' selected='selected'>";
  284.                 $html .= $state['name'];
  285.                 $html .= "</option>";
  286.             }
  287.             $html .= "</select>";
  288.             $response['result'] = '__OK__';
  289.             $response['html'] = $html;
  290.         } else {
  291.             $country_id $request->request->get('country_id');
  292.             $entityStates $em->getRepository('App\Entity\State')->findBy(array('stCountry' => $country_id));
  293.             
  294.             $select_states = [];
  295.             if (!empty($entityStates)) {
  296.                 foreach ($entityStates as $state) {
  297.                     $select_states[(string) $state->getStId()] = $state->getStName();
  298.                 }
  299.                 $response['status'] = 1;
  300.                 $response['states'] = $select_states;
  301.             } else {
  302.                 $response['status'] = 0;
  303.                 $response['states'] = 'Not Found States';
  304.             }
  305.         }
  306.         $r = new Response(json_encode($response));
  307.         $r->headers->set('Content-Type''application/html');
  308.         return $r;
  309.     }
  310.     public function getStatusSession() {
  311.         $resp = [];
  312.         $status true;
  313.         $response 'Session in ok';
  314.         $access_control $this->get('access_control')->checkAccessModule(Module::MODULE_LICENSOR_LICENSE);
  315.         $access_rol $this->get('access_control')->checkAccessRol([
  316.             $this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN'),
  317.             $this->get('security.authorization_checker')->isGranted('ROLE_INTERNAL_SUPPORT'),
  318.             $this->get('security.authorization_checker')->isGranted('ROLE_TICKET_SUPPORT'),
  319.             $this->get('security.authorization_checker')->isGranted('ROLE_AGENT_MANAGER'),
  320.             $this->get('security.authorization_checker')->isGranted('ROLE_AGENT')
  321.         ]);
  322.         if ($access_control !== AccessControl::ACCESS_GRANTED && $access_rol === false) {
  323.             if ($access_control == AccessControl::SESSION_LOST) {
  324.                 $response "Session has expired";
  325.                 $status false;
  326.             } elseif ($access_control == AccessControl::ACCESS_DENIED) {
  327.                 $response "Access Denied";
  328.                 $status false;
  329.             }
  330.         }
  331.         $resp["msn"] = "__OK__";
  332.         $resp["response"] = $response;
  333.         $resp["status"] = $status;
  334.         return $this->respondJsonAjax($resp);
  335.     }
  336.     public function notifications(){
  337.         if ('anon.' == $this->get('security.token_storage')->getToken()->getUser()) {
  338.             return $this->redirect($this->generateUrl('level_licensor_logout'));
  339.         }
  340.         $theToken $this->get('security.token_storage')->getToken();
  341.         $em $this->getDoctrine()->getManager();
  342.         $actualDate Util::getCurrentDate();
  343.         $actualDate->modify('-1 day');
  344.         $numberOfNewNotifications 0;
  345.         $notificationsArrayToShowInBell = [];
  346.         if ($theToken) {
  347.             $user $theToken->getUser();
  348.             $littleBellNotiRepo $em->getRepository('App\Entity\BellNotificationSeenBy');
  349.             $numberOfNewNotifications $littleBellNotiRepo->searchAndCountAllNewNotificationsToBell($user$actualDate);
  350.             $notificationsToShowInBell $littleBellNotiRepo->searchAndGetAllNotificationsToBell($user$actualDate);
  351.             foreach ($notificationsToShowInBell as $index => $notiToSetAsReaded) {
  352.                 $notificationsArrayToShowInBell[$index] = $notiToSetAsReaded->showEverything();
  353.                 $notificationsArrayToShowInBell[$index]['userWhoSaw'] = $notiToSetAsReaded->getUserWhoSaw();
  354.                 $notificationsArrayToShowInBell[$index]['seenNotification'] = $notiToSetAsReaded->getSeenNotification();
  355.                 $codeAreReset explode('>'$notiToSetAsReaded->getSeenNotification()->getNotificationMsg());
  356.                 
  357.                 if (isset($codeAreReset[1])) {
  358.                     $codeAreReset explode('<'$codeAreReset[1]);
  359.                     if (isset($codeAreReset[0])) {
  360.                         $codesEntity $em->getRepository('App\Entity\FoundRaisePlansCode')->findBy(['frpcCode' => $codeAreReset[0], 'deletedAt' => null]);
  361.                     }
  362.                 }
  363.                 if (isset($codesEntity[0])) {
  364.                     $notificationsArrayToShowInBell[$index]['inFancy'] = true;
  365.                 }
  366.             }
  367.         } else {
  368.             $user null;
  369.         }
  370.         return $this->render('Default\notificationMenu.html.twig', [
  371.             'user' => $user,
  372.             'numberOfNewNotifications' => $numberOfNewNotifications,
  373.             'notificationsToShowInBell' => $notificationsArrayToShowInBell
  374.         ]);
  375.     }
  376.     public function updateSecurityActivity(Request $request) {
  377.         $data json_decode($request->getContent(), true);
  378.         $idActivity $request->getSession()->get("activitySecurityId");
  379.         $em $this->getDoctrine()->getManager();
  380.         $resultInfoActivity $em->getRepository('App\Entity\SecurityActivityUser')->find($idActivity);
  381.         if (isset($resultInfoActivity) && isset($data) && $data["id_dis"]) {
  382.             $resultInfoActivity->setSauIpAddress($data["id_dis"]);
  383.             $em->persist($resultInfoActivity);
  384.             $em->flush();
  385.         }
  386.         $resp["msn"] = "__OK__";
  387.         $resp["response"] = "success update";
  388.         $resp["status"] = 200;
  389.         $r = new Response(json_encode($resp));
  390.         $r->headers->set('Content-Type''application/json');
  391.         return $r;
  392.     }
  393.     public function createFileJson($path$text) {
  394.         $file fopen($path"a+");
  395.         fwrite($file$text);
  396.         fclose($file);
  397.     }
  398.     public function switchUser(Request $request){
  399.         $targetUser $request->query->get('_switch_user');
  400.         return $this->redirectToRoute('level_licensor_homepage', ['_switch_user' => $targetUser]);
  401.     }
  402.     
  403. }