<?php
/**
* Created by Mediterranean Develup Solutions
* User: jorge.defreitas@develup.solutions
* Date: 07/08/2017
* Time: 10:55
*/
namespace App\MDS\EventsBundle\Controller;
use App\Entity\Client;
use App\Entity\ClientContact;
use App\Entity\PresentationMusic;
use App\Entity\SendMail;
use App\Entity\SettingsOffice;
use App\Entity\SettingsRol;
use App\Entity\SettingsTeam;
use App\Entity\SupplierSettingsType;
use App\Entity\User;
use App\MDS\AvexpressBundle\Entity\AveFiles;
use App\MDS\DevelupBundle\Entity\MdvTelegramUser;
use App\MDS\EventsBundle\Entity\Proposal;
use App\MDS\EventsBundle\Entity\ProposalControl;
use App\MDS\EventsBundle\Entity\ProposalSupplierControl;
use App\MDS\EventsBundle\Entity\ProposalSupplierServices;
use App\MDS\EventsBundle\Entity\ProposalAgents;
use App\MDS\EventsBundle\Entity\ProposalBriefingList;
use App\MDS\EventsBundle\Entity\ProposalTracing;
use App\MDS\EventsBundle\Form\ProposalType;
use DateTime;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\Session\Session;
use Google_Client;
use Google_Service_Calendar;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class ProposalController extends AbstractController
{
private $translator;
protected $googleCalendar;
private $validator;
public function __construct(TranslatorInterface $translator, ValidatorInterface $validator)
{
// $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;
$this->validator = $validator;
}
/*
* ATENCION LAS RAIZ DE @Route POR DEFECTO DEL BUNDLE: EventsBundle ES /events/, NO PONERLO EN LA @Route("")
*
* */
/**
* @Route("/proposal/add/", name="proposal_add")
*/
public function addAction(Request $request)
{
$proposal = new Proposal();
$proposal->setDateProposedAt(new \DateTime("now"));
$form = $this->createProposalCreateForm($proposal);
$em = $this->getDoctrine()->getManager();
$type_supplier = $em->getRepository(SupplierSettingsType::class)->findAll();
// $userAgents = $em->getRepository(User::class)->findAll();
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$userAgents = $query->getResult();
/* FIN Consulta de agente activos MICE */
$nameGeneral = $this->translator->trans('SUPPLIER');
$type = array();
foreach($type_supplier as $typesupplier){
$type[$nameGeneral.' '.$typesupplier->getGroupBase()][$typesupplier->getBase()] = array(
'typeName' => $typesupplier->getBase()
);
}
$services['AGRUPATION OF SERVICES'] = array(
'IDEA' => array(
'typeName' => 'IDEA'
),
'ACTIVITY' => array(
'typeName' => 'ACTIVITY'
)
);
$destinos['DESTINATION'] = array(
'DESTINATION' => array(
'typeName' => 'DESTINATION'
)
);
$type_data = array_merge($type, $services, $destinos);
return $this->render('MDS/EventsBundle/proposal/add-proposal.html.twig',
array(
'typeSupplier' => $type_data,
'userAgents' => $userAgents,
'form' => $form->createView()
)
);
}
private function createProposalCreateForm(Proposal $entity)
{
$form = $this->createForm(ProposalType::class, $entity, array(
'action' => $this->generateUrl('proposal_create'),
'method' => 'POST'
));
return $form;
}
//public function createProposalAction(Request $request, LoggerInterface $logger)
/**
* @Route("/proposal/create", name="proposal_create")
*/
public function createProposalAction(Request $request)
{
// Se genera la información de la tabla Proposal_Agents (Porcentajes de agentes)
$propAgents = new ProposalAgents();
if($request->request->get('agent')['Agent3']['agentId']!=''){
$propAgents->setAgThree($request->request->get('agent')['Agent3']['agentId']);
$propAgents->setAgThreePerc($request->request->get('percent')['3']);
$propAgents->setAgThreeWork($request->request->get('agentWork')['3']);
} else {
$propAgents->setAgThree(null);
$propAgents->setAgThreePerc(0);
$propAgents->setAgThreeWork(null);
}
if($request->request->get('agent')['Agent4']['agentId']!=''){
$propAgents->setAgFour($request->request->get('agent')['Agent4']['agentId']);
$propAgents->setAgFourPerc($request->request->get('percent')['4']);
$propAgents->setAgFourWork($request->request->get('agentWork')['4']);
} else {
$propAgents->setAgFour(null);
$propAgents->setAgFourPerc(0);
$propAgents->setAgFourWork(null);
}
if($request->request->get('agent')['Agent1']['agentId']!=''){
$propAgents->setAgOne($request->request->get('agent')['Agent1']['agentId']);
$propAgents->setAgOnePerc($request->request->get('percent')['1']);
$propAgents->setAgOneWork($request->request->get('agentWork')['1']);
} else {
$propAgents->setAgOne(null);
$propAgents->setAgOnePerc(0);
$propAgents->setAgOneWork(null);
}
if($request->request->get('agent')['Agent2']['agentId']!=''){
$propAgents->setAgTwo($request->request->get('agent')['Agent2']['agentId']);
$propAgents->setAgTwoPerc($request->request->get('percent')['2']);
$propAgents->setAgTwoWork($request->request->get('agentWork')['2']);
} else {
$propAgents->setAgTwo(null);
$propAgents->setAgTwoPerc(0);
$propAgents->setAgTwoWork(null);
}
if ($request->request->get('percent')['1']==''){
$propAgents->setAgOnePerc(0);
} else {
$propAgents->setAgOnePerc($request->request->get('percent')['1']);
}
/* prevenir que contacto no este en blanco */
$proposal = new Proposal();
$form = $this->createProposalCreateForm($proposal);
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
// $userAgents = $em->getRepository(User::class)->findAll();
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$userAgents = $query->getResult();
/* FIN Consulta de agente activos MICE */
$contactId = $form->get('contactId')->getData();
$contactIdConstraint = new Assert\NotBlank();
$errorList = $this->validator->validate($contactId, $contactIdConstraint);
if (!count($errorList) == 0) {
$errorMessage_contact = $this->translator->trans('Check contact field');
} else {
$errorMessage_contact = "";
}
if (!is_null($contactId)){
/* Consulta el agente comercial asignado */
$data_contact = $em->getRepository(ClientContact::class)->findOneById($contactId);
$proposal->setAgencommercialId($data_contact->getAssignedAgent());
}
$office_proposal = $form->get('officeId')->getData();
if(!is_null($office_proposal)){
$proposal->setOfficeId($office_proposal->getId());
}
$client_proposal = $form->get('clientId')->getData();
if(!is_null($client_proposal)){
$proposal->setClientId($client_proposal->getId());
}
// $agent_proposal = $form->get('agentId')->getData();
$agent_proposal = ($request->request->get('agent')['Agent1']['agentId']);
if(!(is_null($agent_proposal) or empty($agent_proposal))){
$proposal->setAgentId($agent_proposal);
}
$team_proposal = $form->get('teamId')->getData();
if(!is_null($team_proposal)){
$proposal->setTeamId($team_proposal->getId());
}
$idmusic_proposal = $form->get('idMusic')->getData();
if(!is_null($idmusic_proposal)){
$proposal->setIdMusic($idmusic_proposal->getId());
}
//$agenttwo_proposal = array(($request->request->get('agent')['Agent2']['agentId']),($request->request->get('agent')['Agent3']['agentId']),($request->request->get('agent')['Agent4']['agentId']));
$agenttwo_proposal = array();
if (($request->request->get('agent')['Agent2']['agentId'])!=''){
//agrego a 2
$agenttwo_proposal[] = ($request->request->get('agent')['Agent2']['agentId']);
if (($request->request->get('agent')['Agent3']['agentId'])!=''){
//agrego a 3
$agenttwo_proposal[] = ($request->request->get('agent')['Agent3']['agentId']);
if (($request->request->get('agent')['Agent4']['agentId'])!=''){
//agrego a 4
$agenttwo_proposal[] = ($request->request->get('agent')['Agent4']['agentId']);
}
} else {
// no agrego 3
if (($request->request->get('agent')['Agent4']['agentId'])!=''){
//agrego a 4
$agenttwo_proposal[] = ($request->request->get('agent')['Agent4']['agentId']);
}
}
} else {
// no agrego 2
if (($request->request->get('agent')['Agent3']['agentId'])!=''){
//agrego a 3
$agenttwo_proposal[] = ($request->request->get('agent')['Agent3']['agentId']);
} else {
// no agrego 3
if (($request->request->get('agent')['Agent4']['agentId'])!=''){
//agrego a 4
$agenttwo_proposal[] = ($request->request->get('agent')['Agent4']['agentId']);
}
}
}
$str_array_agents = implode(",", $agenttwo_proposal);
$proposal->setAgentTwoId($str_array_agents);
if(isset($request->request->get('proposal_esp')['type'])){
// d($request->request->get('proposal')['type']);
$select_type = $request->request->get('proposal_esp')['type'];
if(!is_null($select_type)){
$proposal->setSelectType(implode(",", $select_type));
}
}
$type_supplier = $em->getRepository(SupplierSettingsType::class)->findAll();
$type = array();
foreach($type_supplier as $typesupplier){
$type[$typesupplier->getBase()] = array(
'typeName' => $typesupplier->getBase()
);
}
if($form->isValid() && count($errorList) == 0)
{
$proposal->setContactId($contactId);
$proposal->setStatus('Pending');
//Access Key para entrar en el proposal
$accessKey = md5('CR-JDEF'. rand() * time());
$proposal->setAccessKey($accessKey);
$proposal->setViewedAt(new \DateTime("now"));
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$proposal->setCreatedId($user_id);
$proposal->setUpdatedId($user_id);
/* Gestión de eventos en Log */
$user_lastname = $user_logueado->getLastname();
$user_name = $user_logueado->getName();
$user_email = $user_logueado->getEmail();
$user_rol = $user_logueado->getRoles();
$event_url = $request->getPathInfo();
$event_complete = $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
// -------------- INICIO: Si el usuario logeado es un ROLE_USER (no es ADMIN) no hay asignacion de agentes
if ($user_logueado->getRole()=='ROLE_USER'){
$proposal->setAgentId(null);
$proposal->setAgentTwoId(null);
$propAgents->setAgOne(null);
$propAgents->setAgOnePerc(null);
$propAgents->setAgOneWork(null);
$propAgents->setAgTwo(null);
$propAgents->setAgTwoPerc(null);
$propAgents->setAgTwoWork(null);
$propAgents->setAgThree(null);
$propAgents->setAgThreePerc(null);
$propAgents->setAgThreeWork(null);
$propAgents->setAgFour(null);
$propAgents->setAgFourPerc(null);
$propAgents->setAgFourWork(null);
}
// -------------- FIN: Si el usuario logeado es un ROLE_USER (no es ADMIN) no hay asignacion de agentes
if (empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
$em->persist($proposal);
$em->flush();
$zeroPropAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
$identificador = $proposal->getId();
$propAgents->setIdProp($identificador);
$em->persist($propAgents);
$em->flush();
// Se verifica si es la primera asignacion de agente para enviar correo al cliente
if (is_null($zeroPropAgents)){
// Primera insercion del agente
if (($propAgents->getAgOne() != 0) and (!empty($propAgents->getAgOne()))){
// y no viene vacio ni en cero -- A L E R T A R
// Envio de correo notificacion al CLIENTE asignado
$time = new \DateTime("now");
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$allAgents = '<table width="100%">';
if ($propAgents->getAgOne() != 0){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgOne());
$allAgents = $allAgents . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
if (($propAgents->getAgTwo() != 0) and (!empty($propAgents->getAgTwo()))){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgTwo());
$allAgents = $allAgents . '<tr height="10px"></tr><tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
if (($propAgents->getAgThree() != 0) and (!empty($propAgents->getAgThree()))){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgThree());
$allAgents = $allAgents . '<tr height="10px"></tr><tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
if (($propAgents->getAgFour() != 0) and (!empty($propAgents->getAgFour()))){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgFour());
$allAgents = $allAgents . '<tr height="10px"></tr><tr>
<td width="10%">'.
// '<img src="https://'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
$allAgents = $allAgents .'</table>';
$clara = $em->getRepository(User::class)->findOneByEmail('clara.pedreno@avexpress.tv');
// Tabla de datos CLARA / DEPARTAMENTO DE RENDER Y CREATIVIDAD
$tabClara = '<table width="100%">';
$tabClara = $tabClara . '<tr>
<td width="10%">'.
// '<img src="https://'.$_SERVER['HTTP_HOST'].'/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $clara->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $clara->getName().' '. $clara->getLastName().' <br> Teléfono: '. $clara->getMobile() .' <br> Correo electrónico: '. $clara->getEmail() .'</td></tr>';
$tabClara = $tabClara .'</table>';
// Tabla de datos CLARA / DEPARTAMENTO DE RENDER Y CREATIVIDAD
// Tabla de datos Jorge / DEPARTAMENTO DE TECNOLOGIA
if (!(strpos($proposal->getSelectType(),'TECNOLOGÍA')===false)){
// Tecnología estaba seleccionada entre las opciones
$jorge = $em->getRepository(User::class)->findOneByEmail('jorge.defreitas@develup.solutions');
$tabJorge = '<table width="100%">';
$tabJorge = $tabJorge . '<tr>
<td width="10%">'.
// '<img src="https://'.$_SERVER['HTTP_HOST'].'/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $jorge->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $jorge->getName().' '. $jorge->getLastName().' <br> Teléfono: '. $jorge->getMobile() .' <br> Correo electrónico: '. $jorge->getEmail() .'</td></tr>';
$tabJorge = $tabJorge .'</table>';
$tabClara = $tabClara .'</p><p><b>Departamento de Tecnología </b></p><p>'. $tabJorge;
}
// Tabla de datos Jorge / DEPARTAMENTO DE TECNOLOGIA
$rafa = $em->getRepository(User::class)->findOneByEmail('rafael.guerrero@inout-travel.com');
// Tabla de datos RAFA
$tabRafa = '<table width="100%">';
$tabRafa = $tabRafa . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $rafa->getName().' '. $rafa->getLastName().' <br> Teléfono: '. $rafa->getMobile() .' <br> Correo electrónico: '. $rafa->getEmail() .'</td></tr>';
$tabRafa = $tabRafa .'</table>';
// FIN Tabla de datos RAFA
$salva = $em->getRepository(User::class)->findOneByEmail('salvador@avexpress.tv');
// Tabla de datos SALVA
$tabSalva = '<table width="100%">';
$tabSalva = $tabSalva . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $salva->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $salva->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $salva->getName().' '. $salva->getLastName().' <br> Teléfono: '. $salva->getMobile() .' <br> Correo electrónico: '. $salva->getEmail() .'</td></tr>';
$tabSalva = $tabSalva .'</table>';
// FIN Tabla de datos SALVA
$zclient = $em->getRepository(Client::class)->findOneById($proposal->getClientId());
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$zagentReplyTo = array(
$agent->getEmail() => $agent->getName().' '. $agent->getLastName()
);
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$zclient->getEmail() => $zclient->getName()
);
$mailAgentFrom = array(
$agent->getEmail() => $agent->getName().' '. $agent->getLastName()
);
$data = array(
// 'body' => ''. '<p>Estimado cliente,</p><p>Gracias por esta nueva solicitud y por confiar una vez más en nosotros. </p><p>Su petición ha sido dada de alta en nuestro sistema y ya estamos trabajando en su propuesta, en breve recibirá una comunicación de nuestro agente.</p><p> </p><p><b><h2>' . $proposal->getTitle() . '</h2></b></p><p></p><p>Su equipo para esta propuesta estará formado por:</p><p> </p><p></p><b>Project Manager </b></p><p>'. $allAgents .'</p><p></p><b><br>Director de producción audiovisual y escenografía</b></p><p>'. $tabSalva . '</p><p><b>Director de departamento y creatividad </b></p><p>'. $tabRafa . '</p><p><b>Departamento de Eventos </b></p><p>Teléfono: (+34) 911 878 393 - Correo electrónico: events@inout-travel.com</p><p> </p><p>Gracias de nuevo por su amable petición, en breve recibirá nuestra propuesta. </p><p> </p>',
'body' => ''. '<p>Estimado cliente,</p><p>Gracias por esta nueva solicitud y por confiar una vez más en nosotros. </p><p>Su petición ha sido dada de alta en nuestro sistema y ya estamos trabajando en su propuesta, en breve recibirá una comunicación de nuestro agente.</p><p> </p><p><b><h2>' . $proposal->getTitle() . '</h2></b></p><p></p><p>Su equipo para esta propuesta estará formado por:</p><p> </p><p></p><b>Project Manager </b></p><p>'. $allAgents .'</p><p><b>Departamento de Renderización y Creatividad </b></p><p>'. $tabClara .'</p><p></p><b><br>Director de producción audiovisual y escenografía</b></p><p>'. $tabSalva . '</p><p><b>Director de departamento y creatividad </b></p><p>'. $tabRafa . '</p><p><b>Departamento de Eventos </b></p><p>Teléfono: (+34) 911 878 393 - Correo electrónico: events@inout-travel.com</p><p> </p><p>Gracias de nuevo por su amable petición, en breve recibirá nuestra propuesta. </p><p> </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="http://firmas.inout.events/firmas/events/LOGO_INOUT_TRAVEL&EVENTS.png" 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>',
);
if (!empty($zclient->getEmail())) {
// 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($agent->getEmail())
->setPassword($agent->getPassGmail());
$mailer = new \Swift_Mailer($transporter);
$message = new \Swift_Message();
$message->setSubject('P#' . $proposal->getId() . ', Alta de petición')
->setSender($agentMail)
->setFrom($mailAgentFrom)
->setReplyTo($zagentReplyTo)
->setTo($mailAgentSent)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
}
}
} else {
// verificamos si lo que existia en la tabla en agentOne es cero es porque no se le habia asignado a nadie
if ($zeroPropAgents->getAgOne() == 0){
// A L E R T A R
// Envio de correo notificacion al CLIENTE asignado
$time = new \DateTime("now");
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$allAgents = '<table width="100%">';
if ($propAgents->getAgOne() != 0){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgOne());
$allAgents = $allAgents . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
if ($propAgents->getAgTwo() != 0){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgTwo());
$allAgents = $allAgents . '<tr height="10px"></tr><tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
if ($propAgents->getAgThree() != 0){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgThree());
$allAgents = $allAgents . '<tr height="10px"></tr><tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
if ($propAgents->getAgFour() != 0){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgFour());
$allAgents = $allAgents . '<tr height="10px"></tr><tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
$allAgents = $allAgents .'</table>';
$clara = $em->getRepository(User::class)->findOneByEmail('clara.pedreno@avexpress.tv');
// Tabla de datos CLARA / DEPARTAMENTO DE RENDER Y CREATIVIDAD
$tabClara = '<table width="100%">';
$tabClara = $tabClara . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $clara->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $clara->getName().' '. $clara->getLastName().' <br> Teléfono: '. $clara->getMobile() .' <br> Correo electrónico: '. $clara->getEmail() .'</td></tr>';
$tabClara = $tabClara .'</table>';
// Tabla de datos CLARA / DEPARTAMENTO DE RENDER Y CREATIVIDAD
// Tabla de datos Jorge / DEPARTAMENTO DE TECNOLOGIA
if (!(strpos($proposal->getSelectType(),'TECNOLOGÍA')===false)){
// Tecnología estaba seleccionada entre las opciones
$jorge = $em->getRepository(User::class)->findOneByEmail('jorge.defreitas@develup.solutions');
$tabJorge = '<table width="100%">';
$tabJorge = $tabJorge . '<tr>
<td width="10%">'.
// '<img src="https://'.$_SERVER['HTTP_HOST'].'/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $jorge->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $jorge->getName().' '. $jorge->getLastName().' <br> Teléfono: '. $jorge->getMobile() .' <br> Correo electrónico: '. $jorge->getEmail() .'</td></tr>';
$tabJorge = $tabJorge .'</table>';
$tabClara = $tabClara .'</p><p><b>Departamento de Tecnología </b></p><p>'. $tabJorge;
}
// Tabla de datos Jorge / DEPARTAMENTO DE TECNOLOGIA
$rafa = $em->getRepository(User::class)->findOneByEmail('rafael.guerrero@inout-travel.com');
// Tabla de datos RAFA
$tabRafa = '<table width="100%">';
$tabRafa = $tabRafa . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $rafa->getName().' '. $rafa->getLastName().' <br> Teléfono: '. $rafa->getMobile() .' <br> Correo electrónico: '. $rafa->getEmail() .'</td></tr>';
$tabRafa = $tabRafa .'</table>';
// FIN Tabla de datos RAFA
$salva = $em->getRepository(User::class)->findOneByEmail('salvador@avexpress.tv');
// Tabla de datos SALVA
$tabSalva = '<table width="100%">';
$tabSalva = $tabSalva . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $salva->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $salva->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $salva->getName().' '. $salva->getLastName().' <br> Teléfono: '. $salva->getMobile() .' <br> Correo electrónico: '. $salva->getEmail() .'</td></tr>';
$tabSalva = $tabSalva .'</table>';
// FIN Tabla de datos SALVA
$zclient = $em->getRepository(Client::class)->findOneById($proposal->getClientId());
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$zagentReplyTo = array(
$agent->getEmail() => $agent->getName().' '. $agent->getLastName()
);
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$zclient->getEmail() => $zclient->getName()
);
$data = array(
// 'body' => ''. '<p>Estimado cliente,</p><p>Gracias por esta nueva solicitud y por confiar una vez más en nosotros. </p><p>Su petición ha sido dada de alta en nuestro sistema y ya estamos trabajando en su propuesta, en breve recibirá una comunicación de nuestro agente.</p><p> </p><p><b><h2>' . $proposal->getTitle() . '</h2></b></p><p></p><p>Su equipo para esta propuesta estará formado por:</p><p> </p><p></p><b>Project Manager </b></p><p>'. $allAgents .'</p><p></p><b><br>Director de producción audiovisual y escenografía</b></p><p>'. $tabSalva . '</p><p><b>Director de departamento y creatividad </b></p><p>'. $tabRafa . '</p><p><b>Departamento de Eventos </b></p><p>Teléfono: (+34) 911 878 393 - Correo electrónico: events@inout-travel.com</p><p> </p><p>Gracias de nuevo por su amable petición, en breve recibirá nuestra propuesta. </p><p> </p>',
'body' => ''. '<p>Estimado cliente,</p><p>Gracias por esta nueva solicitud y por confiar una vez más en nosotros. </p><p>Su petición ha sido dada de alta en nuestro sistema y ya estamos trabajando en su propuesta, en breve recibirá una comunicación de nuestro agente.</p><p> </p><p><b><h2>' . $proposal->getTitle() . '</h2></b></p><p></p><p>Su equipo para esta propuesta estará formado por:</p><p> </p><p></p><b>Project Manager </b></p><p>'. $allAgents .'</p><p><b>Departamento de Renderización y Creatividad </b></p><p>'. $tabClara .'</p><p></p><b><br>Director de producción audiovisual y escenografía</b></p><p>'. $tabSalva . '</p><p><b>Director de departamento y creatividad </b></p><p>'. $tabRafa . '</p><p><b>Departamento de Eventos </b></p><p>Teléfono: (+34) 911 878 393 - Correo electrónico: events@inout-travel.com</p><p> </p><p>Gracias de nuevo por su amable petición, en breve recibirá nuestra propuesta. </p><p> </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="http://firmas.inout.events/firmas/events/LOGO_INOUT_TRAVEL&EVENTS.png" 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>',
);
// 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($agent->getEmail())
->setPassword($agent->getPassGmail());
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject('P#' . $proposal->getId() . ', Alta de petición')
->setSender($agentMail)
->setFrom($mailAgent)
->setReplyTo($zagentReplyTo)
->setTo($mailAgentSent)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
}
}
// FIN Se verifica si es la primera asignacion de agente para enviar correo al cliente
$event = 'The Proposal has been created.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeproposaldestination', $successMessage);
if(!is_null($proposal->getAgentId()))
{
// Envio de correo notificacion al agente asignado
$time = new \DateTime("now");
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$agent->getEmail() => $agent->getName() . ' ' . $agent->getLastName()
);
$data = array(
'body' => 'P#' . $proposal->getId() . ', ' . $proposal->getTitle() . '<br><a href="http://' . $request->server->get('HTTP_HOST') . '/events/proposal/edit/' . $proposal->getId() . '">Ir al Proposal</a><br><br>Alerta de Proposal Asignado: ' . $time->format('d/m/Y H:i:s') . '<br><br>',
'firm' => $firmGmail,
);
// 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('P#' . $proposal->getId() . ', Alerta de Proposal Asignado')
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setReplyTo($mailAgentSent)
->setTo($mailAgent)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
}
if (empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
try{
$em->persist($proposal);
$em->flush();
$event = 'The Client has been created. Now, add some contacts';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeclient', $successMessage);
// Alertar por Telegram y correo a Rafa y Elena
$this->sendTelegramMail(6, $proposal->getId(),'Nuevo Proposal: #'.$proposal->getId(). ' - '.$proposal->getTitle(). ' - BRIEFING: ' .$proposal->getBriefing());
$this->sendTelegramMail(22, $proposal->getId(),'Nuevo Proposal: #'.$proposal->getId(). ' - '.$proposal->getTitle(). ' - BRIEFING: ' .$proposal->getBriefing());
$this->sendTelegramMail(20, $proposal->getId(),'Nuevo Proposal: #'.$proposal->getId(). ' - '.$proposal->getTitle(). ' - BRIEFING: ' .$proposal->getBriefing());
} catch (\Exception $e){
$event = 'An error occurred: '.$e->getMessage();
/* Para el usuario */
$errorMessage = $this->translator->trans($event);
$this->addFlash('mensajeclienterror', $errorMessage);
}
/* Fin Gestión de eventos en Log */
$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));
return $this->redirectToRoute('proposal_destination_view',
array(
'id' => $proposal->getId()
)
);
}else{
$errorMessagebase = $this->translator->trans('Error, some fields are empty');
$errorMessage = $errorMessagebase.' | '.$errorMessage_contact;
$this->addFlash('mensajeproposalerror', $errorMessage);
}
return $this->render('MDS/EventsBundle/proposal/add-proposal.html.twig', array(
'typeSupplier' => $type,
'userAgents' => $userAgents,
'form' => $form->createView()
)
);
}
/**
* @Route("/proposal/list", name="proposal_list")
*/
public function indexListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$desde = isset($request->request->get('buscarFecha')['desde'])? $request->request->get('buscarFecha')['desde'] : '';
$hasta = isset($request->request->get('buscarFecha')['hasta'])? $request->request->get('buscarFecha')['hasta'] : '';
$cliente = isset($request->request->get('buscarFecha')['clientid'])? $request->request->get('buscarFecha')['clientid'] : '';
$agentId = isset($request->request->get('data')['agent'])? $request->request->get('data')['agent'] : '';
$busquedaporagente = false;
if (empty($desde) && empty($hasta))
{
if(empty($cliente))
{
if(empty($agentId))
{
$hoy = date('Y-m-01', strtotime('-2 month'));
$parameters = array(
'hoy' => $hoy,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :hoy
AND p.status != :status AND p.agentId is not null
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
else
{
$busquedaporagente = true;
$hoy = date('Y-m-01', strtotime('-2 month'));
$parameters = array(
'agentId' => $agentId,
'hoy' => $hoy,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
INNER JOIN EventsBundle:ProposalAgents u with u.idProp = p.id
WHERE (p.dateEventStarAt >= :hoy AND p.status != :status) AND ((p.agentId = :agentId) OR (u.agOne= :agentId))
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposalsOne = $query->getResult();
foreach ($proposalsOne as $item){
// $item->setAgentTwoId('1'.($item->getDateEventStarAt())->format('Ymd'));
$item->setAgentTwoId('1');
}
$dql = 'SELECT p
FROM EventsBundle:Proposal p
INNER JOIN EventsBundle:ProposalAgents u with u.idProp = p.id
WHERE (p.dateEventStarAt >= :hoy AND p.status != :status) AND (u.agTwo= :agentId)
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposalsTwo = $query->getResult();
foreach ($proposalsTwo as $item){
$item->setAgentTwoId('2');
}
$dql = 'SELECT p
FROM EventsBundle:Proposal p
INNER JOIN EventsBundle:ProposalAgents u with u.idProp = p.id
WHERE (p.dateEventStarAt >= :hoy AND p.status != :status) AND (u.agThree= :agentId)
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposalsThree = $query->getResult();
foreach ($proposalsThree as $item){
$item->setAgentTwoId('3');
}
$dql = 'SELECT p
FROM EventsBundle:Proposal p
INNER JOIN EventsBundle:ProposalAgents u with u.idProp = p.id
WHERE (p.dateEventStarAt >= :hoy AND p.status != :status) AND (u.agFour= :agentId)
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposalsFour = $query->getResult();
foreach ($proposalsFour as $item){
$item->setAgentTwoId('4');
}
$proposals = array_merge($proposalsOne,$proposalsTwo,$proposalsThree,$proposalsFour);
}
}
else
{ // el cliente no viene vacio
if(empty($agentId))
{
/* Si solo tiene el cliente id lo reenvió a consulta por id cliente */
return $this->redirectToRoute('proposal_list_client', array(
'id' => $cliente
));
}
else
{ //el cliente no viene vacio y hay agente
// $hoy = date('Y') . '-01-01';
// $hoy = date('Y-m-01', strtotime('-12 month'));
$hoy = date('Y-m-01', strtotime('-2 month'));
$parameters = array(
'agentId' => $agentId,
'cliente' => $cliente,
'hoy' => $hoy,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :hoy
AND p.status != :status AND p.agentId = :agentId AND p.clientId = :cliente
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
}
} else {
/* Consulta con fechas desde y hasta con id cliente */
if(!empty($cliente)){
if(!empty($agentId)){
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'cliente' => $cliente,
'agentId' => $agentId,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.clientId = :cliente AND p.status != :status AND p.agentId = :agentId
ORDER BY p.id DESC';
} else {
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'cliente' => $cliente,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.clientId = :cliente AND p.status != :status AND p.agentId is not null
ORDER BY p.id DESC';
}
} else {
if(!empty($agentId)){
/* Consulta con fechas desde y hasta sin id cliente */
$parameters = array(
'agentId' => $agentId,
'desde' => $desde,
'hasta' => $hasta,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.status != :status AND p.agentId = :agentId
ORDER BY p.id DESC';
} else {
/* Consulta con fechas desde y hasta sin id cliente */
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.status != :status AND p.agentId is not null
ORDER BY p.id DESC';
}
}
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
$datos_proposal = array();
foreach($proposals as $proposal){
/*
* Estado, date create, id, Nombre, Cliente, Comercial, Equipo, Usuario, Inicio, Fin
* */
switch ($proposal->getStatus()) {
case "Pending":
// $iconstatus ='<i class="icon-bell3 text-danger parpadea"></i>';
$iconstatus ='<i class="icon-hammer text-danger parpadea"></i>';
break;
case "Sent":
$iconstatus ='<i class="icon-paperplane text-orange"></i>';
break;
case "Confirmed":
// $iconstatus ='<i class="icon-unlocked text-success"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-green-800"></i>';
break;
case "Invoiced":
// $iconstatus ='<i class="icon-lock2 text-gold"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-gold"></i>';
break;
case "Cancel":
// $iconstatus ='<i class=" icon-blocked text-grey"></i>';
$iconstatus ='<i class="icon-thumbs-down3 text-danger"></i>';
break;
case "Blocked":
$iconstatus ='<i class="icon-lock2 text-grey"></i>';
break;
case "Unblocked":
$iconstatus ='<i class="icon-unlocked2 text-black"></i>';
break;
}
if ($proposal->getSent() == "Yes"){
$iconsent ='<i class="icon-paperplane text-orange"></i>';
if ($proposal->getStatus() == "Pending"){
// $iconstatus ='<i class="icon-bell3 text-danger"></i>';
$iconstatus ='<i class="icon-hammer text-danger"></i>';
}
} else {
$iconsent ='';
}
/* Consultas */
$client = $em->getRepository(Client::class)->findOneByid($proposal->getClientId());
$contact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$commercial = $em->getRepository(User::class)->findOneById($proposal->getAgencommercialId());
if(empty($commercial)){$comercial="";}else{$comercial = $commercial->getName();}
$teams = $em->getRepository(SettingsTeam::class)->findOneById($proposal->getTeamId());
if(empty($teams)){$team="";}else{$team = $teams->getTeam();}
$agente = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if(empty($agente)){$agent="";}else{$agent = $agente->getName();}
/* Visto por ultima ves por parte del cliente o atraves del Access Key */
if ($proposal->getViewedAt() == $proposal->getCreatedAt()){
//no Visto
$novisto = $this->translator->trans('Not seen');
}else{
//visto
$novisto = $this->translator->trans('Seen by Client');
}
//Nombres resumidos de los agentes
$allAgentesResumidos = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
$agentesResumidos = '';
$nombreOne= '';
if (!empty($allAgentesResumidos)) {
if (!empty($allAgentesResumidos->getAgOne())) {
if ($allAgentesResumidos->getAgOne() != 0) {
// Hay Agente One
$theOne = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgOne());
if (empty($theOne)){ $theOne = $em->getRepository(User::class)->findOneByid(6); }
$nombreOne = $theOne->getName() . ' ' . substr($theOne->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreOne;
} else {
$agentesResumidos = $nombreOne;
}
}
}
if (!empty($allAgentesResumidos->getAgTwo())) {
if ($allAgentesResumidos->getAgTwo() != 0) {
// Hay Agente Two
$theTwo = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgTwo());
if (empty($theTwo)){ $theTwo = $em->getRepository(User::class)->findOneByid(6); }
$nombreTwo = $theTwo->getName() . ' ' . substr($theTwo->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreTwo;
} else {
$agentesResumidos = $nombreTwo;
}
}
}
if (!empty($allAgentesResumidos->getAgThree())) {
if ($allAgentesResumidos->getAgThree() != 0) {
// Hay Agente Three
$theThree = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgThree());
if (empty($theThree)){ $theThree = $em->getRepository(User::class)->findOneByid(6); }
$nombreThree = $theThree->getName() . ' ' . substr($theThree->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreThree;
} else {
$agentesResumidos = $nombreThree;
}
}
}
if (!empty($allAgentesResumidos->getAgFour())) {
if ($allAgentesResumidos->getAgFour() != 0) {
// Hay Agente Four
$theFour = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgFour());
if (empty($theFour)){ $theFour = $em->getRepository(User::class)->findOneByid(6); }
$nombreFour = $theFour->getName() . ' ' . substr($theFour->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreFour;
} else {
$agentesResumidos = $nombreFour;
}
}
}
}
if (strpos($agentesResumidos,',')===false){
//Hay mas de un agente
$masdeunagente = true;
$agentView = $agent;
} else {
//No hay mas de un agente
$masdeunagente = false;
$agentView = $agentesResumidos;
}
//Nombres resumidos de los agentes
if(empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
$name = empty($contact)? '' : $contact->getName();
$lastname = empty($contact)? '' : $contact->getLastname();
$contacto = $name .' '. $lastname;
$datos_proposal[] = array(
'status' => $this->translator->trans($proposal->getStatus()),
'iconstatus' => $iconstatus,
'iconsent' => $iconsent,
'viewedAt' => $proposal->getViewedAt()->format('d/m/Y H:i:s'),
'novisto' => $novisto,
'create' => $proposal->getDateProposedAt()->format('d/m/Y'),
'id' => $proposal->getId(),
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'name' => $proposal->getName(),
'client' => $client == Null? '' : $client->getName(),
'client_id' => $client == Null? '' : $client->getId(),
'contact' => $contacto,
'contactdepartment' => empty($contact)? '' : $contact->getDepartment(),
'contactphone' => empty($contact)? '' : $contact->getPhone(),
'contactmovil' => empty($contact)? '' : $contact->getMobile(),
'contactmail' => empty($contact)? '' : $contact->getEmail(),
'commercial' => $comercial,
'team' => $team,
'agent' => $agentView,
'event_star' => $proposal->getDateEventStarAt()->format('d/m/Y'),
'event_end' => $proposal->getDateEventEndAt()->format('d/m/Y'),
'list_client' => 'si',
'send' => $proposal->getSent(),
'masdeunagente' => $masdeunagente,
'agentesResumidos' => $agentesResumidos,
'busquedaporagente' => $busquedaporagente,
'refagent' => $agentView
);
}
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$agent_data = $query->getResult();
/* FIN Consulta de agente activos MICE */
return $this->render('MDS/EventsBundle/proposal/list-proposal.html.twig', array(
'proposals' => $datos_proposal,
'unassigned' => '',
'agents' => $agent_data,
));
}
/**
* @Route("/proposal/cancel/list", name="proposal_cancel_list")
*/
public function indexCancelListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$desde = isset($request->request->get('buscarFecha')['desde'])? $request->request->get('buscarFecha')['desde'] : '';
$hasta = isset($request->request->get('buscarFecha')['hasta'])? $request->request->get('buscarFecha')['hasta'] : '';
$cliente = isset($request->request->get('buscarFecha')['clientid'])? $request->request->get('buscarFecha')['clientid'] : '';
if (empty($desde) && empty($hasta))
{
if(empty($cliente))
{
// $proposals = $em->getRepository(Proposal::class)->findAll();
// $proposals = $em->getRepository(Proposal::class)->findBy(array(), array('dateProposedAt' => 'DESC'));
// $proposals = $em->getRepository(Proposal::class)->findBy(array(), array('id' => 'DESC'));
// $hoy = new \DateTime("Y");
$hoy = date('Y').'-01-01';
// $hoy->modify('-3 month');
$parameters = array(
'hoy' => $hoy,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :hoy
AND p.status = :status
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
} else {
/* Si solo tiene el cliente id lo reenvió a consulta por id cliente */
return $this->redirectToRoute('proposal_list_client', array(
'id' => $cliente
));
}
} else {
/* Consulta con fechas desde y hasta con id cliente */
if(!empty($cliente)){
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'cliente' => $cliente,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.clientId = :cliente AND p.status = :status
ORDER BY p.id DESC';
// ORDER BY p.dateProposedAt DESC';
} else {
/* Consulta con fechas desde y hasta sin id cliente */
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateProposedAt >= :desde AND p.dateProposedAt <= :hasta AND p.status = :status
ORDER BY p.id DESC';
// ORDER BY p.dateProposedAt DESC';
}
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
$datos_proposal = array();
foreach($proposals as $proposal){
/*
* Estado, date create, id, Nombre, Cliente, Comercial, Equipo, Usuario, Inicio, Fin
* */
switch ($proposal->getStatus()) {
case "Pending":
// $iconstatus ='<i class="icon-bell3 text-danger parpadea"></i>';
$iconstatus ='<i class="icon-hammer text-danger parpadea"></i>'; // martillo rojo
break;
case "Sent":
$iconstatus ='<i class="icon-paperplane text-orange"></i>';
break;
case "Confirmed":
// $iconstatus ='<i class="icon-unlocked text-success"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-green-800"></i>'; // pulgar arriba verde
break;
case "Invoiced":
// $iconstatus ='<i class="icon-lock2 text-gold"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-gold"></i>'; // pulgar arriba dorado
break;
case "Cancel":
// $iconstatus ='<i class=" icon-blocked text-grey"></i>';
$iconstatus ='<i class="icon-thumbs-down3 text-danger"></i>'; // pulgar abajo rojo
break;
case "Blocked":
// $iconstatus ='<i class=" icon-blocked text-grey"></i>';
$iconstatus ='<i class="icon-lock2 text-grey"></i>'; // candado
break;
}
if ($proposal->getSent() == "Yes"){
$iconsent ='<i class="icon-paperplane text-orange"></i>';
if ($proposal->getStatus() == "Pending"){
// $iconstatus ='<i class="icon-bell3 text-danger"></i>';
$iconstatus ='<i class="icon-hammer text-danger"></i>';
}
} else {
$iconsent ='';
}
/* Consultas */
$client = $em->getRepository(Client::class)->findOneByid($proposal->getClientId());
$contact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$commercial = $em->getRepository(User::class)->findOneById($proposal->getAgencommercialId());
if(empty($commercial)){$comercial="";}else{$comercial = $commercial->getName();}
$teams = $em->getRepository(SettingsTeam::class)->findOneById($proposal->getTeamId());
if(empty($teams)){$team="";}else{$team = $teams->getTeam();}
$agente = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if(empty($agente)){$agent="";}else{$agent = $agente->getName();}
/* Visto por ultima ves por parte del cliente o atraves del Access Key */
if ($proposal->getViewedAt() == $proposal->getCreatedAt()){
//no Visto
$novisto = $this->translator->trans('Not seen');
} else {
//visto
$novisto = $this->translator->trans('Seen by Client');
}
//Nombres resumidos de los agentes
$allAgentesResumidos = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
$agentesResumidos = '';
$nombreOne= '';
if (!empty($allAgentesResumidos)) {
if (!empty($allAgentesResumidos->getAgOne())) {
if ($allAgentesResumidos->getAgOne() != 0) {
// Hay Agente One
$theOne = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgOne());
if (empty($theOne)){ $theOne = $em->getRepository(User::class)->findOneByid(6); }
$nombreOne = $theOne->getName() . ' ' . substr($theOne->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreOne;
} else {
$agentesResumidos = $nombreOne;
}
}
}
if (!empty($allAgentesResumidos->getAgTwo())) {
if ($allAgentesResumidos->getAgTwo() != 0) {
// Hay Agente Two
$theTwo = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgTwo());
if (empty($theTwo)){ $theTwo = $em->getRepository(User::class)->findOneByid(6); }
$nombreTwo = $theTwo->getName() . ' ' . substr($theTwo->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreTwo;
} else {
$agentesResumidos = $nombreTwo;
}
}
}
if (!empty($allAgentesResumidos->getAgThree())) {
if ($allAgentesResumidos->getAgThree() != 0) {
// Hay Agente Three
$theThree = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgThree());
if (empty($theThree)){ $theThree = $em->getRepository(User::class)->findOneByid(6); }
$nombreThree = $theThree->getName() . ' ' . substr($theThree->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreThree;
} else {
$agentesResumidos = $nombreThree;
}
}
}
if (!empty($allAgentesResumidos->getAgFour())) {
if ($allAgentesResumidos->getAgFour() != 0) {
// Hay Agente Four
$theFour = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgFour());
if (empty($theFour)){ $theFour = $em->getRepository(User::class)->findOneByid(6); }
$nombreFour = $theFour->getName() . ' ' . substr($theFour->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreFour;
} else {
$agentesResumidos = $nombreFour;
}
}
}
}
if (strpos($agentesResumidos,',')===false){
//Hay mas de un agente
$masdeunagente = true;
$agentView = $agent;
} else {
//No hay mas de un agente
$masdeunagente = false;
$agentView = $agentesResumidos;
}
//Nombres resumidos de los agentes
if(empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
$datos_proposal[] = array(
'status' => $this->translator->trans($proposal->getStatus()),
'iconstatus' => $iconstatus,
'iconsent' => $iconsent,
'viewedAt' => $proposal->getViewedAt()->format('d/m/Y H:i:s'),
'novisto' => $novisto,
'create' => $proposal->getDateProposedAt()->format('d/m/Y'),
'id' => $proposal->getId(),
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'name' => $proposal->getName(),
'client' => $client->getName(),
'client_id' => $client->getId(),
'contact' => $contact->getName().' '.$contact->getLastname(),
'contactdepartment' => $contact->getDepartment(),
'contactphone' => $contact->getPhone(),
'contactmovil' => $contact->getMobile(),
'contactmail' => $contact->getEmail(),
'commercial' => $comercial,
'team' => $team,
'agent' => $agent,
'event_star' => $proposal->getDateEventStarAt()->format('d/m/Y'),
'event_end' => $proposal->getDateEventEndAt()->format('d/m/Y'),
'list_client' => 'si',
'send' => $proposal->getSent(),
// 'refagent' => ''
'refagent' => $agentView
);
}
// $agent_data = $em->getRepository(User::class)->findAll();
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$agent_data = $query->getResult();
/* FIN Consulta de agente activos MICE */
return $this->render('MDS/EventsBundle/proposal/list-proposal.html.twig', array(
'proposals' => $datos_proposal,
'unassigned' => '',
'agents' => $agent_data,
));
}
/**
* @Route("/proposal/unassigned/list", name="proposal_list_unassigned")
*/
public function indexListUnassignedAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$desde = isset($request->request->get('buscarFecha')['desde'])? $request->request->get('buscarFecha')['desde'] : '';
$hasta = isset($request->request->get('buscarFecha')['hasta'])? $request->request->get('buscarFecha')['hasta'] : '';;
$cliente = isset($request->request->get('buscarFecha')['clientid'])? $request->request->get('buscarFecha')['clientid'] : '';
if (empty($desde) && empty($hasta))
{
if(empty($cliente))
{
// $proposals = $em->getRepository(Proposal::class)->findAll();
// $proposals = $em->getRepository(Proposal::class)->findBy(array(), array('dateProposedAt' => 'DESC'));
// $proposals = $em->getRepository(Proposal::class)->findBy(array(), array('id' => 'DESC'));
// $hoy = new \DateTime("Y");
$hoy = date('Y').'-01-01';
// $hoy->modify('-3 month');
$parameters = array(
// 'hoy' => $hoy
'cancel' => 'Cancel'
);
// $dql = 'SELECT p
// FROM EventsBundle:Proposal p
// WHERE p.dateEventStarAt >= :hoy AND p.agentId IS null
// ORDER BY p.id DESC';
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.agentId IS null AND p.status != :cancel
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
} else {
/* Si solo tiene el cliente id lo reenvió a consulta por id cliente */
return $this->redirectToRoute('proposal_list_client', array(
'id' => $cliente
));
}
} else {
/* Consulta con fechas desde y hasta con id cliente */
if(!empty($cliente)){
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'cliente' => $cliente
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.clientId = :cliente and p.agentId IS null
ORDER BY p.id DESC';
// ORDER BY p.dateProposedAt DESC';
} else {
/* Consulta con fechas desde y hasta sin id cliente */
$parameters = array(
'desde' => $desde,
'hasta' => $hasta
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateProposedAt >= :desde AND p.dateProposedAt <= :hasta and (p.agentId IS null)
ORDER BY p.id DESC';
// ORDER BY p.dateProposedAt DESC';
}
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
$datos_proposal = array();
foreach($proposals as $proposal){
/*
* Estado, date create, id, Nombre, Cliente, Comercial, Equipo, Usuario, Inicio, Fin
* */
switch ($proposal->getStatus()) {
case "Pending":
// $iconstatus ='<i class="icon-bell3 text-danger parpadea"></i>';
$iconstatus ='<i class="icon-hammer text-danger parpadea"></i>';
break;
case "Sent":
$iconstatus ='<i class="icon-paperplane text-orange"></i>';
break;
case "Confirmed":
// $iconstatus ='<i class="icon-unlocked text-success"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-green-800"></i>';
break;
case "Invoiced":
// $iconstatus ='<i class="icon-lock2 text-gold"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-gold"></i>';
break;
case "Cancel":
// $iconstatus ='<i class=" icon-blocked text-grey"></i>';
$iconstatus ='<i class="icon-thumbs-down3 text-danger"></i>';
break;
case "Blocked":
// $iconstatus ='<i class=" icon-blocked text-grey"></i>';
$iconstatus ='<i class="icon-lock2 text-grey"></i>';
break;
}
if ($proposal->getSent() == "Yes"){
$iconsent ='<i class="icon-paperplane text-orange"></i>';
if ($proposal->getStatus() == "Pending"){
// $iconstatus ='<i class="icon-bell3 text-danger"></i>';
$iconstatus ='<i class="icon-hammer text-danger"></i>';
}
}else{
$iconsent ='';
}
/* Consultas */
$client = $em->getRepository(Client::class)->findOneByid($proposal->getClientId());
$contact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$commercial = $em->getRepository(User::class)->findOneById($proposal->getAgencommercialId());
if(empty($commercial)){$comercial="";}else{$comercial = $commercial->getName();}
$teams = $em->getRepository(SettingsTeam::class)->findOneById($proposal->getTeamId());
if(empty($teams)){$team="";}else{$team = $teams->getTeam();}
$agente = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if(empty($agente)){$agent="";}else{$agent = $agente->getName();}
/* Visto por ultima ves por parte del cliente o atraves del Access Key */
if ($proposal->getViewedAt() == $proposal->getCreatedAt()){
//no Visto
$novisto = $this->translator->trans('Not seen');
}else{
//visto
$novisto = $this->translator->trans('Seen by Client');
}
//Nombres resumidos de los agentes
$allAgentesResumidos = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
$agentesResumidos = '';
$nombreOne= '';
if (!empty($allAgentesResumidos)) {
if (!empty($allAgentesResumidos->getAgOne())) {
if ($allAgentesResumidos->getAgOne() != 0) {
// Hay Agente One
$theOne = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgOne());
if (empty($theOne)){ $theOne = $em->getRepository(User::class)->findOneByid(6); }
$nombreOne = $theOne->getName() . ' ' . substr($theOne->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreOne;
} else {
$agentesResumidos = $nombreOne;
}
}
}
if (!empty($allAgentesResumidos->getAgTwo())) {
if ($allAgentesResumidos->getAgTwo() != 0) {
// Hay Agente Two
$theTwo = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgTwo());
if (empty($theTwo)){ $theTwo = $em->getRepository(User::class)->findOneByid(6); }
$nombreTwo = $theTwo->getName() . ' ' . substr($theTwo->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreTwo;
} else {
$agentesResumidos = $nombreTwo;
}
}
}
if (!empty($allAgentesResumidos->getAgThree())) {
if ($allAgentesResumidos->getAgThree() != 0) {
// Hay Agente Three
$theThree = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgThree());
if (empty($theThree)){ $theThree = $em->getRepository(User::class)->findOneByid(6); }
$nombreThree = $theThree->getName() . ' ' . substr($theThree->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreThree;
} else {
$agentesResumidos = $nombreThree;
}
}
}
if (!empty($allAgentesResumidos->getAgFour())) {
if ($allAgentesResumidos->getAgFour() != 0) {
// Hay Agente Four
$theFour = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgFour());
if (empty($theFour)){ $theFour = $em->getRepository(User::class)->findOneByid(6); }
$nombreFour = $theFour->getName() . ' ' . substr($theFour->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreFour;
} else {
$agentesResumidos = $nombreFour;
}
}
}
}
if (strpos($agentesResumidos,',')===false){
//Hay mas de un agente
$masdeunagente = true;
$agentView = $agent;
} else {
//No hay mas de un agente
$masdeunagente = false;
$agentView = $agentesResumidos;
}
//Nombres resumidos de los agentes
if(empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
$datos_proposal[] = array(
'status' => $this->translator->trans($proposal->getStatus()),
'iconstatus' => $iconstatus,
'iconsent' => $iconsent,
'viewedAt' => $proposal->getViewedAt()->format('d/m/Y H:i:s'),
'novisto' => $novisto,
'create' => $proposal->getDateProposedAt()->format('d/m/Y'),
'id' => $proposal->getId(),
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'name' => $proposal->getName(),
'client' => $client->getName(),
'client_id' => $client->getId(),
'contact' => $contact->getName().' '.$contact->getLastname(),
'contactdepartment' => $contact->getDepartment(),
'contactphone' => $contact->getPhone(),
'contactmovil' => $contact->getMobile(),
'contactmail' => $contact->getEmail(),
'commercial' => $comercial,
'team' => $team,
'agent' => $agent,
'event_star' => $proposal->getDateEventStarAt()->format('d/m/Y'),
'event_end' => $proposal->getDateEventEndAt()->format('d/m/Y'),
'list_client' => 'si',
'send' => $proposal->getSent(),
// 'refagent' => ''
'refagent' => $agentView
);
}
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
// Agregampos Av 5, develup 2 y Green Patio 16
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$agent_data = $query->getResult();
/* FIN Consulta de agente activos MICE */
return $this->render('MDS/EventsBundle/proposal/list-proposal.html.twig', array(
'proposals' => $datos_proposal,
'unassigned' => 'Unassigned',
'agents' => $agent_data,
));
}
/**
* @Route("/proposal/assigned/{id}", name="proposal_update_assigned_agent", methods={"POST"})
*/
public function updateAssignedAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$propAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($id);
$agent = $request->request->get('agent')['agent'];
$historicAgentId = $proposal->getAgentId();
if(!empty($agent))
{
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$proposal->setAgentId($agent);
$proposal->setUpdatedId($user_id);
// INICIO: Solo un role admin puede asignar los proposal o Miriam Chavez, En reunion de Green Patio se le concedio acceso a Elena y a Yulia tambien. En reunion Rafa indico que solo Miriam puede asignar
$agentzz = $em->getRepository(User::class)->findOneById($user_id);
// if (!($agentzz->getRole() == 'ROLE_ADMIN') and !($agentzz->getUserrol() == 44) and !($agentzz->getId() == 22) and !($agentzz->getId() == 27)){
if (!($agentzz->getRole() == 'ROLE_ADMIN') and !($agentzz->getId() == 22)){
$errorMessage = $this->translator->trans('Error, usuario NO AUTORIZADO');
$this->addFlash('mensajeproposalerror', $errorMessage);
return $this->redirectToRoute('proposal_list_unassigned');
}
// INICIO: Solo un role admin puede asignar los proposal o Miriam Chavez
if (empty($propAgents)){
$propAgents = new ProposalAgents();
$propAgents->setIdProp($id);
$propAgents->setAgOne(0);
$propAgents->setAgTwo(0);
$propAgents->setAgThree(0);
$propAgents->setAgFour(0);
$propAgents->setAgOnePerc(0);
$propAgents->setAgTwoPerc(0);
$propAgents->setAgThreePerc(0);
$propAgents->setAgFourPerc(0);
}
$propAgents->setAgOne($agent);
$propAgents->setAgOnePerc(100);
/* Gestión de eventos en Log */
$user_lastname = $user_logueado->getLastname();
$user_name = $user_logueado->getName();
$user_email = $user_logueado->getEmail();
$user_rol = $user_logueado->getRoles();
$event_url = $request->getPathInfo();
$event_complete = $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
if (empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
$em->persist($proposal);
$em->flush();
$event = 'The agent was assigned';
$em->persist($propAgents);
$em->flush();
// Envio de correo notificacion al agente asignado
$time = new \DateTime("now");
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$agent->getEmail() => $agent->getName() . ' ' . $agent->getLastName()
);
$data = array(
'body' => 'P#' . $proposal->getId() . ', ' . $proposal->getTitle() . '<br><a href="http://' . $request->server->get('HTTP_HOST') . '/events/proposal/edit/' . $proposal->getId() . '">Ir al Proposal</a><br><br>Alerta de Proposal Asignado: ' . $time->format('d/m/Y H:i:s') . '<br><br>',
'firm' => $firmGmail,
);
// 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('P#' . $proposal->getId() . ', Alerta de Proposal Asignado')
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setReplyTo($mailAgentSent)
->setTo($mailAgent)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
$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));
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeproposal', $successMessage);
} else {
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajeproposalerror', $errorMessage);
}
if( !is_null($historicAgentId))
{
return $this->redirectToRoute('proposal_list');
} else {
return $this->redirectToRoute('proposal_list_unassigned');
}
}
/**
* @Route("/proposal/listclient/{id}", name="proposal_list_client")
*/
public function indexListClientAction($id, Request $request) {
$em = $this->getDoctrine()->getManager();
//$proposals = $em->getRepository(Proposal::class)->findByClientId($id);
$proposals = $em->getRepository(Proposal::class)->findBy(array('clientId' => $id), array('dateProposedAt' => 'DESC'));
$datos_proposal = array();
foreach($proposals as $proposal){
/*
* Estado, date create, id, Nombre, Cliente, Comercial, Equipo, Usuario, Inicio, Fin
* */
$iconstatus ='';
switch ($proposal->getStatus()) {
case "Pending":
// $iconstatus ='<i class="icon-bell3 text-danger parpadea"></i>';
$iconstatus ='<i class="icon-hammer text-danger parpadea"></i>';
break;
case "Sent":
$iconstatus ='<i class="icon-paperplane text-orange parpadea"></i>';
break;
case "Confirmed":
// $iconstatus ='<i class="icon-unlocked text-success"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-green-800"></i>';
break;
case "Invoiced":
// $iconstatus ='<i class="icon-lock2 text-gold"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-gold"></i>';
break;
case "Cancel":
// $iconstatus ='<i class=" icon-blocked text-grey"></i>';
$iconstatus ='<i class="icon-thumbs-down3 text-danger"></i>';
break;
case "Blocked":
$iconstatus ='<i class="icon-lock2 text-grey"></i>';
// $iconstatus ='<i class="icon-thumbs-up3 text-gold"></i>';
break;
}
if ($proposal->getSent() == "Yes"){
$iconsent ='<i class="icon-paperplane text-orange parpadea"></i>';
} else {
$iconsent ='';
}
/* Consultas */
$client = $em->getRepository(Client::class)->findOneByid($proposal->getClientId());
$contact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$commercial = $em->getRepository(User::class)->findOneById($proposal->getAgencommercialId());
if(empty($commercial)){$comercial="";}else{$comercial = $commercial->getName();}
$teams = $em->getRepository(SettingsTeam::class)->findOneById($proposal->getTeamId());
if(empty($teams)){$team="";}else{$team = $teams->getTeam();}
$agente = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if(empty($agente)){$agent="";}else{$agent = $agente->getName();}
/* Visto por ultima ves por parte del cliente o atraves del Access Key */
if ($proposal->getViewedAt() == $proposal->getCreatedAt()){
//no Visto
$novisto = $this->translator->trans('Not seen');
}else{
//visto
$novisto = "";
}
//Nombres resumidos de los agentes
$allAgentesResumidos = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
$agentesResumidos = '';
$nombreOne= '';
if (!empty($allAgentesResumidos)) {
if (!empty($allAgentesResumidos->getAgOne())) {
if ($allAgentesResumidos->getAgOne() != 0) {
// Hay Agente One
$theOne = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgOne());
if (empty($theOne)){ $theOne = $em->getRepository(User::class)->findOneByid(6); }
$nombreOne = $theOne->getName() . ' ' . substr($theOne->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreOne;
} else {
$agentesResumidos = $nombreOne;
}
}
}
if (!empty($allAgentesResumidos->getAgTwo())) {
if ($allAgentesResumidos->getAgTwo() != 0) {
// Hay Agente Two
$theTwo = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgTwo());
if (empty($theTwo)){ $theTwo = $em->getRepository(User::class)->findOneByid(6); }
$nombreTwo = $theTwo->getName() . ' ' . substr($theTwo->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreTwo;
} else {
$agentesResumidos = $nombreTwo;
}
}
}
if (!empty($allAgentesResumidos->getAgThree())) {
if ($allAgentesResumidos->getAgThree() != 0) {
// Hay Agente Three
$theThree = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgThree());
if (empty($theThree)){ $theThree = $em->getRepository(User::class)->findOneByid(6); }
$nombreThree = $theThree->getName() . ' ' . substr($theThree->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreThree;
} else {
$agentesResumidos = $nombreThree;
}
}
}
if (!empty($allAgentesResumidos->getAgFour())) {
if ($allAgentesResumidos->getAgFour() != 0) {
// Hay Agente Four
$theFour = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgFour());
if (empty($theFour)){ $theFour = $em->getRepository(User::class)->findOneByid(6); }
$nombreFour = $theFour->getName() . ' ' . substr($theFour->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreFour;
} else {
$agentesResumidos = $nombreFour;
}
}
}
}
if (strpos($agentesResumidos,',')===false){
//Hay mas de un agente
$masdeunagente = true;
$agentView = $agent;
} else {
//No hay mas de un agente
$masdeunagente = false;
$agentView = $agentesResumidos;
}
//Nombres resumidos de los agentes
if(empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
$datos_proposal[] = array(
'status' => $this->translator->trans($proposal->getStatus()),
'iconstatus' => $iconstatus,
'iconsent' => $iconsent,
'viewedAt' => $proposal->getViewedAt()->format('d/m/Y H:i:s'),
'novisto' => $novisto,
'create' => $proposal->getDateProposedAt()->format('d/m/Y'),
'id' => $proposal->getId(),
'name' => $proposal->getName(),
'token' => $proposal->getAccessKey(),
'client' => $client->getName(),
'client_id' => $client->getId(),
'contact' => $contact->getName().' '.$contact->getLastname(),
'contactdepartment' => $contact->getDepartment(),
'contactphone' => $contact->getPhone(),
'contactmovil' => $contact->getMobile(),
'contactmail' => $contact->getEmail(),
'commercial' => $comercial,
'team' => $team,
'agent' => $agent,
'event_star' => $proposal->getDateEventStarAt()->format('d/m/Y'),
'event_end' => $proposal->getDateEventEndAt()->format('d/m/Y'),
'list_client' => 'no',
// 'refagent' => ''
'refagent' => $agentView
);
}
// $agent_data = $em->getRepository(User::class)->findAll();
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$agent_data = $query->getResult();
/* FIN Consulta de agente activos MICE */
return $this->render('MDS/EventsBundle/proposal/list-proposal.html.twig',
array(
'proposals' => $datos_proposal,
'unassigned' => '',
'agents' => $agent_data
)
);
}
/**
* @Route("/proposal/edit/{id}", name="proposal_edit")
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$agentTwoId = $proposal->getAgentTwoId();
$office = $em->getRepository(SettingsOffice::class)->findOneById($proposal->getOfficeId());
$proposal->setOfficeId($office);
$client = $em->getRepository(Client::class)->findOneById($proposal->getClientId());
$proposal->setClientId($client);
// $contact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
// $proposal->setContactId($contact);
$agente = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$proposal->setAgentId($agente);
$teams = $em->getRepository(SettingsTeam::class)->findOneById($proposal->getTeamId());
$proposal->setTeamId($teams);
$music = $em->getRepository(PresentationMusic::class)->findOneById($proposal->getIdMusic());
$proposal->setIdMusic($music);
// $agentetwo = $em->getRepository(SettingsTeam::class)->findOneById($proposal->getAgentTwoId());
// $proposal->setAgentTwoId($agentetwo);
$agentetwo = explode(",", $proposal->getAgentTwoId());
$agentetworesultado = $em->getRepository(User::class)->findById($agentetwo);
$proposal->setAgentTwoId($agentetworesultado);
$type_supplier = $em->getRepository(SupplierSettingsType::class)->findAll();
$nameGeneral = $this->translator->trans('SUPPLIER');
$type = array();
foreach($type_supplier as $typesupplier){
$type[$nameGeneral.' '.$typesupplier->getGroupBase()][$typesupplier->getBase()] = array(
'typeName' => $typesupplier->getBase()
);
}
$services['AGRUPATION OF SERVICES'] = array(
'IDEA' => array(
'typeName' => 'IDEA'
),
'ACTIVITY' => array(
'typeName' => 'ACTIVITY'
)
);
$destinos['DESTINATION'] = array(
'DESTINATION' => array(
'typeName' => 'DESTINATION'
)
);
$type_data = array_merge($type, $services, $destinos);
// $idea['AGRUPACIÓN DE SERVICIOS']['IDEA'] = array(
// 'typeName' => 'IDEA'
// );
// $activity['AGRUPACIÓN DE SERVICIOS']['ACTIVITY'] = array(
// 'typeName' => 'ACTIVITY'
// );
// $type_data = array_merge($type, $idea, $activity);
// $type = array();
// foreach($type_supplier as $typesupplier){
// $type[$typesupplier->getBase()] = array(
// 'typeName' => $typesupplier->getBase()
// );
// }
// $idea['IDEA'] = array(
// 'typeName' => 'IDEA'
// );
// $activity['ACTIVITY'] = array(
// 'typeName' => 'ACTIVITY'
// );
// $type_data = array_merge($type, $idea, $activity);
$selectType = explode(",", $proposal->getSelectType());
if (empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
$form = $this->createEditProposalForm($proposal, $id);
$briefing = $em->getRepository(ProposalBriefingList::class)->findBy(
array(
'proposalId' => $id,
)
);
// INFORMACION DE TRACKING
$tracinglists_fin = array();
if(!is_null($proposal->getAgentId())){
$tracing= new ProposalTracing();
$tracing->setDateAt(new \DateTime("now"));
$tracing->setProposalId($id);
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$user = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$proposal->setAgentId($user->getUsername());
$tracingLists = $em->getRepository(ProposalTracing::class)->findByProposalId($id);
$tracinglists_fin = array();
foreach($tracingLists as $tracingList){
if ($tracingList->getAgentId() == "0"){
$tracingList->setAgentId('Client');
$tracingList->setCreatedId('Client');
}else{
$agent = $em->getRepository(User::class)->findOneById($tracingList->getAgentId());
$user = $em->getRepository(User::class)->findOneById($tracingList->getCreatedId());
if(!is_null($agent)){
$tracingList->setAgentId($agent->getName());
}
if(!is_null($user)){
$tracingList->setCreatedId($user->getName());
}
}
$tracinglists_fin[] = $tracingList;
}
}
// $userAgents = $em->getRepository(User::class)->findAll();
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$userAgents = $query->getResult();
/* FIN Consulta de agente activos MICE */
$agentsPercentage=$em->getRepository(ProposalAgents::class)->findOneByIdProp($id);
return $this->render('MDS/EventsBundle/proposal/edit-proposal.html.twig',
array(
'id' => $id,
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'agentTwoId' => $agentTwoId,
'selectType' => $selectType,
'typeSupplier' => $type_data,
'proposal' => $proposal,
'form' => $form->createView(),
'briefing' => $briefing,
'tracings' => $tracinglists_fin,
'userAgents' => $userAgents,
'agentsPercentage'=>$agentsPercentage
)
);
}
private function createEditProposalForm(Proposal $entity, $id)
{
$form = $this->createForm(ProposalType::class, $entity,
array(
'action' => $this->generateUrl('proposal_update',
array(
'id' => $id
)
), 'method' => 'PUT'));
return $form;
}
/**
* @Route("/proposal/update/{id}", name="proposal_update", methods={"POST", "PUT"})
*/
public function updateAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$originPrpDateStart = $proposal->getDateEventStarAt();
$originPrpDateEnd = $proposal->getDateEventEndAt();
$originPrpStatus = $proposal->getStatus();
// -------------- INICIO 1/2: Solo un admin hace la primera asignacion de agentes
$zero_old_pp_agt = $em->getRepository(ProposalAgents::class)->findOneByIdProp($id);
$zero_old_agents = (empty($zero_old_pp_agt->getAgOne()) and empty($zero_old_pp_agt->getAgTwo()) and empty($zero_old_pp_agt->getAgThree()) and empty($zero_old_pp_agt->getAgFour()));
// -------------- FIN 1/2: Solo un admin hace la primera asignacion de agentes
$created_at = $proposal->getCreatedAt();
$fechaFin = $proposal->getDateEventEndAt();
$fechaInicio = $proposal->getDateEventStarAt();
$previusStatus = $proposal->getStatus();
$previusAgentId = $proposal->getAgentId();
$previusAgentTwoId = $proposal->getAgentTwoId();
// if(!isset($request->request->get('proposal')['agentTwoId'])){
// $proposal->setAgentTwoId(null);
// }
$proposal->setAgentTwoId(null);
if (empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
$form = $this->createEditProposalForm($proposal, $id);
$form->handleRequest($request);
$contactId = $form->get('contactId')->getData();
/* Consulta el agente comercial asignado */
$data_contact = $em->getRepository(ClientContact::class)->findOneById($contactId);
$proposal->setAgencommercialId($data_contact->getAssignedAgent());
$office_proposal = $form->get('officeId')->getData();
if(!is_null($office_proposal)){
$proposal->setOfficeId($office_proposal->getId());
}
$client_proposal = $form->get('clientId')->getData();
if(!is_null($client_proposal)){
$proposal->setClientId($client_proposal->getId());
}
$idmusic_proposal = $form->get('idMusic')->getData();
if(!is_null($idmusic_proposal)){
$proposal->setIdMusic($idmusic_proposal->getId());
}
$agent_proposal = $em->getRepository(User::class)->findOneById($request->request->get('agent')['Agent1']['agentId']);
$agentToNotify = array();
$logicoNotificarCliente = false;
if(!is_null($agent_proposal)){
//-- Inicio: Verifico si se cambio de Agente
if ($previusAgentId != $agent_proposal->getId()){
$agentToNotify[] = $agent_proposal;
}
//-- Fin: Verifico si se cambio de Agente
if (($previusAgentId == 0) or (is_null($previusAgentId))) {
$logicoNotificarCliente = true;
} else {
$logicoNotificarCliente = false;
}
$proposal->setAgentId($agent_proposal->getId());
}else{
$proposal->setAgentId(null);
}
$team_proposal = $form->get('teamId')->getData();
if(!is_null($team_proposal)){
$proposal->setTeamId($team_proposal->getId());
}
//$agenttwo_proposal = array(($request->request->get('agent')['Agent2']['agentId']),($request->request->get('agent')['Agent3']['agentId']),($request->request->get('agent')['Agent4']['agentId']));
$prpAg = $em->getRepository(ProposalAgents::class)->findOneByIdProp($id);
$agentTwoPreviusArray = array();
if ($prpAg->getAgTwo()!=''){
//agrego a 2
$agentTwoPreviusArray[] = $prpAg->getAgTwo();
if ($prpAg->getAgThree()!=''){
//agrego a 3
$agentTwoPreviusArray[] = $prpAg->getAgThree();
if ($prpAg->getAgFour()!=''){
//agrego a 4
$agentTwoPreviusArray[] = $prpAg->getAgFour();
}
} else {
// no agrego 3
if ($prpAg->getAgFour()!=''){
//agrego a 4
$agentTwoPreviusArray[] = $prpAg->getAgFour();
}
}
} else {
// no agrego 2
if ($prpAg->getAgThree()!=''){
//agrego a 3
$agentTwoPreviusArray[] = $prpAg->getAgThree();
} else {
// no agrego 3
if ($prpAg->getAgFour()!=''){
//agrego a 4
$agentTwoPreviusArray[] = $prpAg->getAgFour();
}
}
}
$agenttwo_proposal = array();
if (($request->request->get('agent')['Agent2']['agentId'])!=''){
//agrego a 2
$agenttwo_proposal[] = ($request->request->get('agent')['Agent2']['agentId']);
if (($request->request->get('agent')['Agent3']['agentId'])!=''){
//agrego a 3
$agenttwo_proposal[] = ($request->request->get('agent')['Agent3']['agentId']);
if (($request->request->get('agent')['Agent4']['agentId'])!=''){
//agrego a 4
$agenttwo_proposal[] = ($request->request->get('agent')['Agent4']['agentId']);
}
} else {
// no agrego 3
if (($request->request->get('agent')['Agent4']['agentId'])!=''){
//agrego a 4
$agenttwo_proposal[] = ($request->request->get('agent')['Agent4']['agentId']);
}
}
} else {
// no agrego 2
if (($request->request->get('agent')['Agent3']['agentId'])!=''){
//agrego a 3
$agenttwo_proposal[] = ($request->request->get('agent')['Agent3']['agentId']);
} else {
// no agrego 3
if (($request->request->get('agent')['Agent4']['agentId'])!=''){
//agrego a 4
$agenttwo_proposal[] = ($request->request->get('agent')['Agent4']['agentId']);
}
}
}
$str_array_agents = implode(",", $agentTwoPreviusArray);
if(isset($str_array_agents)){
//-- Inicio: Verifico si se cambio de AgenteTwo
//$agentTwoPreviusArray = explode(",",$previusAgentTwoId); //-- convierto en array el string de los agentTwo
foreach ($agenttwo_proposal as $item){
if(!(in_array($item,$agentTwoPreviusArray))) //-- Si el elemento no esta en los antiguos agentTwo se debe notificar
{$agentToNotify[] = $em->getRepository(User::class)->findOneById($item);}
}
//-- Fin: Verifico si se cambio de AgenteTwo
$proposal->setAgentTwoId(implode(",", $agenttwo_proposal));
}else{
$proposal->setAgentTwoId(null);
}
if(isset($request->request->get('proposal_esp')['type'])){
$select_type = $request->request->get('proposal_esp')['type'];
$proposal->setSelectType(implode(",", $select_type));
}else{
$proposal->setSelectType(null);
}
$type_supplier = $em->getRepository(SupplierSettingsType::class)->findAll();
$type = array();
foreach($type_supplier as $typesupplier){
$type[$typesupplier->getBase()] = array(
'typeName' => $typesupplier->getBase()
);
}
if($form->isValid())
{
$boolAsignacionPorDefectoPerc = false;
$propAgents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($id);
if($request->request->get('agent')['Agent2']['agentId']!=''){
$propAgents->setAgTwo($request->request->get('agent')['Agent2']['agentId']);
if ( $this->AsignacionPorcentajeAgente() ){
if ($request->request->get('percent')['2'] != 0) {
$propAgents->setAgTwoPerc($request->request->get('percent')['2']);
} else {
//Asignacion de valor por defecto
$boolAsignacionPorDefectoPerc = true;
}
}
$propAgents->setAgTwoWork($request->request->get('agentWork')['2']);
} else {
$propAgents->setAgTwo(0);
if ( $this->AsignacionPorcentajeAgente() ){ $propAgents->setAgTwoPerc(0); }
$propAgents->setAgTwoWork(null);
}
if($request->request->get('agent')['Agent3']['agentId']!=''){
$propAgents->setAgThree($request->request->get('agent')['Agent3']['agentId']);
if ( $this->AsignacionPorcentajeAgente() ){
if ($request->request->get('percent')['3'] != 0) {
$propAgents->setAgThreePerc($request->request->get('percent')['3']);
} else {
//Asignacion de valor por defecto
$boolAsignacionPorDefectoPerc = true;
}
}
$propAgents->setAgThreeWork($request->request->get('agentWork')['3']);
} else {
$propAgents->setAgThree(0);
if ( $this->AsignacionPorcentajeAgente() ){ $propAgents->setAgThreePerc(0); }
$propAgents->setAgThreeWork(null);
}
if($request->request->get('agent')['Agent4']['agentId']!=''){
$propAgents->setAgFour($request->request->get('agent')['Agent4']['agentId']);
if ( $this->AsignacionPorcentajeAgente() ){
if ($request->request->get('percent')['4'] != 0) {
$propAgents->setAgFourPerc($request->request->get('percent')['4']);
} else {
//Asignacion de valor por defecto
$boolAsignacionPorDefectoPerc = true;
}
}
$propAgents->setAgFourWork($request->request->get('agentWork')['4']);
} else {
$propAgents->setAgFour(0);
if ( $this->AsignacionPorcentajeAgente() ){ $propAgents->setAgFourPerc(0); }
$propAgents->setAgFourWork(null);
}
if($request->request->get('agent')['Agent1']['agentId']!=''){
$propAgents->setAgOne($request->request->get('agent')['Agent1']['agentId']);
if ( $this->AsignacionPorcentajeAgente() ){
if ($request->request->get('percent')['1'] != 0) {
$propAgents->setAgOnePerc($request->request->get('percent')['1']);
} else {
//Asignacion de valor por defecto
$boolAsignacionPorDefectoPerc = true;
}
}
$propAgents->setAgOneWork($request->request->get('agentWork')['1']);
} else {
$propAgents->setAgOne(0);
if ( $this->AsignacionPorcentajeAgente() ){ $propAgents->setAgOnePerc(0); }
$propAgents->setAgOneWork(null);
}
if ($boolAsignacionPorDefectoPerc){
$arrayRequestAgents = array( $request->request->get('agent')['Agent1']['agentId'], $request->request->get('agent')['Agent2']['agentId'], $request->request->get('agent')['Agent3']['agentId'], $request->request->get('agent')['Agent4']['agentId'] );
$valorParaAgente = $this->MontoPorcentajeAgente(1, $arrayRequestAgents);
$propAgents->setAgOnePerc($valorParaAgente);
$valorParaAgente = $this->MontoPorcentajeAgente(2, $arrayRequestAgents);
$propAgents->setAgTwoPerc($valorParaAgente);
$valorParaAgente = $this->MontoPorcentajeAgente(3, $arrayRequestAgents);
$propAgents->setAgThreePerc($valorParaAgente);
$valorParaAgente = $this->MontoPorcentajeAgente(4, $arrayRequestAgents);
$propAgents->setAgFourPerc($valorParaAgente);
}
// if (!empty($request->request->get('agent')['Agent1']['agentId'])){
// $propAgents->setAgOne($request->request->get('agent')['Agent1']['agentId']);
// $propAgents->setAgOneWork($request->request->get('agentWork')['1']);
// if (sizeof($request->request->get('percent')['1']) == 0){
// $propAgents->setAgOnePerc(100);
// } else {
// if ( $this->AsignacionPorcentajeAgente() ){ $propAgents->setAgOnePerc($request->request->get('percent')['1']); }
// if (empty($propAgents->getAgOnePerc())){
// $propAgents->setAgOnePerc(0);
// }
// }
// } else {
// $propAgents->setAgOne(0);
// $propAgents->setAgOnePerc(0);
// $propAgents->setAgOneWork(null);
// }
// -------------- INICIO 2/2: Solo un admin hace la primera asignacion de agentes
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
// Elena Paret y Yulia Akmethova pueden asignar porcentajes y agentes
// if (($zero_old_agents) and ($user_logueado->getRole()=='ROLE_USER') and !($user_logueado->getId()==22) and !($user_logueado->getId()==27)){
if (($zero_old_agents) and ($user_logueado->getRole()=='ROLE_USER') and !($user_logueado->getId()==57)){
$propAgents->setAgOne(null);
$propAgents->setAgTwo(null);
$propAgents->setAgThree(null);
$propAgents->setAgFour(null);
$proposal->setAgentId(null);
$proposal->setAgentTwoId(null);
}
// -------------- FIN 2/2: Solo un admin hace la primera asignacion de agentes
$em->persist($propAgents);
$em->flush();
// Envio correo a administracion en caso que de cambie el estatus y este como no enviado
if($request->request->get('proposal')['status'] == "Confirmed" and $proposal->getSendAdmin() != "yes"){
$time = new \DateTime("now");
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if (!empty($agent)){
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$passGmail = $agent->getPassGmail();
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$agent->getEmail() => $agent->getName().' '. $agent->getLastName()
);
$setting_rol = $em->getRepository(SettingsRol::class)->findBy(
array(
'weight' => array('2','3'),
'madmin' => '1',
)
);
foreach($setting_rol as $settingRol){
$administration = $em->getRepository(User::class)->findByUserrol($settingRol->getId());
foreach($administration as $admin){
$mailAdmin[] = $admin->getEmail();
}
}
$data = array(
'body' => 'P#'.$proposal->getId().', '.$proposal->getTitle().'<br><a href="http://'.$request->server->get('HTTP_HOST').'/events/proposal/edit/'.$proposal->getId().'">Ir al Proposal</a> - <a href="http://'.$request->server->get('HTTP_HOST').'/events/proposal/summary/prices/'.$proposal->getId().'">Ver Resumen</a><br><br>Alerta de Proposal Confirmado: '.$time->format('d/m/Y H:i:s').'<br><br>',
'firm' => $firmGmail,
);
$mailTodos = array_merge($mailAgent, $mailAdmin);
if (!is_null($passGmail) and (!empty($passGmail))) {
// EJECUTAR ENVIO DE ALERTA DE VISTO POR CLIENTE
$transporter = new Swift_SmtpTransport();
$transporter->setHost('smtp.gmail.com')
->setEncryption('ssl')//ssl / tls
->setPort(465)// 465 / 587
->setUsername($agentMail)
->setPassword($passGmail);
// ->setUsername('desarrollo@develup.solutions')
// ->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject('P#' . $proposal->getId() . ', Alerta de Proposal Confirmado')
->setSender($agentMail)
->setFrom($mailAgentSent)
->setReplyTo($mailAgentSent)
->setTo($mailTodos)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
$proposal->setSendAdmin('yes');
}
}else{
$errorMessage = $this->translator->trans('Attention: Confirmed Proposal, without assigned agent');
$this->addFlash('mensajeproposaldestinationerror', $errorMessage);
}
}
//-- Envio correo a los agentes que hayan sido modificados
if(sizeof($agentToNotify)>0){
$time = new \DateTime("now");
// $agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
foreach ($agentToNotify as $agent) {
// if (!empty($agent)){
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
// $passGmail = $agent->getPassGmail();
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$agent->getEmail() => $agent->getName() . ' ' . $agent->getLastName()
);
$data = array(
'body' => 'P#' . $proposal->getId() . ', ' . $proposal->getTitle() . '<br><a href="http://' . $request->server->get('HTTP_HOST') . '/events/proposal/edit/' . $proposal->getId() . '">Ir al Proposal</a><br><br>Alerta de Proposal Asignado: ' . $time->format('d/m/Y H:i:s') . '<br><br>',
'firm' => $firmGmail,
);
// $mailTodos = $mailAgent;
// 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($agentMail)
// ->setPassword($passGmail)//;
->setUsername('desarrollo@develup.solutions')
->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject('P#' . $proposal->getId() . ', Alerta de Proposal Asignado')
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setReplyTo($agentMail)
->setTo($mailAgent)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
}
}
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$proposal->setUpdatedId($user_id);
$proposal->setDateProposedAt($created_at);
if (empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
$em = $this->getDoctrine()->getManager();
// $em->persist($client);
// $em->flush();
/* Gestión de eventos en Log */
$user_lastname = $user_logueado->getLastname();
$user_name = $user_logueado->getName();
$user_email = $user_logueado->getEmail();
$user_rol = $user_logueado->getRoles();
$event_url = $request->getPathInfo();
$event_complete = $user_name.' '.$user_lastname.' - '.$user_email.' - '.$user_rol[0].' | '.$event_url;
if(!is_null($form->get('briefing')->getData())){
$reg_exp = array('<p>','<br></p>');
$briefing = str_ireplace($reg_exp, '', $form->get('briefing')->getData());
$addBriefing = new ProposalBriefingList();
$addBriefing->setBriefing($briefing);
$addBriefing->setProposalId($id);
$addBriefing->setUserId($user_id);
$addBriefing->setUserName($user_name);
$addBriefing->setActualTime();
$proposal->setBriefing(null);
$em->persist($addBriefing);
$em->flush();
}
$hoy = date('Y-m-d', strtotime('-31 day'));
$fechaFinSt = $fechaFin->format('Y-m-d');
$expiredTime = $fechaFinSt < $hoy;
// Si ponen el estado en desbloqueado y no es un administrador se debe deshacer el cambio
if (($proposal->getStatus() == 'Unblocked') and ($user_rol[0] != 'ROLE_ADMIN')){
$proposal->setStatus($previusStatus);
}
// Si el Proposal ha expirado y no es un administrador los cambios en Fechas o cifras de servicios no se deben modificar ni tampoco el Status
if ($expiredTime and ($user_rol[0] != 'ROLE_ADMIN')){
$proposal->setDateEventStarAt($fechaInicio);
$proposal->setDateEventEndAt($fechaFin);
$proposal->setStatus($previusStatus);
}
if (empty($proposal->getDateProposedAt())){
$proposal->setDateProposedAt($proposal->getCreatedAt());
}
$em->persist($proposal);
$em->flush();
$agent = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if ($logicoNotificarCliente and !empty($agent)){
// Envio de correo notificacion al CLIENTE asignado
$time = new \DateTime("now");
$allAgents = '<table width="100%">';
if ($propAgents->getAgOne() != 0){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgOne());
$allAgents = $allAgents . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
if ($propAgents->getAgTwo() != 0){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgTwo());
$allAgents = $allAgents . '<tr height="10px"></tr><tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
if ($propAgents->getAgThree() != 0){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgThree());
$allAgents = $allAgents . '<tr height="10px"></tr><tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
if ($propAgents->getAgFour() != 0){
$age = $em->getRepository(User::class)->findOneById($propAgents->getAgFour());
$allAgents = $allAgents . '<tr height="10px"></tr><tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $age->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $age->getName().' '. $age->getLastName().' <br> Teléfono: '. $age->getMobile() .' <br> Correo electrónico: '. $age->getEmail() .'</td></tr>';
}
$allAgents = $allAgents .'</table>';
$clara = $em->getRepository(User::class)->findOneByEmail('clara.pedreno@avexpress.tv');
// Tabla de datos CLARA / DEPARTAMENTO DE RENDER Y CREATIVIDAD
$tabClara = '<table width="100%">';
$tabClara = $tabClara . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $clara->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $clara->getName().' '. $clara->getLastName().' <br> Teléfono: '. $clara->getMobile() .' <br> Correo electrónico: '. $clara->getEmail() .'</td></tr>';
$tabClara = $tabClara .'</table>';
// Tabla de datos CLARA / DEPARTAMENTO DE RENDER Y CREATIVIDAD
// Tabla de datos Jorge / DEPARTAMENTO DE TECNOLOGIA
if (!(strpos($proposal->getSelectType(),'TECNOLOGÍA')===false)){
// Tecnología estaba seleccionada entre las opciones
$jorge = $em->getRepository(User::class)->findOneByEmail('jorge.defreitas@develup.solutions');
$tabJorge = '<table width="100%">';
$tabJorge = $tabJorge . '<tr>
<td width="10%">'.
// '<img src="https://'.$_SERVER['HTTP_HOST'].'/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $jorge->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $jorge->getName().' '. $jorge->getLastName().' <br> Teléfono: '. $jorge->getMobile() .' <br> Correo electrónico: '. $jorge->getEmail() .'</td></tr>';
$tabJorge = $tabJorge .'</table>';
$tabClara = $tabClara .'</p><p><b>Departamento de Tecnología </b></p><p>'. $tabJorge;
}
// Tabla de datos Jorge / DEPARTAMENTO DE TECNOLOGIA
$rafa = $em->getRepository(User::class)->findOneByEmail('rafael.guerrero@inout-travel.com');
// Tabla de datos RAFA
$tabRafa = '<table width="100%">';
$tabRafa = $tabRafa . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $rafa->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $rafa->getName().' '. $rafa->getLastName().' <br> Teléfono: '. $rafa->getMobile() .' <br> Correo electrónico: '. $rafa->getEmail() .'</td></tr>';
$tabRafa = $tabRafa .'</table>';
// FIN Tabla de datos RAFA
$salva = $em->getRepository(User::class)->findOneByEmail('salvador@avexpress.tv');
// Tabla de datos SALVA
$tabSalva = '<table width="100%">';
$tabSalva = $tabSalva . '<tr>
<td width="10%">'.
// '<img src="'.$_SERVER['HTTP_HOST'].'/'. $salva->getPicture(). '" alt="No Image" height="45" width="45">
'<img src="https://inout.mante.solutions/'. $salva->getPicture(). '" alt="No Image" height="45" width="45">
</td width="90%">
<td>' . $salva->getName().' '. $salva->getLastName().' <br> Teléfono: '. $salva->getMobile() .' <br> Correo electrónico: '. $salva->getEmail() .'</td></tr>';
$tabSalva = $tabSalva .'</table>';
// FIN Tabla de datos SALVA
$zclient = $em->getRepository(Client::class)->findOneById($proposal->getClientId());
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$zagentReplyTo = array(
$agent->getEmail() => $agent->getName().' '. $agent->getLastName()
);
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$zclient->getEmail() => $zclient->getName()
);
$mailAgentFrom = array(
$agent->getEmail() => $agent->getName().' '. $agent->getLastName()
);
$data = array(
'body' => ''. '<p>Estimado cliente,</p><p>Gracias por esta nueva solicitud y por confiar una vez más en nosotros. </p><p>Su petición ha sido dada de alta en nuestro sistema y ya estamos trabajando en su propuesta, en breve recibirá una comunicación de nuestro agente.</p><p> </p><p><b><h2>' . $proposal->getTitle() . '</h2></b></p><p></p><p>Su equipo para esta propuesta estará formado por:</p><p> </p><p></p><b>Project Manager </b></p><p>'. $allAgents .'</p><p><b>Departamento de Renderización y Creatividad </b></p><p>'. $tabClara .'</p><p></p><b><br>Director de producción audiovisual y escenografía</b></p><p>'. $tabSalva . '</p><p><b>Director de departamento y creatividad </b></p><p>'. $tabRafa . '</p><p><b>Departamento de Eventos </b></p><p>Teléfono: (+34) 911 878 393 - Correo electrónico: events@inout-travel.com</p><p> </p><p>Gracias de nuevo por su amable petición, en breve recibirá nuestra propuesta. </p><p> </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="http://firmas.inout.events/firmas/events/LOGO_INOUT_TRAVEL&EVENTS.png" 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>',
);
// 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($agent->getEmail())
->setPassword($agent->getPassGmail());
$mailer = new Swift_Mailer($transporter);
$message = new Swift_Message();
$message->setSubject('P#' . $proposal->getId() . ', Alta de petición')
->setSender($agentMail)
->setFrom($mailAgentFrom)
->setReplyTo($zagentReplyTo)
->setTo($mailAgentSent)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
}
$event = 'The Proposal has been Updated. Now';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeproposaldestination', $successMessage);
// try{
// $em->persist($client);
// $em->flush();
// $event = 'The Client has been Updated. Now';
//
// $successMessage = $this->translator->trans($event);
// $this->addFlash('mensajeclient', $successMessage);
//
// $logger->info($event_complete.' | '.$event);
//
// } catch (\Exception $e){
//
// $event = 'An error occurred: '.$e->getMessage();
//
// /* Para el log */
// $logger->error($event_complete.' | '.$event);
// /* Para el usuario */
// $errorMessage = $this->translator->trans($event);
// $this->addFlash('mensajeclienterror', $errorMessage);
// }
// /* Fin Gestión de eventos en Log */
// ALL LO QUE HAY -- PROPOSAL NO ASIGNADOS
// $parameterspc = array();
// $dqlpc = 'SELECT COUNT (pc.id) FROM EventsBundle:Proposal pc WHERE pc.agentId is null';
// $querypc = $em->createQuery($dqlpc)->setParameters($parameterspc);
// $cantidadpc = $querypc->getResult();
// $request->getSession()->set('_proposal_unassigned', $cantidadpc[0][1]);
$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));
// Notificar a AV Express si se cambia a estado de Confirmado/Cancelado o se cambia la fecha del evento
$avFile = $em->getRepository(AveFiles::class)->findOneByIdProposal($proposal->getId());
if (!empty($avFile)){
if ((!($originPrpStatus == 'Confirmed') and ($proposal->getStatus() == 'Confirmed')) or
(!($originPrpStatus == 'Cancel') and ($proposal->getStatus() == 'Cancel')) or
(!($originPrpDateStart->format('d/m/Y') == $proposal->getDateEventStarAt()->format('d/m/Y'))) or
(!($originPrpDateEnd->format('d/m/Y') == $proposal->getDateEventEndAt()->format('d/m/Y')))){
$this->NotifyAvExpress($proposal, $avFile, $originPrpDateStart, $originPrpDateEnd, $originPrpStatus);
}
}
return $this->redirectToRoute('proposal_destination_view',
array(
'id' => $id
)
);
}else{
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajeproposaldestinationerror', $errorMessage);
}
// $userAgents = $em->getRepository(User::class)->findAll();
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$userAgents = $query->getResult();
/* FIN Consulta de agente activos MICE */
return $this->render('MDS/EventsBundle/proposal/add-proposal.html.twig', array(
'typeSupplier' => $type,
'userAgents' => $userAgents,
'form' => $form->createView()
)
);
}
/**
* @Route("/proposals/events", name="get_proposal_select")
*/
public function proposalSelectAction(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();
$team_id = $user_logueado->getTeam();
$user_role = $user_logueado->getRole();
if ($user_role == 'ROLE_ADMIN'){ $team_id = 1; }
// Cargar los proposals que sean depués de un año atras desde el día de la búsqueda
$dql = "SELECT p
FROM App\MDS\EventsBundle\Entity\Proposal p
WHERE p.teamId = :teamId
AND p.status in (:status)
AND p.dateEventStarAt > :dateEventStarAt";
$parameters = [
'teamId' => $team_id,
'status' => array('Confirmed', 'Invoiced'),
'dateEventStarAt' => new DateTime('now -365 days'),
];
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
$datos = array();
if (!empty($proposals)){
//Buscamos de una vez, todos los clientes y usuarios relacionados con los proposals
$clientsIds = array_map(function($proposal) { return $proposal->getClientId(); }, $proposals);
$usersIds = array_map(function($proposal) { return $proposal->getAgentId(); }, $proposals);
$clients = $em->getRepository(Client::class)->findById($clientsIds);
$users = $em->getRepository(User::class)->findById($usersIds);
//Creamos arrays referenciados para encontrar los clientes y usuarios por su id.
$clientsMapped = array_reduce($clients, function($carry, $client) {
$carry[$client->getId()] = $client;
return $carry;
}, []);
$usersMapped = array_reduce($users, function($carry, $user) {
$carry[$user->getId()] = $user;
return $carry;
}, []);
//Recorremos los proposals
foreach($proposals as $proposal){
if ($connectGoogle == 1){
$egcuno = '<a href="/calendar/addEvent/ep/'.$proposal->getId().'" class="text-white"><i class="icon-google-plus2"></i></a> ';
}else{
$egcuno = '';
}
$clientId = $proposal->getClientId();
$agentId = $proposal->getAgentId();
$client = $clientsMapped[$clientId] ?? null;
$user = $usersMapped[$agentId] ?? null;
if(empty($user) || is_null($user)){
if(!is_null($proposal->getTeamId())){
$userAsignar = $em->getRepository(User::class)->findOneBy(array('team'=>$proposal->getTeamId(),'teamleader'=>1));
if(!empty($userAsignar)){
$id=$userAsignar->getId();
}else{
$id = null;
}
}else{
$id = null;
}
if (!is_null($id)){
$proposal->setAgentId($id);
$em->persist($proposal);
$em->flush();
$user = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$userColor = $user->getColor();
$userPicture = $user->getPicture();
$userLastname = $user->getLastname();
$userName = $user->getName();
}else{
$userColor = "#ff0000";
$userPicture = null;
$userLastname = "Not Assigned";
$userName = "Not Assigned";
}
}else{
$userColor = $user->getColor();
$userPicture = $user->getPicture();
$userLastname = $user->getLastname();
$userName = $user->getName();
}
$colorHay = $userColor;
if (empty($colorHay)){
$color = "#ff0000";
}else{
$color = $userColor;
}
if (is_null($userPicture)){
$picture = "";
}else{
$picture = "<img src='".$userPicture."' class='img-circle img-lg'><br>";
}
$tooltip = $picture." ".
$userName." ".$userLastname."<br>".
$client->getName()."<br>".
$proposal->getName()."</b><br>";
$datos[] = array(
"id" => $proposal->getId(),
"title" => $egcuno.$userName." ".$userLastname." | ".$client->getName().": ".$proposal->getName(),
"tooltip" => $tooltip,
"start" => $proposal->getDateEventStarAt(),
"end" => $proposal->getDateEventEndAt(),
"color" => $color,
"url" => "/events/proposal/destination/add/".$proposal->getId()
);
}
}
$return = array(
'proposal' => $datos,
);
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/proposals/events-admin", name="get_proposal_select-admin")
*/
public function proposalAdminSelectAction(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();
$proposals = $em->getRepository(Proposal::class)->findBy(
array(
'status' => array('Confirmed', 'Invoiced'),
),
array('dateEventStarAt' => 'ASC')
);
$datos = array();
if (!empty($proposals)){
foreach($proposals as $proposal){
if ($connectGoogle == 1){
$egcuno = '<a href="/calendar/addEvent/ep/'.$proposal->getId().'" class="text-white"><i class="icon-google-plus2"></i></a> ';
}else{
$egcuno = '';
}
$client = $em->getRepository(Client::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));
if(!empty($userAsignar)){
$id=$userAsignar->getId();
}else{
$id = null;
}
}else{
$id = null;
}
// d($id);
if (!is_null($id)){
$proposal->setAgentId($id);
$em->persist($proposal);
$em->flush();
$user = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
$userColor = $user->getColor();
$userPicture = $user->getPicture();
$userLastname = $user->getLastname();
$userName = $user->getName();
}else{
$userColor = "#ff0000";
$userPicture = null;
$userLastname = "Not Assigned";
$userName = "Not Assigned";
}
}else{
$userColor = $user->getColor();
$userPicture = $user->getPicture();
$userLastname = $user->getLastname();
$userName = $user->getName();
}
$colorHay = $userColor;
if (empty($colorHay)){
$color = "#ff0000";
}else{
$color = $userColor;
}
if (is_null($userPicture)){
$picture = "";
}else{
$picture = "<img src='".$userPicture."' class='img-circle img-lg'><br>";
}
$tooltip = $picture." ".
$userName." ".$userLastname."<br>".
$client->getName()."<br>".
$proposal->getName()."</b><br>";
$datos[] = array(
"id" => $proposal->getId(),
"title" => $egcuno.$userName." ".$userLastname." | ".$client->getName().": ".$proposal->getName(),
"tooltip" => $tooltip,
"start" => $proposal->getDateEventStarAt(),
"end" => $proposal->getDateEventEndAt(),
"color" => $color,
"url" => "/events/proposal/destination/add/".$proposal->getId()
);
}
}
else
{
$datos = [];
}
$return = array(
'proposal' => $datos,
);
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/proposal/sentmail/{id}", name="list_SentMail_Proposal")
*/
public function listSentMailAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$sentMaillist = $em->getRepository(SendMail::class)->findByProposalId($id);
return $this->render('MDS/EventsBundle/mail/list-mail.html.twig', array(
'id' => $id,
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'mailsent' => $sentMaillist
));
}
/**
* @Route("/proposal/detailsmail/{idm}/{id}", name="list_DeatilsMail_Proposal")
*/
public function listDetailsMailAction($idm, $id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$sentMaillist = $em->getRepository(SendMail::class)->findOneById($idm);
return $this->render('MDS/EventsBundle/mail/details-mail.html.twig', array(
'id' => $id,
'idm' => $idm,
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'mailsent' => $sentMaillist
));
}
/**
* @Route("/proposal/cancel/{id}", name="proposal_cancel")
*/
public function cancelAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
if($proposal->getAgentId() == null){
$proposal->setAgentId(999999);
$proposal->setAgentTwoId('999999');
}
$proposal->setStatus('Cancel');
$em->persist($proposal);
$em->flush();
$event = 'The Proposal has been canceled.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeproposaldestination', $successMessage);
$parameterspc = array();
$dqlpc = 'SELECT COUNT (pc.id) FROM EventsBundle:Proposal pc WHERE pc.agentId is null';
$querypc = $em->createQuery($dqlpc)->setParameters($parameterspc);
$cantidadpc = $querypc->getResult();
$request->getSession()->set('_proposal_unassigned', $cantidadpc[0][1]);
if ( is_null(($proposal->getAgentId())) and is_null(($proposal->getAgentTwoId()))){
//No tiene agente asignado, el controlador fue llamado desde Unassigned Porposals
return $this->redirectToRoute('proposal_list_unassigned');
} else {
return $this->redirectToRoute('proposal_list');
}
}
/**
* @Route("/proposal/blocked/list", name="proposal_list_blocked")
*/
public function indexListBlockedAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$props = $em->getRepository(Proposal::class)->findAll();
$proposals = array();
foreach ($props as $prop){
if ($prop->getStatus() == 'Blocked'){
$proposals[] = $prop;
}
}
// $proposals = $em->getRepository(Proposal::class)->findBy(
// array(
// 'status' => $status
// )
// );
// $proposals = $em->getRepository(Proposal::class)->findByStatus($status);
// $desde = $request->request->get('buscarFecha')['desde'];
// $hasta = $request->request->get('buscarFecha')['hasta'];
// $cliente = isset($request->request->get('buscarFecha')['clientid'])? $request->request->get('buscarFecha')['clientid'] : '';
//
// if (empty($desde) && empty($hasta))
// {
// if(empty($cliente))
// {
// $hoy = date('Y').'-01-01';
//// $hoy->modify('-3 month');
// $parameters = array(
// 'hoy' => $hoy,
// 'status' => 'Blocked'
// );
// $dql = 'SELECT p
// FROM EventsBundle:Proposal p
// WHERE p.dateEventStarAt >= :hoy AND p.status = :status
// ORDER BY p.id DESC';
//
// $query = $em->createQuery($dql)->setParameters($parameters);
// // $proposals = $query->getResult();
//
// }
// else
// {
// /* Si solo tiene el cliente id lo reenvió a consulta por id cliente */
// return $this->redirectToRoute('proposal_list_client', array(
// 'id' => $cliente
// ));
// }
//
// }
// else
// {
// /* Consulta con fechas desde y hasta con id cliente */
// if(!empty($cliente)){
// $parameters = array(
// 'desde' => $desde,
// 'hasta' => $hasta,
// 'cliente' => $cliente,
// 'status' => 'Blocked'
// );
//
// $dql = 'SELECT p
// FROM EventsBundle:Proposal p
// WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.clientId = :cliente and p.agentId IS null and p.status = :status
// ORDER BY p.id DESC';
//// ORDER BY p.dateProposedAt DESC';
// }
// else
// {
// /* Consulta con fechas desde y hasta sin id cliente */
// $parameters = array(
// 'desde' => $desde,
// 'hasta' => $hasta,
// 'status' => 'Blocked'
// );
//
// $dql = 'SELECT p
// FROM EventsBundle:Proposal p
// WHERE p.dateProposedAt >= :desde AND p.dateProposedAt <= :hasta and (p.agentId IS null) and p.status = :status
// ORDER BY p.id DESC';
//// ORDER BY p.dateProposedAt DESC';
// }
//
// $query = $em->createQuery($dql)->setParameters($parameters);
// $proposals = $query->getResult();
// }
$datos_proposal = array();
foreach($proposals as $proposal){
/*
* Estado, date create, id, Nombre, Cliente, Comercial, Equipo, Usuario, Inicio, Fin
* */
switch ($proposal->getStatus()) {
case "Pending":
// $iconstatus ='<i class="icon-bell3 text-danger parpadea"></i>';
$iconstatus ='<i class="icon-hammer text-danger parpadea"></i>';
break;
case "Sent":
$iconstatus ='<i class="icon-paperplane text-orange"></i>';
break;
case "Confirmed":
// $iconstatus ='<i class="icon-unlocked text-success"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-green-800"></i>';
break;
case "Invoiced":
// $iconstatus ='<i class="icon-lock2 text-gold"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-gold"></i>';
break;
case "Cancel":
// $iconstatus ='<i class=" icon-blocked text-grey"></i>';
$iconstatus ='<i class="icon-thumbs-down3 text-danger"></i>';
break;
case "Blocked":
$iconstatus ='<i class=" icon-lock2 text-grey"></i>';
break;
}
if ($proposal->getSent() == "Yes"){
$iconsent ='<i class="icon-paperplane text-orange"></i>';
if ($proposal->getStatus() == "Pending"){
// $iconstatus ='<i class="icon-bell3 text-danger"></i>';
$iconstatus ='<i class="icon-hammer text-danger"></i>';
}
}else{
$iconsent ='';
}
/* Consultas */
$client = $em->getRepository(Client::class)->findOneByid($proposal->getClientId());
$contact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$commercial = $em->getRepository(User::class)->findOneById($proposal->getAgencommercialId());
if(empty($commercial)){$comercial="";}else{$comercial = $commercial->getName();}
$teams = $em->getRepository(SettingsTeam::class)->findOneById($proposal->getTeamId());
if(empty($teams)){$team="";}else{$team = $teams->getTeam();}
$agente = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if(empty($agente)){$agent="";}else{$agent = $agente->getName();}
/* Visto por ultima ves por parte del cliente o atraves del Access Key */
if ($proposal->getViewedAt() == $proposal->getCreatedAt()){
//no Visto
$novisto = $this->translator->trans('Not seen');
}else{
//visto
$novisto = $this->translator->trans('Seen by Client');
}
//Nombres resumidos de los agentes
$allAgentesResumidos = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
$agentesResumidos = '';
$nombreOne= '';
if (!empty($allAgentesResumidos)) {
if (!empty($allAgentesResumidos->getAgOne())) {
if ($allAgentesResumidos->getAgOne() != 0) {
// Hay Agente One
$theOne = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgOne());
if(is_null($theOne)){
$nombreOne = 'N/A';
}else{
$nombreOne = $theOne->getName() . ' ' . substr($theOne->getLastName(), 0, 1);
}
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreOne;
} else {
$agentesResumidos = $nombreOne;
}
}
}
if (!empty($allAgentesResumidos->getAgTwo())) {
if ($allAgentesResumidos->getAgTwo() != 0) {
// Hay Agente Two
$theTwo = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgTwo());
if(is_null($theTwo)){
$nombreTwo = 'N/A';
}else{
$nombreTwo = $theTwo->getName() . ' ' . substr($theTwo->getLastName(), 0, 1);
}
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreTwo;
} else {
$agentesResumidos = $nombreTwo;
}
}
}
if (!empty($allAgentesResumidos->getAgThree())) {
if ($allAgentesResumidos->getAgThree() != 0) {
// Hay Agente Three
$theThree = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgThree());
if(is_null($theThree)){
$nombreThree = 'N/A';
}else{
$nombreThree = $theThree->getName() . ' ' . substr($theThree->getLastName(), 0, 1);
}
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreThree;
} else {
$agentesResumidos = $nombreThree;
}
}
}
if (!empty($allAgentesResumidos->getAgFour())) {
if ($allAgentesResumidos->getAgFour() != 0) {
// Hay Agente Four
$theFour = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgFour());
if(is_null($theFour)){
$nombreFour = 'N/A';
}else{
$nombreFour = $theFour->getName() . ' ' . substr($theFour->getLastName(), 0, 1);
}
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreFour;
} else {
$agentesResumidos = $nombreFour;
}
}
}
}
if (strpos($agentesResumidos,',')===false){
//Hay mas de un agente
$masdeunagente = true;
$agentView = $agent;
} else {
//No hay mas de un agente
$masdeunagente = false;
$agentView = $agentesResumidos;
}
//Nombres resumidos de los agentes
$datos_proposal[] = array(
'status' => $this->translator->trans($proposal->getStatus()),
'iconstatus' => $iconstatus,
'iconsent' => $iconsent,
'viewedAt' => $proposal->getViewedAt()->format('d/m/Y H:i:s'),
'novisto' => $novisto,
'create' => $proposal->getDateProposedAt()->format('d/m/Y'),
'id' => $proposal->getId(),
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'name' => $proposal->getName(),
'client' => $client->getName(),
'client_id' => $client->getId(),
'contact' => $contact->getName().' '.$contact->getLastname(),
'contactdepartment' => $contact->getDepartment(),
'contactphone' => $contact->getPhone(),
'contactmovil' => $contact->getMobile(),
'contactmail' => $contact->getEmail(),
'commercial' => $comercial,
'team' => $team,
'agent' => $agent,
'event_star' => $proposal->getDateEventStarAt()->format('d/m/Y'),
'event_end' => $proposal->getDateEventEndAt()->format('d/m/Y'),
'list_client' => 'si',
'send' => $proposal->getSent(),
// 'refagent' => ''
'refagent' => $agentView
);
}
// $agent_data = $em->getRepository(User::class)->findAll();
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$agent_data = $query->getResult();
/* FIN Consulta de agente activos MICE */
return $this->render('MDS/EventsBundle/proposal/list-proposal-blocked.html.twig', array(
'proposals' => $datos_proposal,
'numblock' => sizeof($datos_proposal),
'unassigned' => 'Unassigned',
'agents' => $agent_data,
));
}
/**
* @Route("/proposal/my/list", name="proposal_my")
*/
public function indexListMyAction(Request $request)
{
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$em = $this->getDoctrine()->getManager();
$desde = isset($request->request->get('buscarFecha')['desde'])? $request->request->get('buscarFecha')['desde'] : '';
$hasta = isset($request->request->get('buscarFecha')['hasta'])? $request->request->get('buscarFecha')['hasta'] : '';;
$cliente = isset($request->request->get('buscarFecha')['clientid'])? $request->request->get('buscarFecha')['clientid'] : '';
$agentId = isset($request->request->get('data')['agent'])? $request->request->get('data')['agent'] : '';
if (empty($desde) && empty($hasta))
{
if(empty($cliente))
{
if(empty($agentId))
{
$parameters = array(
'idUser' => $user_id
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
INNER JOIN EventsBundle:ProposalAgents pa WITH p.id = pa.idProp
WHERE pa.agOne = :idUser
OR pa.agTwo = :idUser OR pa.agThree = :idUser OR pa.agFour = :idUser
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
else
{// El buscador no esta llegando a este punto ya que devuelve a la lista principal, corregir cuando haya tiempo creando un nuevo buscador
$parameters = array(
'idUser' => $user_id,
'agentId' => $agentId
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
INNER JOIN EventsBundle:ProposalAgents pa WITH p.id = pa.idProp
WHERE (pa.agOne = :idUser and (pa.agTwo = :agentId OR pa.agThree = :agentId OR pa.agFour = :agentId))
OR (pa.agTwo = :idUser and (pa.agOne = :agentId OR pa.agThree = :agentId OR pa.agFour = :agentId))
OR (pa.agThree = :idUser and (pa.agTwo = :agentId OR pa.agOne = :agentId OR pa.agFour = :agentId))
OR (pa.agFour = :idUser and (pa.agTwo = :agentId OR pa.agThree = :agentId OR pa.agOne = :agentId))
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
}
else
{ // el cliente no viene vacio
if(empty($agentId))
{
// El buscador no esta llegando a este punto ya que devuelve a la lista principal, corregir cuando haya tiempo creando un nuevo buscador
$parameters = array(
'cliente' => $cliente,
'idUser' => $user_id
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
INNER JOIN EventsBundle:ProposalAgents pa WITH p.id = pa.idProp
WHERE (pa.agOne = :idUser and (p.clientId = cliente))
OR (pa.agTwo = :idUser and (p.clientId = cliente))
OR (pa.agThree = :idUser and (p.clientId = cliente))
OR (pa.agFour = :idUser and (p.clientId = cliente))
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
else
{ //el cliente no viene vacio y hay agente
// El buscador no esta llegando a este punto ya que devuelve a la lista principal, corregir cuando haya tiempo creando un nuevo buscador
$parameters = array(
'cliente' => $cliente,
'idUser' => $user_id,
'agentId' => $agentId
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
INNER JOIN EventsBundle:ProposalAgents pa WITH p.id = pa.idProp
WHERE (pa.agOne = :idUser and (pa.agTwo = :agentId OR pa.agThree = :agentId OR pa.agFour = :agentId) and (p.clientId = cliente))
OR (pa.agTwo = :idUser and (pa.agOne = :agentId OR pa.agThree = :agentId OR pa.agFour = :agentId) and (p.clientId = cliente))
OR (pa.agThree = :idUser and (pa.agTwo = :agentId OR pa.agOne = :agentId OR pa.agFour = :agentId) and (p.clientId = cliente))
OR (pa.agFour = :idUser and (pa.agTwo = :agentId OR pa.agThree = :agentId OR pa.agOne = :agentId) and (p.clientId = cliente))
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
}
}
else
{
/* Consulta con fechas desde y hasta con id cliente */
if(!empty($cliente)){
if(!empty($agentId)){
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'cliente' => $cliente,
'agentId' => $agentId,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.clientId = :cliente AND p.status != :status AND p.agentId = :agentId
ORDER BY p.id DESC';
}
else
{
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'cliente' => $cliente,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.clientId = :cliente AND p.status != :status AND p.agentId is not null
ORDER BY p.id DESC';
// ORDER BY p.dateProposedAt DESC';
}
}
else
{
if(!empty($agentId)){
/* Consulta con fechas desde y hasta sin id cliente */
$parameters = array(
'agentId' => $agentId,
'desde' => $desde,
'hasta' => $hasta,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateProposedAt >= :desde AND p.dateProposedAt <= :hasta AND p.status != :status AND p.agentId = :agentId
ORDER BY p.id DESC';
}
else
{
/* Consulta con fechas desde y hasta sin id cliente */
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateProposedAt >= :desde AND p.dateProposedAt <= :hasta AND p.status != :status AND p.agentId is not null
ORDER BY p.id DESC';
// ORDER BY p.dateProposedAt DESC';
}
}
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
$datos_proposal = array();
foreach($proposals as $proposal){
/*
* Estado, date create, id, Nombre, Cliente, Comercial, Equipo, Usuario, Inicio, Fin
* */
switch ($proposal->getStatus()) {
case "Pending":
// $iconstatus ='<i class="icon-bell3 text-danger parpadea"></i>';
$iconstatus ='<i class="icon-hammer text-danger parpadea"></i>';
break;
case "Sent":
$iconstatus ='<i class="icon-paperplane text-orange"></i>';
break;
case "Confirmed":
// $iconstatus ='<i class="icon-unlocked text-success"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-green-800"></i>';
break;
case "Invoiced":
// $iconstatus ='<i class="icon-lock2 text-gold"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-gold"></i>';
break;
case "Cancel":
// $iconstatus ='<i class=" icon-blocked text-grey"></i>';
$iconstatus ='<i class="icon-thumbs-down3 text-danger"></i>';
break;
case "Blocked":
$iconstatus ='<i class="icon-lock2 text-grey"></i>';
break;
case "Unblocked":
$iconstatus ='<i class="icon-unlocked2 text-black"></i>';
break;
}
if ($proposal->getSent() == "Yes"){
$iconsent ='<i class="icon-paperplane text-orange"></i>';
if ($proposal->getStatus() == "Pending"){
// $iconstatus ='<i class="icon-bell3 text-danger"></i>';
$iconstatus ='<i class="icon-hammer text-danger"></i>';
}
}else{
$iconsent ='';
}
/* Consultas */
$client = $em->getRepository(Client::class)->findOneByid($proposal->getClientId());
$contact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$commercial = $em->getRepository(User::class)->findOneById($proposal->getAgencommercialId());
if(empty($commercial)){$comercial="";}else{$comercial = $commercial->getName();}
$teams = $em->getRepository(SettingsTeam::class)->findOneById($proposal->getTeamId());
if(empty($teams)){$team="";}else{$team = $teams->getTeam();}
$agente = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if(empty($agente)){$agent="";}else{$agent = $agente->getName();}
/* Visto por ultima ves por parte del cliente o atraves del Access Key */
if ($proposal->getViewedAt() == $proposal->getCreatedAt()){
//no Visto
$novisto = $this->translator->trans('Not seen');
}else{
//visto
$novisto = $this->translator->trans('Seen by Client');
}
//Nombres resumidos de los agentes
$allAgentesResumidos = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
$agentesResumidos = '';
$nombreOne= '';
if (!empty($allAgentesResumidos)) {
if (!empty($allAgentesResumidos->getAgOne())) {
if ($allAgentesResumidos->getAgOne() != 0) {
// Hay Agente One
$theOne = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgOne());
if(!is_null($theOne)){
$nombreOne = $theOne->getName() . ' ' . substr($theOne->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreOne;
} else {
$agentesResumidos = $nombreOne;
}
}
}
}
if (!empty($allAgentesResumidos->getAgTwo())) {
if ($allAgentesResumidos->getAgTwo() != 0) {
// Hay Agente Two
$theTwo = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgTwo());
if(!is_null($theTwo)){
$nombreTwo = $theTwo->getName() . ' ' . substr($theTwo->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreTwo;
} else {
$agentesResumidos = $nombreTwo;
}
}
}
}
if (!empty($allAgentesResumidos->getAgThree())) {
if ($allAgentesResumidos->getAgThree() != 0) {
// Hay Agente Three
$theThree = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgThree());
if(!is_null($theThree)){
$nombreThree = $theThree->getName() . ' ' . substr($theThree->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreThree;
} else {
$agentesResumidos = $nombreThree;
}
}
}
}
if (!empty($allAgentesResumidos->getAgFour())) {
if ($allAgentesResumidos->getAgFour() != 0) {
// Hay Agente Four
$theFour = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgFour());
if(!is_null($theFour)){
$nombreFour = $theFour->getName() . ' ' . substr($theFour->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreFour;
} else {
$agentesResumidos = $nombreFour;
}
}
}
}
}
if (strpos($agentesResumidos,',')===false){
//Hay mas de un agente
$masdeunagente = true;
$agentView = $agent;
} else {
//No hay mas de un agente
$masdeunagente = false;
$agentView = $agentesResumidos;
}
//Nombres resumidos de los agentes
$datos_proposal[] = array(
'status' => $this->translator->trans($proposal->getStatus()),
'iconstatus' => $iconstatus,
'iconsent' => $iconsent,
'viewedAt' => $proposal->getViewedAt()->format('d/m/Y H:i:s'),
'novisto' => $novisto,
'create' => $proposal->getDateProposedAt() == Null? '' : $proposal->getDateProposedAt()->format('d/m/Y'),
'id' => $proposal->getId(),
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'name' => $proposal->getName(),
'client' => $client->getName(),
'client_id' => $client->getId(),
'contact' => $contact->getName().' '.$contact->getLastname(),
'contactdepartment' => $contact->getDepartment(),
'contactphone' => $contact->getPhone(),
'contactmovil' => $contact->getMobile(),
'contactmail' => $contact->getEmail(),
'commercial' => $comercial,
'team' => $team,
'agent' => $agent,
'event_star' => $proposal->getDateEventStarAt()->format('d/m/Y'),
'event_end' => $proposal->getDateEventEndAt()->format('d/m/Y'),
'list_client' => 'si',
'send' => $proposal->getSent(),
// 'refagent' => ''
'refagent' => $agentView
);
}
// $agent_data = $em->getRepository(User::class)->findAll();
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$agent_data = $query->getResult();
/* FIN Consulta de agente activos MICE */
return $this->render('MDS/EventsBundle/proposal/list-proposal.html.twig', array(
'proposals' => $datos_proposal,
'unassigned' => '',
'agents' => $agent_data,
));
}
/**
* @Route("/proposal/historic", name="proposal_historic")
*/
public function indexListHistoricAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$desde = isset($request->request->get('buscarFecha')['desde'])? $request->request->get('buscarFecha')['desde'] : '';;
$hasta = isset($request->request->get('buscarFecha')['hasta'])? $request->request->get('buscarFecha')['hasta'] : '';;
$cliente = isset($request->request->get('buscarFecha')['clientid'])? $request->request->get('buscarFecha')['clientid'] : '';
$agentId = isset($request->request->get('data')['agent'])? $request->request->get('data')['agent'] : '';
if (empty($desde) && empty($hasta))
{
if(empty($cliente))
{
if(empty($agentId))
{
// $hoy = date('Y-m-01', strtotime('-12 month'));
$hoy = date('Y-m-01', strtotime('-24 month'));
$parameters = array(
'hoy' => $hoy,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :hoy
AND p.status != :status AND p.agentId is not null
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
else
{
// $hoy = date('Y') . '-01-01';
// $hoy = date('Y-m-01', strtotime('-12 month'));
$hoy = date('Y-m-01', strtotime('-2 month'));
$parameters = array(
'agentId' => $agentId,
'hoy' => $hoy,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :hoy AND p.status != :status AND p.agentId = :agentId
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
}
else
{ // el cliente no viene vacio
if(empty($agentId))
{
/* Si solo tiene el cliente id lo reenvió a consulta por id cliente */
return $this->redirectToRoute('proposal_list_client', array(
'id' => $cliente
));
}
else
{ //el cliente no viene vacio y hay agente
// $hoy = date('Y') . '-01-01';
// $hoy = date('Y-m-01', strtotime('-12 month'));
$hoy = date('Y-m-01', strtotime('-2 month'));
$parameters = array(
'agentId' => $agentId,
'cliente' => $cliente,
'hoy' => $hoy,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :hoy
AND p.status != :status AND p.agentId = :agentId AND p.clientId = :cliente
ORDER BY p.id DESC';
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
}
}
else
{
/* Consulta con fechas desde y hasta con id cliente */
if(!empty($cliente)){
if(!empty($agentId)){
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'cliente' => $cliente,
'agentId' => $agentId,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.clientId = :cliente AND p.status != :status AND p.agentId = :agentId
ORDER BY p.id DESC';
}
else
{
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'cliente' => $cliente,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateEventStarAt >= :desde AND p.dateEventStarAt <= :hasta AND p.clientId = :cliente AND p.status != :status AND p.agentId is not null
ORDER BY p.id DESC';
// ORDER BY p.dateProposedAt DESC';
}
}
else
{
if(!empty($agentId)){
/* Consulta con fechas desde y hasta sin id cliente */
$parameters = array(
'agentId' => $agentId,
'desde' => $desde,
'hasta' => $hasta,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateProposedAt >= :desde AND p.dateProposedAt <= :hasta AND p.status != :status AND p.agentId = :agentId
ORDER BY p.id DESC';
}
else
{
/* Consulta con fechas desde y hasta sin id cliente */
$parameters = array(
'desde' => $desde,
'hasta' => $hasta,
'status' => 'Cancel'
);
$dql = 'SELECT p
FROM EventsBundle:Proposal p
WHERE p.dateProposedAt >= :desde AND p.dateProposedAt <= :hasta AND p.status != :status AND p.agentId is not null
ORDER BY p.id DESC';
// ORDER BY p.dateProposedAt DESC';
}
}
$query = $em->createQuery($dql)->setParameters($parameters);
$proposals = $query->getResult();
}
$datos_proposal = array();
foreach($proposals as $proposal){
/*
* Estado, date create, id, Nombre, Cliente, Comercial, Equipo, Usuario, Inicio, Fin
* */
switch ($proposal->getStatus()) {
case "Pending":
// $iconstatus ='<i class="icon-bell3 text-danger parpadea"></i>';
$iconstatus ='<i class="icon-hammer text-danger parpadea"></i>';
break;
case "Sent":
$iconstatus ='<i class="icon-paperplane text-orange"></i>';
break;
case "Confirmed":
// $iconstatus ='<i class="icon-unlocked text-success"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-green-800"></i>';
break;
case "Invoiced":
// $iconstatus ='<i class="icon-lock2 text-gold"></i>';
$iconstatus ='<i class="icon-thumbs-up3 text-gold"></i>';
break;
case "Cancel":
// $iconstatus ='<i class=" icon-blocked text-grey"></i>';
$iconstatus ='<i class="icon-thumbs-down3 text-danger"></i>';
break;
case "Blocked":
$iconstatus ='<i class="icon-lock2 text-grey"></i>';
break;
case "Unblocked":
$iconstatus ='<i class="icon-unlocked2 text-black"></i>';
break;
}
if ($proposal->getSent() == "Yes"){
$iconsent ='<i class="icon-paperplane text-orange"></i>';
if ($proposal->getStatus() == "Pending"){
// $iconstatus ='<i class="icon-bell3 text-danger"></i>';
$iconstatus ='<i class="icon-hammer text-danger"></i>';
}
}else{
$iconsent ='';
}
/* Consultas */
$client = $em->getRepository(Client::class)->findOneById($proposal->getClientId());
$contact = $em->getRepository(ClientContact::class)->findOneById($proposal->getContactId());
$commercial = $em->getRepository(User::class)->findOneById($proposal->getAgencommercialId());
if(empty($commercial)){$comercial="";}else{$comercial = $commercial->getName();}
$teams = $em->getRepository(SettingsTeam::class)->findOneById($proposal->getTeamId());
if(empty($teams)){$team="";}else{$team = $teams->getTeam();}
$agente = $em->getRepository(User::class)->findOneById($proposal->getAgentId());
if(empty($agente)){$agent="";}else{$agent = $agente->getName();}
/* Visto por ultima ves por parte del cliente o atraves del Access Key */
if ($proposal->getViewedAt() == $proposal->getCreatedAt()){
//no Visto
$novisto = $this->translator->trans('Not seen');
}else{
//visto
$novisto = $this->translator->trans('Seen by Client');
}
//Nombres resumidos de los agentes
$allAgentesResumidos = $em->getRepository(ProposalAgents::class)->findOneByIdProp($proposal->getId());
$agentesResumidos = '';
$nombreOne= '';
if (!empty($allAgentesResumidos)) {
if (!empty($allAgentesResumidos->getAgOne())) {
if ($allAgentesResumidos->getAgOne() != 0) {
// Hay Agente One
$theOne = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgOne());
if (empty($theOne)){ $theOne = $em->getRepository(User::class)->findOneByid(6); }
$nombreOne = $theOne->getName() . ' ' . substr($theOne->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreOne;
} else {
$agentesResumidos = $nombreOne;
}
}
}
if (!empty($allAgentesResumidos->getAgTwo())) {
if ($allAgentesResumidos->getAgTwo() != 0) {
// Hay Agente Two
$theTwo = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgTwo());
if (empty($theTwo)){ $theTwo = $em->getRepository(User::class)->findOneByid(6); }
$nombreTwo = $theTwo->getName() . ' ' . substr($theTwo->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreTwo;
} else {
$agentesResumidos = $nombreTwo;
}
}
}
if (!empty($allAgentesResumidos->getAgThree())) {
if ($allAgentesResumidos->getAgThree() != 0) {
// Hay Agente Three
$theThree = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgThree());
if (empty($theThree)){ $theThree = $em->getRepository(User::class)->findOneByid(6); }
$nombreThree = $theThree->getName() . ' ' . substr($theThree->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreThree;
} else {
$agentesResumidos = $nombreThree;
}
}
}
if (!empty($allAgentesResumidos->getAgFour())) {
if ($allAgentesResumidos->getAgFour() != 0) {
// Hay Agente Four
$theFour = $em->getRepository(User::class)->findOneByid($allAgentesResumidos->getAgFour());
if (empty($theFour)){ $theFour = $em->getRepository(User::class)->findOneByid(6); }
$nombreFour = $theFour->getName() . ' ' . substr($theFour->getLastName(), 0, 1);
if (!empty($agentesResumidos)) {
$agentesResumidos = $agentesResumidos.', '. $nombreFour;
} else {
$agentesResumidos = $nombreFour;
}
}
}
}
if (strpos($agentesResumidos,',')===false){
//Hay mas de un agente
$masdeunagente = true;
$agentView = $agent;
} else {
//No hay mas de un agente
$masdeunagente = false;
$agentView = $agentesResumidos;
}
//Nombres resumidos de los agentes
if (empty($client)){ $client = new Client(); }
if (empty($contact)){ $contact = new ClientContact(); }
$datos_proposal[] = array(
'status' => $this->translator->trans($proposal->getStatus()),
'iconstatus' => $iconstatus,
'iconsent' => $iconsent,
'viewedAt' => $proposal->getViewedAt()->format('d/m/Y H:i:s'),
'novisto' => $novisto,
'create' => $proposal->getDateProposedAt() == Null? '' : $proposal->getDateProposedAt()->format('d/m/Y'),
'id' => $proposal->getId(),
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'name' => $proposal->getName(),
'client' => $client->getName(),
'client_id' => $client->getId(),
'contact' => $contact->getName().' '.$contact->getLastname(),
'contactdepartment' => $contact->getDepartment(),
'contactphone' => $contact->getPhone(),
'contactmovil' => $contact->getMobile(),
'contactmail' => $contact->getEmail(),
'commercial' => $comercial,
'team' => $team,
'agent' => $agent,
'event_star' => $proposal->getDateEventStarAt()->format('d/m/Y'),
'event_end' => $proposal->getDateEventEndAt()->format('d/m/Y'),
'list_client' => 'si',
'send' => $proposal->getSent(),
// 'refagent' => ''
'refagent' => $agentView
);
}
// $agent_data = $em->getRepository(User::class)->findAll();
/* INICIO Consulta de agente activos MICE */
$parameters = array(
'status' => true
);
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$agent_data = $query->getResult();
/* FIN Consulta de agente activos MICE */
return $this->render('MDS/EventsBundle/proposal/list-proposal.html.twig', array(
'proposals' => $datos_proposal,
'unassigned' => '',
'agents' => $agent_data,
));
}
/**
* @Route("/proposal/duplicate/{id}", name="proposal_duplicate")
*/
public function duplicateAction($id)
{
// Inicio: Se genera el nuevo proposal (Tabla Proposals)
$em = $this->getDoctrine()->getManager();
$proposalOrigen = $em->getRepository(Proposal::class)->findOneById($id);
$proposal = new Proposal();
$proposal->setName('PROPOSAL DUPLICADO (' . $id . '): '. $proposalOrigen->getName());
$proposal->setTitle('PROPOSAL DUPLICADO (' . $id . '): '. $proposalOrigen->getTitle());
$proposal->setCommission($proposalOrigen->getCommission());
$proposal->setPax($proposalOrigen->getPax());
$proposal->setBedrooms($proposalOrigen->getBedrooms());
$proposal->setOfficeId($proposalOrigen->getOfficeId());
$proposal->setClientId($proposalOrigen->getClientId());
$proposal->setContactId($proposalOrigen->getContactId());
$proposal->setReferenceName($proposalOrigen->getReferenceName());
$proposal->setReferenceId($proposalOrigen->getReferenceId());
// $proposal->setAgentId($proposalOrigen->getAgentId()); No se duplicara el agente
$proposal->setAgentId('0');
// $proposal->setTeamId($proposalOrigen->getTeamId()); No se duplicara nada de los agentes
// $proposal->setAgentTwoId($proposalOrigen->getAgentTwoId()); No se duplicara el agente
// $proposal->setAgencommercialId($proposalOrigen->getAgencommercialId()); No se duplicara nada de los agentes
$proposal->setDateProposedAt(new \DateTime("now"));
// $proposal->setDateEventStarAt($proposalOrigen->getDateEventStarAt()); // La fecha de inicio y fin del evento no debe ser la misma ya que podria bloquearse el proposal de forma automatica
$proposal->setDateEventStarAt(new \DateTime("now"));
// $proposal->setDateEventEndAt($proposalOrigen->getDateEventEndAt()); // La fecha de inicio y fin del evento no debe ser la misma ya que podria bloquearse el proposal de forma automatica
$proposal->setDateEventEndAt(new \DateTime("now"));
$proposal->setDaysEmailReminder($proposalOrigen->getDaysEmailReminder());
$proposal->setLanguage($proposalOrigen->getLanguage());
$proposal->setIncludeLogo($proposalOrigen->getIncludeLogo());
$proposal->setVersionPpt($proposalOrigen->getVersionPpt());
$proposal->setVersionExcel($proposalOrigen->getVersionExcel());
$proposal->setVersionFlahs($proposalOrigen->getVersionFlahs());
$proposal->setVersionWord($proposalOrigen->getVersionWord());
$proposal->setBriefing($proposalOrigen->getBriefing());
$proposal->setDatePresentationAt($proposalOrigen->getDatePresentationAt());
$proposal->setStatus('Pending');
// $proposal->setSent($proposalOrigen->getSent()); No se copia el envio
$proposal->setSelectType($proposalOrigen->getSelectType());
$proposal->setCreatedAt(new \DateTime("now"));
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$proposal->setCreatedId($user_logueado->getId()); // El nuevo proposal lo crea es el usuario loggeado y no el usuario que creo el original
$proposal->setUpdatedAt(new \DateTime("now")); // La fecha de actualizacion es la actual
$proposal->setUpdatedId($user_logueado->getId()); // El nuevo proposal lo actualiza es el usuario loggeado y no el usuario que actualizo el original
//Access Key para entrar en el proposal
$accessKey = md5('CR-JDEF'. rand() * time());
$proposal->setAccessKey($accessKey);
// $proposal->setViewedAt($proposalOrigen->getViewedAt()); Este proposal no ha sido visto por el usuario
$proposal->setViewedAt(new \DateTime("now"));
// $proposal->setObservation($proposalOrigen->getObservation());
// $proposal->setSendAdmin($proposalOrigen->getSendAdmin());
// $proposal->setMcp($proposalOrigen->getMcp());
// $proposal->setImage($proposalOrigen->getImage());
$proposal->setCategory($proposalOrigen->getCategory());
$proposal->setIdMusic($proposalOrigen->getIdMusic());
$em->persist($proposal);
$em->flush();
$newId = $proposal->getId();
$proposalAgents = new ProposalAgents();
$proposalAgents->setAgOne('0');
$proposalAgents->setAgOnePerc('0');
$proposalAgents->setAgTwo('0');
$proposalAgents->setAgTwoPerc('0');
$proposalAgents->setAgThree('0');
$proposalAgents->setAgThreePerc('0');
$proposalAgents->setAgFour('0');
$proposalAgents->setAgFourPerc('0');
$proposalAgents->setIdProp($newId);
$em->persist($proposalAgents);
$em->flush();
// Fin: Se genera el nuevo proposal (Tabla Proposals)
// Inicio: Se generan los controles del proposal (Tabla Proposals_control)
$proposalControlOrigen = $em->getRepository(ProposalControl::class)->findByProposalId($id);
$arrayTranslateProposalControl = array();
foreach ($proposalControlOrigen as $control){
$proposalControl = new ProposalControl();
$proposalControl->setDestinationId($control->getDestinationId());
$proposalControl->setDisabled($control->getDisabled());
$proposalControl->setDisabledPresentation($control->getDisabledPresentation());
$proposalControl->setProposalId($newId);
$em->persist($proposalControl);
$em->flush();
$arrayTranslateProposalControl[$control->getId()] = $proposalControl->getId(); // Arreglo que traduce un indice del antiguo proposal control al nuevo
}
// Fin: Se generan los controles del proposal (Tabla Proposals_control)
// Inicio: Se generan los controles para los proveedores (Tabla Proposals_supplier_control)
$proposalSupplierControlOrigen = $em->getRepository(ProposalSupplierControl::class)->findByProposalId($id);
$arrayTranslateProposalSupplierControl = array();
foreach ($proposalSupplierControlOrigen as $supcontrol){
$proposalSupplierControl = new ProposalSupplierControl();
$proposalSupplierControl->setDestinoId($supcontrol->getDestinoId());
$proposalSupplierControl->setSupplierId($supcontrol->getSupplierId());
$proposalSupplierControl->setIdeaId($supcontrol->getIdeaId());
$proposalSupplierControl->setStatus($supcontrol->getStatus());
$proposalSupplierControl->setDisabled($supcontrol->getDisabled());
$proposalSupplierControl->setRank($supcontrol->getRank());
$proposalSupplierControl->setDateBlockLimit($supcontrol->getDateBlockLimit());
$proposalSupplierControl->setActivityId($supcontrol->getActivityId());
$proposalSupplierControl->setProposalId($newId);
if (array_key_exists($supcontrol->getControlDestinationId(),$arrayTranslateProposalControl)) {
$proposalSupplierControl->setControlDestinationId($arrayTranslateProposalControl[$supcontrol->getControlDestinationId()]);
} else {
$proposalSupplierControl->setControlDestinationId(1);
}
$em->persist($proposalSupplierControl);
$em->flush();
$arrayTranslateProposalSupplierControl[$supcontrol->getId()] = $proposalSupplierControl->getId(); // Arreglo que traduce un indice del antiguo proposal supplier control al nuevo
}
// Fin: Se generan los controles para los proveedores (Tabla Proposals_supplier_control)
// Inicio: Se generan los servicios (Proposals_supplier_services)
$proposalSupplierServicesOrigen = $em->getRepository(ProposalSupplierServices::class)->findByProposalId($id);
foreach ($proposalSupplierServicesOrigen as $suppserv) {
$proposalSupplierServices = new ProposalSupplierServices();
$proposalSupplierServices->setServiceIdFather($suppserv->getServiceIdFather());
$proposalSupplierServices->setDestinationId($suppserv->getDestinationId());
$proposalSupplierServices->setSupplierId($suppserv->getSupplierId());
$proposalSupplierServices->setIdeaId($suppserv->getIdeaId());
$proposalSupplierServices->setActivityId($suppserv->getActivityId());
$proposalSupplierServices->setServiceId($suppserv->getServiceId());
$proposalSupplierServices->setServiceCatId($suppserv->getServiceCatId());
$proposalSupplierServices->setServiceCatName($suppserv->getServiceCatName());
$proposalSupplierServices->setName($suppserv->getName());
$proposalSupplierServices->setPrice($suppserv->getPrice());
$proposalSupplierServices->setCurrency($suppserv->getCurrency());
$proposalSupplierServices->setUnits($suppserv->getUnits());
$proposalSupplierServices->setCommission($suppserv->getCommission());
$proposalSupplierServices->setOver($suppserv->getOver());
$proposalSupplierServices->setIva($suppserv->getIva());
$proposalSupplierServices->setPax($suppserv->getPax());
$proposalSupplierServices->setHour($suppserv->getHour());
$proposalSupplierServices->setDateInAt($suppserv->getDateInAt()); // **************************************************
$proposalSupplierServices->setDateOutAt($suppserv->getDateOutAt()); // **************************************************
$proposalSupplierServices->setDirectPayment($suppserv->getDirectPayment());
$proposalSupplierServices->setStatus('Pending');
$proposalSupplierServices->setCreatedAt(new \DateTime("now"));
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$proposalSupplierServices->setCreatedId($user_logueado->getId());
$proposalSupplierServices->setUpdatedAt(new \DateTime("now"));
$proposalSupplierServices->setUpdatedId($user_logueado->getId());
$proposalSupplierServices->setStatusinternal($suppserv->getStatusinternal());
$proposalSupplierServices->setPreCommission($suppserv->getPreCommission());
$proposalSupplierServices->setPreIva($suppserv->getPreIva());
$proposalSupplierServices->setDateBlockLimit($suppserv->getDateBlockLimit());
$proposalSupplierServices->setOpCommission($suppserv->getOpCommission());
$proposalSupplierServices->setOpOver($suppserv->getOpOver());
$proposalSupplierServices->setOpIva($suppserv->getOpIva());
$proposalSupplierServices->setBreakdown($suppserv->getBreakdown());
$proposalSupplierServices->setIsFather($suppserv->getIsFather());
$proposalSupplierServices->setRank($suppserv->getRank());
$proposalSupplierServices->setOriginalopIva($suppserv->getOriginalopIva());
$proposalSupplierServices->setOriginalIva($suppserv->getOriginalIva());
$proposalSupplierServices->setOriginalPrice($suppserv->getOriginalPrice());
$proposalSupplierServices->setStatusRec($suppserv->getStatusRec());
// $proposalSupplierServices->setAssistantId($suppserv->getAssistantId()); // **************************************************/
$proposalSupplierServices->setProposalId($newId);
$proposalSupplierServices->setControlId($arrayTranslateProposalSupplierControl[$suppserv->getControlId()]);
$em->persist($proposalSupplierServices);
$em->flush();
}
// Fin: Se generan los servicios (Proposals_supplier_services)
return $this->redirectToRoute('proposal_edit', array('id'=>$newId));
}
/**
* @Route("/proposal/duplicatedestination/{id}/{destiIdOriCtrl}", name="proposal_duplicate_destination")
*/
public function duplicateDestinationAction($id, $destiIdOriCtrl, Request $request)
{//$id = id del proposal; $destiIdOriCtrl destination Id Control del origen; $request contiene el Id destino
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
// Verificamos STATUS, si esta Cancelado, Bloqueado o Facturado no se toma ninguna acción
if (($proposal->getStatus()=='Cancel') or ($proposal->getStatus()=='Blocked') or ($proposal->getStatus()=='Invoiced')){
return $this->redirectToRoute('proposal_edit', array('id'=>$id));
}
// Buscamos el Id de Origen
$proposalControlOri = $em->getRepository(ProposalControl::class)->findOneById($destiIdOriCtrl);
$destiIdOri = $proposalControlOri->getDestinationId();
// Buscamos el Id de Destino
$destiIdDst = $request->request->get('destinationList');
// Verificamos si hay un IdDestino, si no es asi no se toma ninguna acción
if (empty($destiIdDst)){
return $this->redirectToRoute('proposal_edit', array('id'=>$id));
}
// Inicio: Se genera el control del proposal para el destino en caso de no existir (Tabla Proposals_control)
$proposalControlDst = $em->getRepository(ProposalControl::class)->findOneBy(
array(
'proposalId'=>$id,
'destinationId'=>$destiIdDst));
// Si no existe el destino en el proposal se debe crear
if (empty($proposalControlDst)){
$proposalControlDst = new ProposalControl();
$proposalControlDst->setProposalId($id);
$proposalControlDst->setDestinationId($destiIdDst);
$proposalControlDst->setDisabled(0);
$proposalControlDst->setDisabledPresentation(0);
$em->persist($proposalControlDst);
$em->flush();
}
// Fin: Se genera el control del proposal para el destino en caso de no existir (Tabla Proposals_control)
// Inicio: Se generan los controles para los proveedores (Tabla Proposals_supplier_control)
$proposalSupplierControlOrigen = $em->getRepository(ProposalSupplierControl::class)->findBy(
array(
'proposalId'=>$id,
'destinoId'=>$destiIdOri));
$arrayTranslateProposalSupplierControl = array();
foreach ($proposalSupplierControlOrigen as $supcontrol){
//Verificamos que no exista previamente el ProposalSupplierControl
$proposalSupplierControl = $em->getRepository(ProposalSupplierControl::class)->findOneBy(
array(
'proposalId'=>$id,
'supplierId'=>$supcontrol->getSupplierId(),
'destinoId'=>$destiIdDst));
if (empty($proposalSupplierControl)){
$proposalSupplierControl = new ProposalSupplierControl();
$proposalSupplierControl->setDestinoId($destiIdDst);
$proposalSupplierControl->setSupplierId($supcontrol->getSupplierId());
$proposalSupplierControl->setIdeaId($supcontrol->getIdeaId());
$proposalSupplierControl->setStatus($supcontrol->getStatus());
$proposalSupplierControl->setDisabled($supcontrol->getDisabled());
$proposalSupplierControl->setRank($supcontrol->getRank());
$proposalSupplierControl->setDateBlockLimit($supcontrol->getDateBlockLimit());
$proposalSupplierControl->setActivityId($supcontrol->getActivityId());
$proposalSupplierControl->setProposalId($id);
$proposalSupplierControl->setControlDestinationId($proposalControlDst->getId());
$em->persist($proposalSupplierControl);
$em->flush();
}
$arrayTranslateProposalSupplierControl[$supcontrol->getId()] = $proposalSupplierControl->getId(); // Arreglo que traduce un indice del antiguo proposal supplier control al nuevo
}
// Fin: Se generan los controles para los proveedores (Tabla Proposals_supplier_control)
// Inicio: Se generan los servicios (Proposals_supplier_services)
$proposalSupplierServicesOrigen = $em->getRepository(ProposalSupplierServices::class)->findByProposalId($id);
foreach ($proposalSupplierServicesOrigen as $suppserv) {
$proposalSupplierServices = new ProposalSupplierServices();
$proposalSupplierServices->setServiceIdFather($suppserv->getServiceIdFather());
// $proposalSupplierServices->setDestinationId($suppserv->getDestinationId());
$proposalSupplierServices->setDestinationId($destiIdDst);
$proposalSupplierServices->setSupplierId($suppserv->getSupplierId());
$proposalSupplierServices->setIdeaId($suppserv->getIdeaId());
$proposalSupplierServices->setActivityId($suppserv->getActivityId());
$proposalSupplierServices->setServiceId($suppserv->getServiceId());
$proposalSupplierServices->setServiceCatId($suppserv->getServiceCatId());
$proposalSupplierServices->setServiceCatName($suppserv->getServiceCatName());
$proposalSupplierServices->setName($suppserv->getName());
$proposalSupplierServices->setPrice($suppserv->getPrice());
$proposalSupplierServices->setCurrency($suppserv->getCurrency());
$proposalSupplierServices->setUnits($suppserv->getUnits());
$proposalSupplierServices->setCommission($suppserv->getCommission());
$proposalSupplierServices->setOver($suppserv->getOver());
$proposalSupplierServices->setIva($suppserv->getIva());
$proposalSupplierServices->setPax($suppserv->getPax());
$proposalSupplierServices->setHour($suppserv->getHour());
$proposalSupplierServices->setDateInAt($suppserv->getDateInAt());
$proposalSupplierServices->setDateOutAt($suppserv->getDateOutAt());
$proposalSupplierServices->setDirectPayment($suppserv->getDirectPayment());
$proposalSupplierServices->setStatus('Pending');
$proposalSupplierServices->setCreatedAt(new \DateTime("now"));
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$proposalSupplierServices->setCreatedId($user_logueado->getId());
$proposalSupplierServices->setUpdatedAt(new \DateTime("now"));
$proposalSupplierServices->setUpdatedId($user_logueado->getId());
$proposalSupplierServices->setStatusinternal($suppserv->getStatusinternal());
$proposalSupplierServices->setPreCommission($suppserv->getPreCommission());
$proposalSupplierServices->setPreIva($suppserv->getPreIva());
$proposalSupplierServices->setDateBlockLimit($suppserv->getDateBlockLimit());
$proposalSupplierServices->setOpCommission($suppserv->getOpCommission());
$proposalSupplierServices->setOpOver($suppserv->getOpOver());
$proposalSupplierServices->setOpIva($suppserv->getOpIva());
$proposalSupplierServices->setBreakdown($suppserv->getBreakdown());
$proposalSupplierServices->setIsFather($suppserv->getIsFather());
$proposalSupplierServices->setRank($suppserv->getRank());
$proposalSupplierServices->setOriginalopIva($suppserv->getOriginalopIva());
$proposalSupplierServices->setOriginalIva($suppserv->getOriginalIva());
$proposalSupplierServices->setOriginalPrice($suppserv->getOriginalPrice());
$proposalSupplierServices->setStatusRec($suppserv->getStatusRec());
// $proposalSupplierServices->setAssistantId($suppserv->getAssistantId()); // **************************************************/
$proposalSupplierServices->setProposalId($id);
// Si existe el indice hay que crear y guardar el elemento,en caso contrario es un elemento que ya existia previamente en el destino
if (array_key_exists($suppserv->getControlId(),$arrayTranslateProposalSupplierControl)){
$proposalSupplierServices->setControlId($arrayTranslateProposalSupplierControl[$suppserv->getControlId()]);
$em->persist($proposalSupplierServices);
$em->flush();
}
}
// Fin: Se generan los servicios (Proposals_supplier_services)
return $this->redirectToRoute('proposal_destination_view', array('id'=>$id));
}
/**
* @Route("/proposal/mobile/viewbriefing/{id}", name="proposal_mobile_view_briefing")
* Vista para el movil del briefing del proposal para asignación del agente
*/
public function viewBriefingMobileAction($id)
{
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$agents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($id);
if (empty($proposal) or empty($proposal->getBriefing())){ return $this->redirectToRoute('proposal_edit', array('id'=>$id)); }
/* INICIO Consulta de agente activos MICE */
$parameters = array( 'status' => true );
// Los equipos 1 y 4 son 'Eventos' y 'Comercial MICE'
$dql = 'SELECT us
FROM App\Entity\User us
WHERE us.status = :status AND us.team IN (1,2,4,5,16)
ORDER BY us.name ASC';
$query = $em->createQuery($dql)->setParameters($parameters);
$userAgents = $query->getResult();
/* FIN Consulta de agente activos MICE */
return $this->render('MDS/EventsBundle/proposal/mobile-proposal-briefing.html.twig',
array(
'id' => $id,
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'proposal' => $proposal,
'briefing' => $proposal->getBriefing(),
'userAgents' => $userAgents,
'agents'=> $agents
)
);
}
/**
* @Route("/proposal/mobile/updatebriefing/{id}", name="proposal_mobile_update_briefing")
* Actualizar desde el movil el briefing del proposal ID y sus agentes
*/
public function updateBriefingMobileAction($id, Request $request){
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$agents = $em->getRepository(ProposalAgents::class)->findOneByIdProp($id);
$propReq = $request->request->get('proposal');
//Verificamos si se cambia el agente
$logNotify = false;
if (!empty($agents)){
if ($agents->getAgOne() != $propReq['Agent1']){ $logNotify = true; }
if ($agents->getAgTwo() != $propReq['Agent2']){ $logNotify = true; }
if ($agents->getAgThree() != $propReq['Agent3']){ $logNotify = true; }
if ($agents->getAgFour() != $propReq['Agent4']){ $logNotify = true; }
} else {
$logNotify = true;
}
empty($propReq['Agent1']) ? $agents->setAgOne(0) : $agents->setAgOne($propReq['Agent1']);
empty($propReq['Agent2']) ? $agents->setAgTwo(0) : $agents->setAgTwo($propReq['Agent2']);
empty($propReq['Agent3']) ? $agents->setAgThree(0) : $agents->setAgThree($propReq['Agent3']);
empty($propReq['Agent4']) ? $agents->setAgFour(0) : $agents->setAgFour($propReq['Agent4']);
$em->persist($agents);
$em->flush();
$proposal->setBriefing($propReq['briefing']);
$em->persist($proposal);
$em->flush();
if ($logNotify){
// NOTIFICAR AL AGENTE
$agentToNotify = array();
if (!empty($agents->getAgOne()) and ($agents->getAgOne() != 0)){ $agentToNotify[] = $em->getRepository(User::class)->findOneById($agents->getAgOne()); }
if (!empty($agents->getAgTwo()) and ($agents->getAgTwo() != 0)){ $agentToNotify[] = $em->getRepository(User::class)->findOneById($agents->getAgTwo()); }
if (!empty($agents->getAgThree()) and ($agents->getAgThree() != 0)){ $agentToNotify[] = $em->getRepository(User::class)->findOneById($agents->getAgThree()); }
if (!empty($agents->getAgFour()) and ($agents->getAgFour() != 0)){ $agentToNotify[] = $em->getRepository(User::class)->findOneById($agents->getAgFour()); }
//-- Envio correo a los agentes que hayan sido modificados
$time = new \DateTime("now");
foreach ($agentToNotify as $agent) {
$mailAgent[] = $agent->getEmail();
$agentMail = $agent->getEmail();
$firmGmail = $agent->getFirmGmail();
$mailAgentSent = array(
$agent->getEmail() => $agent->getName() . ' ' . $agent->getLastName()
);
$data = array(
'body' => 'P#' . $proposal->getId() . ', ' . $proposal->getTitle() . '<br><a href="http://' . $request->server->get('HTTP_HOST') . '/events/proposal/edit/' . $proposal->getId() . '">Ir al Proposal</a><br><br>Alerta de Proposal Asignado: ' . $time->format('d/m/Y H:i:s') . '<br><br>',
'firm' => $firmGmail,
);
// EJECUTAR ENVIO DE ALERTA PARA EL AGENTE
$transporter = \Swift_SmtpTransport::newInstance()
->setHost('smtp.gmail.com')
->setEncryption('ssl')//ssl / tls
->setPort(465)// 465 / 587
->setUsername('desarrollo@develup.solutions')
->setPassword('MeDITeRRANeAN_Develup30102023#');
$mailer = \Swift_Mailer::newInstance($transporter);
$message = \Swift_Message::newInstance()
->setSubject('P#' . $proposal->getId() . ', Alerta de Proposal Asignado')
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setReplyTo($agentMail)
->setTo($mailAgent)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
}
}
return $this->redirectToRoute('proposal_edit', array('id'=>$id));
}
private function NotifyAvExpress($proposal, $avFile, $originPrpDateStart, $originPrpDateEnd, $originPrpStatus)
{
$em = $this->getDoctrine()->getManager();
$agent = $em->getRepository(User::class)->findOneById($proposal->getUpdatedId());
$mailSubject = '';
$mailBody = '';
$boolStatus = false;
$boolDates = false;
if (($proposal->getStatus() == 'Confirmed') and !($proposal->getStatus() == $originPrpStatus)){
$boolStatus = true;
$mailSubject = $mailSubject.'Proposal #'.$proposal->getId().' CONFIRMADO, expediente AvExpress #'.$avFile->getId().' - '.$avFile->getTitle();
$mailBody = $mailBody.'<p>'. 'Proposal #'.$proposal->getId().' <b>CONFIRMADO</b> por '.$agent->getName().' '.$agent->getLastName().'</p>';
$mailBody = $mailBody.'<p>'. 'AvExpress #'.$avFile->getId().' - '.$avFile->getTitle().'</p>';
// $mailBody = $mailBody.'<a href="http://127.0.0.1:8000/avexpress/fileedit/'.$avFile->getId().'">Ir al expediente</a>';
$mailBody = $mailBody.'<a href="https://inout.mante.solutions/avexpress/fileedit/'.$avFile->getId().'">Ir al expediente. Es necesario iniciar la sesión previamente.</a>';
$mailBody = $mailBody.'<p><br><br>'. 'Fecha de actualización: '.$proposal->getUpdatedAt()->format('d/m/Y').'<p>';
}
if (($proposal->getStatus() == 'Cancel') and !($proposal->getStatus() == $originPrpStatus)){
$boolStatus = true;
$mailSubject = $mailSubject.'Proposal #'.$proposal->getId().' CANCELADO, expediente AvExpress #'.$avFile->getId().' - '.$avFile->getTitle();
$mailBody = $mailBody.'<p>'. 'Proposal #'.$proposal->getId().' <b>CANCELADO</b> por '.$agent->getName().' '.$agent->getLastName().'</p>';
$mailBody = $mailBody.'<p>'. 'AvExpress #'.$avFile->getId().' - '.$avFile->getTitle().'</p>';
$mailBody = $mailBody.'<a href="https://inout.mante.solutions/avexpress/fileedit/'.$avFile->getId().'">Ir al expediente. Es necesario iniciar la sesión previamente.</a>';
$mailBody = $mailBody.'<p><br><br>'. 'Fecha de actualización: '.$proposal->getUpdatedAt()->format('d/m/Y').'<p>';
}
if ((!($proposal->getDateEventStarAt()->format('dmY') == $originPrpDateStart->format('dmY'))) or ((!($proposal->getDateEventEndAt()->format('dmY') == $originPrpDateEnd->format('dmY'))))){
$boolDates = true;
$mailSubject = $mailSubject.'Proposal #'.$proposal->getId().' FECHAS MODIFICADAS, expediente AvExpress #'.$avFile->getId().' - '.$avFile->getTitle();
$mailBody = $mailBody.'<p>'. 'Proposal #'.$proposal->getId().' <b>FECHAS MODIFICADAS</b> por '.$agent->getName().' '.$agent->getLastName().'</p>';
$mailBody = $mailBody.'<p>'. 'AvExpress #'.$avFile->getId().' - '.$avFile->getTitle().'</p>';
$mailBody = $mailBody.'<p>'. 'Fecha de inicio del evento: '.$proposal->getDateEventStarAt()->format('d/m/Y').'</p>';
$mailBody = $mailBody.'<p>'. 'Fecha fin del evento: '.$proposal->getDateEventEndAt()->format('d/m/Y').'</p>';
$mailBody = $mailBody.'<a href="https://inout.mante.solutions/avexpress/fileedit/'.$avFile->getId().'">Ir al expediente. Es necesario iniciar la sesión previamente.</a>';
$mailBody = $mailBody.'<p><br><br>'. 'Fecha de actualización: '.$proposal->getUpdatedAt()->format('d/m/Y').'<p>';
}
if ($boolStatus and $boolDates){
$mailSubject = 'Proposal #'.$proposal->getId().' ESTADO Y FECHAS MODIFICADAS, expediente AvExpress #'.$avFile->getId().' - '.$avFile->getTitle();
}
$mailAddress = 'gustavo.ayala@develup.solutions';
$replyTo = array();
$replyTo['salvador@avexpress.tv'] = 'salvador@avexpress.tv';
$replyTo['ayudantedeproduccion@avexpress.tv'] = 'ayudantedeproduccion@avexpress.tv';
$replyTo['ayudantedeproduccion2@avexpress.tv'] = 'ayudantedeproduccion2@avexpress.tv';
$agentMail = $mailAddress;
//Se prepara el correo con los agentes a notificar
$firmGmail = $agent->getFirmGmail();
$data = array(
'body' => $mailBody,
'firm' => $firmGmail,
);
// 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($mailSubject)
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setReplyTo($agentMail)
->setTo($replyTo)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
return true;
}
private function AsignacionPorcentajeAgente(){
// Solo Rafa, Elena, Yulia o algun ADMIN pueden asignar porcentajes
$em = $this->getDoctrine()->getManager();
$bool = false;
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$agent = $em->getRepository(User::class)->findOneById($user_id);
if (($agent->getRole() == 'ROLE_ADMIN') or ($agent->getId() == 22) or ($agent->getId() == 27)){ $bool = true; }
return $bool;
}
private function MontoPorcentajeAgente($numberAgent, $arrayRequest){
// Asignacion de valores por defecto a los porcentajes de los agentes
// Las aignaciones son para un agente 100%, para dos agentes 60% y 40%, para tres agentes, 60%, 20% y 20%, para cuatro agentes, 25%, 25%, 25% y 25%
// $numberAgent numero del agente sobre el cual se buscará el porcentaje
// $arrayRequest contiene el arreglo con los nombre de los agentes
$numeroAgentesSolicitados = 0;
$porcentajeParaAsignar = 0;
if (!empty($arrayRequest[0])) { $numeroAgentesSolicitados ++; }
if (!empty($arrayRequest[1])) { $numeroAgentesSolicitados ++; }
if (!empty($arrayRequest[2])) { $numeroAgentesSolicitados ++; }
if (!empty($arrayRequest[3])) { $numeroAgentesSolicitados ++; }
switch ($numeroAgentesSolicitados) {
case 1:
switch ($numberAgent) {
case 1: $porcentajeParaAsignar = 100; break;
case 2: $porcentajeParaAsignar = 0; break;
case 3: $porcentajeParaAsignar = 0; break;
case 4: $porcentajeParaAsignar = 0; break;
default: break;
}
break;
case 2:
switch ($numberAgent) {
case 1: $porcentajeParaAsignar = 60; break;
case 2: $porcentajeParaAsignar = 40; break;
case 3: $porcentajeParaAsignar = 0; break;
case 4: $porcentajeParaAsignar = 0; break;
default: break;
}
break;
case 3:
switch ($numberAgent) {
case 1: $porcentajeParaAsignar = 60; break;
case 2: $porcentajeParaAsignar = 20; break;
case 3: $porcentajeParaAsignar = 20; break;
case 4: $porcentajeParaAsignar = 0; break;
default: break;
}
break;
case 4:
switch ($numberAgent) {
case 1: $porcentajeParaAsignar = 25; break;
case 2: $porcentajeParaAsignar = 25; break;
case 3: $porcentajeParaAsignar = 25; break;
case 4: $porcentajeParaAsignar = 25; break;
default: break;
}
break;
default: break;
}
return $porcentajeParaAsignar;
}
private function sendTelegramMail($id, $idProp, $text )
{
$em = $this->getDoctrine()->getManager();
$telegUser = $em->getRepository(MdvTelegramUser::class)->findOneByUserId($id);
$xbody = '<a href="//' . $_SERVER['HTTP_HOST'] . '/events/proposal/edit/' . $idProp . '">' . $idProp . '</a> ' . $text;
if (!empty($telegUser)) {
$text = 'NUEVO PROPOSAL - ' . 'https://' . $_SERVER['HTTP_HOST'] . '/events/proposal/mobile/viewbriefing/' . $idProp;
$parameters = array(
'chat_id' => $telegUser->getChatId(),
'text' => $text,
);
$bot_token = $telegUser->getBotToken();
$url = "https://api.telegram.org/bot$bot_token/sendMessage";
if (!$curl = curl_init()) {
exit();
}
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curl);
curl_close($curl);
}
$agent = $em->getRepository(User::class)->findOneById($id);
$agentMail = $agent->getEmail();
$mailAgent = $agentMail;
//Se prepara el correo con los agentes a notificar
$firmGmail = $agent->getFirmGmail();
$data = array(
'body' => $xbody,
'firm' => $firmGmail,
);
// 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('Proposal #' . $idProp. ', Notificación de nuevo proposal')
->setSender($agentMail)
->setFrom(array("desarrollo@develup.solutions" => "System Mante 3.0"))
->setReplyTo($agentMail)
->setTo($mailAgent)
->setBody(
$this->renderView(
'mail/structure-mail.html.twig',
array('data' => $data)
),
'text/html'
);
$mailer->send($message);
return true;
}
}