<?php
namespace Aviatur\MultiBundle\Controller;
use Aviatur\GeneralBundle\Services\AviaturAthServices;
use Knp\Snappy\Pdf;
use Aviatur\AgencyBundle\Entity\Agency;
use Doctrine\Persistence\ManagerRegistry;
use Aviatur\TwigBundle\Services\TwigFolder;
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\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;
use Aviatur\FlightBundle\Services\GenerateFlightResumeEmail;
use Aviatur\GeneralBundle\Services\QuotationUtils;
use Aviatur\CustomerBundle\Services\PhoneNumberService;
use Aviatur\GeneralBundle\Service\MaintenanceTimeValidator;
use Aviatur\SearchBundle\Entity\TravelDestination;
class FlightHotelController extends AbstractController
{
private $em;
/**
* @var Agency|object|null
*/
protected $agency;
/**
* @var bool
*/
protected $isAval;
private MaintenanceTimeValidator $maintenanceTimeValidator;
public function __construct(ManagerRegistry $managerRegistry, SessionInterface $session, MaintenanceTimeValidator $maintenanceTimeValidator) {
$this->session = $session;
$this->em = $managerRegistry->getManager();
$this->agency = $this->em->getRepository(Agency::class)->find($session->get('agencyId'));
$this->isAval = $this->agency->getAssetsFolder() == 'aval';
$this->maintenanceTimeValidator = $maintenanceTimeValidator;
}
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 = $this->em;
$fullRequest = $request;
$isFront = $session->has('operatorId');
$paymentType = "online"; // flightHotel have not another payment method by now
$isFront = $session->has('operatorId');
$redirectResponse = $this->maintenanceTimeValidator->validateMaintenanceTime('avail');
if ($redirectResponse !== null && !$isFront) {
return $redirectResponse;
}
// generate request url with
$configsHotelAgency = $this->em
->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)
->findProviderForHotelsWithAgency($this->agency, $paymentType);
//dd($configsHotelAgency, $this->agency);
$hotelProviders = json_encode(
array_map(
fn($config) => $config->getId(),
$configsHotelAgency
)
);
$parameters = json_decode($session->get($fullRequest->getHost().'[parameters]'));
$providersApi = $parameters->hotel_avail_api;
$providersForHotelFilter = [];
if($isFront){
$providersForHotelFilter = $this->em
->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)
->getProvidersForHotelFilter($this->agency, $paymentType);
}
$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' => 'results',
]
);
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 > 11) {
++$adults;
}
elseif ($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};
if ($children >= 1 ) {
$AvailabilityArray[$i]['ChildrenAges'] = $childAgesCookie;
}
}
$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]'));
$rooms = [];
// Habitación 1
if ($adult1 !== null) {
$rooms[] = [
"Adults" => (int)$adult1,
"Children" => $child1 !== 'n' ? count(explode('-', $child1)) : 0,
"childAges" => $child1 !== 'n' ? explode('-', $child1) : []
];
}
// Habitación 2
if ($adult2 !== null) {
$rooms[] = [
"Adults" => (int)$adult2,
"Children" => $child2 !== 'n' ? count(explode('-', $child2)) : 0,
"childAges" => $child2 !== 'n' ? explode('-', $child2) : []
];
}
// Habitación 3
if ($adult3 !== null) {
$rooms[] = [
"Adults" => (int)$adult3,
"Children" => $child3 !== 'n' ? count(explode('-', $child3)) : 0,
"childAges" => $child3 !== 'n' ? explode('-', $child3) : []
];
}
$currentDate = date('Y-m-d');
$endDateCensocud = $parameters->date_end_cencosud;
$activeCheckCencosud = (strtotime($endDateCensocud) >= strtotime($currentDate));
$searchCitiesResult = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($destination1);
//si no obtiene datos se busca como id referencia de aeropuerto
if($searchCitiesResult === null){
$searchCitiesResult = $destinationLabel;
}
$defaultCoordinates = json_decode($searchCitiesResult->getCoordinates(), true);
// $hotelInfo = (Object)[];
// $hotelInfo->latitude = $defaultCoordinates['latitude'];
// $hotelInfo->longitude = $defaultCoordinates['longitude'];
// $hotelInfo->countryIata = $defaultCoordinates["countryCode"];
// $hotelInfo->providerId = "";
// $hotelInfo->hotelname = "";
// $travelDestination = $searchCitiesResult->getTravelDestination();
// if ($travelDestination === null) {
// $storeResult = TravelDestinationController::fetchAndStoreHotelLocation($registry, $hotelInfo);
// $latitude = $storeResult->results[0]->latitude ?? null;
// $longitude = $storeResult->results[0]->longitude ?? null;
// } else {
// $latitude = $travelDestination->getLatitude();
// $longitude = $travelDestination->getLongitude();
// }
$hotelUrl = $urlService->generateUrlHotelForMulti($destination1, $date1, $date2, (int) $adult1, $child1, $defaultCoordinates['latitude'],
$defaultCoordinates['longitude'], $rooms, $searchCitiesResult);
$roomsToConsult = $urlService->urlToRoomsArray($hotelUrl);
$jsonHotelAvailrq = $urlService->jsonHotelAvailability($date1, $date2, strtoupper($searchCitiesResult->getIata()), 'MX', $defaultCoordinates['latitude'], $defaultCoordinates['longitude'], "10", $roomsToConsult, $transactionIdResponse, "HotelPackage");
$formatted = 'las islas';
$type = 'hotel';
$normalized_city = 'Cartagena de Indias';
$destinationExist = $this->em->getRepository(TravelDestination::class)->getMostPopularTravelDestinationResult($formatted, $type, $normalized_city);
$infoUrlPromoLasIslas = null;
if(!is_null($destinationExist)) {
$providerId = $destinationExist->getProviderIdentifier();
$hotelCode = $destinationExist->getHotelCode();
if(!is_null($providerId) && !is_null($hotelCode)) {
$infoUrlPromoLasIslas = $hotelCode . "-" . $providerId;
}
}
$jsonHotelAvail = [
'HotelRq' => $jsonHotelAvailrq,
'payment' => 'online',
];
$urlConsultPromo = "";
$adults = $AvailabilityArray['Adults'];
$children = $AvailabilityArray['Children'];
if($children === 0) {
$children = 'n';
}
for ($i = 1; $i <= $AvailabilityArray['rooms']; $i++) {
if($i === 1) {
$urlConsultPromo = $date1 . '+' . $date2 . '/';
}
$urlConsultPromo = $urlConsultPromo . 'room=' . $i . "&adults=" . 1 . "&children=" . $children;
if($i !== $AvailabilityArray['rooms']) {
$urlConsultPromo = $urlConsultPromo . '/';
}
}
$countrycodePromo = 'country=' . strtolower($destinationLabel->getCountrycode());
$response = $this->render($view, [
'availabilityFront' => $session->has('operatorId'),
'ajaxMultiUrl' => $requestUrl,
'destinationMetadata' => null,
'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,
'QSE' => isset($QSE) ? $QSE : null,
'safeUrl' => $safeUrl,
'urlDescription' => $urlDescription,
'AvailabilityArray' => $AvailabilityArray,
'cityOriginName' => $originLabel->getCity(),
'cityDestinationName' => $destinationLabel->getCity(),
'flights' => $flights,
'inlineEngine' => true,
'hotelProviders' => $hotelProviders,
'providersApi' => $providersApi,
'providersForHotelFilter' => $providersForHotelFilter,
// 'cookieLastSearch' => $cookieLastSearch,
'pixel_info' => $pixelInfo,
'activeCheckCencosud' => $activeCheckCencosud,
'online' => 'online',
'infoUrlPromoLasIslas' => $infoUrlPromoLasIslas,
'urlConsultPromo' => $urlConsultPromo,
'countrycodePromo' => $countrycodePromo
]);
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 FD'));
}
// 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);
$detailFlightJson = json_encode($responseFlightDetail, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_PARTIAL_OUTPUT_ON_ERROR);
$compressedDetailFlight = base64_encode(gzcompress($detailFlightJson));
$availAbilityPrice = (int) $currentRequest->get('AvailAbilityPrice');
$availAbilityPriceArray = [];
$totalNetRooms = null;
if (!empty($responseHotelDetail['acomodationRooms'])) {
foreach ($responseHotelDetail['acomodationRooms'] as $room) {
if (isset($room['net'])) {
$totalNetRooms += (float) $room['net'];
}
}
}
$totalAmount = $responseFlightDetail['resume_info']['total_amount'] + $totalNetRooms;
$acepttedRangeDiff = 100;
if (isset($availAbilityPrice) && abs($totalAmount - $availAbilityPrice) > $acepttedRangeDiff) {
$availAbilityPriceArray = [
'isPriceEqual' => false,
'availabilityprice' => $availAbilityPrice,
'detailPrice' => $totalAmount
];
}
// Generate Multi Detail
$responseMultiDetail = $responseHotelDetail;
$responseMultiDetail += [
'detailFlight' => $responseFlightDetail,
'hotelProvidersId' => $responseHotelDetail["info"]["providers"][0],
'compressedDetailFlight' => $compressedDetailFlight,
'availAbilityPriceArray' => $availAbilityPriceArray
];
$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);
$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));
}
}
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$transactionId = $session->get($transactionIdSessionName);
$em = $this->em;
$phoneService = new PhoneNumberService($em);
$phonePrefixes = $phoneService->getActivePrefixes();
$responseCheckout['phone_prefixes'] = $phonePrefixes;
$responseCheckout['default_country'] = 'CO';
$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]);
$documentPassengerType = $this->em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAllActiveConfigured();
// 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['documentPassengerType'] = $documentPassengerType;
$responseCheckout['airlineFareTypes'] = $flightDetail['airlineFareTypes'];
$responseCheckout["isMulti"] = true;
$responseCheckout["routeType"] = $flightDetail["routeType"];
// Informacion de puntos para aval
if ($this->isAval) {
$responseCheckout = $this->aviaturAthServices->getPointsInfoByAgency($responseCheckout, $transactionId, $this->agency);
}
$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)
{
$isFront = $this->session->has('operatorId');
$redirectResponse = $this->maintenanceTimeValidator->validateMaintenanceTime();
if ($redirectResponse !== null && !$isFront) {
return $this->json(['error' => 'error', 'message' => $redirectResponse["message"]]);
}
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);
}
if ($session->has('operatorId')) {
$url = 'aviatur_multi_results_reservation_success_secure';
}else{
$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 = ['rejected' => 4, 'pending' => 3, 'success' => 2, 'error' => 1];
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 getCommentValue($search, $comments)
{
return \preg_replace("/^{$search}: (.{0,100}).*$/", '$1', (string) $comments[$this->arraySearcher($comments, $search, true)], 1);
}
public function arraySearcher($array, $substring, $position = true)
{
$return = array_filter($array, fn($var) => preg_match("/\b$substring\b/i", $var));
if ($position) {
$returnPositions = array_keys($return);
return $returnPositions[0];
} else {
return $return;
}
}
public function quotationAction(Request $request, SessionInterface $session, ExceptionLog $exceptionLog, GenerateFlightResumeEmail $generateFlightResumeEmail, Pdf $pdf, ManagerRegistry $registry, RouterInterface $router, ParameterBagInterface $parameterBag, AviaturWebService $aviaturWebService, TwigFolder $twigFolder, \Swift_Mailer $mailer, QuotationUtils $QuotationUtils)
{
$projectDir = $parameterBag->get('kernel.project_dir');
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$emailData = [];
$fullRequest = $request;
$transactionId = $session->get($transactionIdSessionName);
$prepaymentInfo = \simplexml_load_string($session->get($transactionId . '[hotel][prepayment]'));
$server = $fullRequest->server;
$request = $fullRequest->request;
$queryString = $fullRequest->query;
$agency = $this->agency;
$isINNS = 0;
$agencyFolder = $twigFolder->twigFlux();
$responseFlight = \simplexml_load_string($session->get($transactionId . '[flight][detail]'));
$i = 0;
$segments = [];
$itineraryFlights = [];
$j = 0;
$flights = [];
$totalDuration = 0;
$stopoverArrival = null;
$resp = $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions->OriginDestinationOption;
foreach ($resp as $key => $datas) {
foreach ($datas->FlightSegment as $flightSegment) {
if (null != $stopoverArrival) {
$totalDuration += (int) abs(strtotime($flightSegment['DepartureDateTime']) - strtotime($stopoverArrival)) / 60;
$flightSegment->StopoverLength = $generateFlightResumeEmail->convertToHoursMins(abs(strtotime($flightSegment['DepartureDateTime']) - strtotime($stopoverArrival)) / 60);
}
$comments = (array) $flightSegment->Comment;
$flightSegment['DepartureCityName'] = $this->getCommentValue('DepartureCityName', $comments);
$flightSegment['ArrivalCityName'] = $this->getCommentValue('ArrivalCityName', $comments);
$flightSegment['DepartureAirportName'] = $this->getCommentValue('DepartureAirportName', $comments);
$flightSegment['ArrivalAirportName'] = $this->getCommentValue('ArrivalAirportName', $comments);
$flightSegment['DepartureCountryName'] = $this->getCommentValue('DepartureCountryName', $comments);
$flightSegment['ArrivalCountryName'] = $this->getCommentValue('ArrivalCountryName', $comments);
$flightSegment['DepartureCountryCode'] = $this->getCommentValue('DepartureCountryCode', $comments);
$flightSegment['ArrivalCountryCode'] = $this->getCommentValue('ArrivalCountryCode', $comments);
$flightSegment->FlightLength = (string) $generateFlightResumeEmail->convertToHoursMins(substr($comments[$this->arraySearcher($comments, 'Total Duration')], strpos($comments[$this->arraySearcher($comments, 'Total Duration')], ':') + 2, 100));
$totalDuration += (int) substr($comments[$this->arraySearcher($comments, 'Total Duration')], strpos($comments[$this->arraySearcher($comments, 'Total Duration')], ':') + 2, 100);
$stopoverArrival = $flightSegment['ArrivalDateTime'];
$flights[$i][] = $flightSegment;
$departure_place = (string) $flightSegment['DepartureCityName'] . ', ' . (string) $flightSegment['DepartureCountryName'] . ' ' . (string) $flightSegment['DepartureCountryCode'];
$arrival_place = (string) $flightSegment['ArrivalCityName'] . ', ' . (string) $flightSegment['ArrivalCountryName'] . ' ' . (string) $flightSegment['ArrivalCountryCode'];
$itineraryFlights[] = ['dep' => $departure_place, 'arr' => $arrival_place, 'stopover' => ($j > 0) ? true : false];
++$j;
}
++$i;
}
$responseHotel = json_decode($session->get($transactionId . '[hotel][detail]'));
$selectedRooms = $session->get($transactionId . "[hotel][selected_rooms]");
$selectedRate = null;
foreach ($responseHotel->data->hotelRoomlist->hotels[0]->rates as $rate) {
if ($rate->rateKey === $selectedRooms[0]) {
$selectedRate = $rate;
break;
}
}
$additionalUserFront = simplexml_load_string($session->get('front_user_additionals'));
$datosAgente = simplexml_load_string($session->get('front_user'));
$detailHotelRaw = $responseHotel->data->hotelRoomlist->hotels[0]->name;
$locationHotel = $responseHotel->data->hotelRoomlist->hotels[0]->location->address;
$dateIn = strtotime($responseHotel->data->hotelRoomlist->stay->checkIn);
$dateOut = strtotime($responseHotel->data->hotelRoomlist->stay->checkOut);
$postDataJson = $session->get($transactionId . '[hotel][detail_data_hotel]');
if ($session->has($transactionId . '[crossed]' . '[url-hotel]')) {
$urlAvailability = $session->get($transactionId . '[crossed]' . '[url-hotel]');
} elseif ($session->has($transactionId . '[hotel][availability_url]')) {
$urlAvailability = $session->get($transactionId . '[hotel][availability_url]');
} else {
$urlAvailability = $session->get($transactionId . '[availability_url]');
}
$routeParsed = parse_url($urlAvailability);
$availabilityUrl = $router->match($routeParsed['path']);
$rooms = [];
for ($i = 1; $i <= $availabilityUrl['rooms']; ++$i) {
$adult = $availabilityUrl['adult' . $i];
$child = [];
if ('n' != $availabilityUrl['child' . $i]) {
$child = explode('-', $availabilityUrl['child' . $i]);
}
$rooms[$i] = ['adult' => $adult, 'child' => $child];
}
$valorHotel = $fullRequest->request->get('quotationPriceTotalMulti');
$detailHotel = [
'dateIn' => $dateIn,
'dateOut' => $dateOut,
'roomInformation' => $rooms,
'dateInStr' => (string) $responseHotel->data->hotelRoomlist->stay->checkIn,
'dateOutStr' => (string) $responseHotel->data->hotelRoomlist->stay->checkOut,
'nights' => floor(($dateOut - $dateIn) / (24 * 60 * 60)),
'adults' => (string) $session->get($transactionId . '[hotel][totalAdults]'),
'children' => (string) $session->get($transactionId . '[hotel][totalChildren]'),
'rooms' => $responseHotel->data->hotelRoomlist->hotels[0],
'timeSpan' => $responseHotel->data->auditData->timestamp,
'basicInfos' => $selectedRate,
'total' => $selectedRate->net,
'category' => $selectedRate->boardName,
'description' => (string) $responseHotel->data->hotelRoomlist->hotels[0]->description,
// 'email' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
'services' => $responseHotel->data->hotelRoomlist->hotels[0]->services,
'photos' => $responseHotel->data->hotelRoomlist->hotels[0]->gallery,
'agentName' => simplexml_load_string($session->get('NOMBRE_USUARIO')) . ' ' . simplexml_load_string($session->get('APELLIDOS_USUARIO')),
'agentMail' => simplexml_load_string($session->get('CORREO_ELECTRONICO')),
'agentPhone' => simplexml_load_string($session->get('TELEFONO_SUCURSAL')),
'agentAddress' => simplexml_load_string($session->get('DIRECCION_SUCURSAL')),
'namesClient' => $fullRequest->request->get('quotationName'),
'lastnamesClient' => $fullRequest->request->get('quotationLastname'),
'emailClient' => $fullRequest->request->get('quotationEmail'),
'priceTotalQuotation' => $fullRequest->request->get('quotationPriceTotalMulti'),
'priceCurrency' => $fullRequest->request->get('quotationCurrencyMulti'),
'infoTerms' => $fullRequest->request->get('quotationTerms'),
'infoComments' => $fullRequest->request->get('quotationComments'),
'prepaymentsInfo' => $prepaymentInfo,
'longitude' => $responseHotel->data->hotelRoomlist->hotels[0]->location->coordinates->longitude,
'latitude' => $responseHotel->data->hotelRoomlist->hotels[0]->location->coordinates->latitude,
];
$html = $twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Multi/Default/quotation.html.twig');
$namefilepdf = 'Aviatur_cotizacion_hotel+vuelo_' . $transactionId;
$voucherMultiFile = $projectDir . '/app/quotationLogs/multiQuotation/' . $namefilepdf . '.pdf';
$docPDF = [];
$vouchersFiles = [];
$z = 0;
foreach ($responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions->OriginDestinationOption as $countOrgOption) {
++$z;
}
$date = floor(($dateOut - $dateIn) / (24 * 60 * 60));
$totalHotel = str_replace('.', '', $valorHotel);
$codImg = $QuotationUtils->curlImg($session);
$data = [
'countOrgOptionValue' => $z,
'datas' => $detailHotel,
'flightSegment' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions->OriginDestinationOption,
'terms' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->Notes,
'childrens' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions['ChdQuantity'],
'adults' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions['AdtQuantity'],
'infants' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItinerary->OriginDestinationOptions['InfQuantity'],
'agentName' => $datosAgente->NOMBRE_AGENTE,
'agentMail' => $datosAgente->CORREO_ELECTRONICO,
'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL ?? $datosAgente->NOMBRE_OFICINA_PERTENECE,
'priceTotalQuotation' =>$fullRequest->request->get('quotationPriceTotalMulti'),
'priceCurrency' => $fullRequest->request->get('quotationCurrencyMulti'),
'typeRoom' => $fullRequest->request->get('typeRoom'),
'priceRoomNights' => $valorHotel,
'flightSegments' => $flights,
'pricingData' => $responseFlight->Message->OTA_AirLowFareSearchRS->PricedItineraries->PricedItinerary->AirItineraryPricingInfo,
'docCountries' => $docPDF,
'codImg' => $codImg,
'totalHotel' => $totalHotel,
'agentCity' => $datosAgente->CIUDAD,
];
$urlResume = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Cruise/Default/email_quotation.html.twig');
$emailData = [];
$body = $this->renderView($urlResume, $emailData);
if (!file_exists($voucherMultiFile)) {
// Configuración de opciones para generar el PDF
$pdf->setOption('page-size', 'LETTER');
$pdf->setOption('margin-top', 0);
$pdf->setOption('margin-right', 0);
$pdf->setOption('margin-bottom', 0);
$pdf->setOption('margin-left', 0);
$pdf->setOption('orientation', 'portrait');
$pdf->setOption('enable-javascript', true);
$pdf->setOption('no-stop-slow-scripts', true);
$pdf->setOption('no-background', false);
$pdf->setOption('lowquality', false);
$pdf->setOption('encoding', 'utf-8');
$pdf->setOption('images', true);
$pdf->setOption('dpi', 300);
$pdf->setOption('enable-external-links', true);
$pdf->setOption('enable-internal-links', true);
// Genera el PDF
$pdf->generateFromHtml($this->renderView($html, $data), $voucherMultiFile);
}
$nameProduct = str_replace(["cotizacion", "/", "check-conditions"], "", $fullRequest->getPathInfo());
$QuotationUtils->sendQuotation($nameProduct,$voucherMultiFile, $mailer, $session, $twigFolder, $codImg, $fullRequest,$parameterBag , $aviaturWebService ,$pdf , $exceptionLog);
$request = new Request();
if (file_exists($voucherMultiFile)) {
unlink($voucherMultiFile);
}
// $this->saveInformationCGSVuelos($request, $aviaturLogSave, $registry, $aviaturErrorHandler, $aviaturWebService, $responseFlight, $z, $additionalUserFront, $detailHotel, $agency);
return $this->render($twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Hotel/Default/resume_quotation.html.twig'), ['nameProduct'=> $nameProduct]);
}
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;
$detailData = json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
if ($session->has('operatorId')) {
$routeNameFlight = 'aviatur_flight_reservation_success_secure';
$routeNameHotel = 'aviatur_hotel_reservation_success_secureN';
} 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 (empty($responseHotelPaymentOutput)) {
var_dump($responseHotelPaymentOutputForward->getContent());
}
if (isset($responseHotelPaymentOutput['error'])) {
return $this->json($responseHotelPaymentOutput);
}
if (isset($responseHotelPaymentOutput['emissionData']) && !isset($responseHotelPaymentOutput['emailData']['emissionData'])) {
$responseHotelPaymentOutput['emailData']['emissionData'] = $responseHotelPaymentOutput['emissionData'];
}
$responsePaymentOutput = [
'flightResumen' => $responseFlightPaymentOutput,
'hotelResumen' => $responseHotelPaymentOutput,
'rooms' => $responseHotelPaymentOutput["emailData"]["rooms"],
'countryCode' => $responseHotelPaymentOutput["emailData"]["countryCode"],
'alertsValidation' => $responseHotelPaymentOutput["emailData"]["alertsValidation"],
'payment' => $responseHotelPaymentOutput["emailData"]["payment"],
'data_amount_total' => $detailData->data_amount_total ?? 0,
'isAval' => $this->isAval
];
$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);
$datosAgente = simplexml_load_string($session->get('front_user'));
$bccMails = ['supervisorescallcenter@aviatur.com', 'notificacionessitioweb@aviatur.com'];
if ($session->has('operatorId')) {
$setTo = $datosAgente->CORREO_ELECTRONICO;
}else {
$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;
}
try{
$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);
}catch(\Exception $e){
return false;
}
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;
}
}