<?php
/**
* Created by Mediterranean Develup Solutions
* User: jorge.defreitas@develup.solutions
* Date: 29/06/2017
* Time: 14:17
*/
namespace App\Controller;
use App\Entity\Cities;
use App\Entity\ClientContact;
use App\Entity\ReturnInvestment;
use App\Entity\Client;
use App\Entity\Country;
use App\Entity\Group;
use App\Entity\Provinces;
use App\Entity\Regions;
use App\Entity\SettingsOffice;
use App\Entity\User;
use App\Form\ClientType;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Translation\TranslatorInterface;
class ClientController extends AbstractController
{
private $translator;
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}
/**
* @Route("/client/add", name="client_add")
*/
public function addClientAction(EntityManagerInterface $em, Request $request)
{
$user = $this->getUser();
$country = $em->getRepository(Country::class)->findOneBy(['id' => 62]);
// Crear un nuevo cliente
$client = new Client();
if($user->getOffice() == 2){
// Para los usuarios de barcelona se muestra los datos de barcelona
$region = $em->getRepository(Regions::class)->findOneBy(['id' => 967]);
$province = $em->getRepository(Provinces::class)->findOneBy(['id' => 8]);
$client->setCountry($country)
->setRegion($region)
->setProvince($province)
->setPopulation(697806);
}else{
//Para todos los demás se muestra madrid
$region = $em->getRepository(Regions::class)->findOneBy(['id' => 969]);
$province = $em->getRepository(Provinces::class)->findOneBy(['id' => 28]);
$client->setCountry($country)
->setRegion($region)
->setProvince($province)
->setPopulation(713549);
}
// Crear el formulario, pasando las entidades como opciones
$form = $this->createClientCreateForm($client);
// Renderizar la plantilla del formulario
return $this->render('client/client/add-client.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/client/list/{idgroup}", defaults={"idgroup" = 0}, name="client_index")
*/
public function indexAction($idgroup, Request $request) {
$em = $this->getDoctrine()->getManager();
$group = $em->getRepository(Group::class)->findById($idgroup);
if ($idgroup == 0){
$client = $em->getRepository(Client::class)->findAll();
}else{
$client = $em->getRepository(Client::class)->findBy(
array( 'groupId' => $idgroup)
);
}
return $this->render('client/client/list-client.html.twig',
array(
'groups' => $group,
'clients' => $client
)
);
}
// /**
// * @Route("/client/add/{idgroup}", defaults={"idgroup" = 0}, name="client_add")
// */
// public function addClientAction($idgroup, Request $request)
// {
// $client = new Client();
// $client->setGroupId($idgroup);
// $form = $this->createClientCreateForm($client);
//
// return $this->render('client/client/add-client.html.twig', array('form' => $form->createView()));
// }
private function createClientCreateForm(Client $entity)
{
$form = $this->createForm(ClientType::class, $entity, array(
'action' => $this->generateUrl('client_create'),
'method' => 'POST'
));
return $form;
}
/**
* @Route("/client/create", name="client_create")
*/
public function createAction(Request $request, LoggerInterface $logger, EntityManagerInterface $em)
{
// $province = $request->request->get('client')['province'];
// $population = $request->request->get('client')['population'];
$returnnew = $request->request->get('client_esp')['returnnew'];
// $telephone_data = $request->request->get('client')['telephone'];
// $email_data = $request->request->get('client')['email'];
// Crear un nuevo cliente
$client = new Client();
// Para los usuarios de barcelona se muestra los datos de barcelona
$country = $em->getRepository(Country::class)->findOneBy(['id' => $request->request->get('client')['country']]);
$region = $em->getRepository(Regions::class)->findOneBy(['id' => $request->request->get('client')['region']]);
$province = $em->getRepository(Provinces::class)->findOneBy(['id' => $request->request->get('client')['province']]);
$client->setCountry($country)
->setRegion($region)
->setProvince($province)
->setPopulation($request->request->get('client')['population']);
$form = $this->createClientCreateForm($client);
$form->handleRequest($request);
$isClientInOut = $form->get('is_client_in_out')->getData();
$isClientGreenPatio = $form->get('is_client_green_patio')->getData();
$isClientAvExpress = $form->get('is_client_av_express')->getData();
$isClientDevelup = $form->get('is_client_develup')->getData();
if(!is_null($isClientInOut)){
$client->setIsClientInOut($isClientInOut);
}
if(!is_null($isClientGreenPatio)){
$client->setIsClientGreenPatio($isClientGreenPatio);
}
if(!is_null($isClientAvExpress)){
$client->setIsClientAvExpress($isClientAvExpress);
}
if(!is_null($isClientDevelup)){
$client->setIsClientDevelup($isClientDevelup);
}
$telephone_data = $form->get('telephone')->getData();
$client ->setProvince($client->getProvince()->getId());
$client ->setCountry($client->getCountry()->getId());
$client ->setRegion($client->getRegion()->getId());
$office_client = $form->get('idOffice')->getData();
if(!is_null($office_client)){
$client->setIdOffice($office_client->getId());
}
$country_client = $form->get('country')->getData();
if(!is_null($country_client)){
$client->setCountry($country_client->getId());
}
$errores=0;
$campo="";
if (empty($client->getPopulation())){
$errores = 1;
$campo = $this->translator->trans("City");
}elseif (empty($client->getProvince())){
$errores = 1;
$campo = $this->translator->trans("Province");
}
$group_client = $form->get('groupId')->getData();
if(!is_null($group_client)){
$client->setGroupId($group_client->getId());
}
$returninvestment_data = $form->get('returninvestment')->getData();
if(!is_null($returninvestment_data)){
$client->setReturnInvestment($returninvestment_data->getName());
}
$verifico_phone = $em->getRepository(Client::class)->findOneByTelephone($telephone_data);
if($errores == "0") {
if (empty($verifico_phone)) {
if($form->isValid())
{
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$client->setCreatedId($user_id);
$client->setUpdatedId($user_id);
// $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;
try{
$em->persist($client);
$em->flush();
$event = 'The Client has been created. Now, add some contacts';
$successMessage = $this->translator->trans($event);
$this->addFlash('mensajeclient', $successMessage);
if(!empty($returnnew)){
$client->setReturnInvestment($returnnew);
$returninvestment = new ReturnInvestment();
$returninvestment->setName($returnnew);
$em->persist($returninvestment);
$em->flush();
}
$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 */
// $clientrappelcontrol = new ClientRappelControl();
// $clientrappelcontrol->setClientId($client->getId());
// $clientrappelcontrol->setCreatedId($user_id);
// $clientrappelcontrol->setUpdatedId($user_id);
// $em->persist($clientrappelcontrol);
// $em->flush();
// $v = $client->getId(); //GEAO
// d($v); //GEAO
//
// if(!empty($v)) {
return $this->redirectToRoute('contact_add',
array(
'idclient' => $client->getId()
)
);
// }
}else{
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajeclienterror', $errorMessage);
}
}else{
$errorMessage = $this->translator->trans('The Client already exists');
$this->addFlash('mensajeclienterror', $errorMessage);
}
} else {
$errorMessage = $this->translator->trans('Error, this field is empty ');
$this->addFlash('mensajeclienterror', $errorMessage.$campo);
}
return $this->render('client/client/add-client.html.twig', array(
'form' => $form->createView()
)
);
}
/**
* @Route("/client/edit/{id}", name="client_edit")
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$client = $em->getRepository(Client::class)->findOneById($id);
$contacts = $em->getRepository(ClientContact::class)->findByClient_id($id);
$usuarios = $em->getRepository(User::class)->findAll();
$contactos = null;
$nombres_usuarios = array();
foreach ($contacts as $contact){
$user = $em->getRepository(User::class)->findOneById($contact->getAssignedAgent());
$creator = $em->getRepository(User::class)->findOneById($contact->getCreatedId());
$contact->setAssignedAgent($user->getName()." ".$user->getLastName());
$contact->setCreatedId($creator->getName()." ".$creator->getLastName());
$contactos[] = $contact;
}
foreach ($usuarios as $usuario){
$nombres_usuarios[] = array(
"id" => $usuario->getId(),
"nombre" => $usuario->getName()." ".$usuario->getLastName(),
);
}
/*
* Office, Company y Userrol son entityclass (en el formulario) que funcionan como
* unos campos <select>,
* por lo tanto necesitan que le pases el objeto para poder recordar los campos y no
* le vale que le metas a pelo el id o el nombre del campo recuperado
*/
$office = $em->getRepository(SettingsOffice::class)->findOneById($client->getIdOffice());
$client->setIdOffice($office);
$country = $em->getRepository(Country::class)->findOneById($client->getCountry());
$client->setCountry($country);
$regions = $em->getRepository(Regions::class)->findOneById($client->getRegion());
$client->setRegion($regions);
$province = $em->getRepository(Provinces::class)->findOneById($client->getProvince());
$client->setProvince($province);
$grupo = $em->getRepository(Group::class)->findOneById($client->getGroupId());
$client->setGroupId($grupo);
$returninvestment = $em->getRepository(ReturnInvestment::class)->findOneByName($client->getReturnInvestment());
$client->setReturnInvestment($returninvestment);
$form = $this->createEditClientForm($client, $id);
return $this->render('client/client/edit-client.html.twig',
array(
'id' => $id,
'client' => $client,
'nombres_usuarios' => $nombres_usuarios,
'contact' => $contactos,
'idClient' => $id,
'form' => $form->createView()
)
);
}
private function createEditClientForm(Client $entity, $id)
{
$form = $this->createForm(ClientType::class, $entity,
array(
'action' => $this->generateUrl('client_update',
array(
'id' => $id
)
), 'method' => 'PUT'));
return $form;
}
/**
* @Route("/client/update/{id}", name="client_update", methods={"POST", "PUT"})
*/
public function updateAction($id, Request $request, LoggerInterface $logger, EntityManagerInterface $em)
{
// $region = $_POST['client']['region'];
// $province = $_POST['client']['province'];
// $population = $_POST['client']['population'];
$returnnew = $request->request->get('client_esp')['returnnew'];
$client = $em->getRepository(Client::class)->findOneById($id);
$contacts = $em->getRepository(ClientContact::class)->findByClient_id($id);
$usuarios = $em->getRepository(User::class)->findAll();
$contactos = array();
$nombres_usuarios = array();
foreach ($contacts as $contact){
$user = $em->getRepository(User::class)->findOneById($contact->getAssignedAgent());
$creator = $em->getRepository(User::class)->findOneById($contact->getCreatedId());
$datos_agent =array(
'assignedAgent' => $user->getName()." ".$user->getLastName(),
'createdId' => $user->getName()." ".$user->getLastName(),
);
$contactos[] = $datos_agent;
}
foreach ($usuarios as $usuario){
$nombres_usuarios[] = array(
"id" => $usuario->getId(),
"nombre" => $usuario->getName()." ".$usuario->getLastName(),
);
}
// Añadimos la entidades de country, region y province
$country = $em->getRepository(Country::class)->findOneById($client->getCountry());
$client->setCountry($country);
$regions = $em->getRepository(Regions::class)->findOneById($client->getRegion());
$client->setRegion($regions);
$province = $em->getRepository(Provinces::class)->findOneById($client->getProvince());
$client->setProvince($province);
$form = $this->createEditClientForm($client, $id);
$form->handleRequest($request);
$client ->setProvince($client->getProvince()->getId());
$client ->setCountry($client->getCountry()->getId());
$client ->setRegion($client->getRegion()->getId());
$office_usuario = $form->get('idOffice')->getData();
if(!is_null($office_usuario)){
$client->setIdOffice($office_usuario->getId());
}
$country = $form->get('country')->getData();
if(!is_null($country)){
$client->setCountry($country->getId());
}
$groupId = $form->get('groupId')->getData();
if(!is_null($groupId)){
$client->setGroupId($groupId->getId());
}
$returninvestment_data = $form->get('returninvestment')->getData();
if(!is_null($returninvestment_data)){
$client->setReturnInvestment($returninvestment_data->getName());
}
// $client->setRegion($region);
// $client->setProvince($province);
// $client->setPopulation($population);
// $province = $form->get('province')->getData();
// if(!is_null($province)){
// $client->setProvince($province->getId());
// }
//
// $population = $form->get('population')->getData();
// if(!is_null($population)){
// $client->setPopulation($population->getId());
// }
$group_client = $form->get('groupId')->getData();
if(!is_null($group_client)){
$client->setGroupId($group_client->getId());
}
if($form->isValid())
{
if(!empty($returnnew)){
$client->setReturnInvestment($returnnew);
$returninvestment = new ReturnInvestment();
$returninvestment->setName($returnnew);
$em->persist($returninvestment);
}
/* Obtengo usuario logueado */
$user_logueado = $this->get('security.token_storage')->getToken()->getUser();
$user_id = $user_logueado->getId();
$client->getUpdatedId($user_id);
// $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;
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 */
// return $this->redirectToRoute('client_list');
return $this->render('client/client/edit-client.html.twig',
array(
'id' => $client->getId(),
'client' => $client,
'nombres_usuarios' => $nombres_usuarios,
'contact' => $contactos,
'idClient' => $id,
'form' => $form->createView()
)
);
}else{
$errorMessage = $this->translator->trans('Error, some fields are empty');
$this->addFlash('mensajeclienterror', $errorMessage);
}
return $this->render('client/client/edit-client.html.twig',
array(
'id' => $client->getId(),
'client' => $client,
'nombres_usuarios' => $nombres_usuarios,
'contact' => $contactos,
'idClient' => $id,
'form' => $form->createView()
)
);
}
/**
* @Route("/client/add-image", name="client_image")
*/
public function addClientImage()
{
$dataa = $_POST['image'];
list($type, $data) = explode(';', $dataa);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
$ruta = "assets/images/clients/";
if (!file_exists($ruta)) {
mkdir($ruta,0777,true);
}
$file = fopen($ruta.$imageName, "wb");
fwrite($file, $data);
fclose($file);
$return = array(
'base64' => $dataa,
'nombre_archivo' => $ruta.$imageName,
);
$response = new JsonResponse($return);
return $response;
}
/**
* @Route("/client/editt/addContact", name="client_add_contact_from_modal")
*/
public function addContactFromModal()
{
$name = $_POST['name'];
$lastName = $_POST['lastName'];
$position = $_POST['position'];
$department = $_POST['department'];
$birthday = $_POST['birthday'];
$typeclient = $_POST['typeclient'];
$assignedAgent = $_POST['assignedAgent'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$mobile = $_POST['mobile'];
$idClient = $_POST['idClient'];
// d($birthday);
$contact = new ClientContact();
$contact->setName($name);
$contact->setLastName($lastName);
$contact->setPosition($position);
$contact->setDepartment($department);
$contact->setBirthday($birthday);
$contact->setTypeclient($typeclient);
$contact->setAssignedAgent($assignedAgent);
$contact->setEmail($email);
$contact->setPhone($phone);
$contact->setMobile($mobile);
$contact->setClientId($idClient);
$contact->setClientId($idClient);
// $contact->setClientId($idClient);
// $contact->setClientId($idClient);
// $contact->set($idClient);
// $contact->setClientId($idClient);
// d($contact);
$em = $this->getDoctrine()->getManager();
$em->persist($contact);
$em->flush();
}
/**
* @Route("/client/listdesplegable", name="get_client_select")
*/
public function clientSelectAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$clients = $em->getRepository(Client::class)->findAll();
$datos = array();
if (!empty($clients)){
foreach($clients as $client){
$datos[] = array(
"id" => $client->getId(),
"name" => $client->getName(),
"title" => $client->getTitle()
);
}
}
else
{
$datos[] = array(
"id" => '',
"name" => '',
"title" => ''
);
}
$return = array(
'clients' => $datos,
);
$response = new JsonResponse($return);
return $response;
}
}