<?php
namespace App\Controller\Licensor;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Module;
use App\Util\AccessControl;
use App\Controller\ParametersNormalizerController;
use App\Controller\Licensor\ContainerController;
use App\Util\WS\Util;
use App\Util\Util AS Utiles;
use App\Entity\BellNotificationSeenBy;
use App\Entity\SecurityActivityUser;
use App\Entity\Partner;
use App\Entity\DocusignAuthorizationUser;
use App\Entity\WebService;
use App\Util\Util as Util2;
use DateTime;
/**
* DefaultController
*/
class DefaultController extends ParametersNormalizerController {
public function dashboard(Request $request, ContainerController $cc) {
if ('anon.' == $this->get('security.token_storage')->getToken()->getUser()) {
return $this->redirect($this->generateUrl('level_licensor_logout'));
}
$em = $this->getDoctrine()->getManager();
$idActivity = $request->getSession()->get("activitySecurityId");
$checkActivity = false;
if (isset($idActivity) && strlen($idActivity) == 36) {
$resultInfoActivity = $em->getRepository('App\Entity\SecurityActivityUser')->findOneBy(["id" => $idActivity, "sauIpAddress" => null ]);
$checkActivity = (isset($resultInfoActivity) ? true : false );
}
$session = $request->getSession();
$userSession = $this->get('security.token_storage')->getToken()->getUser();
$userId = $userSession->getId();
$user = $em->getRepository('App\Entity\User')->findOneBy(['id' => $userId]);
$em = $this->getDoctrine()->getManager();
$partnerInformation = $em->getRepository('App\Entity\Partner')->getAllPartnersWithoutRelationUser();
if(count($partnerInformation) > 0){
$lastId = $partnerInformation[count($partnerInformation)-1]->getId();
}else{
$lastId = 0;
}
$date = Utiles::getCurrentDate();
$date = date_format($date, 'm/d/Y');
$tasksInformation = $em->getRepository('App\Entity\PlanningTask')->getActiveTasksFromLast($userId,$date);
$partnerAsociation = $em->getRepository('App\Entity\Partner')->getAllPartnersWithoutRelationUser($user);
$expiredTasks = $em->getRepository('App\Entity\PlanningTask')->getExpiredTasks($userId,$date);
$partnerNotChecked = $em->getRepository('App\Entity\Partner')->getPartnersNotChecked($user);
$container = $cc->getContainer();
$translator = $container->get('translator');
$lenguage = [];
for ($i=0; $i <2 ; $i++) {
$lenguage[$i] = $translator->trans('configuration.languages.'. $i);
}
// dump($session);die();
return $this->render('Default\dashboard.html.twig', array(
'menu' => 'dashboard',
'checkActivity' => $checkActivity,
'partnerInformation' => $partnerInformation,
'tasksInformation' => $tasksInformation,
'partnerAsociation' => $partnerAsociation,
'partnerNotChecked' => $partnerNotChecked,
'expiredTasks' => $expiredTasks,
'userData' => $user,
'lastId' => $lastId,
'lenguage' => $lenguage
));
}
public function updateLanguage(Request $req, ContainerController $cc) {
$session = $req->getSession();
$em = $this->getDoctrine()->getManager();
$params = $cc->getContentInRequest($req);
$userSession = $this->get('security.token_storage')->getToken()->getUser();
$userId = $userSession->getId();
$user = $em->getRepository('App\Entity\User')->findOneBy(['id' => $userId]);
$user->setLanguage($params["data"]["application_language"]);
$em->persist($user);
$em->flush();
$session->set('lenguage', ($user->getLanguage() == 0) ? 'en' : 'es');
$container = $cc->getContainer();
$translator = $container->get('translator');
$this->addFlash('notice', $translator->trans('configuration.save_successful'));
return $this->redirect($this->generateUrl('level_licensor_homepage'));
}
/**
* @return type
*/
public function getMyNotiesForTheBell() {
$theToken = $this->get('security.token_storage')->getToken();
$em = $this->getDoctrine()->getManager();
$actualDate = Util::getCurrentDate();
$actualDate->modify('-1 day');
$numberOfNewNotifications = 0;
$notificationsArrayToShowInBell = [];
if ($theToken) {
$user = $theToken->getUser();
$littleBellNotiRepo = $em->getRepository('App\Entity\BellNotificationSeenBy');
$numberOfNewNotifications = $littleBellNotiRepo->searchAndCountAllNewNotificationsToBell($user, $actualDate);
$notificationsToShowInBell = $littleBellNotiRepo->searchAndGetAllNotificationsToBell($user, $actualDate);
foreach ($notificationsToShowInBell as $index => $notiToSetAsReaded) {
$notificationsArrayToShowInBell[$index] = $notiToSetAsReaded->showEverything();
$notificationsArrayToShowInBell[$index]['userWhoSaw'] = $notiToSetAsReaded->getUserWhoSaw();
$notificationsArrayToShowInBell[$index]['seenNotification'] = $notiToSetAsReaded->getSeenNotification();
$codeAreReset = explode('>', $notiToSetAsReaded->getSeenNotification()->getNotificationMsg());
if (isset($codeAreReset[1])) {
$codeAreReset = explode('<', $codeAreReset[1]);
if (isset($codeAreReset[0])) {
$codesEntity = $em->getRepository('App\Entity\FoundRaisePlansCode')->findBy(['frpcCode' => $codeAreReset[0], 'deletedAt' => null]);
}
}
if (isset($codesEntity) && isset($codesEntity[0])) {
$notificationsArrayToShowInBell[$index]['inFancy'] = true;
}
}
} else {
$user = null;
}
return $this->render('Default\defaultNotificationBell.html.twig', [
'user' => $user,
'numberOfNewNotifications' => $numberOfNewNotifications,
'notificationsToShowInBell' => $notificationsArrayToShowInBell
]);
}
public function getTicketsForSupport(){
$em = $this->getDoctrine()->getManager();
$tickets = $em->getRepository('App\Entity\Ticket')->findTicketByOrder();
$numberOfTickets = count($tickets);
return $this->render('Default\defaultTicketList.html.twig', [
'tickets' => $tickets,
'numberOfTickets' => $numberOfTickets
]);
}
/**
* Esta funcion permite validar el acceso de los usuarios del backend al sistema
*/
public function login(Request $request, $id = null, $key = null) {
$helper = $this->get('symfony_security_authentication_utils');
$em = $this->getDoctrine()->getManager();
$msg = $request->query->get('msg');
$csrfToken = $this->get('security.csrf.token_manager')->getToken('authenticate')->getValue();
return $this->render('Default\login.html.twig', array(
'error' => $helper->getLastAuthenticationError(),
'last_username' => $helper->getLastUsername(),
'msg' => $msg,
'csrf_token' => $csrfToken
));
}
/**
* Esta funcion se encarga de crear una variable de session que
* aumentara segun la cantidad de intentos de login que tenga el
* usuario
*/
public function sessionByLoginCompany(Request $request) {
$response = [];
$session = $request->getSession();
if ($request->getMethod() == 'POST') {
$value = $request->request->get('model');
$session->set(sha1('counterRequestAjaxPostCompany'), $value);
$response['result'] = '__OK__';
}
$r = new Response(json_encode($response));
$r->headers->set('Content-Type', 'application/html');
return $r;
}
/**
* Esta funcion permite validar los permisos del usuario logueado y guardarlos en un arreglo en session
* el cual se usara en toda la aplicacion para mostrar u ocultar iconos y enlaces a los modulos correctos
*
* @return \HttpRequest pagina de inicio de la aplicacion
*/
public function accessControl(Request $request) {
$theToken = $this->get('security.token_storage')->getToken();
$path = Util::getValidActiveLogByBaseName($this->realContainer, 'securityActivity', 'securityActivity0.txt');
$em = $this->getDoctrine()->getManager();
if (null != $theToken) {
$user = $theToken->getUser();
$rolesArray = $user->getRoles();
if (!empty($rolesArray) && $rolesArray[0] == 'ROLE_INACTIVE') {
$request->getSession()->invalidate(1);
sleep(1);
return $this->redirect($this->generateUrl('level_licensor_login', ['msg' => 'User Inactive']));
}
$search['only_active'] = true;
$modulesUserCompany = $em->getRepository('App\Entity\UserModules')->findUserModulesToEdition($user->getId(), $search);
$activeModules = [];
for ($i = 0; $i < count($modulesUserCompany); $i++) {
$activeModules[$i] = $modulesUserCompany[$i]->getUmModule()->getMoSlug();
// dump( $activeModules[$i]);
// die;
}
$session = $request->getSession();
$session->set('activeModules', $activeModules);
$paramsAux = [
"userAgent" => $request->headers->get('User-Agent'),
"userId" => $user->getId(),
"clientIp" => null,
"date" => new DateTime("now"),
"typeProject" => SecurityActivityUser::PROJECT_LICENSOR
];
$this->createFileJson($path, "\r" . 'New Login: ' . json_encode($paramsAux) . "\r");
$result = Util::securityActivity($em, $path, $paramsAux);
$session->set("activitySecurityId", $result);
$session->set("superAgentManager", $user->getIsSuperAgentManager());
}
$referer = $request->getUri();
if (strpos($referer, 'readedNoty=')) {
$theNotyIdArray = explode('#readedNoty=', $referer);
$newSeenNoty = $em->getRepository('App\Entity\BellNotificationSeenBy')->find($theNotyIdArray[1]);
if ($newSeenNoty) {
$actualUnmodifiedDate = Util::getCurrentDate();
$newSeenNoty->setDateSeen($actualUnmodifiedDate);
$newSeenNoty->setNotificationStatus(BellNotificationSeenBy::STATUS_NOTIFIED);
$em->persist($newSeenNoty);
$em->flush();
}
}
// CODIGO PARA REFRESCAR DOCUSIGN
$docusign = $em->getRepository('App\Entity\DocusignAuthorizationUser')->find(1);
$authentication = $this->realContainer->get('licensor_authentication');
$userInfo = $authentication->getUserInfoDocusign($docusign->getTokenType(), $docusign->getAccessToken());
$docusignConsumerUrl = $this->realContainer->getParameter('docusign_url_api_consumer');
$docusignConsumerUrl .= 'v2.1/accounts/'. $userInfo['account_id'] .'/envelopes?from_date=' . urlencode(date('Y-m-d\TH:i:s\Z', strtotime('-7 days')));
$headers = [
'Authorization: '. $docusign->getTokenType() .' '. $docusign->getAccessToken(),
'Content-Type: application/json'
];
$authentication->docusingCosumerApi($docusignConsumerUrl, $headers, [], WebService::REQUEST_METHOD_GET);
return $this->redirect($this->generateUrl('level_licensor_homepage'));
}
public function autocompleteCitiesCountry(Request $request) {
$em = $this->getDoctrine()->getManager();
$term = mb_convert_case($request->get('term') . '%', MB_CASE_TITLE, "UTF-8");
$search = [];
$search['term'] = $term;
$search['contry'] = $request->get('cId');
$country = $em->getRepository('App\Entity\Country')->find($request->get('cId'));
$citiesx = [];
if (!$country) {
$citiesx['id'] = 0;
$citiesx['label'] = 'Error: Conutry Not Found!';
$citiesx['value'] = 'Error: Conutry Not Found!';
$cities[0] = $citiesx;
} else {
$cities = $em->getRepository('App\Entity\City')->autocompleteCitiesByCountry($search['term'], $search['contry']);
if (empty($cities)) {
$citiesx['id'] = 0;
$citiesx['label'] = 'Not Matched Results!';
$citiesx['value'] = 'Not Matched Results!';
$cities[0] = $citiesx;
}
}
$r = new Response(json_encode($cities));
$r->headers->set('Content-Type', 'application/json');
return $r;
}
public function selectStateCountry(Request $request) {
$em = $this->getDoctrine()->getManager();
if ($request->request->get('country_id') == NULL) {
$idCo = $request->request->get('idco');
$idCi = $request->request->get('idci');
$states = $em->getRepository('App\Entity\State')->selectStateByCityCountry($idCo, $idCi);
$response = [];
if (empty($states)) {
$response['manual'] = '__YES__';
} else {
$response['manual'] = '__NO__';
}
$html = "<select id='stateBlock' name='state' class='form-control' required='required' readonly>";
foreach ($states as $state) {
$html .= "<option value ='" . $state['id'] . "' selected='selected'>";
$html .= $state['name'];
$html .= "</option>";
}
$html .= "</select>";
$response['result'] = '__OK__';
$response['html'] = $html;
} else {
$country_id = $request->request->get('country_id');
$entityStates = $em->getRepository('App\Entity\State')->findBy(array('stCountry' => $country_id));
$select_states = [];
if (!empty($entityStates)) {
foreach ($entityStates as $state) {
$select_states[(string) $state->getStId()] = $state->getStName();
}
$response['status'] = 1;
$response['states'] = $select_states;
} else {
$response['status'] = 0;
$response['states'] = 'Not Found States';
}
}
$r = new Response(json_encode($response));
$r->headers->set('Content-Type', 'application/html');
return $r;
}
public function getStatusSession() {
$resp = [];
$status = true;
$response = 'Session in ok';
$access_control = $this->get('access_control')->checkAccessModule(Module::MODULE_LICENSOR_LICENSE);
$access_rol = $this->get('access_control')->checkAccessRol([
$this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN'),
$this->get('security.authorization_checker')->isGranted('ROLE_INTERNAL_SUPPORT'),
$this->get('security.authorization_checker')->isGranted('ROLE_TICKET_SUPPORT'),
$this->get('security.authorization_checker')->isGranted('ROLE_AGENT_MANAGER'),
$this->get('security.authorization_checker')->isGranted('ROLE_AGENT')
]);
if ($access_control !== AccessControl::ACCESS_GRANTED && $access_rol === false) {
if ($access_control == AccessControl::SESSION_LOST) {
$response = "Session has expired";
$status = false;
} elseif ($access_control == AccessControl::ACCESS_DENIED) {
$response = "Access Denied";
$status = false;
}
}
$resp["msn"] = "__OK__";
$resp["response"] = $response;
$resp["status"] = $status;
return $this->respondJsonAjax($resp);
}
public function notifications(){
if ('anon.' == $this->get('security.token_storage')->getToken()->getUser()) {
return $this->redirect($this->generateUrl('level_licensor_logout'));
}
$theToken = $this->get('security.token_storage')->getToken();
$em = $this->getDoctrine()->getManager();
$actualDate = Util::getCurrentDate();
$actualDate->modify('-1 day');
$numberOfNewNotifications = 0;
$notificationsArrayToShowInBell = [];
if ($theToken) {
$user = $theToken->getUser();
$littleBellNotiRepo = $em->getRepository('App\Entity\BellNotificationSeenBy');
$numberOfNewNotifications = $littleBellNotiRepo->searchAndCountAllNewNotificationsToBell($user, $actualDate);
$notificationsToShowInBell = $littleBellNotiRepo->searchAndGetAllNotificationsToBell($user, $actualDate);
foreach ($notificationsToShowInBell as $index => $notiToSetAsReaded) {
$notificationsArrayToShowInBell[$index] = $notiToSetAsReaded->showEverything();
$notificationsArrayToShowInBell[$index]['userWhoSaw'] = $notiToSetAsReaded->getUserWhoSaw();
$notificationsArrayToShowInBell[$index]['seenNotification'] = $notiToSetAsReaded->getSeenNotification();
$codeAreReset = explode('>', $notiToSetAsReaded->getSeenNotification()->getNotificationMsg());
if (isset($codeAreReset[1])) {
$codeAreReset = explode('<', $codeAreReset[1]);
if (isset($codeAreReset[0])) {
$codesEntity = $em->getRepository('App\Entity\FoundRaisePlansCode')->findBy(['frpcCode' => $codeAreReset[0], 'deletedAt' => null]);
}
}
if (isset($codesEntity[0])) {
$notificationsArrayToShowInBell[$index]['inFancy'] = true;
}
}
} else {
$user = null;
}
return $this->render('Default\notificationMenu.html.twig', [
'user' => $user,
'numberOfNewNotifications' => $numberOfNewNotifications,
'notificationsToShowInBell' => $notificationsArrayToShowInBell
]);
}
public function updateSecurityActivity(Request $request) {
$data = json_decode($request->getContent(), true);
$idActivity = $request->getSession()->get("activitySecurityId");
$em = $this->getDoctrine()->getManager();
$resultInfoActivity = $em->getRepository('App\Entity\SecurityActivityUser')->find($idActivity);
if (isset($resultInfoActivity) && isset($data) && $data["id_dis"]) {
$resultInfoActivity->setSauIpAddress($data["id_dis"]);
$em->persist($resultInfoActivity);
$em->flush();
}
$resp["msn"] = "__OK__";
$resp["response"] = "success update";
$resp["status"] = 200;
$r = new Response(json_encode($resp));
$r->headers->set('Content-Type', 'application/json');
return $r;
}
public function createFileJson($path, $text) {
$file = fopen($path, "a+");
fwrite($file, $text);
fclose($file);
}
public function switchUser(Request $request){
$targetUser = $request->query->get('_switch_user');
return $this->redirectToRoute('level_licensor_homepage', ['_switch_user' => $targetUser]);
}
}