<?php
namespace Aviatur\CustomerBundle\Controller;
use Aviatur\CustomerBundle\Entity\Customer;
use Aviatur\CustomerBundle\Entity\CustomerBillingList;
use Aviatur\CustomerBundle\Entity\HistoricalCustomer;
use Aviatur\CustomerBundle\Models\CustomerModel;
use Aviatur\CustomerBundle\Services\ValidateSanctionsRenewal;
use Aviatur\FormBundle\Entity\Newsletter;
use Aviatur\GeneralBundle\Services\AviaturEncoder;
use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
use Aviatur\GeneralBundle\Services\AviaturLoginService;
use Aviatur\GeneralBundle\Services\AviaturWebService;
use Aviatur\PaymentBundle\Entity\PaymentMethodCustomer;
use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
use Aviatur\PaymentBundle\Services\TokenizerService;
use Aviatur\TwigBundle\Services\TwigFolder;
use DateTime;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class DefaultController extends AbstractController
{
public function getDataAction(Request $request, ManagerRegistry $managerRegistry, AviaturWebService $webService, AviaturErrorHandler $errorHandler, TwigFolder $twigFolder, ParameterBagInterface $parameterBag)
{
if ($request->isXmlHttpRequest()) {
$doc_type = $request->query->get('doc_type');
$documentNumber = $request->query->get('doc_num');
$em = $managerRegistry->getManager();
$documentType = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($doc_type);
$data = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneBy(['documentType' => $documentType, 'documentnumber' => $documentNumber]);
if (empty($data)) {
//si no encuentra en la base local busca en el servidor de aviatur
$customerModel = new CustomerModel();
$xmlRequest = $customerModel->getXmlFindUser($doc_type, $documentNumber, '0926EB', 'BOGVU2900');
$response = $webService->busWebServiceAmadeus('GENERALLAVE', $parameterBag->get('provider_service'), $xmlRequest);
if ((null != $response) && ('error' != $response)) {
if (!isset($response['error']) && is_object($response)) {
if (('FALLO' == $response->RESULTADO) && (false !== strpos($response->MENSAJE, 'No se enco'))) {
return $this->json(['no_info' => (string) $response->MENSAJE]);
} elseif (('FALLO' == $response->RESULTADO)) {
$errorHandler->errorRedirect('/vuelos/detalle', '', 'Error usuario: '.(string) $response->MENSAJE);
return $this->json(['error' => (string) $response->MENSAJE]);
} else {
$customer = new Customer();
$dataNumber = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneBy(['code' => $response->document->id]);
$dataGender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneBy(['code' => $response->gender->id]);
$dataMaritalStatus = $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneBy(['code' => $response->marital_starus->id]);
$dataCity = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneBy(['code' => $response->city->id]);
$dataCountry = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneBy(['code' => $response->country->id]);
try {
$customer->setAviaturclientid((int) $response->id);
$customer->setDocumentType($dataNumber);
$customer->setCivilStatus($dataMaritalStatus);
$customer->setGenderAviatur($dataGender);
$customer->setCity($dataCity);
$customer->setCountry($dataCountry);
$customer->setDocumentnumber($documentNumber);
$customer->setFirstname($response->name);
$customer->setLastname($response->last_name);
$customer->setBirthdate(new \DateTime($response->birth_date));
$customer->setAddress($response->address);
$customer->setPhone($response->phone_number);
$customer->setCellphone($response->mobile_phone_number);
$customer->setEmail($response->email);
$customer->setEmailCanonical($response->email);
$customer->setUsername($response->email);
$customer->setUsernameCanonical($response->email);
$customer->setPassword($response->password);
$customer->setAcceptInformation(0);
$customer->setAcceptSms(0);
$customer->setPersonType($response->person_type->id);
$customer->setFrecuencySms(0);
$customer->setCorporateId('');
$customer->setCorporateName('');
$customer->setEnabled(1);
$customer->setRoles([]);
$emo = $managerRegistry->getManager();
$emo->persist($customer);
$emo->flush();
$return = [
'id' => $customer->getId(),
'first_name' => substr_replace($response->name, '********', 3),
'last_name' => substr_replace($response->last_name, '********', 3),
'address' => substr_replace($response->address, '********', 3),
'doc_num' => (string) $response->document->number,
'doc_type' => $dataNumber->getExternalcode(),
'phone' => substr_replace($response->phone_number, '*******', 3),
'email' => substr_replace($response->email, '********', 3),
'gender' => $dataGender->getCode(),
'birthday' => ((null != $response->birth_date) && ('' != $response->birth_date)) ? \date('Y-m-d', \strtotime($response->birth_date)) : null,
'nationality' => ((null != $dataCountry) && ('' != $dataCountry)) ? $dataCountry->getIataCode() : null,
'nationality_label' => ((null != $dataCountry) && ('' != $dataCountry)) ? \ucwords(\mb_strtolower($dataCountry->getDescription())).' ('.$dataCountry->getIataCode().')' : null,
];
} catch (\Doctrine\ORM\ORMException $e) {
$errorHandler->errorRedirect('/vuelos/detalle', '', 'Ha ocurrido un error ingresando el nuevo usuario a la base de datos');
return $this->json(['error' => 'Ha ocurrido un error ingresando el nuevo usuario a la base de datos']);
} catch (\Aviatur\CustomerBundle\Exception\ValidateException $e) {
$mensaje = 'Información incompleta o inconsistente: '.$e->getMessage();
$errorHandler->errorRedirect('/vuelos/detalle', '', $mensaje);
return $this->json(['error' => $mensaje]);
} catch (\Exception $e) {
$errorHandler->errorRedirect('/vuelos/detalle', '', 'Ha ocurrido un error inesperado en la creación del nuevo usuario');
return $this->json(['error' => 'Ha ocurrido un error inesperado en la creación del nuevo usuario']);
}
}
} else {
$errorHandler->errorRedirect('/vuelos/detalle', '', 'Error usuario: '.(string) $response['error']);
return $this->json(['error' => (string) $response['error']]);
}
} else {
$errorHandler->errorRedirect('/vuelos/detalle', '', 'Error usuario: Error inesperado en la consulta');
return $this->json(['error' => 'Error inesperado en la consulta']);
}
} else {
$return = [
'id' => $data->getId(),
'first_name' => ((null != $data->getFirstname()) && ('' != $data->getFirstname())) ? utf8_encode(substr_replace($data->getFirstname(), '********', 3)) : null,
'last_name' => ((null != $data->getLastname()) && ('' != $data->getLastname())) ? utf8_encode(substr_replace($data->getLastname(), '********', 3)) : null,
'address' => ((null != $data->getAddress()) && ('' != $data->getAddress())) ? substr_replace($data->getAddress(), '********', 3) : null,
'city' => ((null != $data->getCity()) && ('' != $data->getCity())) ? substr_replace($data->getCity()->getDescription(), '********', 3) : null,
'doc_num' => ((null != $data->getDocumentnumber()) && ('' != $data->getDocumentnumber())) ? $data->getDocumentnumber() : null,
'doc_type' => ((null != $data->getDocumentType()) && ('' != $data->getDocumentType())) ? $data->getDocumentType()->getExternalcode() : null,
'phone' => ((null != $data->getPhone()) && ('' != $data->getPhone())) ? substr_replace($data->getPhone(), '*******', 3) : null,
'cellphone' => ((null != $data->getCellphone()) && ('' != $data->getCellphone())) ? substr_replace($data->getCellphone(), '*******', 3) : null,
'email' => ((null != $data->getEmail()) && ('' != $data->getEmail())) ? substr_replace($data->getEmail(), '********', 3) : null,
'gender' => ((null != $data->getGenderAviatur()) && ('' != $data->getGenderAviatur())) ? $data->getGenderAviatur()->getCode() : null,
'birthday' => ((null != $data->getBirthdate()) && ('' != $data->getBirthdate())) ? \date('Y-m-d', $data->getBirthdate()->getTimestamp()) : null,
'city_id' => ((null != $data->getCity()) && (null != $data->getCity()->getIatacode()) && ('' != $data->getCity()->getIatacode())) ? $data->getCity()->getIatacode() : null,
'nationality' => ((null != $data->getCountry()) && ('' != $data->getCountry())) ? $data->getCountry()->getIataCode() : null,
'nationality_label' => ((null != $data->getCountry()) && ('' != $data->getCountry())) ? \ucwords(\mb_strtolower($data->getCountry()->getDescription())).' ('.$data->getCountry()->getIataCode().')' : null,
];
}
return $this->json($return);
} else {
$errorHandler->errorRedirect('/vuelos/detalle', '', 'Acceso no autorizado');
return $errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado');
}
}
public function getB2TDataAction(Request $request, AviaturWebService $webService, AviaturErrorHandler $errorHandler, ParameterBagInterface $parameterBag)
{
$return = [];
$doc_type = $request->query->get('doc_type');
$documentNumber = $request->query->get('doc_num');
//si no encuentra en la base local busca en el servidor de aviatur
$customerModel = new CustomerModel();
$xmlRequest = $customerModel->getXmlFindUserB2T($doc_type, $documentNumber, 'G_ROA', 'BOGVU2900');
$response = $webService->busWebServiceAmadeus('GENERALLAVE', $parameterBag->get('provider_service'), $xmlRequest);
if ((('FALLO' == $response->RESULTADO) && (false !== strpos($response->MENSAJE, 'No se enco'))) || (('EXITO' == $response->RESULTADO) && empty($response->CLIENTES))) {
return $this->json(['no_info' => (string) $response->MENSAJE]);
} elseif (('FALLO' == $response->RESULTADO)) {
$errorHandler->errorRedirect('/vuelos/detalle', '', 'Error usuario: '.(string) $response->MENSAJE);
return $this->json(['error' => (string) $response->MENSAJE]);
} else {
foreach ($response->CLIENTES->ELEMENTO_LISTA_CLIENTES as $client) {
$return[] = [
'id' => (string) $client->IDENTIFICADOR_INTERNO,
'first_name' => ucwords($this->sanear_string(mb_strtolower((string) $client->NOMBRE))),
'last_name' => ucwords($this->sanear_string(mb_strtolower((string) $client->APELLIDO))),
'doc_num' => ucwords(mb_strtolower((string) $client->NUMERO_DE_DOCUMENTO)),
'doc_type' => $request->query->get('doc_type'),
'phone' => (string) $client->TELEFONO,
'consecutive' => (string) $client->CONSECUTIVO,
];
}
}
return $this->json($return);
}
public function createAction(Request $request, ManagerRegistry $managerRegistry, AviaturWebService $webService, AviaturErrorHandler $errorHandler, TokenStorageInterface $tokenStorage, SessionInterface $session, ValidateSanctionsRenewal $validateSanctionsRenewal, ParameterBagInterface $parameterBag)
{
$customer = null;
$em = $managerRegistry->getManager();
$billingData = $request->get('BD');
$paymentMethod = $request->get('PD')['type'] ?? 'other';
if ($request->request->has('MS')) {
$passangers = $billingData;
} else {
$passangers = array_merge($billingData, $request->get('PI'));
}
$isFront = $session->has('operatorId');
$session->remove('loginFromDetail');
foreach ($passangers as $prop => $passanger) {
if (preg_match('/^doc_num/i', $prop) && '' == $passangers[$prop]) {
$errorHandler->errorRedirect('/vuelos/detalle', '', 'undefined_doc_num');
return $this->json(['error' => 'El número de identificación no puede estar vacío']);
}
}
$server = $request->server;
$urlDomain = parse_url($server->get('HTTP_REFERER'), PHP_URL_HOST);
/* Inicio comparación ONU-OFAC */
$postData = $request->request->all();
if(!$this->getValidationOnuOfac($postData, $server->get('HTTP_REFERER'), $session, $validateSanctionsRenewal)){
$errorHandler->errorRedirect('/vuelos/detalle', '', 'sanctions_candidate');
return $this->json(['error' => 'No se puede continuar con la transacción. Por favor, contáctese con la línea de atención al usuario de AVIATUR']);
}
/* Fin comparación ONU-OFAC */
$parameters = json_decode($session->get($request->getHost().'[parameters]'));
if (isset($parameters->switch_login_agencies) && '' != $parameters->switch_login_agencies) {
$login_agencies = json_decode($parameters->switch_login_agencies, true);
if (isset($login_agencies[$session->get('agencyId')])) {
$login_is_on = $login_agencies[$session->get('agencyId')];
} else {
$login_is_on = $login_agencies['all'];
}
} else {
$login_is_on = '0';
}
if (!$isFront && false !== strpos($urlDomain, 'bbva') && !$this->validateSpecialConditionPayment($request->get('PD')['card_num'])) {
$errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'no_sppayment_condition');
return $this->json(['error' => 'no_sppayment_condition']);
}
if ((isset($billingData['id'])) && ('' != $billingData['id']) && (null != $billingData['id'])) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
/* if ($login_is_on == '1') {
if ($this->get("aviatur_login_service")->validActiveSession() === false) {
$session->set('loginFromDetail', true);
return $this->json(array("error" => "no_granted_session_condition"));
} else if (!isset($request->get('PD')['methodsRecovered'])) { */
// $customerLogin = $this->get('security.token_storage')->getToken()->getUser();
//
// //Verify is client is same logged client
//// if ($customerLogin->getEmail() != $customer->getEmail() && !isset($billingData['anotherCustomerCheck'])) {
//// return $this->json(array("error" => "notSamePersonLogged"));
//// }
//
// $infoMethodPaymentByClient = $this->get("aviatur_methods_customer_service")->getMethodsByCustomer($customerLogin, false);
// if ($infoMethodPaymentByClient['info'] !== 'NoInfo') {
// return $this->json(array("error" => "customer_with_methods_saved", "info" => $infoMethodPaymentByClient['info']));
// }
/* }
} */
if (isset($billingData['address']) && (false === strpos($billingData['address'], '***')) && (('' == $customer->getAddress()) || (null == $customer->getAddress()))) {
$customer->setAddress($billingData['address']);
}
if (isset($billingData['phone']) && (false === strpos($billingData['phone'], '***')) && (('' == $customer->getPhone()) || (null == $customer->getPhone()))) {
$customer->setPhone($billingData['phone']);
}
$em->flush();
/*
if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $customer->getDocumentnumber(), 'name' => $customer->getFirstname().' '.$customer->getLastname()], $paymentMethod)) {
$errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
return $this->json(['error' => 'sanctions_candidate']);
}
*/
$passengerStructured = [];
$passengerStructuredGroup = null;
foreach ($passangers as $passKey => $passengerValue) {
if (!preg_match('/.*_\d_\d$/', $passKey) || strstr($passengerValue, '***')) {
continue;
}
$matchArray = [];
preg_match('/.*_(\d_\d)$/', $passKey, $matchArray);
if (!isset($matchArray[1])) {
continue;
}
$passengerStructuredGroup = !$passengerStructuredGroup ? $matchArray[1] : ($passengerStructuredGroup !== $matchArray[1] ? $matchArray[1] : $passengerStructuredGroup);
if (strstr($passKey, 'doc_num')) {
$passengerStructured[$passengerStructuredGroup]['document'] = $passengerValue;
$passengerStructured[$passengerStructuredGroup]['name'] = '';
} elseif (strstr($passKey, 'first_name') || strstr($passKey, 'last_name')) {
$passengerStructured[$passengerStructuredGroup]['name'] .= $passengerValue.' ';
}
}
foreach ($passengerStructured as $pax) {
if ('' === trim($pax['name'])) {
continue;
}
/*
if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $pax['document'], 'name' => $pax['name']], $paymentMethod)) {
$errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
return $this->json(['error' => 'sanctions_candidate']);
}
*/
}
$return = [
'id' => $customer->getId(),
];
return $this->json($return);
} else {
$userLogged = $tokenStorage->getToken()->getUser();
if ($userLogged && $userLogged = !'anon.') {
$billingData['id'] = $userLogged->getId();
if (null != $userLogged->getFacebookId() || null != $userLogged->getGoogleId()) {
$passangerData = $request->get('PI');
/*
if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $billingData['doc_num'], 'name' => $billingData['first_name'].' '.$billingData['last_name']], $paymentMethod)) {
$errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
return $this->json(['error' => 'sanctions_candidate']);
}
*/
if ($request->get('same-billing')) {
if ('on' == $request->get('same-billing')) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($userLogged->getId());
$dataNumberDocType = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($passangerData['doc_type_1_1']);
$dataCountry = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangerData['nationality_1_1']);
$dataCity = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode('BOG');
$dataGender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangerData['gender_1_1']);
$customer->setDocumentType($dataNumberDocType);
$customer->setDocumentnumber($passangerData['doc_num_1_1']);
$customer->setFirstname($passangerData['first_name_1_1']);
$customer->setLastname($passangerData['last_name_1_1']);
$customer->setAddress($passangerData['address_1_1']);
$customer->setPhone($request->get('CD')['phone']);
$customer->setCountry($dataCountry);
$customer->setCity($dataCity);
$customer->setBirthdate(new \DateTime($passangerData['birthday_1_1']));
$customer->setGenderAviatur($dataGender);
}
} else {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($userLogged->getId());
$dataNumberDocType = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($billingData['doc_type']);
if (isset($billingData['nationality']) && '' != $billingData['nationality']) {
$dataCountry = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($billingData['nationality']);
} else {
$dataCountry = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode('CO');
}
$dataCity = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode('BOG');
$dataGender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($billingData['gender']);
$customer->setDocumentType($dataNumberDocType);
$customer->setDocumentnumber($billingData['doc_num']);
$customer->setFirstname($billingData['first_name']);
$customer->setLastname($billingData['last_name']);
$customer->setAddress($billingData['address']);
$customer->setPhone($billingData['phone']);
$customer->setCountry($dataCountry);
$customer->setCity($dataCity);
$customer->setBirthdate(new \DateTime($billingData['birthday']));
$customer->setGenderAviatur($dataGender);
}
$em->persist($customer);
$em->flush();
$return = [
'id' => $userLogged->getId(),
];
return $this->json($return);
}
}
$documentType = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findByExternalcode($billingData['doc_type']);
$registered = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findBy(['documentnumber' => $billingData['doc_num'], 'documentType' => $documentType]);
if (0 != sizeof($registered)) {
return $this->json(['id' => $registered[0]->getId()]);
}
$data = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findByEmail($billingData['email']);
if (0 != sizeof($data)) {
$errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'email_exist');
return $this->json(['error' => 'email_exist']);
}
$customerModel = new CustomerModel();
$xmlRequest = $customerModel->getXmlFindUserByEmail($billingData['email'], 4);
$response = $webService->busWebServiceAmadeus('GENERALLAVE', $parameterBag->get('provider_service'), $xmlRequest);
if ((isset($response->RESULTADO) && ('FALLO' != $response->RESULTADO)) || (isset($response->ID))) {
$errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'email_exist');
return $this->json(['error' => 'email_exist']);
} elseif (isset($response->MENSAJE) && (false !== strpos($response->MENSAJE, 'No se enco'))) {
$doc_type = explode('-', $billingData['doc_type']);
$passangerData = $request->get('PI');
/* if ($login_is_on == '0') { */
$dataNumber = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($doc_type[0]);
$personType = (3 != $dataNumber->getId()) && (4 != $dataNumber->getId()) && (7 != $dataNumber->getId()) ? 8 : 7;
$customer = new Customer();
$customer->setAddress('' != $billingData['address'] ? $billingData['address'] : $passangerData['address_1_1']);
$dataCity = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode('BOG');
if (isset($passangerData['nationality_1_1']) && '' != $passangerData['nationality_1_1']) {
$dataCountry = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangerData['nationality_1_1']);
} else {
$dataCountry = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode('CO');
}
$dataGender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangerData['gender_1_1']);
$customer->setGenderAviatur($dataGender);
if ($billingData['doc_num'] == $passangerData['doc_num_1_1']) {
$customer->setBirthdate(new \DateTime($passangerData['birthday_1_1']));
} else {
$customer->setBirthdate(new \DateTime(date('Y-m-d', strtotime('-18 year', time()))));
}
$customer->setDocumentType($dataNumber);
$customer->setCity($dataCity);
$customer->setCountry($dataCountry);
$customer->setDocumentnumber($billingData['doc_num']);
$customer->setFirstname($billingData['first_name']);
$customer->setLastname($billingData['last_name']);
$customer->setPhone($billingData['phone']);
$customer->setCellphone($billingData['phone']);
$customer->setEmail($billingData['email']);
$customer->setEmailCanonical($billingData['email']);
$customer->setUsername($billingData['email']);
$customer->setUsernameCanonical($billingData['email']);
$customer->setAcceptInformation(0);
$customer->setAcceptSms(0);
$customer->setAviaturclientid(0);
$customer->setPersonType($personType);
$customer->setPassword(sha1('Default Aviatur'));
$customer->setRoles([]);
try {
$em->persist($customer);
$em->flush();
} catch (\Aviatur\CustomerBundle\Exception\ValidateException $e) {
$mensaje = 'Información incompleta o inconsistente: '.$e->getMessage();
$errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', $mensaje);
return $this->json(['error' => $mensaje]);
}
/* } */
/*
if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $billingData['doc_num'], 'name' => $billingData['first_name'].' '.$billingData['last_name']], $paymentMethod)) {
$errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
return $this->json(['error' => 'sanctions_candidate']);
}
*/
/* if ($login_is_on == '1') {
$session->set('register-extra-data', [
'email' => $billingData["email"],
'documentType' => $doc_type[0],
'documentNumber' => $billingData['doc_num'],
'firstName' => $billingData["first_name"],
'lastName' => $billingData["last_name"],
'gender' => $passangerData["gender_1_1"],
'birthDate' => $passangerData["birthday_1_1"],
'address' => $billingData['address'] != '' ? $billingData['address'] : $passangerData["address_1_1"],
'phone' => $billingData["phone"]
]);
return $this->json(array("error" => "redirect_to_register"));
} */
$return = [
'id' => $customer->getId(),
];
return $this->json($return);
} else {
$errorHandler->errorRedirect('/vuelos/detalle', '', 'Ha ocurrido un error en la consulta de usuarios por email');
return $this->json(['error' => 'Ha ocurrido un error en la consulta de usuarios por email']);
}
}
}
public function loginSelectAction(Request $request, AviaturWebService $webService, RouterInterface $router, ParameterBagInterface $parameterBag)
{
$email = $request->request->get('email');
$em = $this->getDoctrine()->getManager();
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneBy(['email' => $email]);
$enabled = false;
$session = new Session();
$session->set('AnonymousEmail', $email);
if (!empty($customer)) {
if (false == $customer->getEnabled()) {
return $this->redirect($this->generateUrl('aviatur_password_create_nocheck'));
} else {
$route = $router->match($this->generateUrl('fos_user_security_login'));
return $this->forward($route['_controller'], $route);
}
} else {
$customerModel = new CustomerModel();
$xmlRequest = $customerModel->getXmlFindUserByEmail($email, 4);
$response = $webService->busWebServiceAmadeus('GENERALLAVE', $parameterBag->get('provider_service'), $xmlRequest);
if (!is_object($response)) {
return $this->redirect($this->generateUrl('fos_user_registration_register'));
} elseif (('FALLO' == $response->RESULTADO)) {
return $this->redirect($this->generateUrl('fos_user_registration_register'));
} else {
$customer = new Customer();
$dataNumber = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneBy(['code' => $response->document->id]);
$dataGender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneBy(['code' => $response->gender->id]);
$dataMaritalStatus = $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneBy(['code' => $response->marital_starus->id]);
$dataCity = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneBy(['code' => $response->city->id]);
$dataCountry = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneBy(['code' => $response->country->id]);
$customer->setAviaturclientid((int) $response->id);
$customer->setDocumentType($dataNumber);
$customer->setCivilStatus($dataMaritalStatus);
$customer->setGenderAviatur($dataGender);
$customer->setCity($dataCity);
$customer->setCountry($dataCountry);
$customer->setDocumentnumber($response->document->number);
$customer->setFirstname($response->name);
$customer->setLastname($response->last_name);
$customer->setBirthdate(new \DateTime($response->birth_date));
$customer->setAddress($response->address);
$customer->setPhone($response->phone_number);
$customer->setCellphone($response->mobile_phone_number);
$customer->setEmail($response->email);
$customer->setEmailCanonical($response->email);
$customer->setUsername($response->email);
$customer->setUsernameCanonical($response->email);
$customer->setPassword($response->password);
$customer->setAcceptInformation(0);
$customer->setAcceptSms(0);
$customer->setPersonType(8);
$customer->setFrecuencySms(0);
$customer->setCorporateId('');
$customer->setCorporateName('');
$customer->setEnabled(1);
$customer->setRoles([]);
$emo = $this->getDoctrine()->getManager();
$emo->persist($customer);
$emo->flush();
$route = $router->match($this->generateUrl('fos_user_security_login'));
return $this->forward($route['_controller'], $route);
}
}
}
public function getCustomerCardsAction(Request $request, TokenStorageInterface $tokenStorage, CustomerMethodPaymentService $methodPaymentService)
{
if ($request->isXmlHttpRequest()) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $methodPaymentService->getMethodsByCustomer($customerLogin, false);
if ('NoInfo' !== $infoMethodPaymentByClient['info']) {
return $this->json(['info' => 'customer_with_methods_saved', 'info' => $infoMethodPaymentByClient['info']]);
}
return $this->json(['error' => 'no-data']);
}
return $this->json(['error']);
}
public function passwordCreateAction(TwigFolder $twigFolder)
{
$agencyFolder = $twigFolder->twigFlux();
$response = $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/create-password.html.twig'), []);
return $response;
}
public function passwordRessetAction(TwigFolder $twigFolder)
{
$agencyFolder = $twigFolder->twigFlux();
$response = $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/resset-password.html.twig'), []);
return $response;
}
public function customerAccountAction(AviaturErrorHandler $errorHandler, TwigFolder $twigFolder, TokenStorageInterface $tokenStorage, CustomerMethodPaymentService $methodPaymentService, AviaturLoginService $loginService)
{
$agencyFolder = $twigFolder->twigFlux();
$em = $this->getDoctrine()->getManager();
//var_dump($tokenStorage->getToken()->getUser());die;
if (is_object($tokenStorage->getToken()->getUser())) {
$userLogged = $tokenStorage->getToken()->getUser()->getId();
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado'));
}
$customer = $this->getUser();
$infoMethodPaymentByClient = $methodPaymentService->getMethodsByCustomer($customer, false);
if ($infoMethodPaymentByClient) {
$cardSaved = [];
if (false !== $loginService->validActiveSession()) {
if ('NoInfo' !== $infoMethodPaymentByClient['info']) {
foreach ($infoMethodPaymentByClient['info'] as $key => $value) {
$cardSaved['info'][] = [substr($key, 0, 2), substr($key, 2, 4)];
}
}
}
}
$billingList = $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
if ($billingList) {
$dataBilling = [];
$count = 0;
foreach ($billingList as $billings) {
if ('ACTIVE' == $billings->getStatus()) {
$dataBilling[$count]['id'] = $billings->getId();
$dataBilling[$count]['customerId'] = $userLogged;
$dataBilling[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
$dataBilling[$count]['documentNumber'] = $billings->getDocumentnumber();
$dataBilling[$count]['firstname'] = $billings->getFirstname();
$dataBilling[$count]['lastname'] = $billings->getLastname();
$dataBilling[$count]['email'] = $billings->getEmail();
$dataBilling[$count]['address'] = $billings->getAddress();
$dataBilling[$count]['phone'] = $billings->getPhone();
++$count;
}
}
}
$newsletter = new Newsletter();
$newsletterForm = $this->createForm(\Aviatur\FormBundle\Form\NewsletterAsyncType::class, $newsletter);
$data = [
'cards' => !empty($cardSaved) ? $cardSaved : null,
'billings' => !empty($dataBilling) ? $dataBilling : null,
'newsletter_form' => $newsletterForm->createView(),
];
$response = $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-account.html.twig'), $data);
return $response;
}
public function getBillingsAjaxAction(TokenStorageInterface $tokenStorage)
{
$userLogged = $tokenStorage->getToken()->getUser()->getId();
$em = $this->getDoctrine()->getManager();
$billingList = $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
if ($billingList) {
$dataBilling = [];
$count = 0;
foreach ($billingList as $billings) {
if ('ACTIVE' == $billings->getStatus()) {
$dataBilling[$count]['id'] = $billings->getId();
$dataBilling[$count]['customerId'] = $userLogged;
$dataBilling[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
$dataBilling[$count]['documentNumber'] = $billings->getDocumentnumber();
$dataBilling[$count]['firstname'] = $billings->getFirstname();
$dataBilling[$count]['lastname'] = $billings->getLastname();
$dataBilling[$count]['email'] = $billings->getEmail();
$dataBilling[$count]['address'] = $billings->getAddress();
$dataBilling[$count]['phone'] = $billings->getPhone();
$dataBilling[$count]['country'] = $billings->getCountry()->getId();
$dataBilling[$count]['city'] = $billings->getCity()->getId();
++$count;
}
}
return $this->json(['status' => 'success', 'data' => ['billings' => !empty($dataBilling) ? $dataBilling : null, 'totalBillings' => $count]]);
} else {
return $this->json(['status' => 'error']);
}
}
public function customerBookingAction(SessionInterface $session, AviaturEncoder $aviaturEncoder, TwigFolder $twigFolder, TokenStorageInterface $tokenStorage)
{
$customer = $tokenStorage->getToken()->getUser();
$em = $this->getDoctrine()->getManager();
$orderProducts = [];
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$agencyOrderProducts = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer, $agency);
$orderProducts = \array_merge($orderProducts, $agencyOrderProducts);
if ('aviatur.com' == $agency->getDomain()) {
$metasearch = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1); //Metasearch
$metaOrderProducts = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer, $metasearch);
$orderProducts = \array_merge($orderProducts, $metaOrderProducts);
$mobile = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(102); //Mobile
$mobileOrderProducts = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer, $mobile);
$orderProducts = \array_merge($orderProducts, $mobileOrderProducts);
}
$payRequests = [];
$orders = [];
foreach ($orderProducts as $key => $orderProduct) {
$productRequestString = $aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey());
$productResponseString = $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
$productRequest = json_decode($productRequestString, true);
$productResponse = json_decode($productResponseString, true);
if(!is_array($productRequest)){
continue;
}
$productRequest['orderId'] = 'ON'.$orderProduct->getOrder()->getId();
if (isset($productRequest['x_amount'])) {
$productRequest['x_payment_type'] = 'p2p';
$productRequest['x_transaction_date'] = $productResponse['x_transaction_date'] ?? '';
$productRequest['x_response_code'] = $productResponse['x_response_code'] ?? '';
$productRequest['x_response_reason_code'] = $productResponse['x_response_reason_code'] ?? '';
$productRequest['x_response_reason_text'] = isset($productResponse['x_response_reason_text']) ? utf8_decode($productResponse['x_response_reason_text']) : '';
$productRequest['x_ta_response_reason_code'] = $productResponse['x_ta_response_reason_code'] ?? '--';
$productRequest['x_approval_code'] = $productResponse['x_approval_code'] ?? '';
$productRequest['x_ta_approval_code'] = $productResponse['x_ta_approval_code'] ?? '--';
$productRequest['x_transaction_id'] = $productResponse['x_transaction_id'] ?? '--';
$productRequest['x_ta_transaction_id'] = $productResponse['x_ta_transaction_id'] ?? '--';
$payRequests[] = $productRequest;
$orders['ON'.$orderProduct->getOrder()->getId()] = null;
} elseif (isset($productRequest['totalAmount']) && isset($productResponse['getTransactionInformationResult'])) {
$productRequest['x_payment_type'] = 'pse';
$productRequest['x_invoice_num'] = $productRequest['reference'];
$productRequest['x_description'] = $productRequest['description'];
$productRequest['x_currency_code'] = $productRequest['currency'];
$productRequest['x_amount'] = $productRequest['totalAmount'];
$productRequest['x_tax'] = $productRequest['taxAmount'];
$productRequest['x_amount_base'] = $productRequest['devolutionBase'];
$productRequest['x_transaction_date'] = $productResponse['getTransactionInformationResult']['requestDate'] ?? '';
$productRequest['x_response_code'] = $productResponse['getTransactionInformationResult']['responseCode'] ?? '';
$productRequest['x_response_reason_code'] = $productResponse['getTransactionInformationResult']['responseReasonCode'] ?? '';
$productRequest['x_response_reason_text'] = $productResponse['getTransactionInformationResult']['responseReasonText'] ?? '';
$productRequest['x_approval_code'] = $productResponse['getTransactionInformationResult']['trazabilityCode'] ?? '';
$productRequest['x_transaction_id'] = $productResponse['getTransactionInformationResult']['transactionID'] ?? '';
$payRequests[] = $productRequest;
$orders['ON'.$orderProduct->getOrder()->getId()] = null;
} elseif (isset($productRequest['notificationRequest']) && isset($productResponse['payResponse'])) {
$productRequest['x_payment_type'] = 'safetypay';
$productRequest['x_invoice_num'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:MerchantSalesID'];
$productRequest['x_description'] = @$productRequest['dataTransf']['x_description'];
$productRequest['x_currency_code'] = @$productRequest['dataTransf']['x_currency'];
$productRequest['x_amount'] = @$productRequest['dataTransf']['x_total_amount'];
$productRequest['x_tax'] = @$productRequest['dataTransf']['x_tax_amount'];
$productRequest['x_airport_tax'] = 0;
$productRequest['x_service_fee_tax'] = 0;
$productRequest['x_airport_tax'] = 0;
$productRequest['x_airport_tax'] = 0;
$productRequest['x_amount_base'] = @$productRequest['dataTransf']['x_devolution_base'];
$productRequest['x_transaction_date'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:RequestDateTime'];
$productRequest['x_response_reason_code'] = @$productResponse['dataTransf']['x_response_code'];
switch ($productRequest['x_response_reason_code']) {
case 101:
$productRequest['x_response_code'] = 3;
break;
case 100:
$productRequest['x_response_code'] = 2;
break;
case null:
$productRequest['x_response_code'] = 3;
break;
default:
$productRequest['x_response_code'] = 1;
break;
}
$productRequest['x_response_reason_text'] = @$productResponse['dataTransf']['x_response_reason_text'];
$productRequest['x_approval_code'] = 'N/A';
$productRequest['x_transaction_id'] = 'N/A';
$payRequests[] = $productRequest;
$orders['ON'.$orderProduct->getOrder()->getId()] = null;
}
$historicalOrderProducts = $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalOrderProduct::class)->findByOrderProduct($orderProduct);
if (0 != sizeof($historicalOrderProducts)) {
foreach ($historicalOrderProducts as $historicalOrderProduct) {
$productRequest = $aviaturEncoder->AviaturDecode($historicalOrderProduct->getPayrequest(), $historicalOrderProduct->getPublickey());
$productResponse = $aviaturEncoder->AviaturDecode($historicalOrderProduct->getPayresponse(), $historicalOrderProduct->getPublickey());
$productRequest = json_decode($productRequest, true);
$productResponse = json_decode($productResponse, true);
if (isset($productRequest['x_amount'])) {
$productRequest['x_payment_type'] = 'p2p';
$productRequest['x_transaction_date'] = $productResponse['x_transaction_date'] ?? '';
$productRequest['x_response_code'] = $productResponse['x_response_code'] ?? '';
$productRequest['x_response_reason_code'] = $productResponse['x_response_reason_code'] ?? '';
$productRequest['x_response_reason_text'] = isset($productResponse['x_response_reason_text']) ? utf8_decode($productResponse['x_response_reason_text']) : '';
$productRequest['x_ta_response_reason_code'] = $productResponse['x_ta_response_reason_code'] ?? '';
$productRequest['x_approval_code'] = $productResponse['x_approval_code'] ?? '';
$productRequest['x_ta_approval_code'] = $productResponse['x_ta_approval_code'] ?? '';
$productRequest['x_transaction_id'] = $productResponse['x_transaction_id'] ?? '';
$productRequest['x_ta_transaction_id'] = $productResponse['x_ta_transaction_id'] ?? '';
$payRequests[sizeof($payRequests) - 1]['history'][] = $productRequest;
} elseif (isset($productRequest['totalAmount']) && isset($productResponse['getTransactionInformationResult'])) {
$productRequest['x_payment_type'] = 'pse';
$productRequest['x_invoice_num'] = $productRequest['reference'];
$productRequest['x_description'] = $productRequest['description'];
$productRequest['x_currency_code'] = $productRequest['currency'];
$productRequest['x_amount'] = $productRequest['totalAmount'];
$productRequest['x_tax'] = $productRequest['taxAmount'];
$productRequest['x_amount_base'] = $productRequest['devolutionBase'];
$productRequest['x_transaction_date'] = $productResponse['getTransactionInformationResult']['requestDate'] ?? '';
$productRequest['x_response_code'] = $productResponse['getTransactionInformationResult']['responseCode'];
$productRequest['x_response_reason_code'] = $productResponse['getTransactionInformationResult']['responseReasonCode'];
$productRequest['x_response_reason_text'] = utf8_decode($productResponse['getTransactionInformationResult']['responseReasonText']);
$productRequest['x_approval_code'] = $productResponse['getTransactionInformationResult']['trazabilityCode'] ?? '';
$productRequest['x_transaction_id'] = $productResponse['getTransactionInformationResult']['transactionID'] ?? '';
$payRequests[sizeof($payRequests) - 1]['history'][] = $productRequest;
} elseif (isset($productRequest['notificationRequest']) && isset($productResponse['payResponse'])) {
$productRequest['x_payment_type'] = 'safetypay';
$productRequest['x_invoice_num'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:MerchantSalesID'];
$productRequest['x_description'] = @$productRequest['dataTransf']['x_description'];
$productRequest['x_currency_code'] = @$productRequest['dataTransf']['x_currency'];
$productRequest['x_amount'] = @$productRequest['dataTransf']['x_total_amount'];
$productRequest['x_tax'] = @$productRequest['dataTransf']['x_tax_amount'];
$productRequest['x_airport_tax'] = 0;
$productRequest['x_service_fee_tax'] = 0;
$productRequest['x_amount_base'] = @$productRequest['dataTransf']['x_devolution_base'];
$productRequest['x_transaction_date'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:RequestDateTime'];
$productRequest['x_response_code'] = 'N/A'; //$productResponse['getTransactionInformationResult']['responseCode'];
$productRequest['x_response_reason_code'] = 'N/A'; //$productResponse['getTransactionInformationResult']['responseReasonCode'];
$productRequest['x_response_reason_text'] = 'N/A'; //$productResponse['getTransactionInformationResult']['responseReasonText'];
$productRequest['x_approval_code'] = 'N/A'; //$productResponse['getTransactionInformationResult']['trazabilityCode'];
$productRequest['x_transaction_id'] = 'N/A'; //$productResponse['getTransactionInformationResult']['transactionID'];
$payRequests[sizeof($payRequests) - 1]['history'][] = $productRequest;
}
}
}
// var_dump($productResponse);
// CREATE THE PUBLIC KEY AND ENCODE PayRequest AND PayResponse
// $encodedRequest = $this->get("aviatur_md5")->AviaturEncode($orderProduct->getPayRequest(), $orderProduct->getPublicKey());
// $encodedResponse = $this->get("aviatur_md5")->AviaturEncode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
// $publicKey = $this->get("aviatur_md5")->aviaturRandomKey();
// $orderProduct->setPayRequest($encodedRequest);
// $orderProduct->setPayResponse($encodedResponse);
// $orderProduct->setPublicKey($publicKey);
// $em = $this->getDoctrine()->getManager();
// $em->persist($orderProduct);
// $em->flush();
}
$agencyFolder = $twigFolder->twigFlux();
$twigView = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-booking.html.twig');
return $this->render($twigView, ['payRequests' => $payRequests, 'orders' => $orders]);
}
public function editAction(Request $request, SessionInterface $session, AviaturWebService $webService, TwigFolder $twigFolder, UserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailer, AviaturErrorHandler $errorHandler, TokenStorageInterface $tokenStorage, ValidatorInterface $validator, ParameterBagInterface $parameterBag)
{
$providerService = $parameterBag->get('provider_service');
$emailNotification = $parameterBag->get('email_notification');
$em = $this->getDoctrine()->getManager();
$agencyFolder = $twigFolder->twigFlux();
$user = $tokenStorage->getToken()->getUser();
if (false === is_object($user)) {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado'));
}
$id = $user->getId();
$post = $request->request->get('customer_edit_form');
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($id);
$city = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry($customer->getCountry()->getId(), ['description' => 'ASC']);
$email = $customer->getEmail();
foreach ($city as $infocities) {
$idCity[] = $infocities->getCode();
$nameCity[] = $infocities->getDescription();
}
$info = ['idCity' => $idCity, 'nameCity' => $nameCity];
$form = $this->createForm(\Aviatur\CustomerBundle\Form\CustomerEdit::class, $customer);
$method = 'edition';
$date = new DateTime();
$form->handleRequest($request);
if ($form->isSubmitted()) {
$historical = (object) [
'Firstname' => $customer->getFirstname(),
'Documentnumber' => $customer->getDocumentnumber(),
'DocumentType' => $customer->getDocumentType()->getCode(),
'Lastname' => $customer->getLastname(),
'Birthdate' => $customer->getBirthdate(),
'Address' => $customer->getAddress(),
'Phone' => $customer->getPhone(),
'Cellphone' => $customer->getCellphone(),
'Email' => $customer->getEmail(),
'Password' => $customer->getPassword(),
'Username' => $customer->getUsername(),
'UsernameCanonical' => $customer->getUsernameCanonical(),
'EmailCanonical' => $customer->getEmailCanonical(),
'Enabled' => $customer->getEnabled(),
'Salt' => $customer->getSalt(),
'country_id' => $customer->getCountry()->getCode(),
//'CreatedAt' => $customer->getCreatedAt(),
//'UpdatedAt' => $date,
'CustomerId' => $customer->getId(),
];
if ($form->isValid()) {
$userchange = $this->getCustomerInfo($request, $session, $parameterBag, $webService, $twigFolder, $passwordEncoder, $mailer, $customer, $post, $method, $email);
$this->historicalCustomer($historical, $post, $em, null, $customer);
return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_customer_edit_info', ['cityId' => $customer->getCity()->getId(), 'city' => $customer->getCity()->getId(), 'id' => $id]), 'Actualizar Datos', $userchange));
} else {
$errors = $validator->validate($customer);
$datos = ['cityId' => $customer->getCity()->getId(), 'city' => $customer->getCity()->getCode(), 'info' => $info, 'form' => $form->createView(), 'errors' => $errors];
return $this->render($twigFolder->twigExists('@AviaturTwig'.$agencyFolder.'/Customer/Customer/customer-edition.html.twig'), $datos);
}
} else {
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-edition.html.twig'), ['cityId' => $customer->getCity()->getId(), 'city' => $customer->getCity()->getCode(), 'info' => $info, 'form' => $form->createView()]);
}
}
public function resetPasswordAction(Request $request, SessionInterface $session, AviaturWebService $webService, AviaturErrorHandler $errorHandler, TokenStorageInterface $tokenStorage, TwigFolder $twigFolder, UserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailer, ParameterBagInterface $parameterBag)
{
$providerService = $parameterBag->get('provider_service');
$emailNotification = $parameterBag->get('email_notification');
$post = [];
$em = $this->getDoctrine()->getManager();
$agencyFolder = $twigFolder->twigFlux();
$id = $tokenStorage->getToken()->getUser();
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($id);
$post_form = $request->request->get('customer_edit_form');
$method = 'password';
$CivilStatus = '';
if ($customer->getCivilStatus()) {
$CivilStatus = $customer->getCivilStatus()->getId();
}
$date = new DateTime();
$historical = (object) [
'Firstname' => $customer->getFirstname(),
'Documentnumber' => $customer->getDocumentnumber(),
'DocumentType' => $customer->getDocumentType()->getCode(),
'Lastname' => $customer->getLastname(),
'Birthdate' => $customer->getBirthdate(),
'Address' => $customer->getAddress(),
'Phone' => $customer->getPhone(),
'Cellphone' => $customer->getCellphone(),
'Email' => $customer->getEmail(),
'Password' => $customer->getPassword(),
'Username' => $customer->getUsername(),
'UsernameCanonical' => $customer->getUsernameCanonical(),
'EmailCanonical' => $customer->getEmailCanonical(),
'Enabled' => $customer->getEnabled(),
'Salt' => $customer->getSalt(),
'country_id' => $customer->getCountry()->getCode(),
//'CreatedAt' => $customer->getCreatedAt(),
//'UpdatedAt' => $date,
'CustomerId' => $customer->getId(),
];
if ('POST' == $request->getMethod()) {
$post['Firstname'] = $customer->getFirstname();
$post['lastname'] = $customer->getLastname();
$post['birthdate'] = $customer->getBirthdate()->format('Y-m-d');
$post['address'] = $customer->getAddress();
$post['phone'] = $customer->getPhone();
$post['cellphone'] = $customer->getCellphone();
$post['email'] = $customer->getEmail();
$post['city'] = $customer->getCity()->getId();
$post['country'] = $customer->getCountry()->getId();
$post['CivilStatus'] = $CivilStatus;
$post['aviaturclientid'] = $customer->getAviaturclientid();
$post['DocumentNumber'] = $customer->getDocumentnumber();
$post['genderAviatur'] = $customer->getFirstname();
$post['acceptInformation'] = $customer->getAcceptInformation();
$post['acceptSms'] = $customer->getAcceptSms();
$post['password_last'] = $post_form['password_last'];
$post['password_new'] = $post_form['password_new'];
$post['password_repeat'] = $post_form['password_repeat'];
$userchange = $this->getCustomerInfo($request, $session, $parameterBag, $webService, $twigFolder, $passwordEncoder, $mailer, $customer, $post, $method);
$this->historicalCustomer($historical, $post, $em, null, $customer);
return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_customer_edit_info', ['id' => $id]), 'Actualizar Datos', $userchange));
} else {
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/reset-password-user.html.twig'));
}
}
public function historicalCustomer($customer, $post, $doctrine, $asessor, $newData = null)
{
$em = !empty($doctrine) ? $doctrine : $this->getDoctrine()->getManager();
$country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneById($post['country']);
$country_id = $country->getCode();
$json = '{"fields":[';
$json_modfied_fields = null;
//Guardamos los datos antiguos en la tabla historical_customer
$historicalCustomer = new HistoricalCustomer();
//$historicalCustomer->setAviaturclientid($customer->getAviaturclientid());
$historicalCustomer->setDocumentnumber($customer->Documentnumber);
if ($customer->Documentnumber != $newData->getDocumentnumber()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Documentnumber"';
} else {
$json_modfied_fields = '"Documentnumber"';
}
}
$historicalCustomer->setDocumentTypeId($customer->DocumentType);
if ($customer->DocumentType != $newData->getDocumentType()->getCode()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"DocumentType"';
} else {
$json_modfied_fields = '"DocumentType"';
}
}
$historicalCustomer->setFirstname($customer->Firstname);
if ($customer->Firstname != $newData->getFirstname()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Firstname"';
} else {
$json_modfied_fields = '"Firstname"';
}
}
$historicalCustomer->setLastname($customer->Lastname);
if ($customer->Lastname != $newData->getLastname()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Lastname"';
} else {
$json_modfied_fields = '"Lastname"';
}
}
$historicalCustomer->setBirthdate($customer->Birthdate);
if ($customer->Birthdate != $newData->getBirthdate()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Birthdate"';
} else {
$json_modfied_fields = '"Birthdate"';
}
}
$historicalCustomer->setAddress($customer->Address);
if ($customer->Address != $newData->getAddress()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Address"';
} else {
$json_modfied_fields = '"Address"';
}
}
$historicalCustomer->setPhone($customer->Phone);
if ($customer->Phone != $newData->getPhone()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Phone"';
} else {
$json_modfied_fields = '"Phone"';
}
}
$historicalCustomer->setCellphone($customer->Cellphone);
if ($customer->Cellphone != $newData->getCellphone()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Cellphone"';
} else {
$json_modfied_fields = '"Cellphone"';
}
}
$historicalCustomer->setEmail($customer->Email);
if ($customer->Email != $newData->getEmail()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Email"';
} else {
$json_modfied_fields = '"Email"';
}
}
$historicalCustomer->setPassword($customer->Password);
if ($customer->Password != $newData->getPassword()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Password"';
} else {
$json_modfied_fields = '"Password"';
}
}
$historicalCustomer->setUsername($customer->Username);
if ($customer->Username != $newData->getUsername()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Username"';
} else {
$json_modfied_fields = '"Username"';
}
}
$historicalCustomer->setUsernameCanonical($customer->UsernameCanonical);
if ($customer->UsernameCanonical != $newData->getUsernameCanonical()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"UsernameCanonical"';
} else {
$json_modfied_fields = '"UsernameCanonical"';
}
}
$historicalCustomer->setEmailCanonical((string) $customer->EmailCanonical);
if ($customer->EmailCanonical != $newData->getEmailCanonical()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"EmailCanonical"';
} else {
$json_modfied_fields = '"EmailCanonical"';
}
}
$historicalCustomer->setEnabled($customer->Enabled);
$historicalCustomer->setSalt($customer->Salt);
if ($customer->Salt != $newData->getSalt()) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"Salt"';
} else {
$json_modfied_fields = '"Salt"';
}
}
$historicalCustomer->setCityId($customer->country_id);
if ($customer->country_id != $country_id) {
if (isset($json_modfied_fields)) {
$json_modfied_fields = $json_modfied_fields.',"country_id"';
} else {
$json_modfied_fields = '"country_id"';
}
}
//$historicalCustomer->setCreatedAt($customer->CreatedAt);
//$historicalCustomer->setUpdatedAt($customer->UpdatedAt);
if (isset($asessor) && null != $asessor) {
$historicalCustomer->setAsessorID($asessor->getid());
$historicalCustomer->setAsessorEmail($asessor->getemail());
}
//$historicalCustomer->setLocale($customer->getLocale());
//$historicalCustomer->setTimezone($customer->getTimezone());
$historicalCustomer->setCustomerid($customer->CustomerId);
$historicalCustomer->setIpAddres($_SERVER['REMOTE_ADDR']);
if (isset($json_modfied_fields)) {
$json = $json.$json_modfied_fields.']}';
$historicalCustomer->setModifiedfields($json);
// var_dump($json);die;
try {
// var_dump($historicalCustomer);die;
$em->persist($historicalCustomer);
$em->flush();
} catch (\Exception $e) {
}
}
//////////////////////////////////////////////////////////////
}
public function getCustomerInfo(Request $request, SessionInterface $session, ParameterBagInterface $parameterBag, AviaturWebService $webService, TwigFolder $twigFolder, UserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailer, $customer, $post, $method, $email = null, $doctrine = null, $asessor = null)
{
$em = $this->getDoctrine()->getManager();
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$providerService = $parameterBag->get('provider_service');
$emailNotification = $parameterBag->get('email_notification');
$passwordEncode = null;
$passwordUser = null;
$newPassword = null;
$repeatPassword = null;
$mensaje = null;
//var_dump($customer);die();
$em = !empty($doctrine) ? $doctrine : $this->getDoctrine()->getManager();
$fullRequest = $request;
$agencyFolder = $twigFolder->twigFlux();
//Get city code in database clientes web
$city = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneById($post['city']);
$city_id = $city->getCode();
$Lastcustomer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneByEmail($post['email']);
//Get country code in database clientes web
$country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneById($post['country']);
$country_id = $country->getCode();
$customer->setFirstname($post['Firstname']);
$customer->setLastname($post['lastname']);
$customer->setBirthdate(new \DateTime($post['birthdate']));
$customer->setAddress($post['address']);
$customer->setPhone($post['phone']);
$customer->setCellphone($post['cellphone']);
//$customer->setEmail($post['email']);
//$customer->setUsername($post['email']);
//Get document id code in database clientes web
$document = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneById($customer->getDocumentType()->getId());
$document_type_id = $document->getCode();
if (4877 == $document_type_id || 11 == $document_type_id) {
// if document_type_id == NIT or NIT international
$person_type_id = 7;
} else {
$person_type_id = 8;
}
//Get civil status code in database clientes web
$civilStatus = $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneById($post['CivilStatus']);
if (isset($civilStatus)) {
$marital_status_id = $civilStatus->getCode();
} else {
$marital_status_id = '';
}
$client_id = $post['aviaturclientid'];
$document_number = $post['DocumentNumber'];
if ('password' == $method) {
$passwordEncode = $passwordEncoder->encodePassword($customer, $post['password_last']);
$newPassword = $post['password_new'];
$repeatPassword = $post['password_repeat'];
$passwordUser = $customer->getPassword();
$password = $passwordEncoder->encodePassword($customer, $post['password_new']);
} else {
$password = $customer->getPassword();
}
$corporate_name = $customer->getFirstname();
$gender = $post['genderAviatur'];
if (1 == $gender) {
$gender_id = 334;
} else {
$gender_id = 335;
}
$state_id = 0;
$season_id = 1;
$sms_frequency_id = $customer->getFrecuencySms();
$info = [
'client_id' => $client_id,
'person_type_id' => $person_type_id,
'corporate_name' => $post['Firstname'],
'corporate_id' => $post['DocumentNumber'],
'name' => $post['Firstname'],
'last_name' => $post['lastname'],
'document_type_id' => $document_type_id,
'document_number' => $document_number,
'gender_id' => $gender_id,
'marital_status_id' => $marital_status_id,
'birth_date' => $post['birthdate'],
'country_id' => $country_id,
'state_id' => $state_id,
'city_id' => $city_id,
'address' => $post['address'],
'phone_number' => $post['phone'],
'mobile_phone_number' => $post['cellphone'],
'password' => $password,
'season_id' => '',
'class_trip_id' => 0,
'accept_information' => $post['acceptInformation'],
'accept_sms' => $post['acceptSms'],
'status_id' => 1,
];
if ($post['email'] != $customer->getUsername()) {
$info['email'] = $customer->getUsername();
} else {
$info['email'] = $post['email'];
}
//Consulting Id user to modify
$customerModel = new CustomerModel();
$xmlRequest = $customerModel->getXmlEditUser($info, 2);
//Modify User into database
if ('password' == $method) {
if ($passwordEncode != $passwordUser) {
$mensaje = 'El Campo Contraseña Anterior no corresponse a la asignada al usuario '.$customer->getEmail();
} elseif ($newPassword != $repeatPassword) {
$mensaje = 'Los Campos Ingresados No son Iguales, por favor Validar.';
} else {
$customer->setPassword($password);
//$em->persist($customer);
$em->flush();
$mensaje = 'La Contraseña del usuario '.$customer->getEmail().' se ha Modificado Correctamente';
$response = $webService->busWebServiceAmadeus('GENERALLAVE', $providerService, $xmlRequest);
}
} else {
if ((is_countable($Lastcustomer) ? count($Lastcustomer) : 0) > 0 && $email != $Lastcustomer->getEmail()) {
$mensaje = 'El Correo '.$customer->getEmail().' ya se encuentra registrado con otro Usuario';
} else {
try {
if ($post['email'] != $customer->getUsername()) {
$customer->setEmail($post['email']);
$customer->setUsername($post['email']);
$customer->setEmailCanonical($post['email']);
$tokenTemp = bin2hex(random_bytes(64));
$customer->setTempEmail($post['email']);
$customer->setTempEmailToken($tokenTemp);
$customer->setEmail($email);
$customer->setUsername($email);
if ($agency->getAssetsFolder() == 'octopus') {
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($email)
->setSubject('Octopus: Confirmación de Cambios en Tu Correo Electrónico')
->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Customer/Customer/customer-edition-email.html.twig'), [
'nameCustomer' => $post['Firstname'],
'tokenTemp' => $tokenTemp,
'idCustomer' => $customer->getId(),
]), 'text/html');
} else {
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($post['email'])
->setSubject('Cambio de email')
->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Customer/Customer/customer-edition-email.html.twig'), [
'nameCustomer' => $post['Firstname'],
'tokenTemp' => $tokenTemp,
'idCustomer' => $customer->getId(),
]), 'text/html');
}
$em->persist($customer);
$em->flush();
$mailer->send($messageEmail);
$mensaje = 'Hemos enviado un mensaje a su correo actual, por favor confírmenos el cambio.';
} elseif ($post['email'] == $customer->getUsername()) {
$customer->setEmail($post['email']);
$customer->setUsername($post['email']);
$customer->setEmailCanonical($post['email']);
$tokenTemp = bin2hex(random_bytes(64));
$customer->setTempEmail($post['email']);
$customer->setTempEmailToken($tokenTemp);
$customer->setEmail($email);
$customer->setUsername($email);
if ($agency->getAssetsFolder() == 'octopus') {
$mensaje = 'Los datos del agente ' . $customer->getFirstname() . ' ' . $customer->getlastname() . ' se modificaron correctamente';
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($email)
->setSubject('Notificación de Verificación de Datos en Octopus')
->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Customer/Customer/customer-edition-data-notification.html.twig'), [
'nameCustomer' => $post['Firstname'],
'tokenTemp' => $tokenTemp,
'idCustomer' => $customer->getId(),
]), 'text/html');
} else {
$mensaje = 'Los datos del agente ' . $customer->getFirstname() . ' ' . $customer->getlastname() . ' se modificaron correctamente';
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($post['email'])
->setSubject('Notificación')
->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Customer/Customer/customer-edition-email.html.twig'), [
'nameCustomer' => $post['Firstname'],
'tokenTemp' => $tokenTemp,
'idCustomer' => $customer->getId(),
]), 'text/html');
}
$mailer->send($messageEmail);
$em->persist($customer);
$em->flush();
}
if (!isset($doctrine)) {
$response = $webService->busWebServiceAmadeus('GENERALLAVE', $providerService, $xmlRequest);
}
} catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
$mensaje = 'El Correo '.$customer->getEmail().' ya se encuentra registrado con otro Usuario';
} catch (\Aviatur\CustomerBundle\Exception\ValidateException $e) {
$mensaje = 'Información incompleta o inconsistente: '.$e->getMessage();
} catch (\Exception $e) {
$mensaje = 'Se produjo un error al editar los datos, Por favor contactate con nosotros para mejor información.';
}
}
}
if (!isset($response)) {
$mensaje = $mensaje;
} elseif (('FALLO' == $response->RESULTADO)) {
$mailInfo = print_r($info, true).'<br>'.print_r($response, true);
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo('b_botina@aviatur.com', $emailNotification)
->setSubject('Error Al Modificar Usuario en Base de Datos Clientes Web')
->setBody($mailInfo);
$mailer->send($message);
$mensaje = 'Se produjo un error al editar los datos, Por Favor Contactate con Nosotros';
} /* else {
$em->flush();
} */
return $mensaje;
}
public function setNewEmailAction(Request $request, SessionInterface $session, ParameterBagInterface $parameterBag, AviaturWebService $webService, AviaturErrorHandler $errorHandler, \Swift_Mailer $mailer, $customerId, $token)
{
$providerService = $parameterBag->get('provider_service');
$emailNotification = $parameterBag->get('email_notification');
$em = $this->getDoctrine()->getManager();
$fullRequest = $request;
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneById($customerId);
//var_dump($customer);die();
if (!$customer) {
return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), '', 'Ha ocurrido un error'));
}
if ($customerId && $token) {
if (!is_null($customer->getTempEmailToken()) && !is_null($customer->getTempEmail())) {
if ($customerId == $customer->getId() && $token == $customer->getTempEmailToken()) {
$null = null;
$city = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneById($customer->getCity()->getId());
$city_id = $city->getCode();
//Get country code in database clientes web
$country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneById($customer->getCountry()->getId());
$country_id = $country->getCode();
$document = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneById($customer->getDocumentType()->getId());
$document_type_id = $document->getCode();
if (4877 == $document_type_id || 11 == $document_type_id) {
// if document_type_id == NIT or NIT international
$person_type_id = 7;
} else {
$person_type_id = 8;
}
//Get civil status code in database clientes web
$civilStatus = $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneById($customer->getCivilStatus());
if (isset($civilStatus)) {
$marital_status_id = $civilStatus->getCode();
} else {
$marital_status_id = '';
}
//$document_number = $post['DocumentNumber'];
$password = $customer->getPassword();
$corporate_name = $customer->getFirstname();
$gender = $customer->getGenderAviatur()->getCode();
if (1 == $gender) {
$gender_id = 334;
} else {
$gender_id = 335;
}
$state_id = 0;
$season_id = 1;
$sms_frequency_id = $customer->getFrecuencySms();
$info = [
'client_id' => $customer->getAviaturclientid(),
'person_type_id' => $person_type_id,
'corporate_name' => $customer->getFirstname(),
'corporate_id' => $customer->getDocumentnumber(),
'name' => $customer->getFirstname(),
'last_name' => $customer->getLastname(),
'document_type_id' => $document_type_id,
'document_number' => $customer->getDocumentnumber(),
'gender_id' => $gender_id,
'marital_status_id' => $marital_status_id,
'birth_date' => $customer->getBirthdate()->format('Y-m-d'),
'country_id' => $country_id,
'state_id' => $state_id,
'city_id' => $city_id,
'address' => $customer->getAddress(),
'phone_number' => $customer->getPhone(),
'mobile_phone_number' => $customer->getCellphone(),
'password' => $customer->getPassword(),
'season_id' => '',
'class_trip_id' => 0,
'accept_information' => $customer->getAcceptinformation(),
'accept_sms' => $customer->getAcceptsms(),
'status_id' => 1,
'email' => $customer->getTempEmail(),
];
$customerModel = new CustomerModel();
$xmlRequest = $customerModel->getXmlEditUser($info, 2);
$response = $webService->busWebServiceAmadeus('GENERALLAVE', $providerService, $xmlRequest);
if (!isset($response)) {
$mensaje = $mensaje;
} elseif (('FALLO' == $response->RESULTADO)) {
$mailInfo = print_r($info, true).'<br>'.print_r($response, true);
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo('b_botina@aviatur.com', $emailNotification)
->setSubject('Error Al Modificar Usuario en Base de Datos Clientes Web')
->setBody($mailInfo);
$mailer->send($message);
$mensaje = 'Se produjo un error al editar los datos, Por Favor Contactate con Nosotros';
}
$customer->setEmail($customer->getTempEmail());
$customer->setUsername($customer->getTempEmail());
$customer->setEmailCanonical($customer->getTempEmail());
$customer->setTempEmailToken($null);
$customer->setTempEmail($null);
$em->persist($customer);
$em->flush();
return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Felicidades', 'Cambio satifactorio de email'));
} else {
return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Error', 'Ha ocurrido un error'));
}
} else {
return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Error', 'Ha ocurrido un error'));
}
} else {
return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Error', 'Direccion url incorrecta'));
}
}
public function getpaymentMethodsSavedAction(TwigFolder $twigFolder, CustomerMethodPaymentService $methodPaymentService, AviaturLoginService $loginService)
{
$em = $this->getDoctrine()->getManager();
$typeDocument = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$infoSaved = [];
if (false !== $loginService->validActiveSession()) {
$customer = $this->getUser();
$infoMethodPaymentByClient = $methodPaymentService->getMethodsByCustomer($customer, false);
if ('NoInfo' !== $infoMethodPaymentByClient['info']) {
foreach ($infoMethodPaymentByClient['info'] as $key => $value) {
$infoSaved['info'][] = [substr($key, 0, 2), substr($key, 2, 4)];
}
}
}
$infoSaved['doc_type'] = $typeDocument;
$newsletter = new Newsletter();
$newsletterForm = $this->createForm(\Aviatur\FormBundle\Form\NewsletterAsyncType::class, $newsletter);
$infoSaved['newsletter_form'] = $newsletterForm->createView();
$agencyFolder = $twigFolder->twigFlux();
$twigView = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-payments-saved.html.twig');
return $this->render($twigView, $infoSaved);
}
public function saveNewCardAction(Request $request, TokenizerService $tokenizerService, TokenStorageInterface $tokenStorage)
{
if ($request) {
$em = $this->getDoctrine()->getManager();
$customer = $tokenStorage->getToken()->getUser();
$cardNumToken = $tokenizerService->getToken($request->request->get('cardNum'));
$fecha = new \DateTime();
$franchise = $request->request->get('franqui');
$numcard = \substr($request->request->get('cardNum'), -4, 4);
$new_method_payment = [
$franchise.$numcard => [
'token' => $cardNumToken, //['card_num'],
'firstname' => $request->request->get('nombreCard'),
'lastname' => $request->request->get('apellidoCard'),
'datevig' => $request->request->get('cardExp'),
'datecreation' => $fecha->format('Y-m-d H:i:s'),
'typeDocument' => $request->request->get('docType'),
'documentNumber' => $request->request->get('docNum'),
'status' => 'NOTVERIFIED',
],
];
$paymentMethodsCustomer = $em->getRepository(\Aviatur\PaymentBundle\Entity\PaymentMethodCustomer::class)->findBy(['customer' => $customer]);
if (count($paymentMethodsCustomer) > 0) {
$actualInfo = json_decode($paymentMethodsCustomer[0]->getInfoPaymentMethod(), true);
$preExist = array_intersect_key($new_method_payment, $actualInfo);
if (count($preExist) > 0) {
foreach ($preExist as $key => $value) {
$actualInfo[$key]['status'] = 'REPLACED';
$actualInfo[$key.'_'.$fecha->format('YmdHis')] = $actualInfo[$key];
unset($actualInfo[$key]);
}
}
$newInfo = array_merge($actualInfo, $new_method_payment);
$paymentMethodsCustomer[0]->setInfoPaymentMethod(json_encode($newInfo));
} else {
$newMethodObject = new PaymentMethodCustomer();
$newMethodObject->setCustomer($customer);
$newMethodObject->setInfoPaymentMethod(json_encode($new_method_payment));
$newMethodObject->setIsactive(true);
$em->persist($newMethodObject);
}
$em->flush();
return $this->json(['status' => 'success']);
}
}
public function setMethodsByCustomer($customer, $infoCard)
{
$fecha = new \DateTime();
$franchise = $infoCard['franqui'];
$numcard = \substr($infoCard['cardNum'], -4, 4);
$new_method_payment = [
$franchise.$numcard => [
'token' => $infoCard['cardNum'], //['card_num'],
'firstname' => $infoCard['nombreCard'],
'lastname' => $infoCard['apellidoCard'],
'datevig' => $infoCard['cardExp'],
'datecreation' => $fecha->format('Y-m-d H:i:s'),
'typeDocument' => $infoCard['docType'],
'documentNumber' => $infoCard['docNum'],
'status' => 'NOTVERIFIED',
],
];
$paymentMethodsCustomer = $this->em->getRepository(\Aviatur\PaymentBundle\Entity\PaymentMethodCustomer::class)->findBy(['customer' => $customer]);
if ((is_countable($paymentMethodsCustomer) ? count($paymentMethodsCustomer) : 0) > 0) {
$actualInfo = json_decode($paymentMethodsCustomer[0]->getInfoPaymentMethod(), true);
$preExist = array_intersect_key($new_method_payment, $actualInfo);
if (count($preExist) > 0) {
foreach ($preExist as $key => $value) {
$actualInfo[$key]['status'] = 'REPLACED';
$actualInfo[$key.'_'.$fecha->format('YmdHis')] = $actualInfo[$key];
unset($actualInfo[$key]);
}
}
$newInfo = array_merge($actualInfo, $new_method_payment);
$paymentMethodsCustomer[0]->setInfoPaymentMethod(json_encode($newInfo));
} else {
$newMethodObject = new PaymentMethodCustomer();
$newMethodObject->setCustomer($customer);
$newMethodObject->setInfoPaymentMethod(json_encode($new_method_payment));
$newMethodObject->setIsactive(true);
$this->em->persist($newMethodObject);
}
$this->em->flush();
}
public function deletePaymentsSavedAction(Request $request, CustomerMethodPaymentService $methodPaymentService, AviaturErrorHandler $errorHandler)
{
$cardKey = $request->request->get('keycardtodelete');
$customer = $this->getUser();
$methodPaymentService->deleteMethodsByCustomer($customer, $cardKey);
$redirectRoute = 'aviatur_customer_show_saved_pay_info';
return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl($redirectRoute), 'Información actualizada', 'Se actualizaron los medios de pago almacenados'));
}
public function deleteCardSavedAjaxAction(Request $request, CustomerMethodPaymentService $methodPaymentService)
{
$cardKey = $request->request->get('key');
$customer = $this->getUser();
$methodPaymentService->deleteMethodsByCustomer($customer, $cardKey);
return $this->json(['status' => 'success']);
}
public function billingViewAction(TwigFolder $twigFolder, TokenStorageInterface $tokenStorage)
{
$agencyFolder = $twigFolder->twigFlux();
$em = $this->getDoctrine()->getManager();
$userLogged = $tokenStorage->getToken()->getUser()->getId();
$billingList = $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
//var_dump($billingList);die();
$typeDocument = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
if ($billingList) {
$data = [];
$count = 0;
foreach ($billingList as $billings) {
if ('ACTIVE' == $billings->getStatus()) {
$data[$count]['id'] = $billings->getId();
$data[$count]['customerId'] = $userLogged;
$data[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
$data[$count]['documentNumber'] = $billings->getDocumentnumber();
$data[$count]['firstname'] = $billings->getFirstname();
$data[$count]['lastname'] = $billings->getLastname();
$data[$count]['email'] = $billings->getEmail();
$data[$count]['address'] = $billings->getAddress();
$data[$count]['phone'] = $billings->getPhone();
$data[$count]['country'] = ((null != $billings->getCountry()) && ('' != $billings->getCountry())) ? $billings->getCountry()->getIataCode() : null;
$data[$count]['countryname'] = ((null != $billings->getCountry()) && ('' != $billings->getCountry())) ? \ucwords(\mb_strtolower($billings->getCountry()->getDescription())).' ('.$billings->getCountry()->getIataCode().')' : null;
$data[$count]['city'] = $billings->getCity()->getIataCode();
$data[$count]['cityname'] = ((null != $billings->getCity()) && ('' != $billings->getCity())) ? \ucwords(\mb_strtolower($billings->getCity()->getDescription())).' ('.$billings->getCity()->getIataCode().')' : null;
++$count;
}
}
} else {
$data = null;
}
/* $country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->createQueryBuilder('u')->where('u.languagecode = :languagecode')->setParameter('languagecode', 'es-ES')->orderBy('u.description', 'ASC')->getQuery()->getResult();
var_dump($country);die; */
/* $city = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry($customer->getCountry()->getId(), array('description' => 'ASC'));
foreach ($city as $infocities) {
$idCity[] = $infocities->getCode();
$nameCity[] = $infocities->getDescription();
}
$info = array('idCity' => $idCity, 'nameCity' => $nameCity); */
$twigView = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/customer-billing-view.html.twig');
return $this->render($twigView, ['billings' => $data, 'doc_type' => $typeDocument]);
}
public function billingListAction(TokenStorageInterface $tokenStorage)
{
$em = $this->getDoctrine()->getManager();
$userLogged = $tokenStorage->getToken()->getUser()->getId();
$billingList = $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
if ($billingList) {
$data = [];
$count = 0;
foreach ($billingList as $billings) {
if ('ACTIVE' == $billings->getStatus()) {
$data[$count]['id'] = $billings->getId();
$data[$count]['customerId'] = $userLogged;
$data[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
$data[$count]['documentNumber'] = $billings->getDocumentnumber();
$data[$count]['firstname'] = $billings->getFirstname();
$data[$count]['lastname'] = $billings->getLastname();
$data[$count]['email'] = $billings->getEmail();
$data[$count]['address'] = $billings->getAddress();
$data[$count]['phone'] = $billings->getPhone();
++$count;
}
}
} else {
$data = null;
}
return $this->json($data);
}
public function billingDeleteAction(Request $request, TokenStorageInterface $tokenStorage)
{
$idBilling = $request->request->get('idBilling');
$em = $this->getDoctrine()->getManager();
//$userLogged = $tokenStorage->getToken()->getUser()->getId();
$billing = $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->find($idBilling);
$billing->setStatus('ERASED');
$em->flush();
return $this->json(['status' => 'success']);
}
public function billingAddOrEditAction(Request $request, TokenStorageInterface $tokenStorage)
{
$em = $this->getDoctrine()->getManager();
$documentType = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findByExternalcode($request->request->get('doc_type'));
$userLogged = $tokenStorage->getToken()->getUser();
if ($request) {
$fecha = new \DateTime();
if ('' != $request->request->get('id')) {
$billing = $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->find($request->request->get('id'));
if (!$billing) {
return $this->json([
'status' => 'error',
'message' => 'Usuario no existe',
]);
}
$dataCountry = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($request->request->get('country'));
if (!$dataCountry) {
return $this->json([
'status' => 'error',
'message' => 'País no existe',
]);
}
$dataCity = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($request->request->get('city'));
if (!$dataCountry) {
return $this->json([
'status' => 'error',
'message' => 'Ciudad no existe',
]);
}
$billing->setDocumentnumber($request->request->get('doc_num'));
$billing->setDocumentType($documentType[0]);
$billing->setCustomer($userLogged);
$billing->setFirstname($request->request->get('first-name'));
$billing->setLastname($request->request->get('last-name'));
$billing->setEmail($request->request->get('email'));
$billing->setAddress($request->request->get('address'));
$billing->setPhone($request->request->get('phone'));
$billing->setCountry($dataCountry);
$billing->setCity($dataCity);
$billing->setUpdated($fecha->format('Y-m-d H:i:s'));
} else {
$dataCountry = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($request->request->get('country'));
if (!$dataCountry) {
return $this->json([
'status' => 'error',
'message' => 'País no existe',
]);
}
$dataCity = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($request->request->get('city'));
if (!$dataCountry) {
return $this->json([
'status' => 'error',
'message' => 'Ciudad no existe',
]);
}
$billing = new CustomerBillingList();
$billing->setDocumentnumber($request->request->get('doc_num'));
$billing->setDocumentType($documentType[0]);
$billing->setCustomer($userLogged);
$billing->setFirstname($request->request->get('first-name'));
$billing->setLastname($request->request->get('last-name'));
$billing->setEmail($request->request->get('email'));
$billing->setAddress($request->request->get('address'));
$billing->setPhone($request->request->get('phone'));
$billing->setCountry($dataCountry);
$billing->setCity($dataCity);
$billing->setStatus('ACTIVE');
$billing->setCreated($fecha->format('Y-m-d H:i:s'));
$billing->setUpdated($fecha->format('Y-m-d H:i:s'));
$em->persist($billing);
}
$em->flush();
return $this->json([
'status' => 'success',
'message' => 'Registro creado',
]);
} else {
return $this->json([
'status' => 'error',
'message' => 'Ha ocurrido un error',
]);
}
}
public function getCitiesAjaxAction(Request $request)
{
$data = [];
$em = $this->getDoctrine()->getManager();
$term = $request->request->get('term') ?: null;
if (!is_null($term)) {
$em = $this->getDoctrine()->getManager();
$json_template = '<value>:<label>-';
$countries = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findByOrWithSingleValue(['iatacode', 'description'], $term);
$json = [];
if ($countries) {
$data = [];
$count = 0;
foreach ($countries as $country) {
$data[$count]['id'] = $count;
$data[$count]['code'] = $country['iata'];
$data[$count]['label'] = ucwords(mb_strtolower($country['description']));
/* $arraytmp = array(
'description' => ucwords(mb_strtolower($country['description'])),
'iata' => $country['iata']
);
array_push($json, $arraytmp); */
}
} else {
$json['error'] = 'No hay Resultados';
}
return $this->json($data);
} else {
return $this->json(['error' => 'Termino de consulta invalido']);
}
/* $city = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry("165", array('description' => 'ASC'));
$data = [];
$count = 0;
foreach ($city as $infocities) {
$data[$count]['id'] = $infocities->getId();
$data[$count]['code'] = $infocities->getCode();
$data[$count]['name'] = $infocities->getDescription();
$count++;
}
return $this->json(array(
"status" => "success",
"data" => array($data)
)); */
}
public function searchCountryAction(Request $request)
{
$data = json_decode($request->getContent());
$term = $request->request->get('term') ?: null;
if (!is_null($term)) {
$em = $this->getDoctrine()->getManager();
$json_template = '<value>:<label>-';
$countries = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findByOrWithSingleValue(['iatacode', 'description'], $term);
$json = [];
if ($countries) {
foreach ($countries as $country) {
$arraytmp = [
'description' => ucwords(mb_strtolower($country['description'])),
'iata' => $country['iata'],
];
array_push($json, $arraytmp);
}
} else {
$json['error'] = 'No hay Resultados';
}
return $this->json(['country' => $json]);
} else {
return $this->json(['error' => 'Termino de consulta invalido']);
}
}
public function getCitiesAction(Request $request, TwigFolder $twigFolder)
{
$em = $this->getDoctrine()->getManager();
$agencyFolder = $twigFolder->twigFlux();
$country = $request->request->get('country');
$id = $request->request->get('id');
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($id);
$city = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry($country, ['description' => 'ASC']);
foreach ($city as $infocities) {
$idCity[] = $infocities->getId();
$iataCity[] = $infocities->getIatacode();
$nameCity[] = $infocities->getDescription();
}
$info = ['idCity' => $idCity, 'iataCity' => $iataCity, 'nameCity' => $nameCity];
return $this->json($info);
}
public function frozenRateAction(TwigFolder $twigFolder, TokenStorageInterface $tokenStorage)
{
$agencyFolder = $twigFolder->twigFlux();
$em = $this->getDoctrine()->getManager();
$freezeData = $em->getRepository(\Aviatur\RestBundle\Entity\HopperFreeze::class)->findByCustomerid($tokenStorage->getToken()->getUser()->getId());
if (!$freezeData) {
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/frozen-rate.html.twig'), ['status' => false, 'data' => null, 'message' => 'No tiene tarifas congeladas']);
}
$arrayFreeze = [];
for ($i = 0; $i < (is_countable($freezeData) ? count($freezeData) : 0); ++$i) {
// Obtener la informaqción de vuelo en formato JSON
$infoFlight = json_decode($freezeData[$i]->getIdRouteFlight()->getInfo());
// Obtener la información de ida y regreso en formato JSON
$infoIda = json_decode($infoFlight->selection[0]);
$infoRegreso = null;
$infoRegresoDate = null;
$infoRegreso2 = null;
setlocale(LC_TIME, 'spanish');
if ((is_countable($infoFlight->selection) ? count($infoFlight->selection) : 0) > 1) {
$infoRegreso = json_decode($infoFlight->selection[1]);
$infoRegresoDate = strftime('%d %B del %Y', strtotime(date('d-m-Y', $infoRegreso->S[0]->E)));
$infoRegreso = $infoRegreso->S[0]->O;
$infoRegreso2 = $infoIda->S[0]->O;
}
//Calcular los días restantes
$date1 = new \DateTime('now');
$date2 = json_decode(json_encode($freezeData[$i]->getFinishDate()), true);
$diff = $date1->diff(new \DateTime($date2['date']));
$a = (1 == $diff->invert) ? '-'.$diff->days : $diff->days;
$paymentInfo = json_decode($freezeData[$i]->getFlightInfo(), true);
$used = 'used' == $freezeData[$i]->getState() ? 'Usado' : 'Activo';
array_push($arrayFreeze, [
'FlightInfo' => [
'Going' => [
'Date' => strftime('%d %B del %Y', strtotime(date('d-m-Y', $infoIda->S[0]->E))),
'Origin' => [
'Code' => $infoIda->S[0]->O,
],
'Destination' => [
'Code' => $infoIda->S[0]->D,
],
],
'Return' => [
'Date' => $infoRegresoDate,
'Origin' => [
'Code' => $infoRegreso,
],
'Destination' => [
'Code' => $infoRegreso2,
],
],
],
'Dates' => [
'DateCreated' => $freezeData[$i]->getCreationDate(),
'DateExpiration' => $freezeData[$i]->getFinishDate(),
'DaysLeft' => (int) $a,
],
'Url' => $freezeData[$i]->getIdRouteFlight()->getUrl(),
'Prices' => [
'PriceHopper' => $freezeData[$i]->getInfoHopper(),
'PriceFlight' => $paymentInfo['x_total_payment']['x_amount'] + $paymentInfo['x_total_payment']['x_airport_tax'] + $paymentInfo['x_total_payment']['x_service_fee'],
'MaxHopperCover' => $freezeData[$i]->getMaxHopperCover(),
],
'state' => ((int) $a <= 0) ? 'Expirado' : $used,
]);
}
//var_dump(json_encode($arrayFreeze));die;
//var_dump($arrayFreeze);die;
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Customer/Customer/frozen-rate.html.twig'), ['status' => true, 'data' => $arrayFreeze]);
}
public function sanear_string($string)
{
$string = trim($string);
$string = str_replace(
['á', 'à', 'ä', 'â', 'ª'],
['a', 'a', 'a', 'a', 'a'],
$string
);
$string = str_replace(
['é', 'è', 'ë', 'ê'],
['e', 'e', 'e', 'e'],
$string
);
$string = str_replace(
['í', 'ì', 'ï', 'î'],
['i', 'i', 'i', 'i'],
$string
);
$string = str_replace(
['ó', 'ò', 'ö', 'ô'],
['o', 'o', 'o', 'o'],
$string
);
$string = str_replace(
['ú', 'ù', 'ü', 'û'],
['u', 'u', 'u', 'u'],
$string
);
$string = str_replace(
['ç'],
['c'],
$string
);
//Esta parte se encarga de eliminar cualquier caracter extraño
$string = str_replace(
['\\', '¨', 'º', '-', '~',
'#', '|', '!', '"', ':',
'·', '$', '%', '&', '/',
'(', ')', '?', "'", '¡',
'¿', '[', '^', '`', ']',
'+', '}', '{', '¨', '´',
'>', '< ', ';', ',', ],
'',
$string
);
return $string;
}
/*
private function validateSanctions(SessionInterface $session, ValidateSanctionsRenewal $validateSanctions, $info, $paymentMethod)
{
if ($session->has('Marked_name') && $session->has('Marked_document')) {
$session->remove('Marked_name');
$session->remove('Marked_document');
}
if ($validateSanctions->validateSanctions($info['documentnumber'], $info['name'])) {
if (!$session->has('Marked_name') && !$session->has('Marked_document')) {
$session->remove('Marked_name');
$session->remove('Marked_document');
$session->set('Marked_name', $info['name']);
$session->set('Marked_document', $info['documentnumber']);
}
return 'p2p' === $paymentMethod;
}
return true;
}
*/
private function validateSpecialConditionPayment($cardNum)
{
$validBins = [
'421892',
'450407',
'492488',
'455100',
'799955',
'813001',
'518761',
'542650',
'527564',
'540699',
'518841',
'454094',
'454759',
'459418',
'492489',
'450408',
'459419',
'404280',
'548115',
'553643',
'450418',
'456783',
'483080',
'485995',
'547457',
'410164',
'404279',
'418253',
'459317',
'462550',
'491268',
'492468',
'589515',
'799955',
];
if (in_array(substr($cardNum, 0, 6), $validBins)) {
return true;
} else {
return false;
}
}
private function getValidationOnuOfac($postData, $urlDomain, SessionInterface $session, ValidateSanctionsRenewal $validateSanctionsRenewal){
// Comprobar si la URL contiene "experiencias"
$exceptionWords = ['experiencias', 'paquetes'];
$isException = false;
foreach ($exceptionWords as $eWord) {
$isException = (strpos($urlDomain, $eWord) !== false);
if($isException){
break;
}
}
$isExperiencia = strpos($urlDomain, 'experiencias') !== false;
// Si es una experiencia, omitir la validación de pago
if ($isException) {
$clientArray = $validateSanctionsRenewal->getClientsArray($postData, $urlDomain);
return $validateSanctionsRenewal->validateSanctions($clientArray, $session, null);
} else {
// Procesar como de costumbre para otros productos
$paymentInfo = $postData['PD'];
$paymentMethod = $paymentInfo['type'];
$clientArray = $validateSanctionsRenewal->getClientsArray($postData, $urlDomain);
return $validateSanctionsRenewal->validateSanctions($clientArray, $session, $paymentMethod);
}
}
}