<?php
/**
* Created by Mediterranean Develup Solutions
* Date: 19/09/2019
*/
namespace App\Controller;
use App\Entity\Client;
use App\Entity\OutOfOffice;
use App\Entity\User;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use App\Form\OutOfOfficeType;
use App\MDS\EventsBundle\Entity\Proposal;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use Symfony\Contracts\Translation\TranslatorInterface;
class OutOfOfficeController extends AbstractController
{
private $translator;
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}
/**
* @Route("/outofoffice", name="outofoffice_home")
*/
public function indexOutOfOfficeAction(Request $request) {
return $this->redirectToRoute('outofoffice_index');
}
/**
* @Route("/outofoffice/list", name="outofoffice_index")
*/
public function listAction(Request $request) {
$em = $this->getDoctrine()->getManager();
// No se realizará la busqueda de todos los OOO, solo se listarán los que tengan fecha de hoy en adelante
$today = new \DateTime("now", NULL);
$yesterday = $today->modify("-1 day");
$parameters = array(
'yesterday' => $yesterday,
);
$dql = 'SELECT p
FROM App:OutOfOffice p
WHERE p.dateAt > :yesterday
ORDER BY p.dateAt DESC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$ooo = $query->getResult();
$data = array();
foreach($ooo as $item) {
if (!empty($item->getProposalId())) {
$proposal = $em->getRepository(Proposal::class)->findOneById($item->getProposalId());
$proposalInfo = '#'.$proposal->getId().' - '.$proposal->getTitle();
} else {
$proposal = null;
$proposalInfo = null;
}
$arrayAgents = array();
$arrayAgentsNames = array();
$arrayAgentsIds = explode(",", $item->getAgentsIds());
foreach ($arrayAgentsIds as $agentId){
$agent = $em->getRepository(User::class)->findOneById($agentId);
if(!is_null($agent)){
$arrayAgents[] = $agent;
$arrayAgentsNames[] = $agent->getName().' '.$agent->getLastName();
}
}
$agentsNames = implode(", ", $arrayAgentsNames);
if (!empty($item->getClientId())) {
$client = $em->getRepository(Client::class)->findOneById($item->getClientId());
} else {
$client = null;
}
$ref = ($item->getDateAt())->format('Ymd');
// Se eliminan las 2 primeras cifras del año 2000 para reducir la longitud del string
$ref = '#'.substr($ref,2);
if ($item->getDateAt() == $item->getDateFinalAt()){
$dateAt = ($item->getDateAt())->format('d-m-Y');
} else {
$dateAt = ($item->getDateAt())->format('d-m-Y').' al '.($item->getDateFinalAt())->format('d-m-Y');
}
$data[] = array(
'id' => $item->getId(),
'ref' => $ref,
'status' => $item->getStatus(),
'dateAt' => $dateAt,
'hourStart' => ($item->getHourStart())->format('H:i'),
'hourEnd' => ($item->getHourEnd())->format('H:i'),
'proposal' => $proposal,
'proposalInfo' => $proposalInfo,
'client' => $client,
'text' => $item->getText(),
'arrayAgents' => $arrayAgents,
'agentsNames' => $agentsNames
);
}
//d($data);exit();
//Usuario Loggeado
$loggedUser = $this->get('security.token_storage')->getToken()->getUser();
return $this->render('outofoffice/outofoffice/list-outofoffice.html.twig', array(
'outofoffice' => $data,
'historic' => false,
'user' => $loggedUser
));
}
/**
* @Route("/outofoffice/add", name="outofoffice_add")
*/
public function addOutOfOfficeAction(Request $request)
{
$ooo = new OutOfOffice();
$form = $this->createOutOfOfficeCreateForm($ooo);
return $this->render('outofoffice/outofoffice/add-outofoffice.html.twig',
array(
// 'description' => '',
'form' => $form->createView()
)
);
}
private function createOutOfOfficeCreateForm(OutOfOffice $entity)
{
$form = $this->createForm(OutOfOfficeType::class, $entity, array(
'action' => $this->generateUrl('outofoffice_create'),
'method' => 'POST'
));
return $form;
}
/**
* @Route("/outofoffice/create", name="outofoffice_create")
*/
public function createOutOfOfficeAction(Request $request)
{
$ooo = new OutOfOffice();
$form = $this->createOutOfOfficeCreateForm($ooo);
$form->handleRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$today = new \DateTime("now");
$ooo->setCreatedId($user_id);
$ooo->setUpdatedId($user_id);
$ooo->setCreatedAt($today);
$ooo->setUpdatedAt($today);
$ooo->setStatus(null);
if (!empty($ooo->getClientId())) {
$ooo->setClientId($ooo->getClientId()->getId());
}
if (!empty($ooo->getProposalId())) {
$ooo->setProposalId($ooo->getProposalId()->getId());
}
// Se genera la lista de los agentes
$listAgents = '';
/**
* @var ArrayCollection $ooo->getAgentsIds()
*/
foreach ($ooo->getAgentsIds() as $item){
if (!empty($listAgents)){
$listAgents = $listAgents.','.$item->getId();
} else {
$listAgents = $item->getId();
}
}
$ooo->setAgentsIds($listAgents);
//Verificación de fechas
if (empty($ooo->getDateFinalAt())){
$ooo->setDateFinalAt($ooo->getDateAt());
}
try{
$em->persist($ooo);
$em->flush();
// INICIO: Envio de Correo a administradores por FDO
// Nombre de los agentes involucrados en la FDO
$textoAgentes ='';
// Se genera el arreglo de agentes a partir del agentsIds
$arraysIds = explode(',',$ooo->getAgentsIds());
foreach ($arraysIds as $item){
$agent = $em->getRepository(User::class)->findOneById($item);
if(!empty($textoAgentes)){
$textoAgentes = $textoAgentes. ', '. $agent->getName().' '.$agent->getLastName();
} else {
$textoAgentes = $agent->getName().' '.$agent->getLastName();
}
}
if (!empty($ooo->getProposalId())){
$proposal = $em->getRepository(Proposal::class)->findOneById($ooo->getProposalId());
$textoProposal = ' '. $proposal->getTitle();
} else {
$textoProposal = '';
}
$loggedUser = $em->getRepository(User::class)->findOneById($user_id);
$allAdmins = $em->getRepository(User::class)->findBy(
array(
'role' => 'ROLE_ADMIN'
));
$mailAgentSent = array();
foreach ($allAdmins as $item){
$mailAgentSent[$item->getEmail()] = $item->getName().' '.$item->getLastName();
}
if ($ooo->getDateAt() == $ooo->getDateFinalAt()){
// Es un solo dia de actividad
$textoDias = 'El día de la actividad es: '.($ooo->getDateAt())->format('d/m/Y');
} else {
// Son varios dias de actividad
$textoDias = 'Los días de la actividad son: del '.($ooo->getDateAt())->format('d/m/Y').' al '.($ooo->getDateFinalAt())->format('d/m/Y');
}
$textoHoras = 'La actividad comienza a las '.($ooo->getHourStart())->format('H:i');
if (!((($ooo->getHourEnd())->format('H')=='00') and (($ooo->getHourEnd())->format('i')=='00'))) {
$textoHoras = $textoHoras . ' y finaliza a las ' . ($ooo->getHourEnd())->format('H:i');
}
$data = array(
'body' => '' . '<p>Estimado administrador, ha sido creada la actividad fuera de oficina. </p>
<p><h2>' . $textoProposal . '</h2></p>
<p>Los agentes de esta actividad son: <strong>' . $textoAgentes . '</strong></p>
<p>'.$textoDias.'</p>
<p>'.$textoHoras.'</p>
<br>
<br>
<a href="https://'.$_SERVER['HTTP_HOST'].'/outofoffice/status/1/' . $ooo->getId() .'"
style="background-color:#0048ff;border:1px solid #3870ff;border-radius:3px;color:#ffffff;display:inline-block;
font-family:sans-serif;font-size:16px;line-height:44px;text-align:center;text-decoration:none;width:150px"
target="_blank">Aprobar</a>
<a href="https://'.$_SERVER['HTTP_HOST'].'/outofoffice/edit/' . $ooo->getId() .'"
style="background-color:#5cb85c;border:1px solid #5cb85c;border-radius:3px;color:#ffffff;display:inline-block;
font-family:sans-serif;font-size:16px;line-height:44px;text-align:center;text-decoration:none;width:150px"
target="_blank">Editar</a>
<a href="https://'.$_SERVER['HTTP_HOST'].'/outofoffice/status/0/' . $ooo->getId() .'"
style="background-color:#ff0700;border:1px solid #d9534f;border-radius:3px;color:#ffffff;display:inline-block;
font-family:sans-serif;font-size:16px;line-height:44px;text-align:center;text-decoration:none;width:150px"
target="_blank">Rechazar</a>
<br>
<p>El usuario que hizo esta solicitud fue: ' . $loggedUser->getName() .' '. $loggedUser->getLastName() . '</p>'
,
// 'firm' => '' . '<div dir="ltr" style="color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 12.8px;"><table border="0" cellpadding="0" style="font-size: 13.3333px; font-family: Verdana, Arial, Helvetica, sans-serif;"><tbody><tr><td width="35%" style="font-family: arial, sans-serif; margin: 0px;"><img src="https://ci4.googleusercontent.com/proxy/xTPcHPPSpFqSf8EjRTvJIv21y6LHuzwbsDqBA4oxRzrrUZQWNYERW7oMbgXjw6CzSDsE9QqPHEk9PiNylx5UaAuSJykk6eA3WiyMGmZmQYc=s0-d-e1-ft#http://www.inout-travel.com/inout-travel/img/logo/logo.jpg" alt="Logo InOut Travel" class="CToWUd"></td><td width="65%" style="font-family: arial, sans-serif; margin: 0px;"><p style="margin-bottom: 0px;"></p><span style="font-size: small; color: rgb(0, 121, 186);"><b>M.I.C.E Dept.</b> <br></span><span style="font-size: x-small; color: rgb(0, 121, 186);">Phone : <a href="tel:+34%20911%2087%2083%2093" value="+34911878393" target="_blank" style="color: rgb(17, 85, 204);">+34 91 187 83 93</a> / <a href="tel:+34%20917%2058%2007%2020" value="+34917580720" target="_blank" style="color: rgb(17, 85, 204);">+34 91 758 07 20</a> </span><span style="font-size: x-small; color: rgb(0, 121, 186);">Fax : <a href="tel:+34%20911%2087%2083%2090" value="+34911878390" target="_blank" style="color: rgb(17, 85, 204);">+34 91 187 83 90</a> <br></span><span style="font-size: x-small; color: rgb(0, 121, 186);"><u></u><a href="mailto:eventos@inout-travel.com" target="_blank" style="color: rgb(17, 85, 204);">eventos@inout-travel.com </a><br></span><span style="font-size: small; color: rgb(0, 128, 128);"><a href="http://s.wisestamp.com/links?url=http%3A%2F%2Fs.wisestamp.com%2Flinks%3Furl%3Dhttps%253A%252F%252Furldefense.proofpoint.com%252Fv1%252Furl%253Fu%253Dhttp%253A%252F%252Fs.wisestamp.com%252Flinks%253Furl%25253Dhttp%2525253A%2525252F%2525252Fs.wisestamp.com%2525252Flinks%2525253Furl%2525253Dhttp%252525253A%252525252F%252525252Fwww.inout-travel.com%25252526amp%2525253Bsn%2525253D%252526sn%25253D%2526amp%253Bk%253D2BjihEEf49EEnl2c9cXhDQ%25253D%25253D%25250A%2526amp%253Br%253DoVBgYJTSgqKobIhrxHXwWFa1hslDOFZMhTZjQm3slhE%25253D%25250A%2526amp%253Bm%253DiRaDYfk0sXIZzunVdLJPLTs52u8wk7HMfjdCh290Q5I%25253D%25250A%2526amp%253Bs%253D1a9ff7d8f4f1fb953d74200f6537f77ca64418a966d39f4786e9aed71833d44c%26amp%3Bsn%3D&sn=" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=es&q=http://s.wisestamp.com/links?url%3Dhttp%253A%252F%252Fs.wisestamp.com%252Flinks%253Furl%253Dhttps%25253A%25252F%25252Furldefense.proofpoint.com%25252Fv1%25252Furl%25253Fu%25253Dhttp%25253A%25252F%25252Fs.wisestamp.com%25252Flinks%25253Furl%2525253Dhttp%252525253A%252525252F%252525252Fs.wisestamp.com%252525252Flinks%252525253Furl%252525253Dhttp%25252525253A%25252525252F%25252525252Fwww.inout-travel.com%2525252526amp%252525253Bsn%252525253D%25252526sn%2525253D%252526amp%25253Bk%25253D2BjihEEf49EEnl2c9cXhDQ%2525253D%2525253D%2525250A%252526amp%25253Br%25253DoVBgYJTSgqKobIhrxHXwWFa1hslDOFZMhTZjQm3slhE%2525253D%2525250A%252526amp%25253Bm%25253DiRaDYfk0sXIZzunVdLJPLTs52u8wk7HMfjdCh290Q5I%2525253D%2525250A%252526amp%25253Bs%25253D1a9ff7d8f4f1fb953d74200f6537f77ca64418a966d39f4786e9aed71833d44c%2526amp%253Bsn%253D%26sn%3D&source=gmail&ust=1516881697636000&usg=AFQjCNGFDs4JRUVibUfVQaFSuQ0u9PVwzQ" style="color: rgb(17, 85, 204); font-size: x-small;">http://www.inout-travel.com</a></span><p></p><span style="font-size: small; color: rgb(51, 102, 255);"><a href="https://www.facebook.com/InOutTravel/" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=es&q=https://www.facebook.com/InOutTravel/&source=gmail&ust=1516881697636000&usg=AFQjCNH3zSTpYN6Jn0ibd4io116DlxPPNg" style="color: rgb(17, 85, 204);"><span style="color: rgb(51, 102, 255);"><img src="https://ci5.googleusercontent.com/proxy/8luozs3Ef6tofaP9YvpFMJfUFEqz1QLUJ4pmjmbiZBmIbtfxbFDGS7mVrEd2y32b_P4vDTb14QmA1gowrSAKvtWxet9R3_02VVFOV4S3mKU=s0-d-e1-ft#https://s3.amazonaws.com/images.wisestamp.com/facebook.png" alt="Facebook" width="16" height="16" border="0" class="CToWUd"></span></a><span lang="ES"> </span><a href="https://twitter.com/inout_travel?lang=es" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=es&q=https://twitter.com/inout_travel?lang%3Des&source=gmail&ust=1516881697636000&usg=AFQjCNEe-ltzYrhEmNPcORkqhPnlInLutw" style="color: rgb(17, 85, 204);"><span style="color: rgb(51, 102, 255);"><img src="https://ci5.googleusercontent.com/proxy/6sqL0BxRRr4QwfAOhK_hNNAXIpUHZNg-gl3CPQKITbX2dpT2jMTzf3zlwMmhB9BgxZehJzFQT_AJzsskN1uQR-SqppTRLIbJIILDeDNjlA=s0-d-e1-ft#https://s3.amazonaws.com/images.wisestamp.com/twitter.png" alt="Twitter" width="16" height="16" border="0" class="CToWUd"></span></a><span lang="ES"> </span><span style="color: rgb(255, 102, 0);"><strong><span lang="ES">Visítanos en las redes sociales!!</span></strong></span></span></td></tr></tbody></table><img src="https://ci4.googleusercontent.com/proxy/rDdypMfZKWPkRRuCB3bp8PSQXo0k5aswGQRjFzy71EB2XEQkr4_rbaroShG2FEJbnrmwoEfE3-Z6r_hNFlfRMNPC1X8yjwJ2eOmZ1DagWHkl8sh7Y60=s0-d-e1-ft#http://www.inout-travel.com/inout-travel/img/logo/firma_MICE.png" class="CToWUd"><br><div></div></div><div dir="ltr" style="color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 12.8px;"><p style="text-align: justify; text-indent: 7.1pt; line-height: 14.72px;"><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">De conformidad con lo dispuesto en la Ley Orgánica 15/1999 de Protección de Datos de carácter Personal VIAJES IN OUT TRAVEL, S.L., domiciliado en </span><a href="https://maps.google.com/?q=C/+CRISTOBAL+BORDIU,+53+-+28003+MADRID&entry=gmail&source=g" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=es&q=https://maps.google.com/?q%3DC/%2BCRISTOBAL%2BBORDIU,%2B53%2B-%2B28003%2BMADRID%26entry%3Dgmail%26source%3Dg&source=gmail&ust=1516881697636000&usg=AFQjCNFHPMBadB0TD0U63EsqPiOZ7TPldg" style="color: rgb(17, 85, 204);"><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">C/ CRISTOBAL BORDIU, 53 - 28003 MADRID</span></a><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">, le informa que los datos que nos ha proporcionado formarán parte de un fichero de datos de carácter personal, responsabilidad de dicha entidad, con la finalidad de gestionar las comunicaciones que pudiera mantener con el personal de la misma.</span></p><p style="text-align: justify; text-indent: 7.1pt; line-height: 14.72px;"><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">En el supuesto de que desee ejercitar los derechos que le asisten de acceso, rectificación, cancelación y oposición dirija una comunicación por escrito a VIAJES IN OUT TRAVEL, S.L. a la dirección </span><a href="https://maps.google.com/?q=C/+CRISTOBAL+BORDIU,+53+-+28003+MADRID&entry=gmail&source=g" target="_blank" data-saferedirecturl="https://www.google.com/url?hl=es&q=https://maps.google.com/?q%3DC/%2BCRISTOBAL%2BBORDIU,%2B53%2B-%2B28003%2BMADRID%26entry%3Dgmail%26source%3Dg&source=gmail&ust=1516881697636000&usg=AFQjCNFHPMBadB0TD0U63EsqPiOZ7TPldg" style="color: rgb(17, 85, 204);"><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">C/ CRISTOBAL BORDIU, 53 - 28003 MADRID</span></a><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;"> incluyendo copia de su Documento Nacional de Identidad o documento identificativo equivalente, ó a través de un mensaje de correo electrónico a la dirección </span><a href="mailto:info@inout-travel.com" target="_blank" style="color: rgb(17, 85, 204);"><b><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">info@inout-travel.com</span></b></a><b><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">.</span></b></p><p style="text-align: justify; text-indent: 7.1pt; line-height: 14.72px;"><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">La información contenida en el presente mensaje de correo electrónico es confidencial y su acceso únicamente está autorizado al destinatario original del mismo, quedando prohibida cualquier comunicación, divulgación, o reenvío, tanto del mensaje como de su contenido. En el supuesto de que usted no sea el destinatario autorizado, le rogamos borre el contenido del mensaje y nos comunique dicha circunstancia a través de un mensaje de correo electrónico a la dirección </span><a href="mailto:info@inout-travel.com" target="_blank" style="color: rgb(17, 85, 204);"><b><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">info@inout-travel.com</span></b></a><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;"> o al teléfono<b> </b></span><a href="tel:911%2087%2083%2091" target="_blank" style="color: rgb(17, 85, 204);"><b><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">+34 </span></b></a><b><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;"> </span></b><a href="tel:917%2058%2007%2085" target="_blank" style="color: rgb(17, 85, 204);"><b><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">917580785</span></b></a><span style="font-size: 10pt; line-height: 15.3333px; font-family: Arial, sans-serif;">.</span></p></div>',
'firm' => '',
);
// EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
$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();
$message->setSubject('#' . $ooo->getId() . ', Nueva Actividad Fuera de Oficina')
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setTo($mailAgentSent)
//->setTo('eduardo.pagola@develup.solutions')
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
// FIN: Envio de Correo a administradores por FDO
$event = 'The Activities has been created..';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajesupplier', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajeactivitieserror', $errorMessage);
}
return $this->redirectToRoute('outofoffice_index');
}else{
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajeactivitieserror', $errorMessage);
}
return $this->render('activities/activities/add-outofoffice.html.twig', array(
// 'description' => $description_form,
'form' => $form->createView())
);
}
/**
* @Route("/outofoffice/edit/{id}", name="outofoffice_edit")
*/
public function editOutOfOfficeAction($id)
{
$em = $this->getDoctrine()->getManager();
$ooo = $em->getRepository(OutOfOffice::class)->findOneById($id);
// Se genera el arreglo de agentes a partir del agentsIds
$arraysIds = explode(',',$ooo->getAgentsIds());
$agents = array();
foreach ($arraysIds as $item){
$agent = $em->getRepository(User::class)->findOneById($item);
$agents[] = $agent;
}
$ooo->setAgentsIds($agents);
// Se genera el cliente a partir del clientId
if(!empty($ooo->getClientId())){
$ooo->setClientId($em->getRepository(Client::class)->findOneById($ooo->getClientId()));
}
// Se genera el proposal a partir del proposalId
if(!empty($ooo->getProposalId())){
$ooo->setProposalId($em->getRepository(Proposal::class)->findOneById($ooo->getProposalId()));
}
$form = $this->createEditOutOfOfficeForm($ooo, $id);
return $this->render('outofoffice/outofoffice/edit-outofoffice.html.twig',
array(
'id' =>$id,
'ooo' => $ooo,
'form' => $form->createView(),
)
);
}
private function createEditOutOfOfficeForm(OutOfOffice $entity, $id)
{
// d($entity, $id);exit();
$form = $this->createForm(OutOfOfficeType::class, $entity,
array(
'action' => $this->generateUrl('outofoffice_update',
array(
'id' => $id
)
), 'method' => 'PUT'));
return $form;
}
/**
* @Route("/outofoffice/update/{id}", name="outofoffice_update", methods={"POST"})
*/
public function updateOutOfOfficeAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$ooo = $em->getRepository(OutOfOffice::class)->findOneById($id);
$agentsID = $ooo->getAgentsIds();
$agentsID = explode(',',$agentsID);
//Se convierte en arreglo de objetos lo Ids para que este acorde con el formulario
$arrayObj = array();
foreach ($agentsID as $item){
$arrayObj[] = $em->getRepository(User::class)->findOneById($item);
}
$ooo->setAgentsIds($arrayObj);
//Se convierte en objeto el ProposalId para que este acorde con el formulario
if(!empty($ooo->getProposalId())) {
$ooo->setProposalId($em->getRepository(Proposal::class)->findOneById($ooo->getProposalId()));
}
//Se convierte en objeto el ClientId para que este acorde con el formulario
if(!empty($ooo->getClientId())) {
$ooo->setClientId($em->getRepository(Client::class)->findOneById($ooo->getClientId()));
}
$form = $this->createEditOutOfOfficeForm($ooo, $id);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
//Se genera el string de AgentsIds a partir del objeto
$arrayObj = $ooo->getAgentsIds();
$txtAgentsIds ='';
foreach ($arrayObj as $item){
if (!empty($txtAgentsIds)){
$txtAgentsIds = $txtAgentsIds.','.$item->getId();
} else {
$txtAgentsIds = $item->getId();
}
}
$ooo->setAgentsIds($txtAgentsIds);
if (!empty($ooo->getClientId())){
$ooo->setClientId(($ooo->getClientId()->getId()));
}
if (!empty($ooo->getProposalId())){
$ooo->setProposalId(($ooo->getProposalId()->getId()));
}
//Verificación de fechas
if (empty($ooo->getDateFinalAt())){
$ooo->setDateFinalAt($ooo->getDateAt());
}
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$today = new \DateTime("now");
$ooo->setUpdatedId($user_id);
$ooo->setUpdatedAt($today);
$em = $this->getDoctrine()->getManager();
try{
$em->persist($ooo);
$em->flush();
$event = 'The Activities has been modified.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeactivities', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage().' | transport';
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajeactivitieserror', $errorMessage);
}
/* Fin Gestión de eventos en Log */
$successMessage = $this->translator->trans('The Activities has been modified.');
$this->addFlash('mensajeactivities', $successMessage);
return $this->redirectToRoute('outofoffice_index');
}
return $this->render('/outofoffice/outofoffice/edit-outofoffice.html.twig', array(
'id'=> $id,
'ooo' => $ooo,
'form' => $form->createView()));
}
/**
* @Route("/outofoffice/delete/{id}", name="outofoffice_delete")
*/
public function deleteOutOfOfficeAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$ooo = $em->getRepository(OutOfOffice::class)->findOneById($id);
try{
$em->remove($ooo);
$em->flush();
$event = 'The '.$ooo->getId().' segment has been Deleted.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensaje', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage().' | Activities';
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajeerror', $errorMessage);
}
return $this->redirectToRoute('outofoffice_index');
}
/**
* @Route("/outofoffice/status/{idst}/{id}", name="outofoffice_status")
*/
public function statusOutOfOfficeAction($idst,$id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$ooo = $em->getRepository(OutOfOffice::class)->findOneById($id);
if ($idst ==1){
$ooo->setStatus(1);
} else {
$ooo->setStatus(0);
}
try{
$em->persist($ooo);
$em->flush();
$event = 'The Activities has been modified.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensaje', $successMessage);
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage().' | transport';
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajeactivitieserror', $errorMessage);
}
return $this->redirectToRoute('outofoffice_index');
}
/**
* @Route("/outofoffice/events", name="get_outofoffice")
*/
public function outofofficeSelectAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$parameters = array(
'status' => true,
);
$dql = 'SELECT p
FROM App\Entity\OutOfOffice p
WHERE p.status = :status
ORDER BY p.dateAt ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$ooo = $query->getResult();
//Usuario Loggeado
$loggedUser = $this->get('security.token_storage')->getToken()->getUser();
$datos = array();
if (!empty($ooo)){
foreach($ooo as $item) {
$arrayAgents = array();
$arrayAgentsNames = array();
$arrayAgentsIds = explode(",", $item->getAgentsIds());
foreach ($arrayAgentsIds as $agentId){
$agent = $em->getRepository(User::class)->findOneById($agentId);
if(!is_null($agent)){
$arrayAgents[] = $agent;
$arrayAgentsNames[] = $agent->getName().' '.$agent->getLastName();
}
}
$agentsNames = implode("<br> ", $arrayAgentsNames);
$tooltip = $item->getText();
$title = '(FDO.)<br>'.($item->getHourStart())->format('H:i').'<br>'.$agentsNames;
$color = "#ff0000";
$desde = ($item->getDateAt())->format('Y-m-d') .' '.($item->getHourStart())->format('H:i');
$hasta = ($item->getDateFinalAt())->format('Y-m-d') .' '.($item->getHourEnd())->format('H:i');
if ($loggedUser->getRole() == 'ROLE_ADMIN'){
$url = "/outofoffice/edit/" . $item->getId();
} else {
$url = "/outofoffice/view/" . $item->getId();
}
if (!empty($item)){
$datos[] = array(
"id" => $item->getId(),
"title" => $title,
"tooltip" => $tooltip,
"start" => $desde,
"end" => $hasta,
"color" => $color,
"url" => $url,
);
} else {
$datos = [];
}
}
}
$return = array(
'outofoffice' => $datos,
);
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/outofoffice/listhistoric", name="outofoffice_listhistoric")
*/
public function listHistoricAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$today = new \DateTime("now", NULL);
$parameters = array(
'today' => $today,
);
$dql = 'SELECT p
FROM App:OutOfOffice p
WHERE p.dateAt < :today
ORDER BY p.dateAt DESC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$ooo = $query->getResult();
$data = array();
foreach($ooo as $item) {
if (!empty($item->getProposalId())) {
$proposal = $em->getRepository(Proposal::class)->findOneById($item->getProposalId());
$proposalInfo = '#'.$proposal->getId().' - '.$proposal->getTitle();
} else {
$proposal = null;
$proposalInfo = null;
}
$arrayAgents = array();
$arrayAgentsNames = array();
$arrayAgentsIds = explode(",", $item->getAgentsIds());
foreach ($arrayAgentsIds as $agentId){
$agent = $em->getRepository(User::class)->findOneById($agentId);
if(!is_null($agent)){
$arrayAgents[] = $agent;
$arrayAgentsNames[] = $agent->getName().' '.$agent->getLastName();
}
}
$agentsNames = implode(", ", $arrayAgentsNames);
if (!empty($item->getClientId())) {
$client = $em->getRepository(Client::class)->findOneById($item->getClientId());
} else {
$client = null;
}
$data[] = array(
'id' => $item->getId(),
'status' => $item->getStatus(),
'dateAt' => ($item->getDateAt())->format('Y-m-d'),
'hourStart' => ($item->getHourStart())->format('H:i'),
'hourEnd' => ($item->getHourEnd())->format('H:i'),
'proposal' => $proposal,
'proposalInfo' => $proposalInfo,
'client' => $client,
'text' => $item->getText(),
'arrayAgents' => $arrayAgents,
'agentsNames' => $agentsNames
);
}
//Usuario Loggeado
$loggedUser = $this->get('security.token_storage')->getToken()->getUser();
return $this->render('outofoffice/outofoffice/list-outofoffice.html.twig', array(
'outofoffice' => $data,
'historic' => true,
'user' => $loggedUser
));
}
/**
* @Route("/outofoffice/view/{id}", name="outofoffice_view")
*/
public function viewOutOfOfficeAction($id)
{
$em = $this->getDoctrine()->getManager();
$ooo = $em->getRepository(OutOfOffice::class)->findOneById($id);
// Se genera el arreglo de agentes a partir del agentsIds
$arraysIds = explode(',',$ooo->getAgentsIds());
$agents = array();
foreach ($arraysIds as $item){
$agent = $em->getRepository(User::class)->findOneById($item);
$agents[] = $agent;
}
$ooo->setAgentsIds($agents);
// Se genera el cliente a partir del clientId
if(!empty($ooo->getClientId())){
$ooo->setClientId($em->getRepository(Client::class)->findOneById($ooo->getClientId()));
}
// Se genera el proposal a partir del proposalId
if(!empty($ooo->getProposalId())){
$ooo->setProposalId($em->getRepository(Proposal::class)->findOneById($ooo->getProposalId()));
}
$form = $this->createViewOutOfOfficeForm($ooo, $id);
return $this->render('outofoffice/outofoffice/view-outofoffice.html.twig',
array(
'id' =>$id,
'ooo' => $ooo,
'form' => $form->createView(),
)
);
}
private function createViewOutOfOfficeForm(OutOfOffice $entity, $id)
{
// d($entity, $id);exit();
$form = $this->createForm(OutOfOfficeType::class, $entity,
array(
'action' => $this->generateUrl('outofoffice_watch',
array(
'id' => $id
)
), 'method' => 'PUT'));
return $form;
}
/**
* @Route("/outofoffice/watch/{id}", name="outofoffice_watch", methods={"POST"})
*/
public function watchOutOfOfficeAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$ooo = $em->getRepository(OutOfOffice::class)->findOneById($id);
$agentsID = $ooo->getAgentsIds();
$agentsID = explode(',',$agentsID);
//Se convierte en arreglo de objetos lo Ids para que este acorde con el formulario
$arrayObj = array();
foreach ($agentsID as $item){
$arrayObj[] = $em->getRepository(User::class)->findOneById($item);
}
$ooo->setAgentsIds($arrayObj);
//Se convierte en objeto el ProposalId para que este acorde con el formulario
if(!empty($ooo->getProposalId())) {
$ooo->setProposalId($em->getRepository(Proposal::class)->findOneById($ooo->getProposalId()));
}
//Se convierte en objeto el ClientId para que este acorde con el formulario
if(!empty($ooo->getClientId())) {
$ooo->setClientId($em->getRepository(Client::class)->findOneById($ooo->getClientId()));
}
$form = $this->createEditOutOfOfficeForm($ooo, $id);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
//Se genera el string de AgentsIds a partir del objeto
$arrayObj = $ooo->getAgentsIds();
$txtAgentsIds ='';
foreach ($arrayObj as $item){
if (!empty($txtAgentsIds)){
$txtAgentsIds = $txtAgentsIds.','.$item->getId();
} else {
$txtAgentsIds = $item->getId();
}
}
$ooo->setAgentsIds($txtAgentsIds);
if (!empty($ooo->getClientId())){
$ooo->setClientId(($ooo->getClientId()->getId()));
}
if (!empty($ooo->getProposalId())){
$ooo->setProposalId(($ooo->getProposalId()->getId()));
}
//Verificación de fechas
if (empty($ooo->getDateFinalAt())){
$ooo->setDateFinalAt($ooo->getDateAt());
}
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$today = new \DateTime("now");
$ooo->setUpdatedId($user_id);
$ooo->setUpdatedAt($today);
$em = $this->getDoctrine()->getManager();
try{
if ($user_logueado->getRole()=='ROLE_ADMIN') {
// En modo vista solo puede modificar un administrador
$em->persist($ooo);
$em->flush();
$event = 'The Activities has been modified.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeactivities', $successMessage);
}
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage().' | transport';
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajeactivitieserror', $errorMessage);
}
/* Fin Gestión de eventos en Log */
$successMessage = $this->translator->trans('The Activities has been modified.');
$this->addFlash('mensajeactivities', $successMessage);
return $this->redirectToRoute('outofoffice_index');
}
return $this->render('/outofoffice/outofoffice/view-outofoffice.html.twig', array(
'id'=> $id,
'ooo' => $ooo,
'form' => $form->createView()));
}
/**
* @Route("/outofoffice/getProposalsOfClient", name="get_proposals_of_client")
*/
public function getProposalsOfClientAction(Request $request) {
$clientId = $_POST['clientId'];
$em = $this->getDoctrine()->getManager();
if ($clientId == 0){
$proposals = $em->getRepository(Proposal::class)->findAll();
} else {
$proposals = $em->getRepository(Proposal::class)->findBy(
array(
'clientId' => $clientId
)
);
}
$datos = array();
if (!empty($proposals)){
foreach($proposals as $item){
$datos[] = array(
"id" => $item->getId(),
"title" => $item->getId() . ' - ' . $item->getTitle(),
);
}
}
$return = array(
'proposals' => $datos,
'id' => $clientId,
);
$response = new JsonResponse($return);
return $response;
}
}