<?php
namespace App\Controller;
use App\Entity\Client;
use App\Entity\ClientContact;
use App\Entity\MailDelivery;
use App\Entity\SettingsRol;
use App\Entity\Supplier;
use App\Entity\User;
use App\Entity\WidgetNotes;
use App\Form\WidgetNotesType;
use App\MDS\EventsBundle\Entity\Proposal;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\JsonResponse;
use Google_Client;
use Google_Service_Calendar;
use Swift_Mailer;
use Swift_SmtpTransport;
use Symfony\Contracts\Translation\TranslatorInterface;
class HomeController extends AbstractController
{
protected $googleCalendar;
private $translator;
public function __construct(TranslatorInterface $translator)
{
// $redirect_uri='urn:ietf:wg:oauth:2.0:oob';
$redirect_uri = 'https://' . $_SERVER['HTTP_HOST'] . '/calendar/token';
$googleCalendar = new Google_Client();
$googleCalendar->setApplicationName('Google Calendar API PHP Quickstart');
//campos a extraer de la base de datos User
$googleCalendar->setClientId('2790497987-57qc3vu4pr7vb0s8phpub2me58pe34lb.apps.googleusercontent.com');
$googleCalendar->setClientSecret('nj2C7unaTO68DRhyORsyipSj');
//fin campos user
// $api_key = "AIzaSyBR84cS1IU2BPvk5V3VnbqdkJESlv440Ac";
// $client->setDeveloperKey($api_key);
$googleCalendar->setRedirectUri($redirect_uri);
$googleCalendar->addScope(Google_Service_Calendar::CALENDAR);
$guzzleClient = new \GuzzleHttp\Client(array('curl' => array(CURLOPT_SSL_VERIFYPEER => false)));
$googleCalendar->setHttpClient($guzzleClient);
$this->googleCalendar = $googleCalendar;
$this->translator = $translator;
}
/**
* @Route("/connectGoogle", name="homepage_Connect_Google")
*/
public function indexConnectGoogleAction(Request $request)
{
$session = new Session();
$token = $session->get('tokenGoogleCalendar');
// d($token);
if (!is_null($token)) {
$this->googleCalendar->setAccessToken($token);
}
// If there is no previous token or it's expired.
$data = array();
if ($this->googleCalendar->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($this->googleCalendar->getRefreshToken()) {
$this->googleCalendar->fetchAccessTokenWithRefreshToken($this->googleCalendar->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $this->googleCalendar->createAuthUrl();
return $this->redirect($authUrl);
}
}
return $this->redirectToRoute('homepage');
}
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request, \Swift_Mailer $mailer)
{
$session = new Session();
$token = $session->get('tokenGoogleCalendar');
if (!is_null($token)) {
$this->googleCalendar->setAccessToken($token);
$connectGoogle = "1";
} else {
$connectGoogle = "0";
}
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_userrol = $user_logueado->getUserrol();
$user_id = $user_logueado->getId();
$em = $this->getDoctrine()->getManager();
$modules = $em->getRepository(SettingsRol::class)->findOneById($user_userrol);
$request->getSession()->set('_modules', $modules);
if ($user_logueado->getTeam() == 16) { return $this->redirectToRoute('gp_cvr_calendar'); }
if ($user_logueado->getTeam() == 17) { return $this->redirectToRoute('ht_calendar'); }
// ALL LO QUE HAY -- PROPOSAL NO ASIGNADOS
$parameterspc = array(
'pending' => 'Pending',
'confirmed' => 'Confirmed',
);
$dqlpc = 'SELECT pc FROM EventsBundle:Proposal pc WHERE pc.agentId is null AND (pc.status = :pending or pc.status = :confirmed)';
$querypc = $em->createQuery($dqlpc)->setParameters($parameterspc);
$cantidadpc = $querypc->getResult();
$request->getSession()->set('_proposal_unassigned', count($cantidadpc));
/* ALL LO QUE HAY -- ALERTAS DE ToDo */
$parametersB = array(
'user_id' => $user_id,
);
$dqlB = 'SELECT COUNT (tdl.id)
FROM App:ToDoLogs tdl
WHERE tdl.readed = FALSE AND tdl.ownerToDoLog = :user_id';
$query = $em->createQuery($dqlB)->setParameters($parametersB);;
$alertTodo = $query->getResult()[0][1];
$request->getSession()->set('_todoalert', $alertTodo);
$hoy = date('Y-m-d');
$hoy_datatime = new \DateTime($hoy);
$parametersA = array(
'commercialId' => $user_id,
'alertAt' => $hoy_datatime,
);
/* ALL LO QUE HAY */
$dql = 'SELECT ct.alertAt, ct, cl.title, cn.name, cn.lastName
FROM CommercialBundle:CommercialTracking ct
INNER JOIN App:Client cl WITH cl.id = ct.clientId
INNER JOIN App:ClientContact cn WITH cn.id = ct.contactId
WHERE ct.commercialId = :commercialId AND ct.alertAt = :alertAt';
$query = $em->createQuery($dql)->setParameters($parametersA);;
$commercial_tracking = $query->getResult();
$wnotes = new WidgetNotes();
$wnotes->setDateAt(new \DateTime("now"));
$form = $this->createWidgetNotesCreateForm($wnotes);
// EJECUTAR ENVIO DE REPORTE COMERCIAL
$dia = date("l");
$hora = date("H:m");
//Si es el dia Friday y la hora 17:00
if ($dia == "Friday" and $hora >= "17:00") {
//si ya no se hizo antes
$hoy = date("Y-m-d");
$hoy_datatime = new \DateTime($hoy);
$consultaMail = $em->getRepository(MailDelivery::class)->findOneBy(
array(
'dateAt' => $hoy_datatime,
'system' => 'Informe Seguimiento Commercial Mante3',
'send' => 'si'
)
);
if (is_null($consultaMail)) {
$this->MandarCorreoSeguimientoComercial($request, $mailer);
}
}
if ($user_id == 122) {
return $this->redirectToRoute('list_news');
} else {
return $this->render(
'home/index.html.twig',
array(
'tracking' => $commercial_tracking,
'alertTodo' => $alertTodo,
'form' => $form->createView(),
'user' => $user_id,
'token' => $user_logueado->getAccessKey(),
'connectGoogle' => $connectGoogle,
)
);
}
}
/**
* @Route("/calendar-admin", name="calendar-admin")
*/
public function calendarAdminAction(Request $request)
{
$session = new Session();
$token = $session->get('tokenGoogleCalendar');
if (!is_null($token)) {
$this->googleCalendar->setAccessToken($token);
$connectGoogle = "1";
} else {
$connectGoogle = "0";
}
// $em = $this->getDoctrine()->getManager();
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_userrol = $user_logueado->getUserrol();
$user_id = $user_logueado->getId();
$wnotes = new WidgetNotes();
$wnotes->setDateAt(new \DateTime("now"));
$form = $this->createWidgetNotesCreateForm($wnotes);
//
//
//
// $hoy = date('Y-m-d');
// $parameters= array(
// 'createdId' => $user_id,
// 'hoy' => $hoy
// );
// $dqlA = 'SELECT wn
// FROM App:WidgetNotes wn
// WHERE wn.createdId = :createdId AND wn.dateAt >= :hoy
// ORDER BY wn.dateAt ASC';
// $query = $em->createQuery($dqlA)->setParameters($parameters);
// $notes = $query->getResult();
//
// $parametersB= array(
// 'user_id' => $user_id,
// );
// $dqlB = 'SELECT COUNT (tdl.id)
// FROM App:ToDoLogs tdl
// WHERE tdl.readed = FALSE AND tdl.ownerToDoLog = :user_id';
// $query = $em->createQuery($dqlB)->setParameters($parametersB);;
// $alertTodo = $query->getResult()[0][1];
//
// $hoy_datatime = new \DateTime($hoy);
//
// $parametersA = array(
// 'commercialId' => $user_id,
// 'alertAt' => $hoy_datatime,
// );
// /* ALL LO QUE HAY */
// $dql = 'SELECT ct.alertAt, ct, cl.title, cn.name, cn.lastName
// FROM CommercialBundle:CommercialTracking ct
// INNER JOIN App:Client cl WITH cl.id = ct.clientId
// INNER JOIN App:ClientContact cn WITH cn.id = ct.contactId
// WHERE ct.commercialId = :commercialId AND ct.alertAt = :alertAt';
//
// $query = $em->createQuery($dql)->setParameters($parametersA);;
// $commercial_tracking = $query->getResult();
return $this->render(
'home/calendar-admin.html.twig',
array(
// 'tracking' => $commercial_tracking,
// 'alertTodo' => $alertTodo,
// 'notes' => $notes,
'form' => $form->createView(),
'user' => $user_id,
'connectGoogle' => $connectGoogle,
// 'token' => $user_logueado->getAccessKey(),
)
);
}
private function createWidgetNotesCreateForm(WidgetNotes $entity)
{
$form = $this->createForm(WidgetNotesType::class, $entity, array(
'action' => $this->generateUrl('widget_notes_create'),
'method' => 'POST'
));
return $form;
}
private function createWidgetNotesEditForm(WidgetNotes $entity, $id)
{
$form = $this->createForm(WidgetNotesType::class, $entity, array(
'action' => $this->generateUrl(
'widget_notes_edit',
array(
'id' => $id
)
),
'method' => 'PUT'
));
return $form;
}
/**
* @Route("/ChangeLanguage/{idioma}", name="change_language")
*/
public function cambioIdioma(Request $request, $idioma)
{
$this->translator->setLocale($idioma);
$this->get('session')->set('_locale', $idioma);
return $this->redirect($request->headers->get('referer'));
}
/**
* @Route("/calendar-full", name="calendar-full")
*/
public function calendarFullAction(Request $request)
{
$token = $request->request->get('token');
$em = $this->getDoctrine()->getManager();
$user_logueado = $em->getRepository(User::class)->findOneByAccessKey($token);
$user_id = $user_logueado->getId();
$wnotes = new WidgetNotes();
$wnotes->setDateAt(new \DateTime("now"));
$form = $this->createWidgetNotesCreateForm($wnotes);
$hoy = date('Y-m-d');
$parameters = array(
'createdId' => $user_id,
'hoy' => $hoy
);
$dqlA = 'SELECT wn
FROM App:WidgetNotes wn
WHERE wn.createdId = :createdId AND wn.dateAt >= :hoy
ORDER BY wn.dateAt ASC';
$query = $em->createQuery($dqlA)->setParameters($parameters);
$notes = $query->getResult();
$parametersB = array(
'user_id' => $user_id,
);
$dqlB = 'SELECT COUNT (tdl.id)
FROM App:ToDoLogs tdl
WHERE tdl.readed = FALSE AND tdl.ownerToDoLog = :user_id';
$query = $em->createQuery($dqlB)->setParameters($parametersB);;
$alertTodo = $query->getResult()[0][1];
$hoy_datatime = new \DateTime($hoy);
$parametersA = array(
'commercialId' => $user_id,
'alertAt' => $hoy_datatime,
);
/* ALL LO QUE HAY */
$dql = 'SELECT ct.alertAt, ct, cl.title, cn.name, cn.lastName
FROM CommercialBundle:CommercialTracking ct
INNER JOIN App:Client cl WITH cl.id = ct.clientId
INNER JOIN App:ClientContact cn WITH cn.id = ct.contactId
WHERE ct.commercialId = :commercialId AND ct.alertAt = :alertAt';
$query = $em->createQuery($dql)->setParameters($parametersA);;
$commercial_tracking = $query->getResult();
return $this->render(
'home/calendar-fullscreen.html.twig',
array(
'tracking' => $commercial_tracking,
'alertTodo' => $alertTodo,
'notes' => $notes,
'form' => $form->createView(),
'user' => $user_id,
'token' => $token,
)
);
}
/**
* @Route("/pdf/calendar-full/{token}", name="calendar-full-pdf")
*/
public function calendarTokenFullAction($token, Request $request)
{
// $token = $request->request->get('token');
// d($token);exit();
$em = $this->getDoctrine()->getManager();
$user_logueado = $em->getRepository(User::class)->findOneByAccessKey($token);
$user_id = $user_logueado->getId();
// $wnotes = new WidgetNotes();
// $wnotes->setDateAt(new \DateTime("now"));
// $form = $this->createWidgetNotesCreateForm($wnotes);
$hoy = date('Y-m-d');
$parameters = array(
'createdId' => $user_id,
'hoy' => $hoy
);
$dqlA = 'SELECT wn
FROM App:WidgetNotes wn
WHERE wn.createdId = :createdId AND wn.dateAt >= :hoy
ORDER BY wn.dateAt ASC';
$query = $em->createQuery($dqlA)->setParameters($parameters);
$notes = $query->getResult();
$parametersB = array(
'user_id' => $user_id,
);
$dqlB = 'SELECT COUNT (tdl.id)
FROM App:ToDoLogs tdl
WHERE tdl.readed = FALSE AND tdl.ownerToDoLog = :user_id';
$query = $em->createQuery($dqlB)->setParameters($parametersB);;
$alertTodo = $query->getResult()[0][1];
$hoy_datatime = new \DateTime($hoy);
$parametersA = array(
'commercialId' => $user_id,
'alertAt' => $hoy_datatime,
);
/* ALL LO QUE HAY */
$dql = 'SELECT ct.alertAt, ct, cl.title, cn.name, cn.lastName
FROM CommercialBundle:CommercialTracking ct
INNER JOIN App:Client cl WITH cl.id = ct.clientId
INNER JOIN App:ClientContact cn WITH cn.id = ct.contactId
WHERE ct.commercialId = :commercialId AND ct.alertAt = :alertAt';
$query = $em->createQuery($dql)->setParameters($parametersA);;
$commercial_tracking = $query->getResult();
return $this->render(
'home/calendar-pdf.html.twig',
array(
'tracking' => $commercial_tracking,
'alertTodo' => $alertTodo,
'notes' => $notes,
// 'form' => $form->createView(),
'user' => $user_id,
'token' => $token,
)
);
}
/**
* @Route("/calendar-admin-fullscreen", name="calendar-admin-fullscreen")
*/
public function calendarAdminFullScreenAction(Request $request)
{
// $em = $this->getDoctrine()->getManager();
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_userrol = $user_logueado->getUserrol();
$user_id = $user_logueado->getId();
$wnotes = new WidgetNotes();
$wnotes->setDateAt(new \DateTime("now"));
$form = $this->createWidgetNotesCreateForm($wnotes);
//
//
//
// $hoy = date('Y-m-d');
// $parameters= array(
// 'createdId' => $user_id,
// 'hoy' => $hoy
// );
// $dqlA = 'SELECT wn
// FROM App:WidgetNotes wn
// WHERE wn.createdId = :createdId AND wn.dateAt >= :hoy
// ORDER BY wn.dateAt ASC';
// $query = $em->createQuery($dqlA)->setParameters($parameters);
// $notes = $query->getResult();
//
// $parametersB= array(
// 'user_id' => $user_id,
// );
// $dqlB = 'SELECT COUNT (tdl.id)
// FROM App:ToDoLogs tdl
// WHERE tdl.readed = FALSE AND tdl.ownerToDoLog = :user_id';
// $query = $em->createQuery($dqlB)->setParameters($parametersB);;
// $alertTodo = $query->getResult()[0][1];
//
// $hoy_datatime = new \DateTime($hoy);
//
// $parametersA = array(
// 'commercialId' => $user_id,
// 'alertAt' => $hoy_datatime,
// );
// /* ALL LO QUE HAY */
// $dql = 'SELECT ct.alertAt, ct, cl.title, cn.name, cn.lastName
// FROM CommercialBundle:CommercialTracking ct
// INNER JOIN App:Client cl WITH cl.id = ct.clientId
// INNER JOIN App:ClientContact cn WITH cn.id = ct.contactId
// WHERE ct.commercialId = :commercialId AND ct.alertAt = :alertAt';
//
// $query = $em->createQuery($dql)->setParameters($parametersA);;
// $commercial_tracking = $query->getResult();
return $this->render(
'home/calendar-admin-fullscreen.html.twig',
array(
// 'tracking' => $commercial_tracking,
// 'alertTodo' => $alertTodo,
// 'notes' => $notes,
'form' => $form->createView(),
'user' => $user_id,
// 'token' => $user_logueado->getAccessKey(),
)
);
}
/**
* @Route("/external/calendar-reservation/okyh759ofiuytd573450j8sdlwdf2", name="calendar-external-fullscreen")
*/
public function calendarExternalReservasFullScreenAction(Request $request)
{
return $this->render('home/calendar-reservation.html.twig');
}
/**
* @Route("/external/proposals/events-reservation", name="calendar_datos_external_reservation")
*/
public function proposalAdminExternalSelectAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposals = $em->getRepository(Proposal::class)->findBy(
array(
'status' => array('Confirmed', 'Invoiced'),
),
array('dateEventStarAt' => 'ASC')
);
$datos = array();
if (!empty($proposals)) {
foreach ($proposals as $proposal) {
$client = $em->getRepository(Clientent::class)->findOneById($proposal->getClientId());
$user = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if (empty($user) || is_null($user)) {
// d($proposal->getAgentTwoId());
if (!is_null($proposal->getTeamId())) {
$userAsignar = $em->getRepository(User::class)->findOneBy(array('team' => $proposal->getTeamId(), 'teamleader' => 1));
$id = $userAsignar->getId();
} else {
$admin = $em->getRepository(User::class)->findOneByRole('ROLE_ADMIN');
$id = $admin->getId();
}
// d($id);
$proposal->setAgentId($id);
$em->persist($proposal);
$em->flush();
$user = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
}
$colorHay = $user->getColor();
if (empty($colorHay)) {
$color = "#ff0000";
} else {
$color = $user->getColor();
}
if (is_null($user->getPicture())) {
$picture = "";
} else {
$picture = "<img src='https://" . $_SERVER['HTTP_HOST'] . '/' . $user->getPicture() . "' class='img-circle img-lg'><br>";
}
$tooltip = $picture . " " .
$user->getName() . " " . $user->getLastname() . "<br>" .
$client->getName() . "<br>" .
$proposal->getName() . "</b><br>";
$datos[] = array(
"id" => $proposal->getId(),
"title" => $user->getName() . " " . $user->getLastname() . " | " . $client->getName() . ": " . $proposal->getName(),
"tooltip" => $tooltip,
"start" => $proposal->getDateEventStarAt(),
"end" => $proposal->getDateEventEndAt(),
"color" => $color,
"url" => null
);
}
} else {
$datos = [];
}
$return = array(
'proposal' => $datos,
);
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/external/envioinformecomercial/ftdkwu6df6dfwyjdfvwsdjvdjyde6w", name="external_informe_comercial_ejecute")
*/
public function envioInformeComercialxAction(Request $request, \Swift_Mailer $mailer)
{
$em = $this->getDoctrine()->getManager();
// EJECUTAR ENVIO DE REPORTE COMERCIAL
$dia = date("l");
$hora = date("H:m");
//Si es el dia Friday y la hora 17:00
// if( $dia == "Friday" AND $hora >= "17:00"){
//si ya no se hizo antes
$hoy = date("Y-m-d");
$hoy_datatime = new \DateTime($hoy);
$consultaMail = $em->getRepository('App:MailDelivery')->findOneBy(
array(
'dateAt' => $hoy_datatime,
'system' => 'Informe Seguimiento Commercial Mante3',
'send' => 'si'
)
);
if (is_null($consultaMail)) {
$enviarCorreos = $this->MandarCorreoSeguimientoComercial($request, $mailer);
}
// }
$response = new Response("enviado", 200);
return $response;
}
private function MandarCorreoSeguimientoComercial(Request $request, \Swift_Mailer $mailer)
{
$em = $this->getDoctrine()->getManager();
$hoy = date("Y-m-d");
$hoy_datatime = new \DateTime($hoy);
// $ellunes = date('Y-m-d', strtotime('-4 day'));
$ellunes = date('Y-m-d', strtotime('last monday'));
$consultaMail = $em->getRepository(MailDelivery::class)->findOneBy(
array(
'dateAt' => $hoy_datatime,
'system' => 'Informe Seguimiento Commercial Mante3',
'send' => 'si'
)
);
if (is_null($consultaMail)) {
$mailDelivery = new MailDelivery();
$mailDelivery->setDateAt($hoy_datatime);
$mailDelivery->setSystem('Informe Seguimiento Commercial Mante3');
$mailDelivery->setSend('si');
$em->persist($mailDelivery);
$em->flush();
$parametersA = array(
'hoy' => $hoy . ' 00:00:00',
'elLunes' => $ellunes . ' 00:00:00',
);
$dqlA = 'SELECT c
FROM CommercialBundle:CommercialTracking c
WHERE c.dateAt >= :elLunes AND c.dateAt <= :hoy
ORDER BY c.dateAt DESC';
$queryA = $em->createQuery($dqlA)->setParameters($parametersA);
$tracking = $queryA->getResult();
$data = array();
foreach ($tracking as $trackings) {
$user = $em->getRepository(User::class)->findOneById($trackings->getCommercialId());
$client = $em->getRepository(Client::class)->findOneById($trackings->getClientId());
$contact = $em->getRepository(ClientContact::class)->findOneById($trackings->getContactId());
$fecha = $trackings->getDateAt()->format('d/m/Y');
// El desarrollo de los proveedores al parecer Jorge no lo finalizo, por eso este condicional se agrega para evitar error 500
if (empty($client)) {
$client = $em->getRepository(Supplier::class)->findOneById($trackings->getSupplierId());
}
$data[$user->getName() . ' ' . $user->getLastName()][] = array(
'fecha' => $fecha,
'hourIn' => $trackings->getTimeStart()->format('H:m'),
'hourOut' => $trackings->getTimeEnd()->format('H:m'),
'client' => $client->getName(),
'contact' => $contact->getName() . ' ' . $contact->getLastName(),
'situation' => $this->translator->trans($trackings->getSituation()),
'commercial' => $user->getName() . ' ' . $user->getLastName(),
'observation' => $trackings->getMessage(),
);
}
$dqlZ = 'SELECT c
FROM App:Client c
WHERE c.createdAt >= :elLunes AND c.createdAt <= :hoy
ORDER BY c.createdAt DESC';
$queryZ = $em->createQuery($dqlZ)->setParameters($parametersA);
$clientsStoreLastWeek = $queryZ->getResult();
$commercialAgents = $em->getRepository(User::class)->findBy(array('team' => 7)); // Grupo Comercial (7)
$commercialAgentsId = array();
$dataB = array();
foreach ($commercialAgents as $item) { $commercialAgentsId[$item->getId()] = $item->getName() . ' ' . $item->getLastName(); }
foreach ($clientsStoreLastWeek as $item) {
foreach ($commercialAgentsId as $key => $elem) { if ($item->getCreatedId() == $key) { $dataB[] = array($elem, $item); } }
}
// Buscamos los correos de los administradores
$emailarray = array();
$usermails = $em->getRepository(User::class)->findByRole('ROLE_ADMIN');
foreach ($usermails as $usermail) {
$emailarray[] = $usermail->getEmail();
}
// $emailarray = 'gustavo.ayala@develup.solutions';
$transporter = new Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl')//ssl / tls
->setPort(465)// 465 / 587
->setUsername('desarrollo@develup.solutions')
->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = new Swift_Mailer($transporter);
$message = (new \Swift_Message())
->setSubject('Informe Seguimiento Commercial Mante3')
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setTo($emailarray)
->setBody(
$this->renderView(
'MDS/CommercialBundle/emails/list-email-report.html.twig',
array('data' => $data, 'dataB' => $dataB)
),
'text/html'
);
$mailer->send($message);
}
}
}