src/Aviatur/CustomerBundle/Controller/DefaultController.php line 695

Open in your IDE?
  1. <?php
  2. namespace Aviatur\CustomerBundle\Controller;
  3. use Aviatur\CustomerBundle\Entity\Customer;
  4. use Aviatur\CustomerBundle\Entity\CustomerBillingList;
  5. use Aviatur\CustomerBundle\Entity\HistoricalCustomer;
  6. use Aviatur\GeneralBundle\Entity\OrderTrace;
  7. use Aviatur\CustomerBundle\Models\CustomerModel;
  8. use Aviatur\CustomerBundle\Services\ValidateSanctionsRenewal;
  9. use Aviatur\FormBundle\Entity\Newsletter;
  10. use Aviatur\GeneralBundle\Services\AviaturAthServices;
  11. use Aviatur\GeneralBundle\Services\AviaturEncoder;
  12. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  13. use Aviatur\GeneralBundle\Services\AviaturLoginService;
  14. use Aviatur\GeneralBundle\Services\AviaturWebService;
  15. use Aviatur\PaymentBundle\Entity\PaymentMethodCustomer;
  16. use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
  17. use Aviatur\PaymentBundle\Services\TokenizerService;
  18. use Aviatur\TwigBundle\Services\TwigFolder;
  19. use DateTime;
  20. use Doctrine\Persistence\ManagerRegistry;
  21. use Aviatur\GeneralBundle\Entity\DocumentBlacklist;
  22. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  23. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  24. use Symfony\Component\HttpFoundation\JsonResponse;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\HttpFoundation\Session\Session;
  28. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  29. use Symfony\Component\Routing\RouterInterface;
  30. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  31. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  32. use Symfony\Component\Validator\Validator\ValidatorInterface;
  33. use Aviatur\CustomerBundle\Services\PhoneNumberService;
  34. class DefaultController extends AbstractController
  35. {
  36.     /**
  37.      * @var \Doctrine\Persistence\ObjectManager
  38.      */
  39.     protected $em;
  40.     /**
  41.      * @var \Aviatur\AgencyBundle\Entity\Agency|object|null
  42.      */
  43.     protected $agency;
  44.     /**
  45.      * @var AviaturAthServices
  46.      */
  47.     protected $athServices;
  48.     /**
  49.      * @var bool
  50.      */
  51.     protected $isAval;
  52.     public function __construct(ManagerRegistry $managerRegistrySessionInterface $sessionAviaturAthServices $athServices)
  53.     {
  54.         $em $managerRegistry->getManager();
  55.         $agencyId $session->has('agencyId') ? $session->get('agencyId') : 1;
  56.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($agencyId);
  57.         $this->em $em;
  58.         $this->agency $agency;
  59.         $this->athServices $athServices;
  60.         // Validación para agencia Aval
  61.         if ($agency->getAssetsFolder() == 'aval') {
  62.             $this->isAval true;
  63.         } else {
  64.             $this->isAval false;
  65.         }
  66.     }
  67.     public function getDataAction(Request $requestManagerRegistry $managerRegistryAviaturWebService $webServiceAviaturErrorHandler $errorHandlerTwigFolder $twigFolderParameterBagInterface $parameterBag)
  68.     {
  69.         if ($request->isXmlHttpRequest()) {
  70.             $doc_type $request->query->get('doc_type');
  71.             $documentNumber $request->query->get('doc_num');
  72.             $em $managerRegistry->getManager();
  73.             $documentFact $doc_type .'-'.$documentNumber;
  74.             $isBlacklisted $this->em->getRepository(\Aviatur\GeneralBundle\Entity\DocumentBlacklist::class)->isDocumentBlacklisted($documentFact);
  75.             if($isBlacklisted){
  76.                 return $this->json([
  77.                     'error' => 'documentBlackList',
  78.                     'title' => 'Lo sentimos algo salió mal',
  79.                     'message' => 'Este documento no está disponible para realizar compras. Si necesitas más información, comunícate con nuestro equipo de soporte.',
  80.                     'cta' => 'Contactar soporte',
  81.                     'link_wa' => 'https://api.whatsapp.com/send?phone=5713821616&text=%C2%A1Hola!%20Necesito%20soporte%20en%20un%20compra%20%C2%BFPuedes%20ayudarme%3F',
  82.                 ]);
  83.             }
  84.             $documentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($doc_type);
  85.             $data $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneBy(['documentType' => $documentType'documentnumber' => $documentNumber]);
  86.             if (empty($data)) {
  87.                 //si no encuentra en la base local busca en el servidor de aviatur
  88.                 $customerModel = new CustomerModel();
  89.                 $xmlRequest $customerModel->getXmlFindUser($doc_type$documentNumber'0926EB''BOGVU2900');
  90.                 $response $webService->busWebServiceAmadeus('GENERALLAVE'$parameterBag->get('provider_service'), $xmlRequest);
  91.                 if ((null != $response) && ('error' != $response)) {
  92.                     if (!isset($response['error']) && is_object($response)) {
  93.                         if (('FALLO' == $response->RESULTADO) && (false !== strpos($response->MENSAJE'No se enco'))) {
  94.                             return $this->json(['no_info' => (string) $response->MENSAJE]);
  95.                         } elseif (('FALLO' == $response->RESULTADO)) {
  96.                             $errorHandler->errorRedirect('/vuelos/detalle''''Error usuario: ' . (string) $response->MENSAJE);
  97.                             return $this->json(['error' => (string) $response->MENSAJE]);
  98.                         } else {
  99.                             $customer = new Customer();
  100.                             $dataNumber $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneBy(['code' => $response->document->id]);
  101.                             $dataGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneBy(['code' => $response->gender->id]);
  102.                             $dataMaritalStatus $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneBy(['code' => $response->marital_starus->id]);
  103.                             $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneBy(['code' => $response->city->id]);
  104.                             $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneBy(['code' => $response->country->id]);
  105.                             try {
  106.                                 $customer->setAviaturclientid((int) $response->id);
  107.                                 $customer->setDocumentType($dataNumber);
  108.                                 $customer->setCivilStatus($dataMaritalStatus);
  109.                                 $customer->setGenderAviatur($dataGender);
  110.                                 $customer->setCity($dataCity);
  111.                                 $customer->setCountry($dataCountry);
  112.                                 $customer->setDocumentnumber($documentNumber);
  113.                                 $customer->setFirstname($response->name);
  114.                                 $customer->setLastname($response->last_name);
  115.                                 $customer->setBirthdate(new \DateTime($response->birth_date));
  116.                                 $customer->setAddress($response->address);
  117.                                 $customer->setPhone($response->phone_number);
  118.                                 $customer->setCellphone($response->mobile_phone_number);
  119.                                 $customer->setEmail($response->email);
  120.                                 $customer->setEmailCanonical($response->email);
  121.                                 $customer->setUsername($response->email);
  122.                                 $customer->setUsernameCanonical($response->email);
  123.                                 $customer->setPassword($response->password);
  124.                                 $customer->setAcceptInformation(0);
  125.                                 $customer->setAcceptSms(0);
  126.                                 $customer->setPersonType($response->person_type->id);
  127.                                 $customer->setFrecuencySms(0);
  128.                                 $customer->setCorporateId('');
  129.                                 $customer->setCorporateName('');
  130.                                 $customer->setEnabled(1);
  131.                                 $customer->setRoles([]);
  132.                                 $emo $managerRegistry->getManager();
  133.                                 $emo->persist($customer);
  134.                                 $emo->flush();
  135.                                 $return = [
  136.                                     'id' => $customer->getId(),
  137.                                     'first_name' => substr_replace($response->name'********'3),
  138.                                     'last_name' => substr_replace($response->last_name'********'3),
  139.                                     'address' => substr_replace($response->address'********'3),
  140.                                     'doc_num' => (string) $response->document->number,
  141.                                     'doc_type' => $dataNumber->getExternalcode(),
  142.                                     'phone' => substr_replace($response->phone_number'*******'3),
  143.                                     'email' => substr_replace($response->email'********'3),
  144.                                     'gender' => (isset($dataGender) && $dataGender->getCode() !== null) ? $dataGender->getCode() : '',
  145.                                     'birthday' => ((null != $response->birth_date) && ('' != $response->birth_date)) ? \date('Y-m-d', \strtotime($response->birth_date)) : null,
  146.                                     'nationality' => ((null != $dataCountry) && ('' != $dataCountry)) ? $dataCountry->getIataCode() : null,
  147.                                     'nationality_label' => ((null != $dataCountry) && ('' != $dataCountry)) ? \ucwords(\mb_strtolower($dataCountry->getDescription())) . ' (' $dataCountry->getIataCode() . ')' null,
  148.                                 ];
  149.                             } catch (\Doctrine\ORM\ORMException $e) {
  150.                                 $errorHandler->errorRedirect('/vuelos/detalle''''Ha ocurrido un error ingresando el nuevo usuario a la base de datos');
  151.                                 return $this->json(['error' => 'Ha ocurrido un error ingresando el nuevo usuario a la base de datos']);
  152.                             } catch (\Aviatur\CustomerBundle\Exception\ValidateException $e) {
  153.                                 $mensaje 'Información incompleta o inconsistente: ' $e->getMessage();
  154.                                 $errorHandler->errorRedirect('/vuelos/detalle'''$mensaje);
  155.                                 return $this->json(['error' => $mensaje]);
  156.                             } catch (\Exception $e) {
  157.                                 $errorHandler->errorRedirect('/vuelos/detalle''''Ha ocurrido un error inesperado en la creación del nuevo usuario');
  158.                                 return $this->json(['error' => 'Ha ocurrido un error inesperado en la creación del nuevo usuario']);
  159.                             }
  160.                         }
  161.                     } else {
  162.                         $errorHandler->errorRedirect('/vuelos/detalle''''Error usuario: ' . (string) $response['error']);
  163.                         return $this->json(['error' => (string) $response['error']]);
  164.                     }
  165.                 } else {
  166.                     $errorHandler->errorRedirect('/vuelos/detalle''''Error usuario: Error inesperado en la consulta');
  167.                     return $this->json(['error' => 'Error inesperado en la consulta']);
  168.                 }
  169.             } else {
  170.                 $phoneService = new PhoneNumberService($em);
  171.                 $hasPhone = (null != $data->getPhone()) && ('' != $data->getPhone());
  172.                 $hasCellphone = (null != $data->getCellphone()) && ('' != $data->getCellphone());
  173.                 $phoneParts $hasPhone
  174.                     $phoneService->extractPhoneComponents($data->getPhone())
  175.                     : ['prefix' => null'number' => null];
  176.                 $cellphoneParts $hasCellphone
  177.                     $phoneService->extractPhoneComponents($data->getCellphone())
  178.                     : ['prefix' => null'number' => null];
  179.                 $return = [
  180.                     'id' => $data->getId(),
  181.                     'first_name' => ((null != $data->getFirstname()) && ('' != $data->getFirstname())) ? utf8_encode(substr_replace($data->getFirstname(), '********'3)) : null,
  182.                     'last_name' => ((null != $data->getLastname()) && ('' != $data->getLastname())) ? utf8_encode(substr_replace($data->getLastname(), '********'3)) : null,
  183.                     'address' => ((null != $data->getAddress()) && ('' != $data->getAddress())) ? substr_replace($data->getAddress(), '********'3) : null,
  184.                     'city' => ((null != $data->getCity()) && ('' != $data->getCity())) ? substr_replace($data->getCity()->getDescription(), '********'3) : null,
  185.                     'doc_num' => ((null != $data->getDocumentnumber()) && ('' != $data->getDocumentnumber())) ? $data->getDocumentnumber() : null,
  186.                     'doc_type' => ((null != $data->getDocumentType()) && ('' != $data->getDocumentType())) ? $data->getDocumentType()->getExternalcode() : null,
  187.                     'phone' => $hasPhone substr_replace($phoneParts['number'], '*******'3) : null,
  188.                     'cellphone' => $hasCellphone substr_replace($cellphoneParts['number'], '*******'3) : null,
  189.                     'phone_prefix' => $phoneParts['prefix'],
  190.                     'cellphone_prefix' => $cellphoneParts['prefix'],
  191.                     'email' => ((null != $data->getEmail()) && ('' != $data->getEmail())) ? substr_replace($data->getEmail(), '********'3) : null,
  192.                     'gender' => ((null != $data->getGenderAviatur()) && ('' != $data->getGenderAviatur())) ? $data->getGenderAviatur()->getCode() : null,
  193.                     'birthday' => ((null != $data->getBirthdate()) && ('' != $data->getBirthdate())) ? \date('Y-m-d'$data->getBirthdate()->getTimestamp()) : null,
  194.                     'city_id' => ((null != $data->getCity()) && (null != $data->getCity()->getIatacode()) && ('' != $data->getCity()->getIatacode())) ? $data->getCity()->getIatacode() : null,
  195.                     'nationality' => ((null != $data->getCountry()) && ('' != $data->getCountry())) ? $data->getCountry()->getIataCode() : null,
  196.                     'nationality_label' => ((null != $data->getCountry()) && ('' != $data->getCountry())) ? \ucwords(\mb_strtolower($data->getCountry()->getDescription())) . ' (' $data->getCountry()->getIataCode() . ')' null,
  197.                 ];
  198.             }
  199.             return $this->json($return);
  200.         } else {
  201.             $errorHandler->errorRedirect('/vuelos/detalle''''Acceso no autorizado');
  202.             return  $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  203.         }
  204.     }
  205.     public function getB2TDataAction(Request $requestAviaturWebService $webServiceAviaturErrorHandler $errorHandlerParameterBagInterface $parameterBag)
  206.     {
  207.         $return = [];
  208.         $doc_type $request->query->get('doc_type');
  209.         $documentNumber $request->query->get('doc_num');
  210.         $documentFact $doc_type .'-'.$documentNumber;
  211.         $isBlacklisted $this->em->getRepository(\Aviatur\GeneralBundle\Entity\DocumentBlacklist::class)->isDocumentBlacklisted($documentFact);
  212.         if($isBlacklisted){
  213.             return $this->json([
  214.                 'error' => 'documentBlackList',
  215.                 'title' => 'Lo sentimos algo salió mal',
  216.                 'message' => 'Este documento no está disponible para realizar compras. Si necesitas más información, comunícate con nuestro equipo de soporte.',
  217.                 'cta' => 'Contactar soporte',
  218.                 'link_wa' => 'https://api.whatsapp.com/send?phone=5713821616&text=%C2%A1Hola!%20Necesito%20soporte%20en%20un%20compra%20%C2%BFPuedes%20ayudarme%3F',
  219.             ]);
  220.         }
  221.         //si no encuentra en la base local busca en el servidor de aviatur
  222.         $customerModel = new CustomerModel();
  223.         $xmlRequest $customerModel->getXmlFindUserB2T($doc_type$documentNumber'G_ROA''BOGVU2900');
  224.         $response $webService->busWebServiceAmadeus('GENERALLAVE'$parameterBag->get('provider_service'), $xmlRequest);
  225.         if ((('FALLO' == $response->RESULTADO) && (false !== strpos($response->MENSAJE'No se enco'))) || (('EXITO' == $response->RESULTADO) && empty($response->CLIENTES))) {
  226.             return $this->json(['no_info' => (string) $response->MENSAJE]);
  227.         } elseif (('FALLO' == $response->RESULTADO)) {
  228.             $errorHandler->errorRedirect('/vuelos/detalle''''Error usuario: ' . (string) $response->MENSAJE);
  229.             return $this->json(['error' => (string) $response->MENSAJE]);
  230.         } else {
  231.             foreach ($response->CLIENTES->ELEMENTO_LISTA_CLIENTES as $client) {
  232.                 $return[] = [
  233.                     'id' => (string) $client->IDENTIFICADOR_INTERNO,
  234.                     'first_name' => ucwords($this->sanear_string(mb_strtolower((string) $client->NOMBRE))),
  235.                     'last_name' => ucwords($this->sanear_string(mb_strtolower((string) $client->APELLIDO))),
  236.                     'doc_num' => ucwords(mb_strtolower((string) $client->NUMERO_DE_DOCUMENTO)),
  237.                     'doc_type' => $request->query->get('doc_type'),
  238.                     'phone' => (string) $client->TELEFONO,
  239.                     'consecutive' => (string) $client->CONSECUTIVO,
  240.                 ];
  241.             }
  242.         }
  243.         return $this->json($return);
  244.     }
  245.     public function createAction(Request $requestManagerRegistry $managerRegistryAviaturWebService $webServiceAviaturErrorHandler $errorHandlerTokenStorageInterface $tokenStorageSessionInterface $sessionValidateSanctionsRenewal $validateSanctionsRenewalParameterBagInterface $parameterBag)
  246.     {
  247.         $customer null;
  248.         $transactionId $session->get('transactionId');
  249.         $em $this->em;
  250.         $billingData $request->get('BD');
  251.         $paymentData $request->get('PD');
  252.         $customerdData $request->get('CD');
  253.         $customerdData['phone'] = (new PhoneNumberService($em))->choosePhone($customerdData);
  254.         $billingData['phone'] = (new PhoneNumberService($em))->choosePhone($billingData);
  255.         $paymentData['phone'] = (new PhoneNumberService($em))->choosePhone($paymentData);
  256.         $paymentMethod $paymentData['type'] ?? 'other';
  257.         if ($request->request->has('MS')) {
  258.             $passangers $billingData;
  259.         } else {
  260.             $passangers array_merge($billingData$request->get('PI'));
  261.         }
  262.         $isFront $session->has('operatorId');
  263.         $session->remove('loginFromDetail');
  264.         foreach ($passangers as $prop => $passanger) {
  265.             if (preg_match('/^doc_num/i'$prop) && '' == $passangers[$prop]) {
  266.                 $errorHandler->errorRedirect('/vuelos/detalle''''undefined_doc_num');
  267.                 return $this->json(['error' => 'El número de identificación no puede estar vacío']);
  268.             }
  269.         }
  270.         $server $request->server;
  271.         $urlDomain parse_url($server->get('HTTP_REFERER'), PHP_URL_HOST);
  272.         /* Inicio comparación ONU-OFAC */
  273.         $postData $request->request->all();
  274.         if (!$this->getValidationOnuOfac($postData$server->get('HTTP_REFERER'), $session$validateSanctionsRenewal)) {
  275.             $errorHandler->errorRedirect('/vuelos/detalle''''sanctions_candidate');
  276.             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']);
  277.         }
  278.         /* Fin comparación ONU-OFAC */
  279.         $parameters json_decode($session->get($request->getHost() . '[parameters]'));
  280.         if (isset($parameters->switch_login_agencies) && '' != $parameters->switch_login_agencies) {
  281.             $login_agencies json_decode($parameters->switch_login_agenciestrue);
  282.             if (isset($login_agencies[$session->get('agencyId')])) {
  283.                 $login_is_on $login_agencies[$session->get('agencyId')];
  284.             } else {
  285.                 $login_is_on $login_agencies['all'];
  286.             }
  287.         } else {
  288.             $login_is_on '0';
  289.         }
  290.         if (!$isFront && false !== strpos($urlDomain'bbva') && !$this->validateSpecialConditionPayment($request->get('PD')['card_num'])) {
  291.             $errorHandler->errorRedirectNoEmail('/vuelos/detalle''''no_sppayment_condition');
  292.             return $this->json(['error' => 'no_sppayment_condition']);
  293.         }
  294.         if ((isset($billingData['id'])) && ('' != $billingData['id']) && (null != $billingData['id'])) {
  295.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  296.             /* if ($login_is_on == '1') {
  297.               if ($this->get("aviatur_login_service")->validActiveSession() === false) {
  298.               $session->set('loginFromDetail', true);
  299.               return $this->json(array("error" => "no_granted_session_condition"));
  300.               } else if (!isset($request->get('PD')['methodsRecovered'])) { */
  301.             //                $customerLogin = $this->get('security.token_storage')->getToken()->getUser();
  302.             //
  303.             //                //Verify is client is same logged client
  304.             ////                if ($customerLogin->getEmail() != $customer->getEmail() && !isset($billingData['anotherCustomerCheck'])) {
  305.             ////                    return $this->json(array("error" => "notSamePersonLogged"));
  306.             ////                }
  307.             //
  308.             //                $infoMethodPaymentByClient = $this->get("aviatur_methods_customer_service")->getMethodsByCustomer($customerLogin, false);
  309.             //                if ($infoMethodPaymentByClient['info'] !== 'NoInfo') {
  310.             //                    return $this->json(array("error" => "customer_with_methods_saved", "info" => $infoMethodPaymentByClient['info']));
  311.             //                }
  312.             /* }
  313.               } */
  314.             if (isset($billingData['address']) && (false === strpos($billingData['address'], '***')) && (('' == $customer->getAddress()) || (null == $customer->getAddress()))) {
  315.                 $customer->setAddress($billingData['address']);
  316.             }
  317.             if (isset($billingData['phone']) && (false === strpos($billingData['phone'], '***')) && (('' == $customer->getPhone()) || (null == $customer->getPhone()))) {
  318.                 $customer->setPhone($billingData['phone']);
  319.             }
  320.             $em->flush();
  321.             /*
  322.             if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $customer->getDocumentnumber(), 'name' => $customer->getFirstname().' '.$customer->getLastname()], $paymentMethod)) {
  323.                 $errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
  324.                 return $this->json(['error' => 'sanctions_candidate']);
  325.             }
  326.             */
  327.             $passengerStructured = [];
  328.             $passengerStructuredGroup null;
  329.             foreach ($passangers as $passKey => $passengerValue) {
  330.                 if (!preg_match('/.*_\d_\d$/'$passKey) || strstr($passengerValue'***')) {
  331.                     continue;
  332.                 }
  333.                 $matchArray = [];
  334.                 preg_match('/.*_(\d_\d)$/'$passKey$matchArray);
  335.                 if (!isset($matchArray[1])) {
  336.                     continue;
  337.                 }
  338.                 $passengerStructuredGroup = !$passengerStructuredGroup $matchArray[1] : ($passengerStructuredGroup !== $matchArray[1] ? $matchArray[1] : $passengerStructuredGroup);
  339.                 if (strstr($passKey'doc_num')) {
  340.                     $passengerStructured[$passengerStructuredGroup]['document'] = $passengerValue;
  341.                     $passengerStructured[$passengerStructuredGroup]['name'] = '';
  342.                 } elseif (strstr($passKey'first_name') || strstr($passKey'last_name')) {
  343.                     $passengerStructured[$passengerStructuredGroup]['name'] .= $passengerValue ' ';
  344.                 }
  345.             }
  346.             foreach ($passengerStructured as $pax) {
  347.                 if ('' === trim($pax['name'])) {
  348.                     continue;
  349.                 }
  350.                 /*
  351.                 if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $pax['document'], 'name' => $pax['name']], $paymentMethod)) {
  352.                     $errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
  353.                     return $this->json(['error' => 'sanctions_candidate']);
  354.                 }
  355.                 */
  356.             }
  357.             $return = [
  358.                 'id' => $customer->getId(),
  359.             ];
  360.             $redemptionPoint $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($this->agency);
  361.             if (isset($redemptionPoint) && isset($paymentData['pointRedemptionValue'])) {
  362.                 $minCtPayment $redemptionPoint['Config']['Amount']['MinCtPayment'];
  363.                 if ($paymentData['pointRedemptionValue'] !== '0' && $paymentData['pointRedemptionValue'] != null) {
  364.                     $avalPoints $paymentData['pointRedemptionValue'];
  365.                     if ($avalPoints 0) {
  366.                         $info = [
  367.                             "token" => NULL,
  368.                             "transactionId" => $transactionId,
  369.                             "totalPoints" => $avalPoints
  370.                         ];
  371.                         $disposablePoints $this->athServices->disposablePoints($infotrue);
  372.                         if (isset($disposablePoints['ok']) && $avalPoints $disposablePoints['ok']['text']['PointOfService']) {
  373.                             $return += ["error" => "Los puntos que quiere redimir no están disponibles para completar su transacción, por favor intente nuevamente"];
  374.                         } else if (isset($disposablePoints['error'])) {
  375.                             $return += ["error" => "1.Lo sentimos no podemos procesar la transacción, por favor vuelva a intentar más tarde"];
  376.                         } else {
  377.                             $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_ath');
  378.                             if (!isset(json_decode($parameters->getDescription())->NoOtp) || (isset(json_decode($parameters->getDescription())->NoOtp) && !json_decode($parameters->getDescription())->NoOtp)) {
  379.                                 $return += $this->generateOtp($redemptionPoint$session$postData);
  380.                             }
  381.                             if (isset($return['StatusCode'])) {
  382.                                 if ($return['StatusCode'] !== '0' && $return['StatusCode'] !== 0) {
  383.                                     $return += ["error" => "Lo sentimos no podemos procesar  a la transacción, por favor vuelva a intentar más tarde"];
  384.                                 }
  385.                             }
  386.                         }
  387.                     }
  388.                 }
  389.             }
  390.             return $this->json($return);
  391.         } else {
  392.             $userLogged $tokenStorage->getToken()->getUser();
  393.             if ($userLogged && $userLogged = !'anon.') {
  394.                 $billingData['id'] = $userLogged->getId();
  395.                 if (null != $userLogged->getFacebookId() || null != $userLogged->getGoogleId()) {
  396.                     $passangerData $request->get('PI');
  397.                     /*
  398.                     if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $billingData['doc_num'], 'name' => $billingData['first_name'].' '.$billingData['last_name']], $paymentMethod)) {
  399.                         $errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
  400.                         return $this->json(['error' => 'sanctions_candidate']);
  401.                     }
  402.                     */
  403.                     if ($request->get('same-billing')) {
  404.                         if ('on' == $request->get('same-billing')) {
  405.                             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($userLogged->getId());
  406.                             $dataNumberDocType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($passangerData['doc_type_1_1']);
  407.                             $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangerData['nationality_1_1']);
  408.                             $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode('BOG');
  409.                             $dataGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangerData['gender_1_1']);
  410.                             $customer->setDocumentType($dataNumberDocType);
  411.                             $customer->setDocumentnumber($passangerData['doc_num_1_1']);
  412.                             $customer->setFirstname($passangerData['first_name_1_1']);
  413.                             $customer->setLastname($passangerData['last_name_1_1']);
  414.                             $customer->setAddress($passangerData['address_1_1']);
  415.                             $customer->setPhone($customerdData['phone']);
  416.                             $customer->setCountry($dataCountry);
  417.                             $customer->setCity($dataCity);
  418.                             $customer->setBirthdate(new \DateTime($passangerData['birthday_1_1']));
  419.                             $customer->setGenderAviatur($dataGender);
  420.                         }
  421.                     } else {
  422.                         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($userLogged->getId());
  423.                         $dataNumberDocType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($billingData['doc_type']);
  424.                         if (isset($billingData['nationality']) && '' != $billingData['nationality']) {
  425.                             $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($billingData['nationality']);
  426.                         } else {
  427.                             $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode('CO');
  428.                         }
  429.                         $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode('BOG');
  430.                         $dataGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($billingData['gender']);
  431.                         $customer->setDocumentType($dataNumberDocType);
  432.                         $customer->setDocumentnumber($billingData['doc_num']);
  433.                         $customer->setFirstname($billingData['first_name']);
  434.                         $customer->setLastname($billingData['last_name']);
  435.                         $customer->setAddress($billingData['address']);
  436.                         $customer->setPhone($billingData['phone']);
  437.                         $customer->setCountry($dataCountry);
  438.                         $customer->setCity($dataCity);
  439.                         $customer->setBirthdate(new \DateTime($billingData['birthday']));
  440.                         $customer->setGenderAviatur($dataGender);
  441.                     }
  442.                     $em->persist($customer);
  443.                     $em->flush();
  444.                     $return = [
  445.                         'id' => $userLogged->getId(),
  446.                     ];
  447.                     return $this->json($return);
  448.                 }
  449.             }
  450.             $documentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findByExternalcode($billingData['doc_type']);
  451.             $registered $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findBy(['documentnumber' => $billingData['doc_num'], 'documentType' => $documentType]);
  452.             if (!= sizeof($registered)) {
  453.                 return $this->json(['id' => $registered[0]->getId()]);
  454.             }
  455.             /*$data = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findByEmail($billingData['email']);
  456.             if (0 != sizeof($data)) {
  457.                 $errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'email_exist');
  458.                 return $this->json(['error' => 'email_exist']);
  459.             }*/
  460.             $customerModel = new CustomerModel();
  461.             $doc_type explode('-'$billingData['doc_type']);
  462.             $xmlRequest $customerModel->getXmlFindUser($doc_type[0], $billingData['doc_num'], '0926EB''BOGVU2900');
  463.             //$xmlRequest = $customerModel->getXmlFindUserByEmail($billingData['email'], 4);
  464.             $response $webService->busWebServiceAmadeus('GENERALLAVE'$parameterBag->get('provider_service'), $xmlRequest);
  465.             if ((isset($response->RESULTADO) && ('FALLO' != $response->RESULTADO)) || (isset($response->ID))) {
  466.                 $errorHandler->errorRedirectNoEmail('/vuelos/detalle''''Error al crear el usuario');
  467.                 return $this->json(['error' => 'Error al crear el usuario']);
  468.             } elseif (isset($response->MENSAJE) && (false !== strpos($response->MENSAJE'No se enco'))) {
  469.                 $doc_type explode('-'$billingData['doc_type']);
  470.                 $passangerData $request->get('PI');
  471.                 /* if ($login_is_on == '0') { */
  472.                 $dataNumber $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneByExternalcode($doc_type[0]);
  473.                 $personType = (!= $dataNumber->getId()) && (!= $dataNumber->getId()) && (!= $dataNumber->getId()) ? 7;
  474.                 $customer = new Customer();
  475.                 $customer->setAddress('' != $billingData['address'] ? $billingData['address'] : $passangerData['address_1_1']);
  476.                 $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode('BOG');
  477.                 if (isset($passangerData['nationality_1_1']) && '' != $passangerData['nationality_1_1']) {
  478.                     $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangerData['nationality_1_1']);
  479.                 } else {
  480.                     $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode('CO');
  481.                 }
  482.                 $dataGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangerData['gender_1_1']);
  483.                 $customer->setGenderAviatur($dataGender);
  484.                 if ($billingData['doc_num'] == $passangerData['doc_num_1_1']) {
  485.                     $customer->setBirthdate(new \DateTime($passangerData['birthday_1_1']));
  486.                 } else {
  487.                     $customer->setBirthdate(new \DateTime(date('Y-m-d'strtotime('-18 year'time()))));
  488.                 }
  489.                 $customer->setDocumentType($dataNumber);
  490.                 $customer->setCity($dataCity);
  491.                 $customer->setCountry($dataCountry);
  492.                 $customer->setDocumentnumber($billingData['doc_num']);
  493.                 $customer->setFirstname($billingData['first_name']);
  494.                 $customer->setLastname($billingData['last_name']);
  495.                 $customer->setPhone($billingData['phone']);
  496.                 $customer->setCellphone($billingData['phone']);
  497.                 $customer->setEmail($billingData['email']);
  498.                 $customer->setEmailCanonical($billingData['email']);
  499.                 $customer->setUsername($billingData['email']);
  500.                 $customer->setUsernameCanonical($billingData['email']);
  501.                 $customer->setAcceptInformation(0);
  502.                 $customer->setAcceptSms(0);
  503.                 $customer->setAviaturclientid(0);
  504.                 $customer->setPersonType($personType);
  505.                 $customer->setPassword(sha1('Default Aviatur'));
  506.                 $customer->setRoles([]);
  507.                 try {
  508.                     $em->persist($customer);
  509.                     $em->flush();
  510.                 } catch (\Aviatur\CustomerBundle\Exception\ValidateException $e) {
  511.                     $mensaje 'Información incompleta o inconsistente: ' $e->getMessage();
  512.                     $errorHandler->errorRedirectNoEmail('/vuelos/detalle'''$mensaje);
  513.                     return $this->json(['error' => $mensaje]);
  514.                 }
  515.                 /* } */
  516.                 /*
  517.                 if (!$isFront && !$this->validateSanctions($session, $validateSanctions, ['documentnumber' => $billingData['doc_num'], 'name' => $billingData['first_name'].' '.$billingData['last_name']], $paymentMethod)) {
  518.                     $errorHandler->errorRedirectNoEmail('/vuelos/detalle', '', 'sanctions_candidate');
  519.                     return $this->json(['error' => 'sanctions_candidate']);
  520.                 }
  521.                 */
  522.                 /* if ($login_is_on == '1') {
  523.                   $session->set('register-extra-data', [
  524.                   'email' => $billingData["email"],
  525.                   'documentType' => $doc_type[0],
  526.                   'documentNumber' => $billingData['doc_num'],
  527.                   'firstName' => $billingData["first_name"],
  528.                   'lastName' => $billingData["last_name"],
  529.                   'gender' => $passangerData["gender_1_1"],
  530.                   'birthDate' => $passangerData["birthday_1_1"],
  531.                   'address' => $billingData['address'] != '' ? $billingData['address'] : $passangerData["address_1_1"],
  532.                   'phone' => $billingData["phone"]
  533.                   ]);
  534.                   return $this->json(array("error" => "redirect_to_register"));
  535.                   } */
  536.                 $return = [
  537.                     'id' => $customer->getId(),
  538.                 ];
  539.                 if (isset($redemptionPoint)) {
  540.                     $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_ath');
  541.                     if (!isset(json_decode($parameters->getDescription())->NoOtp) || (isset(json_decode($parameters->getDescription())->NoOtp) && json_decode($parameters->getDescription())->NoOtp == false)) {
  542.                         $return += $this->generateOtp($redemptionPoint$session$postData);
  543.                     }
  544.                 }
  545.                 return $this->json($return);
  546.             } else {
  547.                 $errorHandler->errorRedirect('/vuelos/detalle''''Ha ocurrido un error en la consulta de usuarios por email');
  548.                 return $this->json(['error' => 'Ha ocurrido un error en la consulta de usuarios por email']);
  549.             }
  550.         }
  551.     }
  552.     public function loginSelectAction(Request $requestAviaturWebService $webServiceRouterInterface $routerParameterBagInterface $parameterBag)
  553.     {
  554.         $email $request->request->get('email');
  555.         $em $this->getDoctrine()->getManager();
  556.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneBy(['email' => $email]);
  557.         $enabled false;
  558.         $session = new Session();
  559.         $session->set('AnonymousEmail'$email);
  560.         if (!empty($customer)) {
  561.             if (false == $customer->getEnabled()) {
  562.                 return $this->redirect($this->generateUrl('aviatur_password_create_nocheck'));
  563.             } else {
  564.                 $route $router->match($this->generateUrl('fos_user_security_login'));
  565.                 return $this->forward($route['_controller'], $route);
  566.             }
  567.         } else {
  568.             $customerModel = new CustomerModel();
  569.             $xmlRequest $customerModel->getXmlFindUserByEmail($email4);
  570.             $response $webService->busWebServiceAmadeus('GENERALLAVE'$parameterBag->get('provider_service'), $xmlRequest);
  571.             if (!is_object($response)) {
  572.                 return $this->redirect($this->generateUrl('fos_user_registration_register'));
  573.             } elseif (('FALLO' == $response->RESULTADO)) {
  574.                 return $this->redirect($this->generateUrl('fos_user_registration_register'));
  575.             } else {
  576.                 $customer = new Customer();
  577.                 $dataNumber $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneBy(['code' => $response->document->id]);
  578.                 $dataGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneBy(['code' => $response->gender->id]);
  579.                 $dataMaritalStatus $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneBy(['code' => $response->marital_starus->id]);
  580.                 $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneBy(['code' => $response->city->id]);
  581.                 $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneBy(['code' => $response->country->id]);
  582.                 $customer->setAviaturclientid((int) $response->id);
  583.                 $customer->setDocumentType($dataNumber);
  584.                 $customer->setCivilStatus($dataMaritalStatus);
  585.                 $customer->setGenderAviatur($dataGender);
  586.                 $customer->setCity($dataCity);
  587.                 $customer->setCountry($dataCountry);
  588.                 $customer->setDocumentnumber($response->document->number);
  589.                 $customer->setFirstname($response->name);
  590.                 $customer->setLastname($response->last_name);
  591.                 $customer->setBirthdate(new \DateTime($response->birth_date));
  592.                 $customer->setAddress($response->address);
  593.                 $customer->setPhone($response->phone_number);
  594.                 $customer->setCellphone($response->mobile_phone_number);
  595.                 $customer->setEmail($response->email);
  596.                 $customer->setEmailCanonical($response->email);
  597.                 $customer->setUsername($response->email);
  598.                 $customer->setUsernameCanonical($response->email);
  599.                 $customer->setPassword($response->password);
  600.                 $customer->setAcceptInformation(0);
  601.                 $customer->setAcceptSms(0);
  602.                 $customer->setPersonType(8);
  603.                 $customer->setFrecuencySms(0);
  604.                 $customer->setCorporateId('');
  605.                 $customer->setCorporateName('');
  606.                 $customer->setEnabled(1);
  607.                 $customer->setRoles([]);
  608.                 $emo $this->getDoctrine()->getManager();
  609.                 $emo->persist($customer);
  610.                 $emo->flush();
  611.                 $route $router->match($this->generateUrl('fos_user_security_login'));
  612.                 return $this->forward($route['_controller'], $route);
  613.             }
  614.         }
  615.     }
  616.     public function getCustomerCardsAction(Request $requestTokenStorageInterface $tokenStorageCustomerMethodPaymentService $methodPaymentService)
  617.     {
  618.         if ($request->isXmlHttpRequest()) {
  619.             $customerLogin $tokenStorage->getToken()->getUser();
  620.             $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerLoginfalse);
  621.             if ('NoInfo' !== $infoMethodPaymentByClient['info']) {
  622.                 return $this->json(['info' => 'customer_with_methods_saved''info' => $infoMethodPaymentByClient['info']]);
  623.             }
  624.             return $this->json(['error' => 'no-data']);
  625.         }
  626.         return $this->json(['error']);
  627.     }
  628.     public function passwordCreateAction(TwigFolder $twigFolder)
  629.     {
  630.         $agencyFolder $twigFolder->twigFlux();
  631.         $response $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/create-password.html.twig'), []);
  632.         return $response;
  633.     }
  634.     public function passwordResetAction(TwigFolder $twigFolder)
  635.     {
  636.         $agencyFolder $twigFolder->twigFlux();
  637.         $response $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/reset-password.html.twig'), []);
  638.         return $response;
  639.     }
  640.     public function customerAccountAction(AviaturErrorHandler $errorHandlerTwigFolder $twigFolderTokenStorageInterface $tokenStorageCustomerMethodPaymentService $methodPaymentServiceAviaturLoginService $loginService)
  641.     {
  642.         $agencyFolder $twigFolder->twigFlux();
  643.         $em $this->getDoctrine()->getManager();
  644.         //var_dump($tokenStorage->getToken()->getUser());die;
  645.         if (is_object($tokenStorage->getToken()->getUser())) {
  646.             $userLogged $tokenStorage->getToken()->getUser()->getId();
  647.         } else {
  648.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  649.         }
  650.         $customer $this->getUser();
  651.         $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerfalse);
  652.         if ($infoMethodPaymentByClient) {
  653.             $cardSaved = [];
  654.             if (false !== $loginService->validActiveSession()) {
  655.                 if ('NoInfo' !== $infoMethodPaymentByClient['info']) {
  656.                     foreach ($infoMethodPaymentByClient['info'] as $key => $value) {
  657.                         $cardSaved['info'][] = [substr($key02), substr($key24)];
  658.                     }
  659.                 }
  660.             }
  661.         }
  662.         $billingList $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
  663.         if ($billingList) {
  664.             $dataBilling = [];
  665.             $count 0;
  666.             foreach ($billingList as $billings) {
  667.                 if ('ACTIVE' == $billings->getStatus()) {
  668.                     $dataBilling[$count]['id'] = $billings->getId();
  669.                     $dataBilling[$count]['customerId'] = $userLogged;
  670.                     $dataBilling[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
  671.                     $dataBilling[$count]['documentNumber'] = $billings->getDocumentnumber();
  672.                     $dataBilling[$count]['firstname'] = $billings->getFirstname();
  673.                     $dataBilling[$count]['lastname'] = $billings->getLastname();
  674.                     $dataBilling[$count]['email'] = $billings->getEmail();
  675.                     $dataBilling[$count]['address'] = $billings->getAddress();
  676.                     $dataBilling[$count]['phone'] = $billings->getPhone();
  677.                     ++$count;
  678.                 }
  679.             }
  680.         }
  681.         $newsletter = new Newsletter();
  682.         $newsletterForm $this->createForm(\Aviatur\FormBundle\Form\NewsletterAsyncType::class, $newsletter);
  683.         $paylaterParam $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_pay_later');
  684.         $paylinkParam $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_pay_link');
  685.         $data = [
  686.             'cards' => !empty($cardSaved) ? $cardSaved null,
  687.             'billings' => !empty($dataBilling) ? $dataBilling null,
  688.             'newsletter_form' => $newsletterForm->createView(),
  689.             'paylater' => $paylaterParam->getValue() == true false,
  690.             'paylink' => $paylinkParam->getValue() == true false,
  691.         ];
  692.         $response $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-account.html.twig'), $data);
  693.         return $response;
  694.     }
  695.     public function getBillingsAjaxAction(TokenStorageInterface $tokenStorage)
  696.     {
  697.         $userLogged $tokenStorage->getToken()->getUser()->getId();
  698.         $em $this->getDoctrine()->getManager();
  699.         $billingList $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
  700.         if ($billingList) {
  701.             $dataBilling = [];
  702.             $count 0;
  703.             foreach ($billingList as $billings) {
  704.                 if ('ACTIVE' == $billings->getStatus()) {
  705.                     $dataBilling[$count]['id'] = $billings->getId();
  706.                     $dataBilling[$count]['customerId'] = $userLogged;
  707.                     $dataBilling[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
  708.                     $dataBilling[$count]['documentNumber'] = $billings->getDocumentnumber();
  709.                     $dataBilling[$count]['firstname'] = $billings->getFirstname();
  710.                     $dataBilling[$count]['lastname'] = $billings->getLastname();
  711.                     $dataBilling[$count]['email'] = $billings->getEmail();
  712.                     $dataBilling[$count]['address'] = $billings->getAddress();
  713.                     $dataBilling[$count]['phone'] = $billings->getPhone();
  714.                     $dataBilling[$count]['country'] = $billings->getCountry()->getId();
  715.                     $dataBilling[$count]['city'] = $billings->getCity()->getId();
  716.                     ++$count;
  717.                 }
  718.             }
  719.             return $this->json(['status' => 'success''data' => ['billings' => !empty($dataBilling) ? $dataBilling null'totalBillings' => $count]]);
  720.         } else {
  721.             return $this->json(['status' => 'error']);
  722.         }
  723.     }
  724.     public function customerBookingAction(SessionInterface $sessionAviaturEncoder $aviaturEncoderTwigFolder $twigFolderTokenStorageInterface $tokenStorage)
  725.     {
  726.         $customer $tokenStorage->getToken()->getUser();
  727.         $em $this->getDoctrine()->getManager();
  728.         $orderProducts = [];
  729.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  730.         $agencyOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$agency);
  731.         $orderProducts = \array_merge($orderProducts$agencyOrderProducts);
  732.         if ('aviatur.com' == $agency->getDomain()) {
  733.             $metasearch $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1); //Metasearch
  734.             $metaOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$metasearch);
  735.             $orderProducts = \array_merge($orderProducts$metaOrderProducts);
  736.             $mobile $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(102); //Mobile
  737.             $mobileOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$mobile);
  738.             $orderProducts = \array_merge($orderProducts$mobileOrderProducts);
  739.         }
  740.         $payRequests = [];
  741.         $orders = [];
  742.         foreach ($orderProducts as $key => $orderProduct) {
  743.             $productRequestString $aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey());
  744.             $productResponseString $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  745.             $productRequest json_decode($productRequestStringtrue);
  746.             $productResponse json_decode($productResponseStringtrue);
  747.             if (!is_array($productRequest)) {
  748.                 continue;
  749.             }
  750.             $productRequest['orderId'] = 'ON' $orderProduct->getOrder()->getId();
  751.             if (isset($productRequest['x_amount'])) {
  752.                 $productRequest['x_payment_type'] = 'p2p';
  753.                 $productRequest['x_transaction_date'] = $productResponse['x_transaction_date'] ?? '';
  754.                 $productRequest['x_response_code'] = $productResponse['x_response_code'] ?? '';
  755.                 $productRequest['x_response_reason_code'] = $productResponse['x_response_reason_code'] ?? '';
  756.                 $productRequest['x_response_reason_text'] = isset($productResponse['x_response_reason_text']) ? utf8_decode($productResponse['x_response_reason_text']) : '';
  757.                 $productRequest['x_ta_response_reason_code'] = $productResponse['x_ta_response_reason_code'] ?? '--';
  758.                 $productRequest['x_approval_code'] = $productResponse['x_approval_code'] ?? '';
  759.                 $productRequest['x_ta_approval_code'] = $productResponse['x_ta_approval_code'] ?? '--';
  760.                 $productRequest['x_transaction_id'] = $productResponse['x_transaction_id'] ?? '--';
  761.                 $productRequest['x_ta_transaction_id'] = $productResponse['x_ta_transaction_id'] ?? '--';
  762.                 $payRequests[] = $productRequest;
  763.                 $orders['ON' $orderProduct->getOrder()->getId()] = null;
  764.             } elseif (isset($productRequest['totalAmount']) && isset($productResponse['getTransactionInformationResult'])) {
  765.                 $productRequest['x_payment_type'] = 'pse';
  766.                 $productRequest['x_invoice_num'] = $productRequest['reference'];
  767.                 $productRequest['x_description'] = $productRequest['description'];
  768.                 $productRequest['x_currency_code'] = $productRequest['currency'];
  769.                 $productRequest['x_amount'] = $productRequest['totalAmount'];
  770.                 $productRequest['x_tax'] = $productRequest['taxAmount'];
  771.                 $productRequest['x_amount_base'] = $productRequest['devolutionBase'];
  772.                 $productRequest['x_transaction_date'] = $productResponse['getTransactionInformationResult']['requestDate'] ?? '';
  773.                 $productRequest['x_response_code'] = $productResponse['getTransactionInformationResult']['responseCode'] ?? '';
  774.                 $productRequest['x_response_reason_code'] = $productResponse['getTransactionInformationResult']['responseReasonCode'] ?? '';
  775.                 $productRequest['x_response_reason_text'] = $productResponse['getTransactionInformationResult']['responseReasonText'] ?? '';
  776.                 $productRequest['x_approval_code'] = $productResponse['getTransactionInformationResult']['trazabilityCode'] ?? '';
  777.                 $productRequest['x_transaction_id'] = $productResponse['getTransactionInformationResult']['transactionID'] ?? '';
  778.                 $payRequests[] = $productRequest;
  779.                 $orders['ON' $orderProduct->getOrder()->getId()] = null;
  780.             } elseif (isset($productRequest['notificationRequest']) && isset($productResponse['payResponse'])) {
  781.                 $productRequest['x_payment_type'] = 'safetypay';
  782.                 $productRequest['x_invoice_num'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:MerchantSalesID'];
  783.                 $productRequest['x_description'] = @$productRequest['dataTransf']['x_description'];
  784.                 $productRequest['x_currency_code'] = @$productRequest['dataTransf']['x_currency'];
  785.                 $productRequest['x_amount'] = @$productRequest['dataTransf']['x_total_amount'];
  786.                 $productRequest['x_tax'] = @$productRequest['dataTransf']['x_tax_amount'];
  787.                 $productRequest['x_airport_tax'] = 0;
  788.                 $productRequest['x_service_fee_tax'] = 0;
  789.                 $productRequest['x_airport_tax'] = 0;
  790.                 $productRequest['x_airport_tax'] = 0;
  791.                 $productRequest['x_amount_base'] = @$productRequest['dataTransf']['x_devolution_base'];
  792.                 $productRequest['x_transaction_date'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:RequestDateTime'];
  793.                 $productRequest['x_response_reason_code'] = @$productResponse['dataTransf']['x_response_code'];
  794.                 switch ($productRequest['x_response_reason_code']) {
  795.                     case 101:
  796.                         $productRequest['x_response_code'] = 3;
  797.                         break;
  798.                     case 100:
  799.                         $productRequest['x_response_code'] = 2;
  800.                         break;
  801.                     case null:
  802.                         $productRequest['x_response_code'] = 3;
  803.                         break;
  804.                     default:
  805.                         $productRequest['x_response_code'] = 1;
  806.                         break;
  807.                 }
  808.                 $productRequest['x_response_reason_text'] = @$productResponse['dataTransf']['x_response_reason_text'];
  809.                 $productRequest['x_approval_code'] = 'N/A';
  810.                 $productRequest['x_transaction_id'] = 'N/A';
  811.                 $payRequests[] = $productRequest;
  812.                 $orders['ON' $orderProduct->getOrder()->getId()] = null;
  813.             }
  814.             $historicalOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalOrderProduct::class)->findByOrderProduct($orderProduct);
  815.             if (!= sizeof($historicalOrderProducts)) {
  816.                 foreach ($historicalOrderProducts as $historicalOrderProduct) {
  817.                     $productRequest $aviaturEncoder->AviaturDecode($historicalOrderProduct->getPayrequest(), $historicalOrderProduct->getPublickey());
  818.                     $productResponse $aviaturEncoder->AviaturDecode($historicalOrderProduct->getPayresponse(), $historicalOrderProduct->getPublickey());
  819.                     $productRequest json_decode($productRequesttrue);
  820.                     $productResponse json_decode($productResponsetrue);
  821.                     if (isset($productRequest['x_amount'])) {
  822.                         $productRequest['x_payment_type'] = 'p2p';
  823.                         $productRequest['x_transaction_date'] = $productResponse['x_transaction_date'] ?? '';
  824.                         $productRequest['x_response_code'] = $productResponse['x_response_code'] ?? '';
  825.                         $productRequest['x_response_reason_code'] = $productResponse['x_response_reason_code'] ?? '';
  826.                         $productRequest['x_response_reason_text'] = isset($productResponse['x_response_reason_text']) ? utf8_decode($productResponse['x_response_reason_text']) : '';
  827.                         $productRequest['x_ta_response_reason_code'] = $productResponse['x_ta_response_reason_code'] ?? '';
  828.                         $productRequest['x_approval_code'] = $productResponse['x_approval_code'] ?? '';
  829.                         $productRequest['x_ta_approval_code'] = $productResponse['x_ta_approval_code'] ?? '';
  830.                         $productRequest['x_transaction_id'] = $productResponse['x_transaction_id'] ?? '';
  831.                         $productRequest['x_ta_transaction_id'] = $productResponse['x_ta_transaction_id'] ?? '';
  832.                         $payRequests[sizeof($payRequests) - 1]['history'][] = $productRequest;
  833.                     } elseif (isset($productRequest['totalAmount']) && isset($productResponse['getTransactionInformationResult'])) {
  834.                         $productRequest['x_payment_type'] = 'pse';
  835.                         $productRequest['x_invoice_num'] = $productRequest['reference'];
  836.                         $productRequest['x_description'] = $productRequest['description'];
  837.                         $productRequest['x_currency_code'] = $productRequest['currency'];
  838.                         $productRequest['x_amount'] = $productRequest['totalAmount'];
  839.                         $productRequest['x_tax'] = $productRequest['taxAmount'];
  840.                         $productRequest['x_amount_base'] = $productRequest['devolutionBase'];
  841.                         $productRequest['x_transaction_date'] = $productResponse['getTransactionInformationResult']['requestDate'] ?? '';
  842.                         $productRequest['x_response_code'] = $productResponse['getTransactionInformationResult']['responseCode'];
  843.                         $productRequest['x_response_reason_code'] = $productResponse['getTransactionInformationResult']['responseReasonCode'];
  844.                         $productRequest['x_response_reason_text'] = utf8_decode($productResponse['getTransactionInformationResult']['responseReasonText']);
  845.                         $productRequest['x_approval_code'] = $productResponse['getTransactionInformationResult']['trazabilityCode'] ?? '';
  846.                         $productRequest['x_transaction_id'] = $productResponse['getTransactionInformationResult']['transactionID'] ?? '';
  847.                         $payRequests[sizeof($payRequests) - 1]['history'][] = $productRequest;
  848.                     } elseif (isset($productRequest['notificationRequest']) && isset($productResponse['payResponse'])) {
  849.                         $productRequest['x_payment_type'] = 'safetypay';
  850.                         $productRequest['x_invoice_num'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:MerchantSalesID'];
  851.                         $productRequest['x_description'] = @$productRequest['dataTransf']['x_description'];
  852.                         $productRequest['x_currency_code'] = @$productRequest['dataTransf']['x_currency'];
  853.                         $productRequest['x_amount'] = @$productRequest['dataTransf']['x_total_amount'];
  854.                         $productRequest['x_tax'] = @$productRequest['dataTransf']['x_tax_amount'];
  855.                         $productRequest['x_airport_tax'] = 0;
  856.                         $productRequest['x_service_fee_tax'] = 0;
  857.                         $productRequest['x_amount_base'] = @$productRequest['dataTransf']['x_devolution_base'];
  858.                         $productRequest['x_transaction_date'] = @$productRequest['tokenRequest']['urn:ExpressTokenRequest']['urn:RequestDateTime'];
  859.                         $productRequest['x_response_code'] = 'N/A'//$productResponse['getTransactionInformationResult']['responseCode'];
  860.                         $productRequest['x_response_reason_code'] = 'N/A'//$productResponse['getTransactionInformationResult']['responseReasonCode'];
  861.                         $productRequest['x_response_reason_text'] = 'N/A'//$productResponse['getTransactionInformationResult']['responseReasonText'];
  862.                         $productRequest['x_approval_code'] = 'N/A'//$productResponse['getTransactionInformationResult']['trazabilityCode'];
  863.                         $productRequest['x_transaction_id'] = 'N/A'//$productResponse['getTransactionInformationResult']['transactionID'];
  864.                         $payRequests[sizeof($payRequests) - 1]['history'][] = $productRequest;
  865.                     }
  866.                 }
  867.             }
  868.             //            var_dump($productResponse);
  869.             //            CREATE THE PUBLIC KEY AND ENCODE PayRequest AND PayResponse
  870.             //            $encodedRequest = $this->get("aviatur_md5")->AviaturEncode($orderProduct->getPayRequest(), $orderProduct->getPublicKey());
  871.             //            $encodedResponse = $this->get("aviatur_md5")->AviaturEncode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  872.             //            $publicKey = $this->get("aviatur_md5")->aviaturRandomKey();
  873.             //            $orderProduct->setPayRequest($encodedRequest);
  874.             //            $orderProduct->setPayResponse($encodedResponse);
  875.             //            $orderProduct->setPublicKey($publicKey);
  876.             //            $em = $this->getDoctrine()->getManager();
  877.             //            $em->persist($orderProduct);
  878.             //            $em->flush();
  879.         }
  880.         $agencyFolder $twigFolder->twigFlux();
  881.         $twigView $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-booking.html.twig');
  882.         return $this->render($twigView, ['payRequests' => $payRequests'orders' => $orders]);
  883.     }
  884.     public function customerBookingCAction(SessionInterface $sessionAviaturEncoder $aviaturEncoderTwigFolder $twigFolderTokenStorageInterface $tokenStorage)
  885.     {
  886.         $em $this->getDoctrine()->getManager();
  887.         $paylaterParam $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_pay_later');
  888.         //$paylinkParam = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_pay_link');
  889.         if ($paylaterParam->getValue() == /*|| $paylinkParam->getValue() == 1*/) {
  890.             $customer $tokenStorage->getToken()->getUser();
  891.             $em $this->getDoctrine()->getManager();
  892.             $orderProducts = [];
  893.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  894.             $agencyOrderProductsPayLater $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPayLaterWithCustomerAndAgency($customer$agency);
  895.             //$agencyOrderProductsPayLink = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPayLinkWithCustomerAndAgency($customer, $agency);
  896.             $orderProducts = \array_merge($orderProducts$agencyOrderProductsPayLater/*,$agencyOrderProductsPayLink*/);
  897.             if ('aviatur.com' == $agency->getDomain() || 'octopussym.com' == $agency->getDomain()) {
  898.                 $metasearch $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1); //Metasearch
  899.                 $metaOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$metasearch);
  900.                 $orderProducts = \array_merge($orderProducts$metaOrderProducts);
  901.                 $mobile $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(102); //Mobile
  902.                 $mobileOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$mobile);
  903.                 $orderProducts = \array_merge($orderProducts$mobileOrderProducts);
  904.             }
  905.             $payRequests = [];
  906.             $orders = [];
  907.             foreach ($orderProducts as $key => $orderProduct) {
  908.                 $xml simplexml_load_string($orderProduct->getAddproductdata());
  909.                 $totalAmount = (string) $xml->xpath('//fare_data//fare//total_amount')[0];
  910.                 $transa = (string) $xml->xpath('//transaction_id')[0];
  911.                 $data = (string) $xml->xpath('//booking_data')[0];
  912.                 $cdata simplexml_load_string("<root>$data</root>");
  913.                 $arrivalAirportCode = (string) $cdata->xpath('//arrival_airport/code')[0];
  914.                 $departureAirportCode = (string) $cdata->xpath('//departure_airport/code')[0];
  915.                 $departuredate = (string) $cdata->xpath('//departure_datetime')[0];
  916.                 $airline = (string) $xml->xpath('//aerolinea/code')[0];
  917.                 $orderProduct->Amount $totalAmount;
  918.                 $orderProduct->transaction $transa;
  919.                 $orderProduct->destination $departureAirportCode " - " $arrivalAirportCode;
  920.                 $orderProduct->departureDate $departuredate;
  921.                 $orderProduct->airline $airline;
  922.                 
  923.                 $providerIdentifier $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findProviderIdentifierById($orderProduct->getProvider()->getId());
  924.                 
  925.                 $provider $orderProducts[$key]->getProvider();
  926.                 if ($provider) {
  927.                 // Modificar el provideridentifier con el valor que quieres
  928.                 $provider->setProviderIdentifier($providerIdentifier['provideridentifier']."|".$providerIdentifier['provideridentifier']);
  929.             }
  930.                 $trace $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderTrace::class)->findByTransactionId($transa);
  931.                 //valida si se generaron ambas reservas en la combinacion
  932.                 $hasNullOrder false;
  933.                 foreach ($trace as $item) {
  934.                     if ($item->getOrder() === null) {
  935.                         $hasNullOrder true;
  936.                         break;
  937.                     }
  938.                 }
  939.                 if ($hasNullOrder) {
  940.                     unset($orderProducts[$key]);
  941.                     continue;
  942.                 }
  943.                 if (isset($orders[$transa])) {
  944.                     $orders[$transa] .=  "|" $orderProduct->getorder()->getId();
  945.                 } else {
  946.                     $orders[$transa] = $orderProduct->getorder()->getId();                    
  947.                 }
  948.             }
  949.         } else {
  950.             $agencyFolder $twigFolder->twigFlux();
  951.             $twigView $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-booking.html.twig');
  952.             return $this->render($twigView, ['orderProducts' => [], 'orders' => [], 'data' => 'true']);
  953.         }
  954.         $agencyFolder $twigFolder->twigFlux();
  955.         $twigView $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-booking.html.twig');
  956.         return $this->render($twigView, ['orderProducts' => $orderProducts'orders' => $orders'data' => 'true']);
  957.     }
  958.     public function customerBookingPAction(SessionInterface $sessionAviaturEncoder $aviaturEncoderTwigFolder $twigFolderTokenStorageInterface $tokenStorage)
  959.     {
  960.         $em $this->getDoctrine()->getManager();
  961.         $paylinkParam $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_pay_link');
  962.         if ($paylinkParam->getValue() == 1) {
  963.             $customer $tokenStorage->getToken()->getUser();
  964.             $em $this->getDoctrine()->getManager();
  965.             $orderProducts = [];
  966.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  967.             
  968.             $agent $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getAgentForPayLinkFromCustomer($customer);
  969.             $agencyOrderProductsPayLink $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPayLinkWithAgentAndAgency($agent$agency);
  970.             $orderProducts = \array_merge($orderProducts$agencyOrderProductsPayLink);
  971.             if ('aviatur.com' == $agency->getDomain()) {
  972.                 $metasearch $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1); //Metasearch
  973.                 $metaOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$metasearch);
  974.                 $orderProducts = \array_merge($orderProducts$metaOrderProducts);
  975.                 $mobile $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(102); //Mobile
  976.                 $mobileOrderProducts $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsByCustomerAndAgency($customer$mobile);
  977.                 $orderProducts = \array_merge($orderProducts$mobileOrderProducts);
  978.             }
  979.             $payRequests = [];
  980.             $orders = [];
  981.             foreach ($orderProducts as $key => $orderProduct) {
  982.                 $xml simplexml_load_string($orderProduct->getAddproductdata());
  983.                 $totalAmount = (string) $xml->xpath('//fare_data//fare//total_amount')[0];
  984.                 $transa = (string) $xml->xpath('//transaction_id')[0];
  985.                 $data = (string) $xml->xpath('//booking_data')[0];
  986.                 $cdata simplexml_load_string("<root>$data</root>");
  987.                 $arrivalAirportCode = (string) $cdata->xpath('//arrival_airport/code')[0];
  988.                 $departureAirportCode = (string) $cdata->xpath('//departure_airport/code')[0];
  989.                 $departuredate = (string) $cdata->xpath('//departure_datetime')[0];
  990.                 $airline = (string) $xml->xpath('//aerolinea/code')[0];
  991.                 $link $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderLinkPayment($orderProduct->getOrder()->getId());
  992.                 $orderProduct->Amount $totalAmount;
  993.                 $orderProduct->transaction $transa;
  994.                 $orderProduct->destination $departureAirportCode " - " $arrivalAirportCode;
  995.                 $orderProduct->departureDate $departuredate;
  996.                 $orderProduct->airline $airline;
  997.                 $orderProduct->link $link;
  998.                 $trace $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderTrace::class)->findByTransactionId($transa);
  999.                 //valida si se generaron ambas reservas en la combinacion
  1000.                 $hasNullOrder false;
  1001.                 foreach ($trace as $item) {
  1002.                     if ($item->getOrder() === null) {
  1003.                         $hasNullOrder true;
  1004.                         break;
  1005.                     }
  1006.                 }
  1007.                 if ($hasNullOrder) {
  1008.                     unset($orderProducts[$key]);
  1009.                     continue;
  1010.                 }
  1011.                 if (isset($orders[$transa])) {
  1012.                     $orders[$transa] .=  "|" $orderProduct->getorder()->getId();
  1013.                 } else {
  1014.                     $orders[$transa] = $orderProduct->getorder()->getId();
  1015.                 }
  1016.             }
  1017.         } else {
  1018.             $agencyFolder $twigFolder->twigFlux();
  1019.             $twigView $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-booking.html.twig');
  1020.             return $this->render($twigView, ['orderProducts' => [], 'orders' => [], 'data' => 'true']);
  1021.         }
  1022.         $agencyFolder $twigFolder->twigFlux();
  1023.         $twigView $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-booking.html.twig');
  1024.         
  1025.         return $this->render($twigView, ['orderProducts' => $orderProducts'orders' => $orders'data' => 'true''paylink' => true]);
  1026.     }
  1027.     public function editAction(Request $requestSessionInterface $sessionAviaturWebService $webServiceTwigFolder $twigFolderUserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailerAviaturErrorHandler $errorHandlerTokenStorageInterface $tokenStorageValidatorInterface $validatorParameterBagInterface $parameterBag)
  1028.     {
  1029.         $providerService $parameterBag->get('provider_service');
  1030.         $emailNotification $parameterBag->get('email_notification');
  1031.         $em $this->getDoctrine()->getManager();
  1032.         $agencyFolder $twigFolder->twigFlux();
  1033.         $user $tokenStorage->getToken()->getUser();
  1034.         if (false === is_object($user)) {
  1035.             return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '''Acceso no autorizado'));
  1036.         }
  1037.         $id $user->getId();
  1038.         $post $request->request->get('customer_edit_form');
  1039.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($id);
  1040.         $city $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry($customer->getCountry()->getId(), ['description' => 'ASC']);
  1041.         $email $customer->getEmail();
  1042.         foreach ($city as $infocities) {
  1043.             $idCity[] = $infocities->getCode();
  1044.             $nameCity[] = $infocities->getDescription();
  1045.         }
  1046.         $info = ['idCity' => $idCity'nameCity' => $nameCity];
  1047.         $form $this->createForm(\Aviatur\CustomerBundle\Form\CustomerEdit::class, $customer);
  1048.         $method 'edition';
  1049.         $date = new DateTime();
  1050.         $form->handleRequest($request);
  1051.         if ($form->isSubmitted()) {
  1052.             $historical = (object) [
  1053.                 'Firstname' => $customer->getFirstname(),
  1054.                 'Documentnumber' => $customer->getDocumentnumber(),
  1055.                 'DocumentType' => $customer->getDocumentType()->getCode(),
  1056.                 'Lastname' => $customer->getLastname(),
  1057.                 'Birthdate' => $customer->getBirthdate(),
  1058.                 'Address' => $customer->getAddress(),
  1059.                 'Phone' => $customer->getPhone(),
  1060.                 'Cellphone' => $customer->getCellphone(),
  1061.                 'Email' => $customer->getEmail(),
  1062.                 'Password' => $customer->getPassword(),
  1063.                 'Username' => $customer->getUsername(),
  1064.                 'UsernameCanonical' => $customer->getUsernameCanonical(),
  1065.                 'EmailCanonical' => $customer->getEmailCanonical(),
  1066.                 'Enabled' => $customer->getEnabled(),
  1067.                 'Salt' => $customer->getSalt(),
  1068.                 'country_id' => $customer->getCountry()->getCode(),
  1069.                 //'CreatedAt' => $customer->getCreatedAt(),
  1070.                 //'UpdatedAt' => $date,
  1071.                 'CustomerId' => $customer->getId(),
  1072.             ];
  1073.             if ($form->isValid()) {
  1074.                 $userchange $this->getCustomerInfo($request$session$parameterBag$webService$twigFolder$passwordEncoder$mailer$customer$post$method$email);
  1075.                 $this->historicalCustomer($historical$post$emnull$customer);
  1076.                 return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_customer_account_nocheck', ['cityId' => $customer->getCity()->getId(), 'city' => $customer->getCity()->getId(), 'id' => $id]), 'Actualizar Datos'$userchange));
  1077.             } else {
  1078.                 $errors $validator->validate($customer);
  1079.                 $datos = ['cityId' => $customer->getCity()->getId(), 'city' => $customer->getCity()->getCode(), 'info' => $info'form' => $form->createView(), 'errors' => $errors];
  1080.                 return $this->render($twigFolder->twigExists('@AviaturTwig' $agencyFolder '/Customer/customer-edition.html.twig'), $datos);
  1081.             }
  1082.         } else {
  1083.             return $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-edition.html.twig'), ['cityId' => $customer->getCity()->getId(), 'city' => $customer->getCity()->getCode(), 'info' => $info'form' => $form->createView()]);
  1084.         }
  1085.     }
  1086.     public function resetPasswordAction(Request $requestSessionInterface $sessionAviaturWebService $webServiceAviaturErrorHandler $errorHandlerTokenStorageInterface $tokenStorageTwigFolder $twigFolderUserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailerParameterBagInterface $parameterBag)
  1087.     {
  1088.         $providerService $parameterBag->get('provider_service');
  1089.         $emailNotification $parameterBag->get('email_notification');
  1090.         $post = [];
  1091.         $em $this->getDoctrine()->getManager();
  1092.         $agencyFolder $twigFolder->twigFlux();
  1093.         $id $tokenStorage->getToken()->getUser();
  1094.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($id);
  1095.         $post_form $request->request->get('customer_edit_form');
  1096.         $method 'password';
  1097.         $CivilStatus '';
  1098.         if ($customer->getCivilStatus()) {
  1099.             $CivilStatus $customer->getCivilStatus()->getId();
  1100.         }
  1101.         $date = new DateTime();
  1102.         $historical = (object) [
  1103.             'Firstname' => $customer->getFirstname(),
  1104.             'Documentnumber' => $customer->getDocumentnumber(),
  1105.             'DocumentType' => $customer->getDocumentType()->getCode(),
  1106.             'Lastname' => $customer->getLastname(),
  1107.             'Birthdate' => $customer->getBirthdate(),
  1108.             'Address' => $customer->getAddress(),
  1109.             'Phone' => $customer->getPhone(),
  1110.             'Cellphone' => $customer->getCellphone(),
  1111.             'Email' => $customer->getEmail(),
  1112.             'Password' => $customer->getPassword(),
  1113.             'Username' => $customer->getUsername(),
  1114.             'UsernameCanonical' => $customer->getUsernameCanonical(),
  1115.             'EmailCanonical' => $customer->getEmailCanonical(),
  1116.             'Enabled' => $customer->getEnabled(),
  1117.             'Salt' => $customer->getSalt(),
  1118.             'country_id' => $customer->getCountry()->getCode(),
  1119.             //'CreatedAt' => $customer->getCreatedAt(),
  1120.             //'UpdatedAt' => $date,
  1121.             'CustomerId' => $customer->getId(),
  1122.         ];
  1123.         if ('POST' == $request->getMethod()) {
  1124.             $post['Firstname'] = $customer->getFirstname();
  1125.             $post['lastname'] = $customer->getLastname();
  1126.             $post['birthdate'] = $customer->getBirthdate()->format('Y-m-d');
  1127.             $post['address'] = $customer->getAddress();
  1128.             $post['phone'] = $customer->getPhone();
  1129.             $post['cellphone'] = $customer->getCellphone();
  1130.             $post['email'] = $customer->getEmail();
  1131.             $post['city'] = $customer->getCity()->getId();
  1132.             $post['country'] = $customer->getCountry()->getId();
  1133.             $post['CivilStatus'] = $CivilStatus;
  1134.             $post['aviaturclientid'] = $customer->getAviaturclientid();
  1135.             $post['DocumentNumber'] = $customer->getDocumentnumber();
  1136.             $post['genderAviatur'] = $customer->getFirstname();
  1137.             $post['acceptInformation'] = $customer->getAcceptInformation();
  1138.             $post['acceptSms'] = $customer->getAcceptSms();
  1139.             $post['password_new'] = $post_form['password_new'];
  1140.             $post['password_repeat'] = $post_form['password_repeat'];
  1141.             $userchange $this->getCustomerInfo($request$session$parameterBag$webService$twigFolder$passwordEncoder$mailer$customer$post$method);
  1142.             $this->historicalCustomer($historical$post$emnull$customer);
  1143.             return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_customer_edit_info', ['id' => $id]), 'Actualizar Datos'$userchange));
  1144.         } else {
  1145.             return $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/reset-password-user.html.twig'));
  1146.         }
  1147.     }
  1148.     public function historicalCustomer($customer$post$doctrine$asessor$newData null)
  1149.     {
  1150.         $em = !empty($doctrine) ? $doctrine $this->getDoctrine()->getManager();
  1151.         $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneById($post['country']);
  1152.         $country_id $country->getCode();
  1153.         $json '{"fields":[';
  1154.         $json_modfied_fields null;
  1155.         //Guardamos los datos antiguos en la tabla historical_customer
  1156.         $historicalCustomer = new HistoricalCustomer();
  1157.         //$historicalCustomer->setAviaturclientid($customer->getAviaturclientid());
  1158.         $historicalCustomer->setDocumentnumber($customer->Documentnumber);
  1159.         if ($customer->Documentnumber != $newData->getDocumentnumber()) {
  1160.             if (isset($json_modfied_fields)) {
  1161.                 $json_modfied_fields $json_modfied_fields ',"Documentnumber"';
  1162.             } else {
  1163.                 $json_modfied_fields '"Documentnumber"';
  1164.             }
  1165.         }
  1166.         $historicalCustomer->setDocumentTypeId($customer->DocumentType);
  1167.         if ($customer->DocumentType != $newData->getDocumentType()->getCode()) {
  1168.             if (isset($json_modfied_fields)) {
  1169.                 $json_modfied_fields $json_modfied_fields ',"DocumentType"';
  1170.             } else {
  1171.                 $json_modfied_fields '"DocumentType"';
  1172.             }
  1173.         }
  1174.         $historicalCustomer->setFirstname($customer->Firstname);
  1175.         if ($customer->Firstname != $newData->getFirstname()) {
  1176.             if (isset($json_modfied_fields)) {
  1177.                 $json_modfied_fields $json_modfied_fields ',"Firstname"';
  1178.             } else {
  1179.                 $json_modfied_fields '"Firstname"';
  1180.             }
  1181.         }
  1182.         $historicalCustomer->setLastname($customer->Lastname);
  1183.         if ($customer->Lastname != $newData->getLastname()) {
  1184.             if (isset($json_modfied_fields)) {
  1185.                 $json_modfied_fields $json_modfied_fields ',"Lastname"';
  1186.             } else {
  1187.                 $json_modfied_fields '"Lastname"';
  1188.             }
  1189.         }
  1190.         $historicalCustomer->setBirthdate($customer->Birthdate);
  1191.         if ($customer->Birthdate != $newData->getBirthdate()) {
  1192.             if (isset($json_modfied_fields)) {
  1193.                 $json_modfied_fields $json_modfied_fields ',"Birthdate"';
  1194.             } else {
  1195.                 $json_modfied_fields '"Birthdate"';
  1196.             }
  1197.         }
  1198.         $historicalCustomer->setAddress($customer->Address);
  1199.         if ($customer->Address != $newData->getAddress()) {
  1200.             if (isset($json_modfied_fields)) {
  1201.                 $json_modfied_fields $json_modfied_fields ',"Address"';
  1202.             } else {
  1203.                 $json_modfied_fields '"Address"';
  1204.             }
  1205.         }
  1206.         $historicalCustomer->setPhone($customer->Phone);
  1207.         if ($customer->Phone != $newData->getPhone()) {
  1208.             if (isset($json_modfied_fields)) {
  1209.                 $json_modfied_fields $json_modfied_fields ',"Phone"';
  1210.             } else {
  1211.                 $json_modfied_fields '"Phone"';
  1212.             }
  1213.         }
  1214.         $historicalCustomer->setCellphone($customer->Cellphone);
  1215.         if ($customer->Cellphone != $newData->getCellphone()) {
  1216.             if (isset($json_modfied_fields)) {
  1217.                 $json_modfied_fields $json_modfied_fields ',"Cellphone"';
  1218.             } else {
  1219.                 $json_modfied_fields '"Cellphone"';
  1220.             }
  1221.         }
  1222.         $historicalCustomer->setEmail($customer->Email);
  1223.         if ($customer->Email != $newData->getEmail()) {
  1224.             if (isset($json_modfied_fields)) {
  1225.                 $json_modfied_fields $json_modfied_fields ',"Email"';
  1226.             } else {
  1227.                 $json_modfied_fields '"Email"';
  1228.             }
  1229.         }
  1230.         $historicalCustomer->setPassword($customer->Password);
  1231.         if ($customer->Password != $newData->getPassword()) {
  1232.             if (isset($json_modfied_fields)) {
  1233.                 $json_modfied_fields $json_modfied_fields ',"Password"';
  1234.             } else {
  1235.                 $json_modfied_fields '"Password"';
  1236.             }
  1237.         }
  1238.         $historicalCustomer->setUsername($customer->Username);
  1239.         if ($customer->Username != $newData->getUsername()) {
  1240.             if (isset($json_modfied_fields)) {
  1241.                 $json_modfied_fields $json_modfied_fields ',"Username"';
  1242.             } else {
  1243.                 $json_modfied_fields '"Username"';
  1244.             }
  1245.         }
  1246.         $historicalCustomer->setUsernameCanonical($customer->UsernameCanonical);
  1247.         if ($customer->UsernameCanonical != $newData->getUsernameCanonical()) {
  1248.             if (isset($json_modfied_fields)) {
  1249.                 $json_modfied_fields $json_modfied_fields ',"UsernameCanonical"';
  1250.             } else {
  1251.                 $json_modfied_fields '"UsernameCanonical"';
  1252.             }
  1253.         }
  1254.         $historicalCustomer->setEmailCanonical((string) $customer->EmailCanonical);
  1255.         if ($customer->EmailCanonical != $newData->getEmailCanonical()) {
  1256.             if (isset($json_modfied_fields)) {
  1257.                 $json_modfied_fields $json_modfied_fields ',"EmailCanonical"';
  1258.             } else {
  1259.                 $json_modfied_fields '"EmailCanonical"';
  1260.             }
  1261.         }
  1262.         $historicalCustomer->setEnabled($customer->Enabled);
  1263.         $historicalCustomer->setSalt($customer->Salt);
  1264.         if ($customer->Salt != $newData->getSalt()) {
  1265.             if (isset($json_modfied_fields)) {
  1266.                 $json_modfied_fields $json_modfied_fields ',"Salt"';
  1267.             } else {
  1268.                 $json_modfied_fields '"Salt"';
  1269.             }
  1270.         }
  1271.         $historicalCustomer->setCityId($customer->country_id);
  1272.         if ($customer->country_id != $country_id) {
  1273.             if (isset($json_modfied_fields)) {
  1274.                 $json_modfied_fields $json_modfied_fields ',"country_id"';
  1275.             } else {
  1276.                 $json_modfied_fields '"country_id"';
  1277.             }
  1278.         }
  1279.         //$historicalCustomer->setCreatedAt($customer->CreatedAt);
  1280.         //$historicalCustomer->setUpdatedAt($customer->UpdatedAt);
  1281.         if (isset($asessor) && null != $asessor) {
  1282.             $historicalCustomer->setAsessorID($asessor->getid());
  1283.             $historicalCustomer->setAsessorEmail($asessor->getemail());
  1284.         }
  1285.         //$historicalCustomer->setLocale($customer->getLocale());
  1286.         //$historicalCustomer->setTimezone($customer->getTimezone());
  1287.         $historicalCustomer->setCustomerid($customer->CustomerId);
  1288.         $historicalCustomer->setIpAddres($_SERVER['REMOTE_ADDR']);
  1289.         if (isset($json_modfied_fields)) {
  1290.             $json $json $json_modfied_fields ']}';
  1291.             $historicalCustomer->setModifiedfields($json);
  1292.             //        var_dump($json);die;
  1293.             try {
  1294.                 //            var_dump($historicalCustomer);die;
  1295.                 $em->persist($historicalCustomer);
  1296.                 $em->flush();
  1297.             } catch (\Exception $e) {
  1298.             }
  1299.         }
  1300.         //////////////////////////////////////////////////////////////
  1301.     }
  1302.     public function getCustomerInfo(Request $requestSessionInterface $sessionParameterBagInterface $parameterBagAviaturWebService $webServiceTwigFolder $twigFolderUserPasswordEncoderInterface $passwordEncoder, \Swift_Mailer $mailer$customer$post$method$email null$doctrine null$asessor null)
  1303.     {
  1304.         $em $this->getDoctrine()->getManager();
  1305.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  1306.         $providerService $parameterBag->get('provider_service');
  1307.         $emailNotification $parameterBag->get('email_notification');
  1308.         $passwordEncode null;
  1309.         $passwordUser null;
  1310.         $newPassword null;
  1311.         $repeatPassword null;
  1312.         $mensaje null;
  1313.         //var_dump($customer);die();
  1314.         $em = !empty($doctrine) ? $doctrine $this->getDoctrine()->getManager();
  1315.         $fullRequest $request;
  1316.         $agencyFolder $twigFolder->twigFlux();
  1317.         //Get city code in database clientes web
  1318.         $city $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneById($post['city']);
  1319.         $city_id $city->getCode();
  1320.         $Lastcustomer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneByEmail($post['email']);
  1321.         //Get country code in database clientes web
  1322.         $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneById($post['country']);
  1323.         $country_id $country->getCode();
  1324.         $customer->setFirstname($post['Firstname']);
  1325.         $customer->setLastname($post['lastname']);
  1326.         $customer->setBirthdate(new \DateTime($post['birthdate']));
  1327.         $customer->setAddress($post['address']);
  1328.         $customer->setPhone($post['phone']);
  1329.         $customer->setCellphone($post['cellphone']);
  1330.         //$customer->setEmail($post['email']);
  1331.         //$customer->setUsername($post['email']);
  1332.         //Get document id code in database clientes web
  1333.         $document $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneById($customer->getDocumentType()->getId());
  1334.         $document_type_id $document->getCode();
  1335.         if (4877 == $document_type_id || 11 == $document_type_id) {
  1336.             // if document_type_id == NIT or NIT international
  1337.             $person_type_id 7;
  1338.         } else {
  1339.             $person_type_id 8;
  1340.         }
  1341.         //Get civil status code in database clientes web
  1342.         $civilStatus $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneById($post['CivilStatus']);
  1343.         if (isset($civilStatus)) {
  1344.             $marital_status_id $civilStatus->getCode();
  1345.         } else {
  1346.             $marital_status_id '';
  1347.         }
  1348.         $client_id $post['aviaturclientid'];
  1349.         $document_number $post['DocumentNumber'];
  1350.         // if ('password' == $method) {
  1351.         //     // $passwordEncode = $passwordEncoder->encodePassword($customer, $post['password_last']);
  1352.         //     $newPassword = $post['password_new'];
  1353.         //     $repeatPassword = $post['password_repeat'];
  1354.         //     $passwordUser = $customer->getPassword();
  1355.         //     $password = $passwordEncoder->encodePassword($customer, $post['password_new']);
  1356.         // } else {
  1357.         //     $password = $customer->getPassword();
  1358.         // }
  1359.         $password $customer->getPassword();
  1360.         if ('password' == $method) {
  1361.             $newPassword $post['password_new'];
  1362.             $repeatPassword $post['password_repeat'];
  1363.             $passwordUser $customer->getPassword();
  1364.         } else {
  1365.             $password $customer->getPassword();
  1366.         }
  1367.         $corporate_name $customer->getFirstname();
  1368.         $gender $post['genderAviatur'];
  1369.         if (== $gender) {
  1370.             $gender_id 334;
  1371.         } else {
  1372.             $gender_id 335;
  1373.         }
  1374.         $state_id 0;
  1375.         $season_id 1;
  1376.         $sms_frequency_id $customer->getFrecuencySms();
  1377.         $info = [
  1378.             'client_id' => $client_id,
  1379.             'person_type_id' => $person_type_id,
  1380.             'corporate_name' => $post['Firstname'],
  1381.             'corporate_id' => $post['DocumentNumber'],
  1382.             'name' => $post['Firstname'],
  1383.             'last_name' => $post['lastname'],
  1384.             'document_type_id' => $document_type_id,
  1385.             'document_number' => $document_number,
  1386.             'gender_id' => $gender_id,
  1387.             'marital_status_id' => $marital_status_id,
  1388.             'birth_date' => $post['birthdate'],
  1389.             'country_id' => $country_id,
  1390.             'state_id' => $state_id,
  1391.             'city_id' => $city_id,
  1392.             'address' => $post['address'],
  1393.             'phone_number' => $post['phone'],
  1394.             'mobile_phone_number' => $post['cellphone'],
  1395.             'password' => $password,
  1396.             'season_id' => '',
  1397.             'class_trip_id' => 0,
  1398.             'accept_information' => $post['acceptInformation'],
  1399.             'accept_sms' => $post['acceptSms'],
  1400.             'status_id' => 1,
  1401.         ];
  1402.         if ($post['email'] != $customer->getUsername()) {
  1403.             $info['email'] = $customer->getUsername();
  1404.         } else {
  1405.             $info['email'] = $post['email'];
  1406.         }
  1407.         $customerModel = new CustomerModel();
  1408.         $xmlRequest $customerModel->getXmlEditUser($info2);
  1409.         //Modify User into database
  1410.         if ('password' == $method) {
  1411.             $newPassword $post['password_new'];
  1412.             $repeatPassword $post['password_repeat'];
  1413.             if ($newPassword !== $repeatPassword) {
  1414.                 $mensaje 'Las contraseñas ingresadas no coinciden.';
  1415.             } else {
  1416.                 $encodedPassword $passwordEncoder->encodePassword($customer$newPassword);
  1417.                 $customer->setPassword($encodedPassword);
  1418.                 $em->persist($customer);
  1419.                 $em->flush();
  1420.                 $mensaje 'La contraseña del usuario ' $customer->getEmail() . ' se ha modificado correctamente';
  1421.             }
  1422.         } else {
  1423.             if ((is_countable($Lastcustomer) ? count($Lastcustomer) : 0) > && $email != $Lastcustomer->getEmail()) {
  1424.                 $mensaje 'El Correo ' $customer->getEmail() . ' ya se encuentra registrado con otro Usuario';
  1425.             } else {
  1426.                 try {
  1427.                     if ($post['email'] != $customer->getUsername()) {
  1428.                         $customer->setEmail($post['email']);
  1429.                         $customer->setUsername($post['email']);
  1430.                         $customer->setEmailCanonical($post['email']);
  1431.                         $tokenTemp bin2hex(random_bytes(64));
  1432.                         $customer->setTempEmail($post['email']);
  1433.                         $customer->setTempEmailToken($tokenTemp);
  1434.                         $customer->setEmail($email);
  1435.                         $customer->setUsername($email);
  1436.                         if ($agency->getAssetsFolder() == 'octopus') {
  1437.                             $messageEmail = (new \Swift_Message())
  1438.                                 ->setContentType('text/html')
  1439.                                 ->setFrom($session->get('emailNoReply'))
  1440.                                 ->setTo($email)
  1441.                                 ->setSubject('Octopus: Confirmación de Cambios en Tu Correo Electrónico')
  1442.                                 ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-edition-email.html.twig'), [
  1443.                                     'nameCustomer' => $post['Firstname'],
  1444.                                     'tokenTemp' => $tokenTemp,
  1445.                                     'idCustomer' => $customer->getId(),
  1446.                                 ]), 'text/html');
  1447.                         } else {
  1448.                             $messageEmail = (new \Swift_Message())
  1449.                                 ->setContentType('text/html')
  1450.                                 ->setFrom($session->get('emailNoReply'))
  1451.                                 ->setTo($post['email'])
  1452.                                 ->setSubject('Cambio de email')
  1453.                                 ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-edition-email.html.twig'), [
  1454.                                     'nameCustomer' => $post['Firstname'],
  1455.                                     'tokenTemp' => $tokenTemp,
  1456.                                     'idCustomer' => $customer->getId(),
  1457.                                 ]), 'text/html');
  1458.                         }
  1459.                         $em->persist($customer);
  1460.                         $em->flush();
  1461.                         $mailer->send($messageEmail);
  1462.                         $mensaje 'Hemos enviado un mensaje a su correo actual, por favor confírmenos el cambio.';
  1463.                     } elseif ($post['email'] == $customer->getUsername()) {
  1464.                         $customer->setEmail($post['email']);
  1465.                         $customer->setUsername($post['email']);
  1466.                         $customer->setEmailCanonical($post['email']);
  1467.                         $tokenTemp bin2hex(random_bytes(64));
  1468.                         $customer->setTempEmail($post['email']);
  1469.                         $customer->setTempEmailToken($tokenTemp);
  1470.                         $customer->setEmail($email);
  1471.                         $customer->setUsername($email);
  1472.                         if ($agency->getAssetsFolder() == 'octopus') {
  1473.                             $mensaje 'Los datos del agente ' $customer->getFirstname() . ' ' $customer->getlastname() . ' se modificaron correctamente';
  1474.                             $messageEmail = (new \Swift_Message())
  1475.                                 ->setContentType('text/html')
  1476.                                 ->setFrom($session->get('emailNoReply'))
  1477.                                 ->setTo($email)
  1478.                                 ->setSubject('Notificación de Verificación de Datos en Octopus')
  1479.                                 ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-edition-data-notification.html.twig'), [
  1480.                                     'nameCustomer' => $post['Firstname'],
  1481.                                     'tokenTemp' => $tokenTemp,
  1482.                                     'idCustomer' => $customer->getId(),
  1483.                                 ]), 'text/html');
  1484.                         } else {
  1485.                             $mensaje 'Los datos del usuario: ' $customer->getFirstname() . ' ' $customer->getlastname() . ' se modificaron correctamente';
  1486.                             $messageEmail = (new \Swift_Message())
  1487.                                 ->setContentType('text/html')
  1488.                                 ->setFrom($session->get('emailNoReply'))
  1489.                                 ->setTo($post['email'])
  1490.                                 ->setSubject('Notificación')
  1491.                                 ->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-edition-email.html.twig'), [
  1492.                                     'nameCustomer' => $post['Firstname'],
  1493.                                     'tokenTemp' => $tokenTemp,
  1494.                                     'idCustomer' => $customer->getId(),
  1495.                                 ]), 'text/html');
  1496.                         }
  1497.                         $mailer->send($messageEmail);
  1498.                         $em->persist($customer);
  1499.                         $em->flush();
  1500.                     }
  1501.                     if (!isset($doctrine)) {
  1502.                         $response $webService->busWebServiceAmadeus('GENERALLAVE'$providerService$xmlRequest);
  1503.                     }
  1504.                 } catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) {
  1505.                     $mensaje 'El Correo ' $customer->getEmail() . ' ya se encuentra registrado con otro Usuario';
  1506.                     //$mensaje = 'El Documento'.$customer->getDocumentType().' :'.$customer->getDocumentnumber().' ya se encuentra registrado con otro Usuario';
  1507.                 } catch (\Aviatur\CustomerBundle\Exception\ValidateException $e) {
  1508.                     $mensaje 'Información incompleta o inconsistente: ' $e->getMessage();
  1509.                 } catch (\Exception $e) {
  1510.                     $mensaje 'Se produjo un error al editar los datos, Por favor contactate con nosotros para mejor información.';
  1511.                 }
  1512.             }
  1513.         }
  1514.         if (!isset($response)) {
  1515.             $mensaje $mensaje;
  1516.         } elseif ((isset($response->RESULTADO) && 'FALLO' == $response->RESULTADO) ||
  1517.                 (isset($response['RESULTADO']) && 'FALLO' == $response['RESULTADO'])) {
  1518.             $mailInfo print_r($infotrue) . '<br>' print_r($responsetrue);
  1519.             $message = (new \Swift_Message())
  1520.                 ->setContentType('text/html')
  1521.                 ->setFrom($session->get('emailNoReply'))
  1522.                 ->setTo('b_botina@aviatur.com'$emailNotification'negocioselectronicos@aviatur.com.co')
  1523.                 ->setSubject('Error Al Modificar Usuario en Base de Datos Clientes Web')
  1524.                 ->setBody($mailInfo);
  1525.             $mailer->send($message);
  1526.             $mensaje 'Se produjo un error al editar los datos, Por Favor Contactate con Nosotros';
  1527.         } /* else {
  1528.           $em->flush();
  1529.           } */
  1530.         return $mensaje;
  1531.     }
  1532.     public function setNewEmailAction(Request $requestSessionInterface $sessionParameterBagInterface $parameterBagAviaturWebService $webServiceAviaturErrorHandler $errorHandler, \Swift_Mailer $mailer$customerId$token)
  1533.     {
  1534.         $providerService $parameterBag->get('provider_service');
  1535.         $emailNotification $parameterBag->get('email_notification');
  1536.         $em $this->getDoctrine()->getManager();
  1537.         $fullRequest $request;
  1538.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneById($customerId);
  1539.         //var_dump($customer);die();
  1540.         if (!$customer) {
  1541.             return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), '''Ha ocurrido un error'));
  1542.         }
  1543.         if ($customerId && $token) {
  1544.             if (!is_null($customer->getTempEmailToken()) && !is_null($customer->getTempEmail())) {
  1545.                 if ($customerId == $customer->getId() && $token == $customer->getTempEmailToken()) {
  1546.                     $null null;
  1547.                     $city $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneById($customer->getCity()->getId());
  1548.                     $city_id $city->getCode();
  1549.                     //Get country code in database clientes web
  1550.                     $country $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneById($customer->getCountry()->getId());
  1551.                     $country_id $country->getCode();
  1552.                     $document $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findOneById($customer->getDocumentType()->getId());
  1553.                     $document_type_id $document->getCode();
  1554.                     if (4877 == $document_type_id || 11 == $document_type_id) {
  1555.                         // if document_type_id == NIT or NIT international
  1556.                         $person_type_id 7;
  1557.                     } else {
  1558.                         $person_type_id 8;
  1559.                     }
  1560.                     //Get civil status code in database clientes web
  1561.                     $civilStatus $em->getRepository(\Aviatur\CustomerBundle\Entity\CivilStatus::class)->findOneById($customer->getCivilStatus());
  1562.                     if (isset($civilStatus)) {
  1563.                         $marital_status_id $civilStatus->getCode();
  1564.                     } else {
  1565.                         $marital_status_id '';
  1566.                     }
  1567.                     //$document_number = $post['DocumentNumber'];
  1568.                     $password $customer->getPassword();
  1569.                     $corporate_name $customer->getFirstname();
  1570.                     $gender $customer->getGenderAviatur()->getCode();
  1571.                     if (== $gender) {
  1572.                         $gender_id 334;
  1573.                     } else {
  1574.                         $gender_id 335;
  1575.                     }
  1576.                     $state_id 0;
  1577.                     $season_id 1;
  1578.                     $sms_frequency_id $customer->getFrecuencySms();
  1579.                     $info = [
  1580.                         'client_id' => $customer->getAviaturclientid(),
  1581.                         'person_type_id' => $person_type_id,
  1582.                         'corporate_name' => $customer->getFirstname(),
  1583.                         'corporate_id' => $customer->getDocumentnumber(),
  1584.                         'name' => $customer->getFirstname(),
  1585.                         'last_name' => $customer->getLastname(),
  1586.                         'document_type_id' => $document_type_id,
  1587.                         'document_number' => $customer->getDocumentnumber(),
  1588.                         'gender_id' => $gender_id,
  1589.                         'marital_status_id' => $marital_status_id,
  1590.                         'birth_date' => $customer->getBirthdate()->format('Y-m-d'),
  1591.                         'country_id' => $country_id,
  1592.                         'state_id' => $state_id,
  1593.                         'city_id' => $city_id,
  1594.                         'address' => $customer->getAddress(),
  1595.                         'phone_number' => $customer->getPhone(),
  1596.                         'mobile_phone_number' => $customer->getCellphone(),
  1597.                         'password' => $customer->getPassword(),
  1598.                         'season_id' => '',
  1599.                         'class_trip_id' => 0,
  1600.                         'accept_information' => $customer->getAcceptinformation(),
  1601.                         'accept_sms' => $customer->getAcceptsms(),
  1602.                         'status_id' => 1,
  1603.                         'email' => $customer->getTempEmail(),
  1604.                     ];
  1605.                     $customerModel = new CustomerModel();
  1606.                     $xmlRequest $customerModel->getXmlEditUser($info2);
  1607.                     $response $webService->busWebServiceAmadeus('GENERALLAVE'$providerService$xmlRequest);
  1608.                     if (!isset($response)) {
  1609.                         $mensaje $mensaje;
  1610.                     } elseif (('FALLO' == $response->RESULTADO)) {
  1611.                         $mailInfo print_r($infotrue) . '<br>' print_r($responsetrue);
  1612.                         $message = (new \Swift_Message())
  1613.                             ->setContentType('text/html')
  1614.                             ->setFrom($session->get('emailNoReply'))
  1615.                             ->setTo('b_botina@aviatur.com'$emailNotification'negocioselectronicos@aviatur.com.co')
  1616.                             ->setSubject('Error Al Modificar Usuario en Base de Datos Clientes Web')
  1617.                             ->setBody($mailInfo);
  1618.                         $mailer->send($message);
  1619.                         $mensaje 'Se produjo un error al editar los datos, Por Favor Contactate con Nosotros';
  1620.                     }
  1621.                     $customer->setEmail($customer->getTempEmail());
  1622.                     $customer->setUsername($customer->getTempEmail());
  1623.                     $customer->setEmailCanonical($customer->getTempEmail());
  1624.                     $customer->setTempEmailToken($null);
  1625.                     $customer->setTempEmail($null);
  1626.                     $em->persist($customer);
  1627.                     $em->flush();
  1628.                     return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Felicidades''Cambio satifactorio de email'));
  1629.                 } else {
  1630.                     return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Error''Ha ocurrido un error'));
  1631.                 }
  1632.             } else {
  1633.                 return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Error''Ha ocurrido un error'));
  1634.             }
  1635.         } else {
  1636.             return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_general_homepage'), 'Error''Direccion url incorrecta'));
  1637.         }
  1638.     }
  1639.     public function getpaymentMethodsSavedAction(TwigFolder $twigFolderCustomerMethodPaymentService $methodPaymentServiceAviaturLoginService $loginService)
  1640.     {
  1641.         $em $this->getDoctrine()->getManager();
  1642.         $typeDocument $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  1643.         $infoSaved = [];
  1644.         if (false !== $loginService->validActiveSession()) {
  1645.             $customer $this->getUser();
  1646.             $infoMethodPaymentByClient $methodPaymentService->getMethodsByCustomer($customerfalse);
  1647.             if ('NoInfo' !== $infoMethodPaymentByClient['info']) {
  1648.                 foreach ($infoMethodPaymentByClient['info'] as $key => $value) {
  1649.                     $infoSaved['info'][] = [substr($key02), substr($key24)];
  1650.                 }
  1651.             }
  1652.         }
  1653.         $infoSaved['doc_type'] = $typeDocument;
  1654.         $newsletter = new Newsletter();
  1655.         $newsletterForm $this->createForm(\Aviatur\FormBundle\Form\NewsletterAsyncType::class, $newsletter);
  1656.         $infoSaved['newsletter_form'] = $newsletterForm->createView();
  1657.         $agencyFolder $twigFolder->twigFlux();
  1658.         $twigView $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-payments-saved.html.twig');
  1659.         return $this->render($twigView$infoSaved);
  1660.     }
  1661.     public function saveNewCardAction(Request $requestTokenizerService $tokenizerServiceTokenStorageInterface $tokenStorage)
  1662.     {
  1663.         if ($request) {
  1664.             $em $this->getDoctrine()->getManager();
  1665.             $customer $tokenStorage->getToken()->getUser();
  1666.             $cardNumToken $tokenizerService->getToken($request->request->get('cardNum'));
  1667.             $fecha = new \DateTime();
  1668.             $franchise $request->request->get('franqui');
  1669.             $numcard = \substr($request->request->get('cardNum'), -44);
  1670.             $new_method_payment = [
  1671.                 $franchise $numcard => [
  1672.                     'token' => $cardNumToken//['card_num'],
  1673.                     'firstname' => $request->request->get('nombreCard'),
  1674.                     'lastname' => $request->request->get('apellidoCard'),
  1675.                     'datevig' => $request->request->get('cardExp'),
  1676.                     'datecreation' => $fecha->format('Y-m-d H:i:s'),
  1677.                     'typeDocument' => $request->request->get('docType'),
  1678.                     'documentNumber' => $request->request->get('docNum'),
  1679.                     'status' => 'NOTVERIFIED',
  1680.                 ],
  1681.             ];
  1682.             $paymentMethodsCustomer $em->getRepository(\Aviatur\PaymentBundle\Entity\PaymentMethodCustomer::class)->findBy(['customer' => $customer]);
  1683.             if (count($paymentMethodsCustomer) > 0) {
  1684.                 $actualInfo json_decode($paymentMethodsCustomer[0]->getInfoPaymentMethod(), true);
  1685.                 $preExist array_intersect_key($new_method_payment$actualInfo);
  1686.                 if (count($preExist) > 0) {
  1687.                     foreach ($preExist as $key => $value) {
  1688.                         $actualInfo[$key]['status'] = 'REPLACED';
  1689.                         $actualInfo[$key '_' $fecha->format('YmdHis')] = $actualInfo[$key];
  1690.                         unset($actualInfo[$key]);
  1691.                     }
  1692.                 }
  1693.                 $newInfo array_merge($actualInfo$new_method_payment);
  1694.                 $paymentMethodsCustomer[0]->setInfoPaymentMethod(json_encode($newInfo));
  1695.             } else {
  1696.                 $newMethodObject = new PaymentMethodCustomer();
  1697.                 $newMethodObject->setCustomer($customer);
  1698.                 $newMethodObject->setInfoPaymentMethod(json_encode($new_method_payment));
  1699.                 $newMethodObject->setIsactive(true);
  1700.                 $em->persist($newMethodObject);
  1701.             }
  1702.             $em->flush();
  1703.             return $this->json(['status' => 'success']);
  1704.         }
  1705.     }
  1706.     public function setMethodsByCustomer($customer$infoCard)
  1707.     {
  1708.         $fecha = new \DateTime();
  1709.         $franchise $infoCard['franqui'];
  1710.         $numcard = \substr($infoCard['cardNum'], -44);
  1711.         $new_method_payment = [
  1712.             $franchise $numcard => [
  1713.                 'token' => $infoCard['cardNum'], //['card_num'],
  1714.                 'firstname' => $infoCard['nombreCard'],
  1715.                 'lastname' => $infoCard['apellidoCard'],
  1716.                 'datevig' => $infoCard['cardExp'],
  1717.                 'datecreation' => $fecha->format('Y-m-d H:i:s'),
  1718.                 'typeDocument' => $infoCard['docType'],
  1719.                 'documentNumber' => $infoCard['docNum'],
  1720.                 'status' => 'NOTVERIFIED',
  1721.             ],
  1722.         ];
  1723.         $paymentMethodsCustomer $this->em->getRepository(\Aviatur\PaymentBundle\Entity\PaymentMethodCustomer::class)->findBy(['customer' => $customer]);
  1724.         if ((is_countable($paymentMethodsCustomer) ? count($paymentMethodsCustomer) : 0) > 0) {
  1725.             $actualInfo json_decode($paymentMethodsCustomer[0]->getInfoPaymentMethod(), true);
  1726.             $preExist array_intersect_key($new_method_payment$actualInfo);
  1727.             if (count($preExist) > 0) {
  1728.                 foreach ($preExist as $key => $value) {
  1729.                     $actualInfo[$key]['status'] = 'REPLACED';
  1730.                     $actualInfo[$key '_' $fecha->format('YmdHis')] = $actualInfo[$key];
  1731.                     unset($actualInfo[$key]);
  1732.                 }
  1733.             }
  1734.             $newInfo array_merge($actualInfo$new_method_payment);
  1735.             $paymentMethodsCustomer[0]->setInfoPaymentMethod(json_encode($newInfo));
  1736.         } else {
  1737.             $newMethodObject = new PaymentMethodCustomer();
  1738.             $newMethodObject->setCustomer($customer);
  1739.             $newMethodObject->setInfoPaymentMethod(json_encode($new_method_payment));
  1740.             $newMethodObject->setIsactive(true);
  1741.             $this->em->persist($newMethodObject);
  1742.         }
  1743.         $this->em->flush();
  1744.     }
  1745.     public function deletePaymentsSavedAction(Request $requestCustomerMethodPaymentService $methodPaymentServiceAviaturErrorHandler $errorHandler)
  1746.     {
  1747.         $cardKey $request->request->get('keycardtodelete');
  1748.         $customer $this->getUser();
  1749.         $methodPaymentService->deleteMethodsByCustomer($customer$cardKey);
  1750.         $redirectRoute 'aviatur_customer_show_saved_pay_info';
  1751.         return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl($redirectRoute), 'Información actualizada''Se actualizaron los medios de pago almacenados'));
  1752.     }
  1753.     public function deleteCardSavedAjaxAction(Request $requestCustomerMethodPaymentService $methodPaymentService)
  1754.     {
  1755.         $cardKey $request->request->get('key');
  1756.         $customer $this->getUser();
  1757.         $methodPaymentService->deleteMethodsByCustomer($customer$cardKey);
  1758.         return $this->json(['status' => 'success']);
  1759.     }
  1760.     public function billingViewAction(TwigFolder $twigFolderTokenStorageInterface $tokenStorage)
  1761.     {
  1762.         $agencyFolder $twigFolder->twigFlux();
  1763.         $em $this->getDoctrine()->getManager();
  1764.         $userLogged $tokenStorage->getToken()->getUser()->getId();
  1765.         $billingList $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
  1766.         //var_dump($billingList);die();
  1767.         $typeDocument $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  1768.         if ($billingList) {
  1769.             $data = [];
  1770.             $count 0;
  1771.             foreach ($billingList as $billings) {
  1772.                 if ('ACTIVE' == $billings->getStatus()) {
  1773.                     $data[$count]['id'] = $billings->getId();
  1774.                     $data[$count]['customerId'] = $userLogged;
  1775.                     $data[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
  1776.                     $data[$count]['documentNumber'] = $billings->getDocumentnumber();
  1777.                     $data[$count]['firstname'] = $billings->getFirstname();
  1778.                     $data[$count]['lastname'] = $billings->getLastname();
  1779.                     $data[$count]['email'] = $billings->getEmail();
  1780.                     $data[$count]['address'] = $billings->getAddress();
  1781.                     $data[$count]['phone'] = $billings->getPhone();
  1782.                     $data[$count]['country'] = ((null != $billings->getCountry()) && ('' != $billings->getCountry())) ? $billings->getCountry()->getIataCode() : null;
  1783.                     $data[$count]['countryname'] = ((null != $billings->getCountry()) && ('' != $billings->getCountry())) ? \ucwords(\mb_strtolower($billings->getCountry()->getDescription())) . ' (' $billings->getCountry()->getIataCode() . ')' null;
  1784.                     $data[$count]['city'] = $billings->getCity()->getIataCode();
  1785.                     $data[$count]['cityname'] = ((null != $billings->getCity()) && ('' != $billings->getCity())) ? \ucwords(\mb_strtolower($billings->getCity()->getDescription())) . ' (' $billings->getCity()->getIataCode() . ')' null;
  1786.                     ++$count;
  1787.                 }
  1788.             }
  1789.         } else {
  1790.             $data null;
  1791.         }
  1792.         /* $country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->createQueryBuilder('u')->where('u.languagecode = :languagecode')->setParameter('languagecode', 'es-ES')->orderBy('u.description', 'ASC')->getQuery()->getResult();
  1793.           var_dump($country);die; */
  1794.         /* $city = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry($customer->getCountry()->getId(), array('description' => 'ASC'));
  1795.           foreach ($city as $infocities) {
  1796.           $idCity[] = $infocities->getCode();
  1797.           $nameCity[] = $infocities->getDescription();
  1798.           }
  1799.           $info = array('idCity' => $idCity, 'nameCity' => $nameCity); */
  1800.         $twigView $twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/customer-billing-view.html.twig');
  1801.         return $this->render($twigView, ['billings' => $data'doc_type' => $typeDocument]);
  1802.     }
  1803.     public function billingListAction(TokenStorageInterface $tokenStorage)
  1804.     {
  1805.         $em $this->getDoctrine()->getManager();
  1806.         $userLogged $tokenStorage->getToken()->getUser()->getId();
  1807.         $billingList $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->findByCustomer($userLogged);
  1808.         if ($billingList) {
  1809.             $data = [];
  1810.             $count 0;
  1811.             foreach ($billingList as $billings) {
  1812.                 if ('ACTIVE' == $billings->getStatus()) {
  1813.                     $data[$count]['id'] = $billings->getId();
  1814.                     $data[$count]['customerId'] = $userLogged;
  1815.                     $data[$count]['documentType'] = $billings->getDocumentType()->getExternalCode();
  1816.                     $data[$count]['documentNumber'] = $billings->getDocumentnumber();
  1817.                     $data[$count]['firstname'] = $billings->getFirstname();
  1818.                     $data[$count]['lastname'] = $billings->getLastname();
  1819.                     $data[$count]['email'] = $billings->getEmail();
  1820.                     $data[$count]['address'] = $billings->getAddress();
  1821.                     $data[$count]['phone'] = $billings->getPhone();
  1822.                     ++$count;
  1823.                 }
  1824.             }
  1825.         } else {
  1826.             $data null;
  1827.         }
  1828.         return $this->json($data);
  1829.     }
  1830.     public function billingDeleteAction(Request $requestTokenStorageInterface $tokenStorage)
  1831.     {
  1832.         $idBilling $request->request->get('idBilling');
  1833.         $em $this->getDoctrine()->getManager();
  1834.         //$userLogged = $tokenStorage->getToken()->getUser()->getId();
  1835.         $billing $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->find($idBilling);
  1836.         $billing->setStatus('ERASED');
  1837.         $em->flush();
  1838.         return $this->json(['status' => 'success']);
  1839.     }
  1840.     public function billingAddOrEditAction(Request $requestTokenStorageInterface $tokenStorage)
  1841.     {
  1842.         $em $this->getDoctrine()->getManager();
  1843.         $documentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findByExternalcode($request->request->get('doc_type'));
  1844.         $userLogged $tokenStorage->getToken()->getUser();
  1845.         if ($request) {
  1846.             $fecha = new \DateTime();
  1847.             if ('' != $request->request->get('id')) {
  1848.                 $billing $em->getRepository(\Aviatur\CustomerBundle\Entity\CustomerBillingList::class)->find($request->request->get('id'));
  1849.                 if (!$billing) {
  1850.                     return $this->json([
  1851.                         'status' => 'error',
  1852.                         'message' => 'Usuario no existe',
  1853.                     ]);
  1854.                 }
  1855.                 $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($request->request->get('country'));
  1856.                 if (!$dataCountry) {
  1857.                     return $this->json([
  1858.                         'status' => 'error',
  1859.                         'message' => 'País no existe',
  1860.                     ]);
  1861.                 }
  1862.                 $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($request->request->get('city'));
  1863.                 if (!$dataCountry) {
  1864.                     return $this->json([
  1865.                         'status' => 'error',
  1866.                         'message' => 'Ciudad no existe',
  1867.                     ]);
  1868.                 }
  1869.                 $billing->setDocumentnumber($request->request->get('doc_num'));
  1870.                 $billing->setDocumentType($documentType[0]);
  1871.                 $billing->setCustomer($userLogged);
  1872.                 $billing->setFirstname($request->request->get('first-name'));
  1873.                 $billing->setLastname($request->request->get('last-name'));
  1874.                 $billing->setEmail($request->request->get('email'));
  1875.                 $billing->setAddress($request->request->get('address'));
  1876.                 $billing->setPhone($request->request->get('phone'));
  1877.                 $billing->setCountry($dataCountry);
  1878.                 $billing->setCity($dataCity);
  1879.                 $billing->setUpdated($fecha->format('Y-m-d H:i:s'));
  1880.             } else {
  1881.                 $dataCountry $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($request->request->get('country'));
  1882.                 if (!$dataCountry) {
  1883.                     return $this->json([
  1884.                         'status' => 'error',
  1885.                         'message' => 'País no existe',
  1886.                     ]);
  1887.                 }
  1888.                 $dataCity $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($request->request->get('city'));
  1889.                 if (!$dataCountry) {
  1890.                     return $this->json([
  1891.                         'status' => 'error',
  1892.                         'message' => 'Ciudad no existe',
  1893.                     ]);
  1894.                 }
  1895.                 $billing = new CustomerBillingList();
  1896.                 $billing->setDocumentnumber($request->request->get('doc_num'));
  1897.                 $billing->setDocumentType($documentType[0]);
  1898.                 $billing->setCustomer($userLogged);
  1899.                 $billing->setFirstname($request->request->get('first-name'));
  1900.                 $billing->setLastname($request->request->get('last-name'));
  1901.                 $billing->setEmail($request->request->get('email'));
  1902.                 $billing->setAddress($request->request->get('address'));
  1903.                 $billing->setPhone($request->request->get('phone'));
  1904.                 $billing->setCountry($dataCountry);
  1905.                 $billing->setCity($dataCity);
  1906.                 $billing->setStatus('ACTIVE');
  1907.                 $billing->setCreated($fecha->format('Y-m-d H:i:s'));
  1908.                 $billing->setUpdated($fecha->format('Y-m-d H:i:s'));
  1909.                 $em->persist($billing);
  1910.             }
  1911.             $em->flush();
  1912.             return $this->json([
  1913.                 'status' => 'success',
  1914.                 'message' => 'Registro creado',
  1915.             ]);
  1916.         } else {
  1917.             return $this->json([
  1918.                 'status' => 'error',
  1919.                 'message' => 'Ha ocurrido un error',
  1920.             ]);
  1921.         }
  1922.     }
  1923.     public function getCitiesAjaxAction(Request $request)
  1924.     {
  1925.         $data = [];
  1926.         $em $this->getDoctrine()->getManager();
  1927.         $term $request->request->get('term') ?: null;
  1928.         if (!is_null($term)) {
  1929.             $em $this->getDoctrine()->getManager();
  1930.             $json_template '<value>:<label>-';
  1931.             $countries $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findByOrWithSingleValue(['iatacode''description'], $term);
  1932.             $json = [];
  1933.             if ($countries) {
  1934.                 $data = [];
  1935.                 $count 0;
  1936.                 foreach ($countries as $country) {
  1937.                     $data[$count]['id'] = $count;
  1938.                     $data[$count]['code'] = $country['iata'];
  1939.                     $data[$count]['label'] = ucwords(mb_strtolower($country['description']));
  1940.                     /* $arraytmp = array(
  1941.                       'description' => ucwords(mb_strtolower($country['description'])),
  1942.                       'iata' => $country['iata']
  1943.                       );
  1944.                       array_push($json, $arraytmp); */
  1945.                 }
  1946.             } else {
  1947.                 $json['error'] = 'No hay Resultados';
  1948.             }
  1949.             return $this->json($data);
  1950.         } else {
  1951.             return $this->json(['error' => 'Termino de consulta invalido']);
  1952.         }
  1953.         /* $city = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry("165", array('description' => 'ASC'));
  1954.           $data = [];
  1955.           $count = 0;
  1956.           foreach ($city as $infocities) {
  1957.           $data[$count]['id'] = $infocities->getId();
  1958.           $data[$count]['code'] = $infocities->getCode();
  1959.           $data[$count]['name'] = $infocities->getDescription();
  1960.           $count++;
  1961.           }
  1962.           return $this->json(array(
  1963.           "status" => "success",
  1964.           "data" => array($data)
  1965.           )); */
  1966.     }
  1967.     public function searchCountryAction(Request $request)
  1968.     {
  1969.         $data json_decode($request->getContent());
  1970.         $term $request->request->get('term') ?: null;
  1971.         if (!is_null($term)) {
  1972.             $em $this->getDoctrine()->getManager();
  1973.             $json_template '<value>:<label>-';
  1974.             $countries $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findByOrWithSingleValue(['iatacode''description'], $term);
  1975.             $json = [];
  1976.             if ($countries) {
  1977.                 foreach ($countries as $country) {
  1978.                     $arraytmp = [
  1979.                         'description' => ucwords(mb_strtolower($country['description'])),
  1980.                         'iata' => $country['iata'],
  1981.                     ];
  1982.                     array_push($json$arraytmp);
  1983.                 }
  1984.             } else {
  1985.                 $json['error'] = 'No hay Resultados';
  1986.             }
  1987.             return $this->json(['country' => $json]);
  1988.         } else {
  1989.             return $this->json(['error' => 'Termino de consulta invalido']);
  1990.         }
  1991.     }
  1992.     public function getCitiesAction(Request $requestTwigFolder $twigFolder)
  1993.     {
  1994.         $em $this->getDoctrine()->getManager();
  1995.         $agencyFolder $twigFolder->twigFlux();
  1996.         $country $request->request->get('country');
  1997.         $id $request->request->get('id');
  1998.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($id);
  1999.         $city $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findByCountry($country, ['description' => 'ASC']);
  2000.         foreach ($city as $infocities) {
  2001.             $idCity[] = $infocities->getId();
  2002.             $iataCity[] = $infocities->getIatacode();
  2003.             $nameCity[] = $infocities->getDescription();
  2004.         }
  2005.         $info = ['idCity' => $idCity'iataCity' => $iataCity'nameCity' => $nameCity];
  2006.         return $this->json($info);
  2007.     }
  2008.     public function frozenRateAction(TwigFolder $twigFolderTokenStorageInterface $tokenStorage)
  2009.     {
  2010.         $agencyFolder $twigFolder->twigFlux();
  2011.         $em $this->getDoctrine()->getManager();
  2012.         $freezeData $em->getRepository(\Aviatur\RestBundle\Entity\HopperFreeze::class)->findByCustomerid($tokenStorage->getToken()->getUser()->getId());
  2013.         if (!$freezeData) {
  2014.             return $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/frozen-rate.html.twig'), ['status' => false'data' => null'message' => 'No tiene tarifas congeladas']);
  2015.         }
  2016.         $arrayFreeze = [];
  2017.         for ($i 0$i < (is_countable($freezeData) ? count($freezeData) : 0); ++$i) {
  2018.             // Obtener la informaqción de vuelo en formato JSON
  2019.             $infoFlight json_decode($freezeData[$i]->getIdRouteFlight()->getInfo());
  2020.             // Obtener la información de ida y regreso en formato JSON
  2021.             $infoIda json_decode($infoFlight->selection[0]);
  2022.             $infoRegreso null;
  2023.             $infoRegresoDate null;
  2024.             $infoRegreso2 null;
  2025.             setlocale(LC_TIME'spanish');
  2026.             if ((is_countable($infoFlight->selection) ? count($infoFlight->selection) : 0) > 1) {
  2027.                 $infoRegreso json_decode($infoFlight->selection[1]);
  2028.                 $infoRegresoDate strftime('%d %B del %Y'strtotime(date('d-m-Y'$infoRegreso->S[0]->E)));
  2029.                 $infoRegreso $infoRegreso->S[0]->O;
  2030.                 $infoRegreso2 $infoIda->S[0]->O;
  2031.             }
  2032.             //Calcular los días restantes
  2033.             $date1 = new \DateTime('now');
  2034.             $date2 json_decode(json_encode($freezeData[$i]->getFinishDate()), true);
  2035.             $diff $date1->diff(new \DateTime($date2['date']));
  2036.             $a = (== $diff->invert) ? '-' $diff->days $diff->days;
  2037.             $paymentInfo json_decode($freezeData[$i]->getFlightInfo(), true);
  2038.             $used 'used' == $freezeData[$i]->getState() ? 'Usado' 'Activo';
  2039.             array_push($arrayFreeze, [
  2040.                 'FlightInfo' => [
  2041.                     'Going' => [
  2042.                         'Date' => strftime('%d %B del %Y'strtotime(date('d-m-Y'$infoIda->S[0]->E))),
  2043.                         'Origin' => [
  2044.                             'Code' => $infoIda->S[0]->O,
  2045.                         ],
  2046.                         'Destination' => [
  2047.                             'Code' => $infoIda->S[0]->D,
  2048.                         ],
  2049.                     ],
  2050.                     'Return' => [
  2051.                         'Date' => $infoRegresoDate,
  2052.                         'Origin' => [
  2053.                             'Code' => $infoRegreso,
  2054.                         ],
  2055.                         'Destination' => [
  2056.                             'Code' => $infoRegreso2,
  2057.                         ],
  2058.                     ],
  2059.                 ],
  2060.                 'Dates' => [
  2061.                     'DateCreated' => $freezeData[$i]->getCreationDate(),
  2062.                     'DateExpiration' => $freezeData[$i]->getFinishDate(),
  2063.                     'DaysLeft' => (int) $a,
  2064.                 ],
  2065.                 'Url' => $freezeData[$i]->getIdRouteFlight()->getUrl(),
  2066.                 'Prices' => [
  2067.                     'PriceHopper' => $freezeData[$i]->getInfoHopper(),
  2068.                     'PriceFlight' => $paymentInfo['x_total_payment']['x_amount'] + $paymentInfo['x_total_payment']['x_airport_tax'] + $paymentInfo['x_total_payment']['x_service_fee'],
  2069.                     'MaxHopperCover' => $freezeData[$i]->getMaxHopperCover(),
  2070.                 ],
  2071.                 'state' => ((int) $a <= 0) ? 'Expirado' $used,
  2072.             ]);
  2073.         }
  2074.         //var_dump(json_encode($arrayFreeze));die;
  2075.         //var_dump($arrayFreeze);die;
  2076.         return $this->render($twigFolder->twigExists('@AviaturTwig/' $agencyFolder '/Customer/frozen-rate.html.twig'), ['status' => true'data' => $arrayFreeze]);
  2077.     }
  2078.     public function sanear_string($string)
  2079.     {
  2080.         $string trim($string);
  2081.         $string str_replace(
  2082.             ['á''à''ä''â''ª'],
  2083.             ['a''a''a''a''a'],
  2084.             $string
  2085.         );
  2086.         $string str_replace(
  2087.             ['é''è''ë''ê'],
  2088.             ['e''e''e''e'],
  2089.             $string
  2090.         );
  2091.         $string str_replace(
  2092.             ['í''ì''ï''î'],
  2093.             ['i''i''i''i'],
  2094.             $string
  2095.         );
  2096.         $string str_replace(
  2097.             ['ó''ò''ö''ô'],
  2098.             ['o''o''o''o'],
  2099.             $string
  2100.         );
  2101.         $string str_replace(
  2102.             ['ú''ù''ü''û'],
  2103.             ['u''u''u''u'],
  2104.             $string
  2105.         );
  2106.         $string str_replace(
  2107.             ['ç'],
  2108.             ['c'],
  2109.             $string
  2110.         );
  2111.         //Esta parte se encarga de eliminar cualquier caracter extraño
  2112.         $string str_replace(
  2113.             [
  2114.                 '\\',
  2115.                 '¨',
  2116.                 'º',
  2117.                 '-',
  2118.                 '~',
  2119.                 '#',
  2120.                 '|',
  2121.                 '!',
  2122.                 '"',
  2123.                 ':',
  2124.                 '·',
  2125.                 '$',
  2126.                 '%',
  2127.                 '&',
  2128.                 '/',
  2129.                 '(',
  2130.                 ')',
  2131.                 '?',
  2132.                 "'",
  2133.                 '¡',
  2134.                 '¿',
  2135.                 '[',
  2136.                 '^',
  2137.                 '`',
  2138.                 ']',
  2139.                 '+',
  2140.                 '}',
  2141.                 '{',
  2142.                 '¨',
  2143.                 '´',
  2144.                 '>',
  2145.                 '< ',
  2146.                 ';',
  2147.                 ',',
  2148.             ],
  2149.             '',
  2150.             $string
  2151.         );
  2152.         return $string;
  2153.     }
  2154.     /*
  2155.     private function validateSanctions(SessionInterface $session, ValidateSanctionsRenewal $validateSanctions, $info, $paymentMethod)
  2156.     {
  2157.         if ($session->has('Marked_name') && $session->has('Marked_document')) {
  2158.             $session->remove('Marked_name');
  2159.             $session->remove('Marked_document');
  2160.         }
  2161.         if ($validateSanctions->validateSanctions($info['documentnumber'], $info['name'])) {
  2162.             if (!$session->has('Marked_name') && !$session->has('Marked_document')) {
  2163.                 $session->remove('Marked_name');
  2164.                 $session->remove('Marked_document');
  2165.                 $session->set('Marked_name', $info['name']);
  2166.                 $session->set('Marked_document', $info['documentnumber']);
  2167.             }
  2168.             return 'p2p' === $paymentMethod;
  2169.         }
  2170.         return true;
  2171.     }
  2172.     */
  2173.     private function validateSpecialConditionPayment($cardNum)
  2174.     {
  2175.         $validBins = [
  2176.             '421892',
  2177.             '450407',
  2178.             '492488',
  2179.             '455100',
  2180.             '799955',
  2181.             '813001',
  2182.             '518761',
  2183.             '542650',
  2184.             '527564',
  2185.             '540699',
  2186.             '518841',
  2187.             '454094',
  2188.             '454759',
  2189.             '459418',
  2190.             '492489',
  2191.             '450408',
  2192.             '459419',
  2193.             '404280',
  2194.             '548115',
  2195.             '553643',
  2196.             '450418',
  2197.             '456783',
  2198.             '483080',
  2199.             '485995',
  2200.             '547457',
  2201.             '410164',
  2202.             '404279',
  2203.             '418253',
  2204.             '459317',
  2205.             '462550',
  2206.             '491268',
  2207.             '492468',
  2208.             '589515',
  2209.             '799955',
  2210.         ];
  2211.         if (in_array(substr($cardNum06), $validBins)) {
  2212.             return true;
  2213.         } else {
  2214.             return false;
  2215.         }
  2216.     }
  2217.     private function getValidationOnuOfac($postData$urlDomainSessionInterface $sessionValidateSanctionsRenewal $validateSanctionsRenewal)
  2218.     {
  2219.         // Comprobar si la URL contiene "experiencias"
  2220.         $exceptionWords = ['experiencias''paquetes'];
  2221.         $isException false;
  2222.         foreach ($exceptionWords as $eWord) {
  2223.             $isException = (strpos($urlDomain$eWord) !== false);
  2224.             if ($isException) {
  2225.                 break;
  2226.             }
  2227.         }
  2228.         $isExperiencia strpos($urlDomain'experiencias') !== false;
  2229.         // Si es una experiencia, omitir la validación de pago
  2230.         if ($isException) {
  2231.             $clientArray $validateSanctionsRenewal->getClientsArray($postData$urlDomain);
  2232.             return $validateSanctionsRenewal->validateSanctions($clientArray$sessionnull);
  2233.         } else {
  2234.             // Procesar como de costumbre para otros productos
  2235.             $paymentInfo $postData['PD'];
  2236.             $paymentMethod $paymentInfo['type'];
  2237.             $clientArray $validateSanctionsRenewal->getClientsArray($postData$urlDomain);
  2238.             return $validateSanctionsRenewal->validateSanctions($clientArray$session$paymentMethod);
  2239.         }
  2240.     }
  2241.     /**
  2242.      * @param $redemptionPoint
  2243.      * @param $session
  2244.      * @param $postData
  2245.      * @return array[]|string[]
  2246.      */
  2247.     public function generateOtp($redemptionPoint$session$postData)
  2248.     {
  2249.         if (isset($redemptionPoint) && $session->has('token')) {
  2250.             $info = ["token" => NULL"amount" => $postData['PD']['pointRedemptionValue']];
  2251.             if ($postData['PD']['pointRedemptionValue'] !== '0' || (int) $postData['PD']['pointRedemptionValue'] !== 0) {
  2252.                 $response $this->athServices->addOtp($info);
  2253.             }
  2254.         } else {
  2255.             $response = ["StatusDesc" => 'error en sesion'"StatusCode" => "500"];
  2256.         }
  2257.         return $response;
  2258.     }
  2259. }