<?php
/**
* Created by Mediterranean Develup Solutions
* User: jorge.defreitas@develup.solutions
* Date: 11/08/2017
* Time: 11:19
*/
namespace App\MDS\EventsBundle\Controller;
use App\Entity\Cities;
use App\Entity\Country;
use App\Entity\Destination;
use App\Entity\DestinationGallery;
use App\Entity\Provinces;
use App\Entity\Regions;
use App\Entity\Supplier;
use App\MDS\EventsBundle\Entity\Proposal;
use App\MDS\EventsBundle\Entity\ProposalBriefingList;
use App\MDS\EventsBundle\Entity\ProposalControl;
use App\MDS\EventsBundle\Entity\ProposalSupplierControl;
use App\MDS\EventsBundle\Entity\ProposalSupplierServices;
use App\MDS\EventsBundle\Form\ProposalControlType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Translation\TranslatorInterface;
class ProposalControlController extends AbstractController
{
private $translator;
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}
/*
* ATENCION LAS RAIZ DE @Route POR DEFECTO DEL BUNDLE: EventsBundle ES /events/, NO PONERLO EN LA @Route("")
*
* */
/**
* @Route("/proposal/destination/add/{id}", name="proposal_destination_view")
*/
public function viewAction($id, Request $request)
{
/* Formulario */
$control= new ProposalControl();
$control->setProposalId($id);
$form = $this->createDestinationProposalCreateForm($control);
/* Si hay un destino cargado */
$em = $this->getDoctrine()->getManager();
$proposal = $em->getRepository(Proposal::class)->findOneById($id);
$briefing = $em->getRepository(ProposalBriefingList::class)->findByProposalId($id);
$control_destination = $em->getRepository(ProposalControl::class)->findByProposalId($id);
$mostrar_destino = array();
if (!empty($control_destination)){
foreach($control_destination as $destinationCrtl){
$destination = $em->getRepository(Destination::class)->findOneById($destinationCrtl->getDestinationId());
$destinationGallery = $em->getRepository(DestinationGallery::class)->findOneByDestinationId($destinationCrtl->getDestinationId());
$country = $em->getRepository(Country::class)->findOneById($destination->getCountry());
$destination->setCountry($country->getCountry());
$regions = $em->getRepository(Regions::class)->findOneById($destination->getRegion());
$destination->setRegion($regions->getRegion());
$regions = $em->getRepository(Provinces::class)->findOneById($destination->getProvince());
$destination->setProvince($regions->getName());
$cities = $em->getRepository(Cities::class)->findOneById($destination->getPopulation());
$destination->setPopulation($cities->getCity());
$mostrar_destino[] = array(
'idcontrol' => $destinationCrtl->getId(),
'title' => $destination->getTitle(),
'image' => empty($destinationGallery)? null : $destinationGallery->getImageSmall(),
'country' => $destination->getCountry(),
'region' => $destination->getRegion(),
'province' => $destination->getProvince(),
'population' =>$destination->getPopulation(),
'disabled' =>$destinationCrtl->getDisabled(),
'disabledPresentation' =>$destinationCrtl->getDisabledPresentation(),
);
}
}
$parameters = array(
);
$dql = 'SELECT p
FROM App:Destination p
ORDER BY p.title ASC ';
$query = $em->createQuery($dql)->setParameters($parameters);
$destinationList = $query->getResult();
return $this->render('MDS/EventsBundle/destination/add-destination-proposal.html.twig',
array(
'proposal' => $proposal,
'briefing' => $briefing,
'destinations' => $mostrar_destino,
'destinationList' => $destinationList,
'id' => $id,
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'form' => $form->createView()
)
);
}
private function createDestinationProposalCreateForm(ProposalControl $entity)
{
$form = $this->createForm(ProposalControlType::class, $entity, array(
'action' => $this->generateUrl('proposal_destination_create'),
'method' => 'POST'
));
return $form;
}
/**
* @Route("/proposal/destination/create", name="proposal_destination_create")
*/
public function createProposalDestinationAction(Request $request)
{
$control = new ProposalControl();
$form = $this->createDestinationProposalCreateForm($control);
$form->handleRequest($request);
$destination_proposalId = $form->get('proposalId')->getData();
$destination_proposal = $form->get('destinationId')->getData();
if(!is_null($destination_proposal)){
$control->setDestinationId($destination_proposal->getId());
}
$em = $this->getDoctrine()->getManager();
$check_exists = $em->getRepository(ProposalControl::class)->findBy(
array(
'proposalId' => $destination_proposalId,
'destinationId' => $destination_proposal->getId(),
)
);
if(empty($check_exists)){
if($form->isValid())
{
$em->persist($control);
$em->flush();
$event = 'The Destination Proposal has been created.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeproposaldestination', $successMessage);
$proposalsuppliercontrol = new ProposalSupplierControl();
$proposalsuppliercontrol->setControlDestinationId($control->getId());
$proposalsuppliercontrol->setProposalId($destination_proposalId);
$proposalsuppliercontrol->setDestinoId($destination_proposal->getId());
$proposalsuppliercontrol->setSupplierId('0');
$proposalsuppliercontrol->setRank('0');
$proposalsuppliercontrol->setStatus('Pending');
$em->persist($proposalsuppliercontrol);
$em->flush();
// 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);
//
// $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 */
return $this->redirectToRoute('proposal_destination_view', array(
'id' => $control->getProposalId()
));
}else{
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajeproposaldestinationerror', $errorMessage);
}
}else{
$errorMessage = $this->translator->trans('Error, The destination already exists in the proposal');
$this->addFlash('mensajeproposaldestinationerror', $errorMessage);
}
return $this->redirectToRoute('proposal_destination_view',
array(
'id' => $destination_proposalId
)
);
}
/**
* @Route("proposal/destination/deleted/{id}", name="proposal_destination_deleted")
*
*/
// public function deleteAction($id, Request $request, LoggerInterface $logger)
public function deleteAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$delete = $em->getRepository(ProposalControl::class)->findOneById($id);
$delete_suppliers = $em->getRepository(ProposalSupplierControl::class)->findByControlDestinationId($id);
foreach ($delete_suppliers as $delete_supplier) {
$em->remove($delete_supplier);
$delete_services = $em->getRepository(ProposalSupplierServices::class)->findByControlId($delete_supplier->getId());
foreach ($delete_services as $delete_service) {
$em->remove($delete_service);
}
}
$em->remove($delete);
$em->flush();
$event = 'The Destination the has been Deleted.';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeproposaldestinationservices', $successMessage);
// /* Gestión de eventos en Log */
// /* Obtengo usuario logueado */
// $user_logueado = $this->get('security.token_storage')->getToken()->getUser();
// $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;
//
// try{
// $em->remove($delete);
// $em->flush();
//
// $event = 'The supplier services Accommodation has been Deleted.';
// $successMessage = $this->translator->trans($event);
// $this->addFlash('mensajeservices', $successMessage);
//
// $logger->info($event_complete.' | '.$event);
//
// } catch (\Exception $e){
//
// $event = 'An error occurred: '.$e->getMessage().' | transport';
//
// /* Para el log */
// $logger->error($event_complete.' | '.$event);
// /* Para el usuario */
// $errorMessage = $this->translator->trans($event);
// $this->addFlash('mensajeserviceserror', $errorMessage);
// }
// /* Fin Gestión de eventos en Log */
return $this->redirectToRoute('proposal_destination_view',
array(
'id' => $delete->getProposalId()
)
);
}
/**
* @Route("proposal/destination/disabled/{id}", name="proposal_destination_disabled")
*
*/
public function disabledDestinationAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$disabled = $em->getRepository(ProposalControl::class)->findOneById($id);
$proposal= $em->getRepository(Proposal::class)->findOneById($disabled->getProposalId());
$actual = $disabled->getDisabled();
$var_mensaje="";
if($actual == "0"){
$disabled->setDisabled('1');
$var_mensaje = "Disabled";
}
if($actual == "1"){
$disabled->setDisabled('0');
$var_mensaje = "Activated";
}
$em->persist($disabled);
$em->flush();
$event = 'The Destination has been. '.$var_mensaje;
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeproposaldestination', $successMessage);
return $this->redirectToRoute('proposal_destination_view',
array(
'id' => $proposal->getId(),
)
);
}
/**
* @Route("proposal/destination/disabledpresentation/{id}", name="proposal_destination_disabled_presentation")
*
*/
public function disabledDestinationPresentationAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$disabled = $em->getRepository(ProposalControl::class)->findOneById($id);
$proposal= $em->getRepository(Proposal::class)->findOneById($disabled->getProposalId());
$actual = $disabled->getDisabledPresentation();
$var_mensaje="";
if($actual == "0"){
$disabled->setDisabledPresentation('1');
$var_mensaje = "Disabled";
}
if($actual == "1"){
$disabled->setDisabledPresentation('0');
$var_mensaje = "Activated";
}
$em->persist($disabled);
$em->flush();
$event = 'The Destination in presentation has been. '.$var_mensaje;
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeproposaldestination', $successMessage);
return $this->redirectToRoute('proposal_destination_view',
array(
'id' => $proposal->getId(),
)
);
}
/**
* @Route("proposal/destination/editdstsuppliers/{id}", name="proposal_destination_edit_destination_suppliers")
*
*/
public function editDestinationSuppliersAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$proposalControl = $em->getRepository(ProposalControl::class)->findOneById($id);
$proposal = $em->getRepository(Proposal::class)->findOneById($proposalControl->getProposalId());
$arrayProposalSupplierControl = $em->getRepository(ProposalSupplierControl::class)->findByControlDestinationId($id);
//INICIO: Buscamos los proveedores
$arraySuppliersId = array();
$arrayWhiteServicesId = array();
foreach ($arrayProposalSupplierControl as $item){
if ($item->getSupplierId()==0){
//Aqui esta el ID de los servicios blancos
$arrayWhiteServicesId[] = $item->getId();
}
if (!empty($item->getSupplierId())){
//Ademas de ser distinto de null el ID del supplier debe existir en la tabla de Suppliers. Para actividades hay ID de suppliers que no estan en la tabla
$elem = $em->getRepository(Supplier::class)->findOneById($item->getSupplierId());
if (!empty($elem)){
$arraySuppliersId[] = array(
'idSupplier' => $item->getSupplierId(),
'company' => $elem->getCompany(),
'supplier' => $elem,
) ;
}
}
}
//A estos proveedores debemos agregar los proveedores que sean de servicios en blanco, por si se desean pasar a servicios de un proveedor en especifico
$arrayWhiteServices = array();
foreach ($arrayWhiteServicesId as $item){
$elem = $em->getRepository(ProposalSupplierServices::class)->findOneByControlId($item);
if (!empty($elem)){
$arrayWhiteServices[] = $elem->getSupplierId();
}
}
$arraySuppliersIdWhiteServices = array();
if (!empty($arrayWhiteServices)){
foreach ($arrayWhiteServices as $item){
if (!empty($item)){
//Ademas de ser distinto de null el ID del supplier debe existir en la tabla de Suppliers. Para actividades hay ID de suppliers que no estan en la tabla
$elem = $em->getRepository(Supplier::class)->findOneById($item);
if (!empty($elem)){
$arraySuppliersIdWhiteServices[] = array(
'idSupplier' => $item,
'company' => $elem->getCompany(),
'supplier' => $elem,
);
}
}
}
}
//FIN: Buscamos los proveedores
$arrayProposalSupplierServices = array();
foreach ($arrayProposalSupplierControl as $item){
$arrayTemp = $em->getRepository(ProposalSupplierServices::class)->findByControlId($item->getId());
$arrayProposalSupplierServices[] = $arrayTemp;
}
$briefing = $em->getRepository(ProposalBriefingList::class)->findByProposalId($proposal->getId());
$control_destination = $id;
// $mostrar_destino = array();
// if (!empty($control_destination)){
//
// foreach($control_destination as $destinationCrtl){
$destination = $em->getRepository(Destination::class)->findOneById($proposalControl->getDestinationId());
$destinationGallery = $em->getRepository(DestinationGallery::class)->findOneByDestinationId($proposalControl->getDestinationId());
$country = $em->getRepository(Country::class)->findOneById($destination->getCountry());
$destination->setCountry($country->getCountry());
$regions = $em->getRepository(Regions::class)->findOneById($destination->getRegion());
$destination->setRegion($regions->getRegion());
$regions = $em->getRepository(Provinces::class)->findOneById($destination->getProvince());
$destination->setProvince($regions->getName());
$cities = $em->getRepository(Cities::class)->findOneById($destination->getPopulation());
$destination->setPopulation($cities->getCity());
$mostrar_destino = array(
'idcontrol' => $proposalControl->getId(),
'title' => $destination->getTitle(),
'image' => empty($destinationGallery)? null : $destinationGallery->getImageSmall(),
'country' => $destination->getCountry(),
'region' => $destination->getRegion(),
'province' => $destination->getProvince(),
'population' =>$destination->getPopulation(),
// 'disabled' =>$proposalControl->getDisabled(),
// 'disabledPresentation' =>$proposalControl->getDisabledPresentation(),
);
// }
// }
$listAllSuppliers = $em->getRepository("App:Supplier")->findAll();
//Los IDs estan cruzados
$proposalControlId = $id;
$id = $proposal->getId();
return $this->render('MDS/EventsBundle/destination/edit-destination-proposal-suppliers.html.twig',
array(
'proposal' => $proposal,
'briefing' => $briefing,
'listAllSuppliers' => $listAllSuppliers,
'arraySuppliersId' => $arraySuppliersId,
'arraySuppliersIdWhiteServices' => $arraySuppliersIdWhiteServices,
'destination' => $mostrar_destino,
// 'destinationList' => $destinationList,
'id' => $id,
'token' => $proposal->getAccessKey(),
'mcp' => $proposal->getMcp(),
'proposalControlId' => $proposalControlId,
)
);
}
/**
* @Route("proposal/destination/updatesuppliersdestination/{id}", name="update_suppliers_destination")
*
*/
public function updateSuppliersDestinationAction($id, Request $request)
{
// Buscamos el Id de Proveedores de servicios blancos
$arraySuppliersIdWhiteServices = $request->request->get('supplier_white');
// Buscamos el Id de Proveedores de servicios blancos
$arraySuppliersId = $request->request->get('supplier');
$em = $this->getDoctrine()->getManager();
$proposalControl = $em->getRepository(ProposalControl::class)->findOneById($id);
$proposalSupplierControl = $em->getRepository(ProposalSupplierControl::class)->findByControlDestinationId($id);
//Inicio: Caso de Suppliers desde white services
//Crearemos una entrada para los servicios en blanco y luego mofi
if (!empty($arraySuppliersIdWhiteServices)){
$arrayKeys = array_keys($arraySuppliersIdWhiteServices);
} else {
$arrayKeys = array();
}
foreach ($arrayKeys as $key) {
$oldSupplierId = $key;
$newSupplierId = $arraySuppliersIdWhiteServices[$key];
// Si $newSupplierId es empty no se ha seleccionado un proveedor del selector, en este caso no se modifica el supplier
if (!empty($newSupplierId)) {
if (!empty($proposalSupplierControl)) {
//Verificamos que no haya previamente un control de donde deseamos poner el servicio
$existeProposalSupplierControl = $em->getRepository(ProposalSupplierControl::class)->findOneBy(array('controlDestinationId'=>$id,'supplierId'=>$newSupplierId));
if(empty($existeProposalSupplierControl)){
$newProposalSupplierControl = new ProposalSupplierControl();
$newProposalSupplierControl->setControlDestinationId($proposalSupplierControl[0]->getControlDestinationId());
$newProposalSupplierControl->setProposalId($proposalSupplierControl[0]->getProposalId());
$newProposalSupplierControl->setDestinoId($proposalSupplierControl[0]->getDestinoId());
$newProposalSupplierControl->setSupplierId($newSupplierId);
$newProposalSupplierControl->setIdeaId($proposalSupplierControl[0]->getIdeaId());
$newProposalSupplierControl->setStatus($proposalSupplierControl[0]->getStatus());
$newProposalSupplierControl->setDisabled($proposalSupplierControl[0]->getDisabled());
$newProposalSupplierControl->setRank($proposalSupplierControl[0]->getRank());
$newProposalSupplierControl->setDateBlockLimit($proposalSupplierControl[0]->getDateBlockLimit());
$newProposalSupplierControl->setActivityId($proposalSupplierControl[0]->getActivityId());
$em->persist($newProposalSupplierControl);
$em->flush();
} else {
//El supplier ya existia, solo necesitamos agregar el servicio
$newProposalSupplierControl = $existeProposalSupplierControl;
}
//INICIO: Se modifica la tabla ProposalSuplierServices segun lo que se modificara en la tabla ProposalSupplierControl
// $proposalSupplierServices = $em->getRepository(ProposalSupplierServices::class)->findByControlId($newProposalSupplierControl->getId());
$proposalSupplierServices = $em->getRepository(ProposalSupplierServices::class)->findBy(
array('proposalId'=>$newProposalSupplierControl->getProposalId(),
'destinationId'=>$newProposalSupplierControl->getDestinoId()));
foreach ($proposalSupplierServices as $elem) {
if($elem->getSupplierId()==$oldSupplierId){
$elem->setSupplierId($newSupplierId);
$elem->setControlId($newProposalSupplierControl->getId());
$em->persist($elem);
$em->flush();
}
}
//FIN: Se modifica la tabla ProposalSuplierServices segun lo que se modificara en la tabla ProposalSupplierControl
}
}
}
//Fin: Caso de Suppliers desde white services
//Inicio: Caso de Suppliers comunes
if (!empty($arraySuppliersId)){
$arrayKeys = array_keys($arraySuppliersId);
} else {
$arrayKeys = array();
}
foreach ($arrayKeys as $key){
$oldSupplierId = $key;
$newSupplierId = $arraySuppliersId[$key];
// Si $newSupplierId es empty no se ha seleccionado un proveedor del selector, en este caso no se modifica el supplier
if (!empty($newSupplierId)){
foreach ($proposalSupplierControl as $item){
if($item->getSupplierId() == $oldSupplierId){
//INICIO: Se modifica la tabla ProposalSuplierServices segun lo que se modificara en la tabla ProposalSupplierControl
$proposalSupplierServices = $em->getRepository(ProposalSupplierServices::class)->findByControlId($item->getId());
$existeProposalSupplierControl = $em->getRepository(ProposalSupplierControl::class)->findOneBy(array('controlDestinationId'=>$id,'supplierId'=>$newSupplierId));
foreach ($proposalSupplierServices as $elem){
$elem->setSupplierId($newSupplierId);
if (!empty($existeProposalSupplierControl)){
$elem->setControlId($existeProposalSupplierControl->getId());
}
$em->persist($elem);
$em->flush();
}
//FIN: Se modifica la tabla ProposalSuplierServices segun lo que se modificara en la tabla ProposalSupplierControl
$item->setSupplierId($newSupplierId);
$em->persist($item);
$em->flush();
}
}
}
}
//Fin: Caso de Suppliers comunes
return $this->redirectToRoute('proposal_destination_view', array('id'=>$proposalControl->getProposalId()));
}
}