<?php
namespace Aviatur\MultiBundle\Controller;
use Knp\Snappy\Pdf;
use Aviatur\AgencyBundle\Entity\Agency;
use Doctrine\Persistence\ManagerRegistry;
use Aviatur\TwigBundle\Services\TwigFolder;
use Aviatur\FlightBundle\Models\FlightModel;
use Symfony\Component\HttpFoundation\Cookie;
use Aviatur\HotelBundle\Services\UrlService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Aviatur\GeneralBundle\Services\ExceptionLog;
use Aviatur\GeneralBundle\Services\AviaturMailer;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\HttpFoundation\JsonResponse;
use Aviatur\MultiBundle\Services\MultiCustomUtils;
use Aviatur\GeneralBundle\Services\AviaturPixeles;
use Aviatur\GeneralBundle\Services\AviaturLogSave;
use Aviatur\MultiBundle\Services\MultiHotelDiscount;
use Aviatur\FlightBundle\Services\SearchFlightCookie;
use Aviatur\GeneralBundle\Services\AviaturWebService;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Aviatur\GeneralBundle\Services\PayoutExtraService;
use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class FlightHotelController extends AbstractController
{
/**
* @var Agency|object|null
*/
protected $agency;
/**
* @var bool
*/
protected $isAval;
public function __construct(ManagerRegistry $managerRegistry, SessionInterface $session) {
$this->session = $session;
$this->em = $managerRegistry->getManager();
$this->agency = $this->em->getRepository(Agency::class)->find($session->get('agencyId'));
$this->isAval = $this->agency && strpos($this->agency->getName(), 'Aval') !== false;
}
public function resultsAction(Request $request, SessionInterface $session, AviaturPixeles $aviaturPixeles, ManagerRegistry $registry, AviaturErrorHandler $aviaturErrorHandler, SearchFlightCookie $searchFlightCookie, AviaturWebService $aviaturWebService, TwigFolder $twigFolder, UrlService $urlService, $origin1, $destination1, $date1, $date2 = null, $rooms, $adult1 = null, $child1 = null, $adult2 = null,$child2 = null, $adult3 = null, $child3 = null) {
$AvailabilityArray = [];
$urlDescription = [];
$pixel = [];
$em = $registry->getManager();
$fullRequest = $request;
// generate request url with safe optional query string
$safeQuery = [];
$safeParams = ['class', 'stop', 'airline', 'carryOn', 'baggage', 'tourCode', 'airlineTourCode', 'isActiveTourCode'];
foreach ($safeParams as $param) {
if ($fullRequest->query->has($param)) {
$safeQuery[$param] = \urlencode($fullRequest->query->get($param));
}
}
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), array_merge($fullRequest->attributes->get('_route_params'), $safeQuery));
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
if ($session->has('notEnableMultiHVSearch')) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/', 'Busqueda de resultados', 'No podemos realizar la consulta ya que no existe un proveedor configurado para este servicio'));
}
$safeUrl = 'https://'.$agency->getDomainsecure();
// CREATE FLIGHT/HOTEL URL FOR AJAX
$adults = 0;
$children = 0;
$infants = 0;
$hotelPassenger = null;
$services = [];
$countAdults = 0;
$countChildren = 0;
$childAgesCookie = 0;
$flights = 2;
$dateError = [];
for ($i = 1; $i <= $flights; ++$i) {
$AvailabilityArray['date'.$i] = false !== strpos(${'date'.$i}, 'T') ? date('Y-m-d\TH:i:s', strtotime(substr(${'date'.$i}, 0, 10).sprintf('+%d hours', substr(${'date'.$i}, -2)))) : date('Y-m-d\TH:i:s', strtotime(substr(${'date'.$i}, 0, 10)));
if ($i > 1) {
if (($AvailabilityArray['date'.$i] < $AvailabilityArray['date'.($i - 1)]) || ((date('Y-m-d\TH:i:s', strtotime($AvailabilityArray['date'.$i])) < date('Y-m-d\TH:i:s', strtotime('today +6 hour'))) && ((date('H', strtotime('now')) >= 18) || (date('Y-m-d', strtotime('today')) > date('Y-m-d', strtotime($AvailabilityArray['date1']))))) || ($AvailabilityArray['date'.$i] > date('Y-m-d\TH:i:s', strtotime('+12 month')))) {
$dateError[$i] = $AvailabilityArray['date'.$i];
}
} else {
if (((date('Y-m-d\TH:i:s', strtotime($AvailabilityArray['date'.$i])) < date('Y-m-d\TH:i:s', strtotime('today +6 hour'))) && ((date('H', strtotime('now')) >= 18) || (date('Y-m-d', strtotime('today')) > date('Y-m-d', strtotime($AvailabilityArray['date'.$i]))))) || ($AvailabilityArray['date'.$i] > date('Y-m-d\TH:i:s', strtotime('+11 month')))) {
$dateError[$i] = $AvailabilityArray['date'.$i];
}
}
}
if (0 != sizeof($dateError)) {
//test: /vuelos/BAQ-BOG/2014-12-18+2014-12-15/1-0-0
foreach ($dateError as $key => $date) {
if ($date < date('Y-m-d\TH:i:s', strtotime('today +12 hour'))) {
${'date'.$key} = date('Y-m-d', strtotime('+1 day'));
} elseif ($date > date('Y-m-d\TH:i:s', strtotime('+28 day'))) {
if (isset($AvailabilityArray['date'.($key - 1)])) {
${'date'.$key} = date('Y-m-d', strtotime($AvailabilityArray['date'.($key - 1)].'+1 week'));
if (${'date'.$key} > date('Y-m-d\TH:i:s', strtotime('+28 day'))) {
${'date'.$key} = date('Y-m-d', strtotime('+27 day'));
}
} else {
${'date'.$key} = date('Y-m-d', strtotime(${'date'.$key}.'-12 month'));
}
} else {
${'date'.$key} = date('Y-m-d', strtotime($AvailabilityArray['date'.($key - 1)].'+1 week'));
}
}
$url = $this->generateUrl(
$request->get('_route'),
[
'date1' => $date1,
'date2' => $date2,
'origin1' => $origin1,
'destination1' => $destination1,
'rooms' => $rooms,
'adult1' => $adult1,
'child1' => $child1,
'adult2' => $adult2,
'child2' => $child2,
'adult3' => $adult3,
'child3' => $child3,
'multi' => 'vuelo-y-hotel',
]
);
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($url, 'Recomendación Automática', 'La consulta que realizaste no era válida, hemos analizado tu búsqueda y esta es nuestra recomendación'));
}
for ($i = 1; $i <= $rooms; ++$i) {
$adults = $adults + ${'adult'.$i};
$hotelPassenger .= '/'.${'adult'.$i}.'+'.${'child'.$i};
if ('n' != ${'child'.$i}) {
$childs = explode('-', ${'child'.$i});
foreach ($childs as $child) {
if ($child >= 2) {
++$children;
} else {
++$infants;
}
}
}
}
$searchParam = ['class', 'stop', 'airline', 'carryOn', 'baggage', 'isActiveTourCode', 'airlineTourCode', 'tourCode'];
$optionalArray = $this->getParamsInRequest($fullRequest, $searchParam);
$optionals = sizeof($optionalArray) > 0 ? '?'.implode('&', $optionalArray) : '';
// CITY INFORMATION
$originLabel = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($origin1);
if (null == $originLabel) {
$originLabel = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchAirports::class)->findOneByIata($origin1)->getSearchCities();
}
$destinationLabel = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($destination1);
if (null == $destinationLabel) {
$destinationLabel = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchAirports::class)->findOneByIata($destination1)->getSearchCities();
}
$ajaxMultiFlightUrl = '/vuelos/'.$originLabel->getIata().'-'.$destinationLabel->getIata().'/'.$date1.'+'.$date2.'/'.$adults.'-'.$children.'-'.$infants.$optionals;
$hotelDate1 = false !== strpos($date1, 'T') ? substr($date1, 0, 10) : $date1;
$hotelDate2 = false !== strpos($date2, 'T') ? substr($date2, 0, 10) : $date2;
$ajaxMultiHotelUrl = '/hoteles/'.$destinationLabel->getIata().'/'.$hotelDate1.'+'.$hotelDate2.''.$hotelPassenger;
$AvailabilityArray = [
'originLabel1' => $originLabel->getCity().', '.$originLabel->getCountry().' ('.$originLabel->getIata().')',
'destinationLabel1' => $destinationLabel->getCity().', '.$destinationLabel->getCountry().' ('.$destinationLabel->getIata().')',
'originCity1' => $originLabel->getCity(),
'destinationCity1' => $destinationLabel->getCity(),
'date1' => $AvailabilityArray['date1'],
'date2' => $AvailabilityArray['date2'],
'origin1' => $origin1,
'destination1' => $destination1,
'adults' => $adults,
'children' => $children,
'infants' => $infants,
'rooms' => $rooms,
'countryCode' => $destinationLabel->getCountrycode(),
];
$AvailabilityArray = [
'cityName' => $destinationLabel->getCity(),
'countryCode' => $originLabel->getCity(),
'StartDate' => $date1,
'EndDate' => $date2,
'Rooms' => $rooms,
'Destination' => $destinationLabel->getCity(),
'Nights' => (strtotime($date1) - strtotime($date2)) / 86400,
];
for ($i = 1; $i <= $rooms; ++$i) {
${'countAdults'.$i} = 0;
${'countChildren'.$i} = 0;
$childrens = [];
if ('n' != ${'child'.$i}) {
${'child'.$i.'Ages'} = array_filter(explode('-', ${'child'.$i}));
if (1 == $i) {
$childAgesCookie = [
'age'.$i => ${'child'.$i.'Ages'},
];
}
${'child'.$i.'Size'} = is_countable(${'child'.$i.'Ages'}) ? count(${'child'.$i.'Ages'}) : 0;
foreach (${'child'.$i.'Ages'} as $age) {
$childrens[] = $age;
++${'countChildren'.$i};
++$countChildren;
}
}
$countAdults = $countAdults + ${'adult'.$i};
$services[] = ['adults' => ${'adult'.$i}, 'childrens' => $childrens];
$AvailabilityArray[$i] = [];
$AvailabilityArray[$i]['Children'] = ${'countChildren'.$i};
$AvailabilityArray[$i]['Adults'] = ${'adult'.$i};
}
$cookieLastSearch = $searchFlightCookie->searchFlightCookie(['flight' => base64_encode(json_encode($AvailabilityArray))]);
$AvailabilityArray['Children'] = $countChildren;
$AvailabilityArray['Adults'] = $countAdults;
$AvailabilityArray['Rooms'] = 1;
$ages = explode('-', $child1);
for ($j = 0; $j < sizeof($ages); ++$j) {
$cookieLastSearch['childAge'][$j] = $ages[$j];
}
$transactionIdResponse = $aviaturWebService->loginService('SERVICIO_MPT', 'dummy|http://www.aviatur.com.co/dummy/', []);
if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
$aviaturErrorHandler->errorRedirect('', 'Error MPA', 'No se creó Login!');
return new Response('Estamos experimentando dificultades técnicas en este momento.');
}
$ajaxMultiFlightUrl .= (sizeof($optionalArray) > 0 ? '&' : '?').'transactionMulti='.base64_encode($transactionIdResponse);
$ajaxMultiHotelUrl .= '?transactionMulti='.base64_encode($transactionIdResponse);
// RENDER VIEW
$agencyFolder = $twigFolder->twigFlux();
$view = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Multi/Default/results.html.twig');
$seoUrl = $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($ajaxMultiFlightUrl);
$urlDescription['long'] = null != $seoUrl ? $seoUrl[0]->getDescription() : '';
$urlDescription['short'] = null != $seoUrl ? $seoUrl[0]->getShortdescription() : '';
$seoMaskedUrl = $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
$urlDescription['url'] = null != $seoMaskedUrl ? '/'.$seoMaskedUrl[0]->getUrl() : $requestUrl;
$pixelInfo = [];
if (!$session->has('operatorId')) {
// PIXELES INFORMATION
$pixel['partner_datalayer']['flight'] = [
'enabled' => true,
'event' => 'paquete_search',
'dimension1' => $destination1,
'dimension2' => $origin1,
'dimension3' => $date1,
'dimension4' => $date2 ?? '',
'dimension5' => 'Hotel+Vuelo',
'dimension6' => '',
'dimension7' => isset($destination1) ? 'RoundTrip' : 'OneWay',
'dimension8' => 'economy',
'dimension9' => '',
'dimension10' => ((int) $adult1 + (int) $adult2 + (int) $adult3 + (int) $child1 + (int) $child2 + (int) $child3),
'dimension11' => '',
'dimension12' => 'Busqueda-PaqueteVuelos',
'ecommerce' => [
'currencyCode' => 'COP',
],
];
$pixel['partner_datalayer']['hotel'] = [
'enabled' => true,
'event' => 'paquete_search',
'dimension1' => $destination1,
'dimension2' => '',
'dimension3' => $date1,
'dimension4' => $date2,
'dimension5' => 'Hotel+Vuelo',
'dimension6' => '',
'dimension7' => '',
'dimension8' => '',
'dimension9' => '',
'dimension10' => ((int) $adult1 + (int) $child1 + (int) $adult2 + (int) $child2 + (int) $adult3 + (int) $child3),
'dimension11' => $rooms,
'dimension12' => 'Busqueda-PaqueteHotel',
'ecommerce' => [
'currencyCode' => 'COP',
],
];
$pixelInfo = $aviaturPixeles->verifyPixeles($pixel, 'multi', 'availability', $agency->getAssetsFolder(), false);
}
$parameters = json_decode($session->get($request->getHost().'[parameters]'));
$currentDate = date('Y-m-d');
$endDateCensocud = $parameters->date_end_cencosud;
$activeCheckCencosud = (strtotime($endDateCensocud) >= strtotime($currentDate));
$hotelUrl = $urlService->generateUrlFromIata($destination1, $date1, $date2, (int) $adult1, 0);
$roomsToConsult = $urlService->urlToRoomsArray($hotelUrl);
$coordinates = $urlService->getCoordinatesByIata($destination1);
$jsonHotelAvail = $urlService->jsonHotelAvailability($date1, $date2, strtoupper($destinationLabel->getIata()), 'MX', $coordinates['latitude'], $coordinates['longitude'], "10", $roomsToConsult, $transactionIdResponse);
$response = $this->render($view, [
'availabilityFront' => $session->has('operatorId'),
'ajaxMultiUrl' => $requestUrl,
'ajaxMultiFlightUrl' => $ajaxMultiFlightUrl,
'ajaxMultiHotelUrl' => $ajaxMultiHotelUrl,
'ajaxParameters' => base64_encode(json_encode($jsonHotelAvail)),
'countrycode' => $destinationLabel->getCountrycode(),
'checkin' => $date1,
'checkout' => $date2,
'roomsconsulturl' => 'rooms',
'availableArrayHotel' => $AvailabilityArray,
'cityName' => $destinationLabel->getCity(),
'isAval' => $this->isAval,
'safeUrl' => $safeUrl,
'urlDescription' => $urlDescription,
'AvailabilityArray' => $AvailabilityArray,
'cityOriginName' => $originLabel->getCity(),
'cityDestinationName' => $destinationLabel->getCity(),
'flights' => $flights,
'inlineEngine' => true,
// 'cookieLastSearch' => $cookieLastSearch,
'pixel_info' => $pixelInfo,
'activeCheckCencosud' => $activeCheckCencosud,
'online' => 'online'
]);
return $response;
}
public function resultsDetailAction(Request $request, SessionInterface $session, AviaturLogSave $aviaturLogSave, ParameterBagInterface $parameterBag, AviaturPixeles $aviaturPixeles, AuthorizationCheckerInterface $authorizationChecker, ManagerRegistry $registry, RouterInterface $router, AviaturErrorHandler $aviaturErrorHandler, TwigFolder $twigFolder, AviaturWebService $webService) {
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$responseFlightDetail = [];
$fullRequest = null;
$isAgent = false;
$currentRequest=$request;
$parameters = json_decode($session->get($request->getHost().'[parameters]'));
$webService->setUrls($parameters);
$request = $request->request;
$currentRoute= $currentRequest->get('_route') ?? $request->get('_route');
$routeType = explode('_', $currentRoute);
$transactionId = $session->get($transactionIdSessionName);
$returnUrl = $twigFolder->pathWithLocale('aviatur_general_homepage');
if ((is_countable($request->get('RPH')) ? count($request->get('RPH')) : 0) < 2) {
$message = $responseFlightDetail['error'] ?? 'No se ha recibido la información completa para consultar el detalle de tus vuelos.';
if (true === $session->has($transactionId.'[availability_url]')) {
$returnUrl = $session->get($transactionId.'[availability_url]');
}
return $this->redirect($aviaturErrorHandler->errorRedirect($returnUrl, '', $message));
}
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING')) {
$user = $this->getUser();
$agent = $user->getAgent();
if (!empty($agent[0]) && $agent[0]->getAgency()->getId() === $this->agency->getId()) {
$isAgent = true;
}
}
// Generate Flight Detail
$route = $router->match($this->generateUrl('aviatur_flight_'.$routeType[3].'_secure'));
$responseFlightDetail = $this->generateFlightDetail($route, $twigFolder, $request, $aviaturErrorHandler);
if ($responseFlightDetail instanceof RedirectResponse) {
return $responseFlightDetail;
}
if ('error' == $responseFlightDetail || (is_object($responseFlightDetail) && method_exists($responseFlightDetail, 'getStatusCode') && $responseFlightDetail->getStatusCode() === 500)) {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró información de la transacción'));
}
// Generate Hotel Detail
$responseHotelDetail = $this->generateHotelDetail(
$request->get('rooms'),
$request->get('hotelcode'),
$request->get('checkIn'),
$request->get('checkOut'),
$request->get('providerid'),
$request->get('countrycode')
);
if ($responseHotelDetail instanceof RedirectResponse) {
return $responseHotelDetail;
}
if(empty($responseHotelDetail['info'])) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl, '', 'Ha ocurrido un error inesperado'));
}
$detailFlightJson = json_encode($responseFlightDetail, JSON_PRETTY_PRINT);
$compressedDetailFlight = base64_encode(gzcompress($detailFlightJson));
// Generate Multi Detail
$responseMultiDetail = $responseHotelDetail;
$responseMultiDetail += [
'detailFlight' => $responseFlightDetail,
'hotelProvidersId' => $responseHotelDetail["info"]["providers"][0],
'compressedDetailFlight' => $compressedDetailFlight
];
$agencyFolder = $twigFolder->twigFlux();
//$view = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/FlightHotel/roomlistIndex.html.twig');
$view = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Default/roomlist.html.twig');
if (isset($responseMultiDetail['resume_info']['fee_type'])) {
$responseMultiDetail['resume_info']['fee_type'] = implode(',', $responseMultiDetail['resume_info']['fee_type']);
}
$iinRecordsArray = $this->getIINRanges($this->em);
$responseMultiDetail["ccranges"] = $iinRecordsArray["ccranges"];
$responseMultiDetail["ccfranchises"] = $iinRecordsArray["ccfranchises"];
return $this->render($view, $responseMultiDetail);
}
public function generateFlightDetail(array $route, TwigFolder $twigFolder, $request, AviaturErrorHandler $aviaturErrorHandler) {
$responseFlightDetailForward = $this->forward($route['_controller'], $route);
$xmlFlightDetail = new \SimpleXMLElement('<?xml version="1.0"?><info></info>');
$responseFlightDetail = json_decode($responseFlightDetailForward->getContent(), true);
if (null == $responseFlightDetail) {
return $responseFlightDetailForward;
}
if (isset($responseFlightDetail['error'])) {
$message = $responseFlightDetail['error'] ?? 'Ha ocurrido un error inesperado';
$returnUrl = $twigFolder->pathWithLocale('aviatur_general_homepage');
if (true === $request->has('referer')) {
$returnUrl = $request->get('http_referer');
}
if (isset($responseFlightDetail['no_message']) && (true == $responseFlightDetail['no_message'])) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl, '', $message));
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($returnUrl, '', $message));
}
}
// Convertir los segmentos y sus itinerarios a arrays
foreach ($responseFlightDetail['segments'] as $key => $segment) {
foreach ($segment['itinerary'] as $key1 => $flight) {
$responseFlightDetail['segments'][$key]['itinerary'][$key1] = $this->simpleXmlToArray($flight);
}
}
$documentType = $this->em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$genderType = $this->em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
$repositoryDocumentType = $this->em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
$queryDocumentType = $repositoryDocumentType
->createQueryBuilder('p')
->where('p.paymentcode != :paymentcode')
->setParameter('paymentcode', '')
->getQuery();
$documentPaymentType = $queryDocumentType->getResult();
$banks = [];
if (in_array('pse', $responseFlightDetail['paymentOptions'])) {
$banks = $this->em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
}
if (array_search('safety', $responseFlightDetail['paymentOptions'])) {
unset($responseFlightDetail['paymentOptions'][array_search('safety', $responseFlightDetail['paymentOptions'])]);
}
if (array_search('baloto', $responseFlightDetail['paymentOptions'])) {
unset($responseFlightDetail['paymentOptions'][array_search('baloto', $responseFlightDetail['paymentOptions'])]);
}
$today = date('Y-m-d');
$diffDays = (strtotime($responseFlightDetail['destination_array'][0]['DateTime']) - strtotime($today)) / 86400;
if ($diffDays > 0) {
$responseFlightDetail['baloto'] = true;
}
$responseFlightDetail['baloto'] ?? ($responseFlightDetail['baloto'] = false);
foreach ($responseFlightDetail['providersName'] as $providerName) {
if (('Kiu' == $providerName)) {
$responseFlightDetail['baloto'] = false;
}
}
$conditions = $this->em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($this->agency, 'reservation_conditions');
unset($responseFlightDetail['doc_type'], $responseFlightDetail['gender'], $responseFlightDetail['payment_doc_type'], $responseFlightDetail['cards'], $responseFlightDetail['inactiveCards'], $responseFlightDetail['banks'], $responseFlightDetail['conditions']);
$responseFlightDetail += [
'doc_type' => $documentType,
'gender' => $genderType,
'payment_doc_type' => $documentPaymentType,
'cards' => $this->em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]),
'inactiveCards' => $this->em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]),
'banks' => $banks,
'conditions' => $conditions,
];
return $responseFlightDetail;
}
public function generateHotelDetail($rooms, $hotelcode, $checkIn, $checkOut, $providerid, $countrycode) {
$response = $this->forward('Aviatur\HotelBundle\Controller\HotelRestController::roomListAction',
[
'hotelcode' => $hotelcode,
'providerid' => $providerid,
'checkIn' => $checkIn,
'checkOut' => $checkOut,
'rooms' => $rooms,
'countrycode' => $countrycode,
'isFlightHotel' => true
]
);
$data = json_decode($response->getContent(), true);
return $data;
}
public function checkoutAction(Request $request, \Swift_Mailer $mailer, ParameterBagInterface $parameterBag, TwigFolder $twigFolder, SessionInterface $session, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, AviaturWebService $aviaturWebService) {
// Obtener checkout de hoteles
$responseDetailHotel = $this->forward('Aviatur\HotelBundle\Controller\HotelRestController::checkoutAction', [
'request' => $request,
'parameterBag' => $parameterBag,
'twigFolder' => $twigFolder,
'session' => $session,
'aviaturErrorHandler' => $aviaturErrorHandler,
'router' => $router,
'aviaturWebService' => $aviaturWebService,
'isFlightHotel' => true
]);
$responseCheckout = json_decode($responseDetailHotel->getContent(), true);
if (isset($responseCheckout['error'])) {
$message = $responseCheckout['error'] ?? 'Ha ocurrido un error inesperado';
$returnUrl = $twigFolder->pathWithLocale('aviatur_general_homepage');
if (true === $request->has('referer')) {
$returnUrl = $request->get('http_referer');
}
if (isset($responseCheckout['no_message']) && (true == $responseCheckout['no_message'])) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl, '', $message));
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($returnUrl, '', $message));
}
}
$compressedDetailFlight = $request->request->get("flightDetail");
$detailFlightJson = \gzuncompress(base64_decode($compressedDetailFlight));
$flightDetail = json_decode($detailFlightJson, true);
$xmlData = new \SimpleXMLElement('<?xml version="1.0"?><root></root>');
// Convertir los segmentos y sus itinerarios a SimpleXMLElement
foreach ($flightDetail['segments'] as $key => $segment) {
foreach ($segment['itinerary'] as $key1 => $itinerary) {
$xmlData = new \SimpleXMLElement('<?xml version="1.0"?><itinerary></itinerary>');
$this->array_to_xml($itinerary, $xmlData);
$flightDetail['segments'][$key]['itinerary'][$key1] = $xmlData;
}
}
// hoteles
$cards = $this->em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]);
$repositoryDocumentType = $this->em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
$queryDocumentType = $repositoryDocumentType
->createQueryBuilder('p')
->where('p.paymentcode != :paymentcode')
->setParameter('paymentcode', '')
->getQuery();
$documentPaymentType = $queryDocumentType->getResult();
$typeDocument = $this->em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$typeGender = $this->em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
$inactiveCards = $this->em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]);
// Hoteles
$responseCheckout['cards'] = $cards;
$responseCheckout['payment_doc_type'] = $documentPaymentType;
$responseCheckout['doc_type'] = $typeDocument;
$responseCheckout['gender'] = $typeGender;
$responseCheckout['checkoutHoteles'] = $request->request->get("HT");
//Se toma los pasajero de vuelos
$responseCheckout['services'] = $flightDetail['services'];
// Vuelos
$responseCheckout["flightDetail"] = $flightDetail;
$responseCheckout["flightDetail"]['cards'] = $cards;
$responseCheckout["flightDetail"]['payment_doc_type'] = $documentPaymentType;
$responseCheckout["flightDetail"]['doc_type'] = $typeDocument;
$responseCheckout["flightDetail"]['gender'] = $typeGender;
$responseCheckout["flightDetail"]['inactiveCards'] = $inactiveCards;
$responseCheckout["isMulti"] = true;
$agencyFolder = $twigFolder->twigFlux();
$view = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/FlightHotel/checkoutIndex.html.twig');
return $this->render($view, $responseCheckout);
}
public function prePaymentStep1Action(Request $request, RouterInterface $router, SessionInterface $session, AviaturErrorHandler $aviaturErrorHandler) {
if ($request->isXmlHttpRequest()) {
$routeHotel = $router->match($this->generateUrl('aviatur_hotel_prepayment_step_1_secureN'));
$responseHotel = $this->forward($routeHotel['_controller'], $routeHotel);
$responseHotelData = json_decode($responseHotel->getContent(), true);
if (isset($responseHotelData['error'])) {
return $this->json($responseHotelData);
}
return $this->json([
'hotel' => $responseHotelData,
'ajax_url' => $this->generateUrl('aviatur_multi_prepayment_step_2_secureN'),
]);
}
return $this->redirect($aviaturErrorHandler->errorRedirect(
$this->generateUrl('aviatur_general_homepage'),
'',
'Acceso no autorizado'
));
}
public function prePaymentStep2Action(Request $request, RouterInterface $router) {
if ($request->isXmlHttpRequest()) {
$routeFlight = $router->match($this->generateUrl('aviatur_flight_prepayment_step_1_secure'));
$responseFlight = $this->forward($routeFlight['_controller'], $routeFlight);
$responseFlightData = json_decode($responseFlight->getContent(), true);
if (isset($responseFlightData['error'])) {
return $this->json($responseFlightData);
}
$routeHotel = $router->match($this->generateUrl('aviatur_hotel_prepayment_step_2_secureN'));
$responseHotel = $this->forward($routeHotel['_controller'], $routeHotel);
$responseHotelData = json_decode($responseHotel->getContent(), true);
if (isset($responseHotelData['error'])) {
return $this->json($responseHotelData);
}
return $this->json([
'hotel' => $responseHotelData,
'flight' => $responseFlightData,
'ajax_url' => $this->generateUrl('aviatur_multi_prepayment_step_3_secureN'),
]);
}
}
public function prePaymentStep3Action(Request $request, SessionInterface $session, RouterInterface $router) {
if ($request->isXmlHttpRequest()) {
$routeFlight = $router->match($this->generateUrl('aviatur_flight_prepayment_step_2_secure'));
$responseFlightPrepayment2Forward = $this->forward($routeFlight['_controller'], $routeFlight);
$responseFlightPrepayment2 = json_decode($responseFlightPrepayment2Forward->getContent(), true);
if (null == $responseFlightPrepayment2) {
var_dump($responseFlightPrepayment2Forward->getContent());
}
if (isset($responseFlightPrepayment2['error'])) {
return $this->json($responseFlightPrepayment2);
}
$url = 'aviatur_multi_payment_secureN';
$responseFlightPrepayment2['url'] = $this->generateUrl($url);
return $this->json($responseFlightPrepayment2);
}
}
public function paymentAction(Request $request, ParameterBagInterface $parameterBag, RouterInterface $router, SessionInterface $session, AviaturErrorHandler $aviaturErrorHandler) {
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$transactionId = $session->get($transactionIdSessionName);
$postData = json_decode($session->get($transactionId.'[flight][detail_data_flight]'));
$paymentData = $postData->PD;
$routeFlight = $router->match($this->generateUrl('aviatur_flight_payment_secure'));
$responseFlight = $this->forward($routeFlight['_controller'], $routeFlight);
$responseFlightData = json_decode($responseFlight->getContent(), true);
if (isset($responseFlightData['error'])) {
return $this->json($responseFlightData);
}
$routeHotel = $router->match($this->generateUrl('aviatur_hotel_payment_secureN'));
$responseHotel = $this->forward($routeHotel['_controller'], $routeHotel);
$responseHotelData = json_decode($responseHotel->getContent(), true);
if (isset($responseHotelData['error'])) {
return $this->json($responseHotelData);
}
if ('p2p' == $paymentData->type) {
return $this->redirect($this->generateUrl('aviatur_multi_payment_p2p_return_url_secureN', [], true));
} else {
$session->set('redirectedRetry', true);
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_multi_results_retry_secure'), '', 'El tipo de pago es inválido'));
}
}
public function p2pCallbackAction(SessionInterface $session, MultiHotelDiscount $multiHotelDiscount, PayoutExtraService $aviaturPayoutExtra, RouterInterface $router, ManagerRegistry $registry, ParameterBagInterface $parameterBag) {
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$agency = $this->agency;
$transactionId = $session->get($transactionIdSessionName);
$routeFlight = $router->match($this->generateUrl('aviatur_flight_payment_p2p_return_url_secure'));
$responseFlightP2PCallbackForward = $this->forward($routeFlight['_controller'], $routeFlight);
$responseFlightP2PCallback = json_decode($responseFlightP2PCallbackForward->getContent(), true);
if (isset($responseFlightP2PCallback['error'])) {
return $this->json($responseFlightP2PCallback);
}
$routeHotel = $router->match($this->generateUrl('aviatur_hotel_payment_p2p_return_url_secureN'));
$responseHotelP2PCallbackForward = $this->forward($routeHotel['_controller'], $routeHotel);
$responseHotelP2PCallback = json_decode($responseHotelP2PCallbackForward->getContent(), true);
if (isset($responseHotelP2PCallback['error'])) {
return $this->json($responseHotelP2PCallback);
}
$responseFlight = $router->match($responseFlightP2PCallbackForward->getTargetUrl());
$responseHotel = $router->match($responseHotelP2PCallbackForward->getTargetUrl());
$responseFlightArray = explode('_', $responseFlight['_route']);
$responseHotelArray = explode('_', $responseHotel['_route']);
$responsePreference = ['success' => 1, 'rejected' => 2, 'pending' => 3, 'error' => 4];
if ($responsePreference[$responseFlightArray[3]] > $responsePreference[$responseHotelArray[3]]) {
$responseTwig = 'aviatur_multi_results_payment_'.$responseFlightArray[3].'_secure';
} else {
$responseTwig = 'aviatur_multi_results_payment_'.$responseHotelArray[3].'_secure';
}
// $aviaturPayoutExtra->payoutExtrasCallback($responseTwig, $transactionId, 'multi_1', $agency);
// if ('success' === $responseHotelArray[3]) {
// $roomRateDiscount = $multiHotelDiscount->updateHotelReservationDiscount();
// }
return $this->redirect($this->generateUrl($responseTwig, [], true));
}
public function paymentOutputAction(Request $request, SessionInterface $session, \Swift_Mailer $mailer, AviaturPixeles $aviaturPixeles, Pdf $pdf, TwigFolder $twigFolder, ManagerRegistry $registry, RouterInterface $router, ParameterBagInterface $parameterBag, ExceptionLog $exceptionLog) {
$projectDir = $parameterBag->get('kernel.project_dir');
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$emailNotification = $parameterBag->get('email_notification');
$voucherFile = null;
$transactionId = $session->get($transactionIdSessionName);
$session->set($transactionId.'[multi]'.'[validation]', true);
$agency = $this->agency;
if ($session->has('operatorId')) {
$routeNameFlight = 'aviatur_flight_reservation_success_secure';
$routeNameHotel = 'aviatur_hotel_reservation_success_secure';
} else {
$routeName = explode('_', $request->get('_route'));
$routeNameFlight = 'aviatur_flight_payment_'.$routeName[4].'_secure';
$routeNameHotel = $routeName[4] == 'success'
? 'aviatur_hotel_reservation_'.$routeName[4].'_secureN'
: 'aviatur_hotel_payment_'.$routeName[4].'_secureN';
}
//Vuelos
$routeFlight = $router->match($this->generateUrl($routeNameFlight));
$responseFlightPaymentOutputForward = $this->forward($routeFlight['_controller'], $routeFlight);
$responseFlightPaymentOutput = json_decode($responseFlightPaymentOutputForward->getContent(), true);
if (null == $responseFlightPaymentOutput) {
var_dump($responseFlightPaymentOutputForward->getContent());
}
if (isset($responseFlightPaymentOutput['error'])) {
return $this->json($responseFlightPaymentOutput);
}
//Hoteles
$routeHotel = $router->match($this->generateUrl($routeNameHotel));
$responseHotelPaymentOutputForward = $this->forward($routeHotel['_controller'], $routeHotel);
$responseHotelPaymentOutput = json_decode($responseHotelPaymentOutputForward->getContent(), true);
if (!isset($responseHotelPaymentOutput) || empty($responseHotelPaymentOutput)) {
var_dump($responseHotelPaymentOutputForward->getContent());
}
if (isset($responseHotelPaymentOutput['error'])) {
return $this->json($responseHotelPaymentOutput);
}
$responsePaymentOutput = [
'flightResumen' => $responseFlightPaymentOutput,
'hotelResumen' => $responseHotelPaymentOutput
];
$this->sendEmailThankYouPageAction($routeNameFlight, $routeNameHotel, $responsePaymentOutput, $mailer, $session, $twigFolder, $parameterBag);
$agencyFolder = $twigFolder->twigFlux();
$urlResume = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/FlightHotel/thankYouPage.html.twig');
return $this->render($urlResume, $responsePaymentOutput);
}
public function sendEmailThankYouPageAction($routeNameFlight, $routeNameHotel, $responsePaymentOutput, \Swift_Mailer $mailer, SessionInterface $session, TwigFolder $twigFolder, ParameterBagInterface $parameterBag) {
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$transactionId = $session->get($transactionIdSessionName);
$postDataFlight = json_decode($session->get($transactionId . '[flight][detail_data_flight]'));
$postDataHotel = json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
$customerId = $postDataFlight->BD->id ?? $postDataHotel->BD->id;
$customer = $this->em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($customerId);
$bccMails = ['supervisorescallcenter@aviatur.com', 'notificacionessitioweb@aviatur.com'];
$setTo = $customer->getEmail();
$agencyFolder = $twigFolder->twigFlux();
$urlResume = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/FlightHotel/emailThankYou.html.twig');
$subjectPrefix = $session->get('agencyShortName') . ' - ';
$emissionData = $responsePaymentOutput["hotelResumen"]["emissionData"] ?? null;
$flightParts = explode('_', $routeNameFlight);
$hotelParts = explode('_', $routeNameHotel);
$flightStatus = isset($flightParts[3]) ? $flightParts[3] : null;
$hotelStatus = isset($hotelParts[3]) ? $hotelParts[3] : null;
$responsePreference = ['success' => 1, 'rejected' => 2, 'pending' => 3, 'error' => 4];
if ($flightStatus && $hotelStatus) {
$selectedStatus = $responsePreference[$flightStatus] > $responsePreference[$hotelStatus] ? $hotelStatus : $flightStatus;
} else {
$selectedStatus = $flightStatus ?: $hotelStatus;
}
if ($emissionData === 'No Reservation') {
$selectedStatus = 'rejected';
}
switch ($selectedStatus) {
case 'success':
$setSubject = 'Gracias por su compra';
break;
case 'rejected':
$setSubject = 'Pago rechazado';
break;
case 'pending':
$setSubject = 'Pago pendiente';
break;
default:
$setSubject = 'Estado de la transacción';
break;
}
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
->setBcc($bccMails)
->setSubject($subjectPrefix . $setSubject)
->setBody($this->renderView($urlResume, $responsePaymentOutput));
$mailer->send($message);
return true;
}
public function getParamsInRequest(Request $fullRequest, array $searchParam): array {
$optionalArray = [];
foreach ($searchParam as $param) {
if ($fullRequest->query->has($param)) {
$optionalArray[] = $param . '=' . $fullRequest->query->get($param);
}
}
return $optionalArray;
}
private function array_to_xml($info, &$xml_info) {
foreach ($info as $key => $value) {
if (is_array($value)) {
if (!is_numeric($key)) {
if ('@attributes' == $key) {
foreach ($value as $attributeKey => $attribute) {
$xml_info->addAttribute($attributeKey, $attribute);
}
} else {
foreach ($value as $key2 => $value2) {
if (!is_numeric($key2)) {
$subnode = $xml_info->addChild($key);
$this->array_to_xml($value, $subnode);
break;
} else {
if (!is_array($value2)) {
$subnode = $xml_info->addChild($key, $value2);
} else {
$subnode = $xml_info->addChild($key);
$this->array_to_xml($value2, $subnode);
}
}
}
}
} else {
$subnode = $xml_info->addChild('item'.$key);
$this->array_to_xml($value, $subnode);
}
} else {
$xml_info->addChild($key, htmlspecialchars($value));
}
}
}
private function simpleXmlToArray($xml) {
$json = json_encode($xml);
return json_decode($json, true);
}
public function getIINRanges($em) {
$iinRecords = $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findByActiveFranchises();
$iinRecordsArray = [];
$ccranges = [];
$ccfranchises = [];
foreach ($iinRecords as $key => $iinRecord) {
$paymentGatewayCode = $iinRecord["paymentgatewaycode"];
$description = $iinRecord["description"];
$description = strtoupper(str_replace(' ', '', trim($description)));
$stringRanges = $iinRecord["ranges"];
$ranges = json_decode($stringRanges, true);
$stringLengths = $iinRecord["lengths"];
$lengths = json_decode($stringLengths, true);
$luhn = $iinRecord["luhn"];
$cvvDigits = $iinRecord["cvvdigits"];
$tempLengths = [];
foreach ($lengths["lengths"] as $length) {
$tempLengths[] = array(0 => $length[0], 1 => (isset($length[1]) ? $length[1] : $length[0]));
}
$tempRecordArrayFranchises = [];
$tempRecordArrayFranchises["code"] = $paymentGatewayCode;
$tempRecordArrayFranchises["codename"] = $description;
$tempRecordArrayFranchises["luhn"] = $luhn;
$tempRecordArrayFranchises["length"] = $tempLengths;
$tempRecordArrayFranchises["cvvd"] = $cvvDigits;
$ccfranchises[$paymentGatewayCode] = $tempRecordArrayFranchises;
foreach ($ranges["ranges"] as $range) {
$tempRecordArrayRanges = [];
$tempRecordArrayRanges["range"][0] = $range[0];
$tempRecordArrayRanges["range"][1] = (isset($range[1]) ? $range[1] : $range[0]);
$tempRecordArrayRanges["minimum"] = strlen($range[0]);
$tempRecordArrayRanges["code"] = $paymentGatewayCode;
$ccranges[] = $tempRecordArrayRanges;
}
}
$iinRecordsArray = array("ccranges" => $ccranges, "ccfranchises" => $ccfranchises);
return $iinRecordsArray;
}
}