<?php
namespace Aviatur\HotelBundle\Controller;
use Aviatur\AgentBundle\Entity\AgentTransaction;
use Aviatur\GeneralBundle\Services\AviaturRestService;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Aviatur\CustomerBundle\Models\CustomerModel;
use Aviatur\GeneralBundle\Entity\FormUserInfo;
use Aviatur\GeneralBundle\Entity\Metatransaction;
use Aviatur\GeneralBundle\Services\AviaturEncoder;
use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
use Aviatur\HotelBundle\Models\HotelModel;
use Aviatur\TwigBundle\Services\TwigFolder;
use FOS\UserBundle\Model\UserInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Aviatur\GeneralBundle\Services\PayoutExtraService;
use Knp\Snappy\Pdf;
use Aviatur\GeneralBundle\Services\AviaturPixeles;
use Aviatur\GeneralBundle\Services\AviaturWebService;
use Aviatur\GeneralBundle\Services\ExceptionLog;
use Aviatur\GeneralBundle\Services\AviaturLogSave;
use Knp\Component\Pager\Paginator;
use Knp\Component\Pager\PaginatorInterface;
use Aviatur\MultiBundle\Services\MultiHotelDiscount;
use Exception;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Annotation\Route;
use FOS\UserBundle\Security\LoginManager;
use FOS\UserBundle\Security\LoginManagerInterface;
use Aviatur\GeneralBundle\Services\AviaturUpdateBestprices;
use Aviatur\HotelBundle\Services\SearchHotelCookie;
use Aviatur\GeneralBundle\Services\AviaturMailer;
use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
use Aviatur\PaymentBundle\Services\TokenizerService;
use Aviatur\GeneralBundle\Services\CouponDiscountService;
use Aviatur\GeneralBundle\Controller\OrderController;
use Aviatur\PaymentBundle\Controller\P2PController;
use Aviatur\PaymentBundle\Controller\WorldPayController;
use Aviatur\PaymentBundle\Controller\PSEController;
use Aviatur\HotelBundle\Services\ConfirmationWebservice;
use Aviatur\PaymentBundle\Controller\CashController;
use Aviatur\PaymentBundle\Controller\SafetypayController;
use Aviatur\CustomerBundle\Services\ValidateSanctionsRenewal;
use Aviatur\GeneralBundle\Services\AviaturXsltRender;
use Aviatur\MultiBundle\Services\MultiCustomUtils;
class HotelController extends AbstractController
{
/**
* @var \Doctrine\Persistence\ObjectManager
*/
protected $managerRegistry;
/**
* @var SessionInterface
*/
protected $session;
protected $agency;
private $multiCustomUtils;
private $aviaturRestService;
public function __construct(ManagerRegistry $registry, SessionInterface $session, MultiCustomUtils $multiCustomUtils, AviaturRestService $aviaturRestService) {
$this->managerRegistry = $registry->getManager();
$this->session = $session;
$this->agency = $this->managerRegistry->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$this->multiCustomUtils = $multiCustomUtils;
$this->aviaturRestService = $aviaturRestService;
}
public function searchAction()
{
return $this->redirect($this->generateUrl('aviatur_search_hotels',[]));
}
/**
* Metodo encargado de consultar la disponibilidad hotelera, pendiente de conectar con el Qs
* Instancia la clase hotel, obtiene el dummy de RQ de disponibilidad, Asigna el id del provedor de hoteles
* Envia al metodo encargado de la logica de consumo de los servicios.
*
* @return type
*/
public function availabilityAction(
Request $fullRequest,
AuthorizationCheckerInterface $authorizationChecker,
SearchHotelCookie $hotelSearchCookie,
AviaturUpdateBestprices $updateBestPrices,
MultiHotelDiscount $multiHotelDiscount,
ExceptionLog $exceptionLog,
AviaturLogSave $aviaturLogSave,
AviaturErrorHandler $aviaturErrorHandler,
ManagerRegistry $registry,
TwigFolder $twigFolder,
AviaturPixeles $aviaturPixeles,
AviaturWebService $aviaturWebService,
ParameterBagInterface $parameterBag,
$rooms,
$destination,
$date1,
$date2,
$adult1,
$child1 = null,
$adult2 = null,
$child2 = null,
$adult3 = null,
$child3 = null
)
{
$urlDescription = [];
$providers = [];
$roomRate = null;
$em = $this->managerRegistry;
$session = $this->session;
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
$agency = $this->agency;
$isFront = $session->has('operatorId');
$isMulti = strpos($fullRequest->server->get('HTTP_REFERER'), 'multi') ? true : false;
if ($session->has('notEnableHotelSearch')) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/', 'Busqueda de resultados', 'No podemos realizar la consulta ya que no existe un proveedor configurado para este servicio'));
}
$dateIn = strtotime($date1);
$dateOut = strtotime($date2);
$now = strtotime('today');
if (($dateIn <= $now) || ($dateIn >= $dateOut)) {
$redirectText = 'Hemos detectado una inconsistencia en tu consulta, esta es nuestra recomendación';
if ($dateIn == $now) {
$dateOut = date('Y-m-d', strtotime($date2.'+1 day'));
$redirectText = 'Para poder efectuar su reserva en línea, requiere mínimo 24h de anticipación a la fecha de ingreso.';
} else {
$dateOut = $dateIn < $now ? date('Y-m-d', strtotime('+8 day')) : date('Y-m-d', strtotime($date1.'+8 day'));
}
$dateIn = $dateIn <= $now ? date('Y-m-d', strtotime('+1 day')) : date('Y-m-d', $dateIn);
$data = ['destination' => $destination,
'date1' => $dateIn,
'date2' => $dateOut,
'adult1' => $adult1,
'child1' => $child1, ];
$redirectRoute = 'aviatur_hotel_1';
if ($adult3) {
$redirectRoute = 'aviatur_hotel_3';
$data['adult3'] = $adult3;
$data['child3'] = $child3;
$data['adult2'] = $adult2;
$data['child2'] = $child2;
} elseif ($adult2) {
$redirectRoute = 'aviatur_hotel_2';
$data['adult2'] = $adult2;
$data['child2'] = $child2;
}
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl($redirectRoute, $data), 'Recomendación Automática', $redirectText));
}
$AvailabilityArray = [
'StartDate' => $date1,
'EndDate' => $date2,
'Rooms' => $rooms,
'Destination' => $destination,
'Nights' => floor(($dateOut - $dateIn) / (24 * 60 * 60)),
];
$services = [];
$countAdults = 0;
$countChildren = 0;
$childAgesCookie = 0;
for ($i = 1; $i <= $rooms; ++$i) {
${'countAdults'.$i} = 0;
${'countChildren'.$i} = 0;
$childrens = [];
if ('n' != ${'child'.$i}) {
${'child'.$i.'Ages'} = 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};
}
$AvailabilityArray['Children'] = $countChildren;
$AvailabilityArray['Adults'] = $countAdults;
$destinationObject = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($destination);
if (null != $destinationObject) {
$AvailabilityArray['cityName'] = $destinationObject->getCity();
$AvailabilityArray['countryCode'] = $destinationObject->getCountrycode();
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Error en la consulta', 'La ciudad ingresada no es válida'));
}
$session->remove('AvailabilityArrayhotel');
$session->set('AvailabilityArrayhotel', $AvailabilityArray);
$domain = $fullRequest->getHost();
$requestMultiHotelDiscountInfo = false;
$seoUrl = $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
$urlDescription['url'] = null != $seoUrl ? '/'.$seoUrl[0]->getUrl() : $requestUrl;
$pixelInfo = []; //THIS IS INTENDED FOR STORING ALL DATA CLASIFIED BY PIXEL.
if ($fullRequest->isXmlHttpRequest()) {
$session->remove($session->get($transactionIdSessionName).'[hotel][availability_file]');
if ($destinationObject) {
$currency = 'COP';
$configsHotelAgency = $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findProviderForHotelsWithAgency($agency);
if ($configsHotelAgency) {
foreach ($configsHotelAgency as $configHotelAgency) {
$providers[] = $configHotelAgency->getProvider()->getProvideridentifier();
if (strpos($configHotelAgency->getProvider()->getName(), '-USD')) {
$currency = 'USD';
}
}
} else {
$exceptionLog->log('Error Fatal', 'No se encontró la agencia segun el dominio: '.$domain, null, false);
return new Response('no se encontró agencias para consultar disponibilidad.');
}
$hotelModel = new HotelModel();
$xmlTemplate = $hotelModel->getXmlAvailability();
$xmlRequest = $xmlTemplate[0];
$provider = implode(';', $providers);
$requestLanguage = mb_strtoupper($fullRequest->getLocale());
//$MoreDataEchoToken = $isMulti ? 'MoreDataEchoToken="P"' : '';
$MoreDataEchoToken = 'MoreDataEchoToken="P"';
$variable = [
'ProviderId' => $provider,
'date1' => $date1,
'date2' => $date2,
'destination' => $destination,
'country' => $destinationObject->getCountrycode(),
'language' => $requestLanguage,
'currency' => $currency,
'userIp' => $fullRequest->getClientIp(),
'userAgent' => $fullRequest->headers->get('User-Agent'),
];
$i = 1;
foreach ($services as $room) {
$xmlRequest .= str_replace('templateAdults', 'adults_'.$i, $xmlTemplate[1]);
$j = 1;
foreach ($room['childrens'] as $child) {
$xmlRequest .= str_replace('templateChild', 'child_'.$i.'_'.$j, $xmlTemplate[2]);
$variable['child_'.$i.'_'.$j] = $child;
++$j;
}
$variable['adults_'.$i] = $room['adults'];
$xmlRequest .= $xmlTemplate[3];
++$i;
}
$xmlRequest .= $xmlTemplate[4];
$xmlRequest = str_replace('{moreDataEchoToken}', $MoreDataEchoToken, $xmlRequest);
$makeLogin = true;
if ($fullRequest->query->has('transactionMulti')) {
$transactionId = base64_decode($fullRequest->query->get('transactionMulti'));
$session->set($transactionIdSessionName, $transactionId);
$makeLogin = false;
$requestMultiHotelDiscountInfo = true;
}
if ($session->get($session->get($transactionIdSessionName).'[crossed]'.'[url-hotel]')) {
$makeLogin = false;
}
if ($makeLogin) {
$transactionIdResponse = $aviaturWebService->loginService('SERVICIO_MPT', 'dummy|http://www.aviatur.com.co/dummy/', []);
if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
$aviaturErrorHandler->errorRedirect('', 'Error MPA', 'No se creo Login!');
// return new Response('Estamos experimentando dificultades técnicas en este momento.');
return (new JsonResponse())->setData([
'error' => true,
'message' => 'Estamos experimentando dificultades técnicas en este momento.',
]);
}
$transactionId = (string) $transactionIdResponse;
$session->set($transactionIdSessionName, $transactionId);
}
$variable['transactionId'] = $transactionId;
$preResponse = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'HotelAvail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false);
if (isset($preResponse['error'])) {
if (false === strpos($preResponse['error'], '66002')) {
$aviaturErrorHandler->errorRedirect($requestUrl, 'Error disponibilidad hoteles', $preResponse['error']);
}
$preResponse = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'HotelAvail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false);
if (isset($preResponse['error'])) {
if (false === strpos($preResponse['error'], '66002')) {
$aviaturErrorHandler->errorRedirect($requestUrl, 'Error disponibilidad hoteles', $preResponse['error']);
}
return new Response($preResponse['error']);
}
} elseif (empty((array) $preResponse->Message)) {
$aviaturErrorHandler->errorRedirect($requestUrl, 'Error disponibilidad hoteles', $preResponse->Message);
return new Response('No hemos encontrado información para el destino solicitado.');
}
$searchImages = ['hotelbeds.com/giata/small', '/100x100/', '_tn.jpg', '<p><b>Ubicación del establecimiento</b> <br />'];
$replaceImages = ['hotelbeds.com/giata', '/200x200/', '.jpg', ''];
$response = simplexml_load_string(str_replace($searchImages, $replaceImages, $preResponse->asXML()));
$response->Message->OTA_HotelAvailRS['StartDate'] = $date1;
$response->Message->OTA_HotelAvailRS['EndDate'] = $date2;
$response->Message->OTA_HotelAvailRS['Country'] = $variable['country'];
$configHotelAgencyIds = [];
foreach ($configsHotelAgency as $configHotelAgency) {
$configHotelAgencyIds[] = $configHotelAgency->getId();
$providerOfConfig[$configHotelAgency->getId()] = $configHotelAgency->getProvider()->getProvideridentifier();
$providerNames[$configHotelAgency->getId()] = $configHotelAgency->getProvider()->getName();
$typeOfConfig[$configHotelAgency->getId()] = $configHotelAgency->getType();
}
$markups = $em->getRepository(\Aviatur\HotelBundle\Entity\Markup::class)->getMarkups($configHotelAgencyIds, $destinationObject->getId());
$parametersJson = $session->get($domain.'[parameters]');
$parameters = json_decode($parametersJson);
$tax = (float) $parameters->aviatur_payment_iva;
if (property_exists($response->Message->OTA_HotelAvailRS->RoomStays, 'RoomStay')) {
$currencyCode = (string) $response->Message->OTA_HotelAvailRS->RoomStays->RoomStay->RoomRates->RoomRate->Total['CurrencyCode'];
} else {
return new Response('Error no hay hoteles disponibles para esta fecha.');
}
if ('COP' != $currencyCode && 'COP' == $currency) {
$trm = $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->recentTrm($currencyCode);
$trm = $trm[0]['value'];
} else {
$trm = 1;
}
$key = 0;
$searchHotelCodes = ['|', '/'];
$replaceHotelCodes = ['--', '---'];
//load discount info if applicable
$multiHotelDiscountInfo = null;
if ($requestMultiHotelDiscountInfo) {
$transactionId = $session->get($transactionIdSessionName.'Multi');
$multiHotelDiscountInfo = $multiHotelDiscount->getAvailabilityDiscountsInfo($transactionId, [$dateIn, $dateOut], $destinationObject, $agency);
}
//$aviaturLogSave->logSave(print_r($session, true), 'Bpcs', 'availSession');
$homologationObjects = $em->getRepository(\Aviatur\HotelBundle\Entity\HotelHomologation::class)->findBySearchCities([$destinationObject, null]);
$hotelHomologationArray = [];
foreach ($homologationObjects as $homologationObject) {
foreach (json_decode($homologationObject->getHotelcodes()) as $hotelCode) {
$hotelHomologationArray[$hotelCode] = $homologationObject->getPreferredcode();
}
}
$options = [];
$isAgent = false;
foreach ($response->Message->OTA_HotelAvailRS->RoomStays->RoomStay as $roomStay) {
$roomStay['Show'] = '1';
$hotelIdentifier = (string) $roomStay->TPA_Extensions->HotelInfo->providerID.'-'.(string) $roomStay->BasicPropertyInfo['HotelCode'];
if (array_key_exists($hotelIdentifier, $hotelHomologationArray) && ($hotelHomologationArray[$hotelIdentifier] != $hotelIdentifier)) {
$roomStay['Show'] = '0';
} else {
$roomStay->BasicPropertyInfo['HotelCode'] = str_replace($searchHotelCodes, $replaceHotelCodes, (string) $roomStay->BasicPropertyInfo['HotelCode']);
$hotelCode = $roomStay->BasicPropertyInfo['HotelCode'];
$hotelEntity = $em->getRepository(\Aviatur\HotelBundle\Entity\Hotel::class)->findOneByCodhotel($hotelCode);
$hotel = null != $hotelEntity ? $hotelEntity->getId() : null;
$roomRate = $roomStay->RoomRates->RoomRate;
$i = 0;
$markup = false;
while (!$markup) {
if (($markups[$i]['hotel_id'] == $hotel || null == $markups[$i]['hotel_id']) && ($providerOfConfig[$markups[$i]['config_hotel_agency_id']] == (string) $roomStay->TPA_Extensions->HotelInfo->providerID)) {
// if ($hotelEntity != null) {
// $markups[$i]['value'] = $hotelEntity->getMarkupValue();
// }
if ('N' == $typeOfConfig[$markups[$i]['config_hotel_agency_id']]) {
$aviaturMarkup = (float) $roomRate->Total['AmountIncludingMarkup'] * $markups[$i]['value'] / (100 - $markups[$i]['value']);
} else {
$aviaturMarkup = 0;
}
$roomStay->TPA_Extensions->HotelInfo->providerName = $providerNames[$markups[$i]['config_hotel_agency_id']];
$roomRate->Total['AmountAviaturMarkup'] = $aviaturMarkup;
if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
$roomRate->Total['AmountAviaturMarkupTax'] = 0;
} else {
$roomRate->Total['AmountAviaturMarkupTax'] = $aviaturMarkup * $tax;
}
$roomRate->Total['AmountIncludingAviaturMarkup'] = round((float) $roomRate->Total['AmountAfterTax'] + $aviaturMarkup + $roomRate->Total['AmountAviaturMarkupTax'], (int) $roomRate->Total['DecimalPlaces']);
$roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round(((float) $aviaturMarkup + (float) $roomRate->Total['AmountIncludingMarkup']) * $trm, (int) $roomRate->Total['DecimalPlaces']);
if ('COP' == $currencyCode) {
$roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'], (int) $roomRate->Total['DecimalPlaces']);
}
if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
$roomRate->TotalAviatur['AmountTax'] = 0;
} else {
$roomRate->TotalAviatur['AmountTax'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $tax, (int) $roomRate->Total['DecimalPlaces']);
}
$roomRate->TotalAviatur['AmountTotal'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] + $roomRate->TotalAviatur['AmountTax'];
$roomRate->TotalAviatur['CurrencyCode'] = $currency;
$roomRate->TotalAviatur['Markup'] = $markups[$i]['value'];
$roomStay->BasicPropertyInfo['HotelCode'] .= '-'.$markups[$i]['id'];
$roomRate->TotalAviatur['MarkupId'] = $markups[$i]['id'];
$nameProduct = 'hotel';
$productCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
$session->set($transactionId.'_isActiveQse', ((is_countable($productCommission) ? count($productCommission) : 0) > 0) ? true : false);
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING') && $session->get($transactionId.'_isActiveQse')) {
$agent = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
// if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
if (!empty($agent)) {
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agent);
$infoQse = json_decode($agentCommission->getQseproduct());
// TODO: uncomment
// $infoQse = (empty($infoQse)) ? false : (empty($infoQse->$nameProduct)) ? false : $infoQse->$nameProduct;
$productCommissionPercentage = $productCommission->getQsecommissionpercentage();
$hotelCommission = ($infoQse) ? (int) $infoQse->hotel->commission_money : 0;
$commissionActive = ($infoQse) ? (int) $infoQse->hotel->active : 0;
$commissionPercentage = ($infoQse) ? (float) $infoQse->hotel->commission_percentage : 0;
$activeDetail = $agentCommission->getActivedetail();
/* * ***************** Commision Qse Agent ******************* */
$roomRate->TypeHotel['type'] = $typeOfConfig[$markups[$i]['config_hotel_agency_id']];
$nightsCommission = floor(($dateOut - $dateIn) / (24 * 60 * 60));
$roomRate->TotalAviatur['CommissionActive'] = $commissionActive;
if ('0' == $commissionActive) {
$roomRate->TotalAviatur['AgentComission'] = round($hotelCommission);
} elseif ('1' == $commissionActive) {
$roomRate->TotalAviatur['AgentComission'] = round(($roomRate->Total['AmountIncludingMarkup'] * $commissionPercentage) * $nightsCommission);
}
$roomRate->TotalAviatur['CommissionPay'] = round(($roomRate->TotalAviatur['AgentComission'] / 1.19) * $productCommissionPercentage);
$roomRate->TotalAviatur['TotalCommissionFare'] = round($roomRate->Total['AmountAviaturMarkup']);
if ('P' == $typeOfConfig[$markups[$i]['config_hotel_agency_id']]) {
$commissionFare = round($roomRate->Total['AmountIncludingMarkup'] * ($markups[$i]['value'] / 100));
$roomRate->TotalAviatur['TotalCommissionFare'] = $commissionFare;
$roomRate->TotalAviatur['CommissionPay'] = round(((($roomRate->TotalAviatur['AgentComission'] + ($roomRate->TotalAviatur['TotalCommissionFare'] * $nightsCommission)) / 1.19) * $productCommissionPercentage));
}
$roomRate->TotalAviatur['activeDetail'] = $activeDetail;
$isAgent = true;
} else {
$session->set($transactionId.'_isActiveQse', false);
}
}
if (false == $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING')) {
$roomRate->TotalAviatur['submitBuy'] = '1';
}
if ($multiHotelDiscountInfo) {
$roomRateDiscount = $multiHotelDiscount->setAvailabilityDiscount($roomRate, $multiHotelDiscountInfo, (string) $roomStay->TPA_Extensions->HotelInfo->providerID);
$roomRate->TotalAviatur['hasDiscount'] = $roomRateDiscount ? true : false;
$roomRate->TotalAviatur['DiscountTotal'] = $roomRateDiscount ? $roomRateDiscount->discountTotal : 0;
$roomRate->TotalAviatur['DiscountAmount'] = $roomRateDiscount ? $roomRateDiscount->discountAmount : 0;
} else {
$requestMultiHotelDiscountInfo = false;
}
$markup = true;
}
++$i;
}
$options[$key]['amount'] = (float) $roomStay->RoomRates->RoomRate->TotalAviatur['AmountTotal'];
$options[$key]['provider'] = (int) $roomStay->TPA_Extensions->HotelInfo->providerID;
$options[$key]['HotelName'] = (string) $roomStay->BasicPropertyInfo['HotelName'];
$options[$key]['xml'] = $roomStay->asXml();
++$key;
}
}
$roomRate->TotalAviatur['isAgent'] = $isAgent;
if (0 != sizeof($options)) {
usort($options, fn($a, $b) => $a['amount'] - $b['amount']);
$tempOptions = [[], []];
$providerMPT = [58, 66]; // hoteles propios produccion / pruebas
if ($isFront) {
foreach ($options as $option) {
if (in_array($option['provider'], $providerMPT)) {
$tempOptions[0][] = $option;
} else {
$tempOptions[1][] = $option;
}
}
$options = [...$tempOptions[0], ...$tempOptions[1]];
} else {
foreach ($options as $option) {
if (in_array($option['provider'], $providerMPT) && false !== strpos(strtolower($option['HotelName']), 'las islas')) {
$tempOptions[0][] = $option;
} else {
$tempOptions[1][] = $option;
}
}
$options = [...$tempOptions[0], ...$tempOptions[1]];
}
$responseXml = explode('<RoomStay>', str_replace(['</RoomStay>', '<RoomStay InfoSource="B2C" Show="1">', '<RoomStay InfoSource="B2C" Show="0">', '<RoomStay InfoSource="B2B" Show="1">', '<RoomStay InfoSource="B2B" Show="0">'], '<RoomStay>', $response->asXml()));
$orderedResponse = $responseXml[0];
foreach ($options as $option) {
$orderedResponse .= $option['xml'];
}
$orderedResponse .= $responseXml[sizeof($responseXml) - 1];
$response = simplexml_load_string($orderedResponse);
$fileName = $aviaturLogSave->logSave($orderedResponse, 'HotelAvailResponse', 'RS');
$session->set($session->get($transactionIdSessionName).'[hotel][availability_file]', $fileName);
$agencyFolder = $twigFolder->twigFlux();
$HotelBestPrice[0] = ['price' => (string) $response->Message->OTA_HotelAvailRS->RoomStays->RoomStay[0]->RoomRates->RoomRate->TotalAviatur['AmountTotal'][0], 'accomodationNumber' => (string) count($response->Message->OTA_HotelAvailRS->RoomStays->RoomStay)];
//$HotelBestPrice = (string) $response->Message->OTA_HotelAvailRS->RoomStays->RoomStay[0]->RoomRates->RoomRate->TotalAviatur['AmountTotal'][0];
$session->set($session->get($transactionIdSessionName).'[hotel][HotelBestPrice]', $HotelBestPrice);
$updateBestPrices->add((object) $HotelBestPrice, $requestUrl); //Always send array or object, as price list
$renderTwig = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/AjaxAvailability.html.twig');
// Prueba de llamado a Geocoding Api solo para 3.4519988, -76.5325259
$geocodingResponseApi = $this->aviaturRestService->getPlaceByCoordinates('3.4519988', '-76.5325259', 'd4ea2db24f6448dcbb1551c3546851d6');
$resultsGeocoding = [];
if (isset($geocodingResponseApi->status) && $geocodingResponseApi->status->code === 200) {
$resultsGeocoding = $geocodingResponseApi->results;
}
return $this->render($renderTwig , [
'hotels' => $response->Message->OTA_HotelAvailRS,
'AvailabilityHasDiscount' => $requestMultiHotelDiscountInfo,
'urlDescription' => $urlDescription,
'HotelMinPrice' => $HotelBestPrice[0]['price'],
'isMulti' => $isMulti,
'resultsGeocoding' => $resultsGeocoding
]);
} else {
return new Response('No hay hoteles disponibles para pago en línea en este destino actualmente.');
}
} else {
$exceptionLog->log(
'Error Fatal',
'La ciudad de destino no se pudo encontrar en la base de datos, iata: '.$destination,
null,
false
);
return new Response('La ciudad de destino no se pudo encontrar en la base de datos');
}
} else {
$cookieArray = [
'destination' => $destination,
'destinationLabel' => $destinationObject->getCity().', '.$destinationObject->getCountry().' ('.$destination.')',
'adults' => $AvailabilityArray['1']['Adults'],
'children' => $AvailabilityArray['1']['Children'],
'childAge' => $childAgesCookie,
'date1' => date('Y-m-d\TH:i:s', $dateIn),
'date2' => date('Y-m-d\TH:i:s', $dateOut),
];
$agencyFolder = $twigFolder->twigFlux();
$urlAvailability = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/availability.html.twig');
if ($agency->getDomainsecure() == $agency->getDomain() && '443' != $agency->getCustomport()) {
$safeUrl = 'https://'.$agency->getDomain();
} else {
$safeUrl = 'https://'.$agency->getDomainsecure();
}
$cookieLastSearch = $hotelSearchCookie->searchHotelCookie(['hotel' => base64_encode(json_encode($cookieArray))]);
if (!$isFront) {
// PIXELES INFORMATION
$pixel['partner_datalayer'] = [
'enabled' => true,
'event' => 'hotel_search',
'dimension1' => $destination,
'dimension2' => '',
'dimension3' => $date1,
'dimension4' => $date2,
'dimension5' => 'Hotel',
'dimension6' => '',
'dimension7' => '',
'dimension8' => '',
'dimension9' => '',
'dimension10' => ((int) $adult1 + (int) $child1 + (int) $adult2 + (int) $child2 + (int) $adult3 + (int) $child3),
'dimension11' => $rooms,
'dimension12' => 'Busqueda-Hotel',
'ecommerce' => [
'currencyCode' => 'COP',
],
];
//$pixel['dataxpand'] = true;
$pixelInfo = $aviaturPixeles->verifyPixeles($pixel, 'hotel', 'availability', $agency->getAssetsFolder(), false);
}
$pointRedemption = $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
if (null != $pointRedemption) {
$points = 0;
if ($fullRequest->request->has('pointRedemptionValue')) {
$points = $fullRequest->request->get('pointRedemptionValue');
$session->set('point_redemption_value', $points);
} elseif ($fullRequest->query->has('pointRedeem')) {
$points = $fullRequest->query->get('pointRedeem');
$session->set('point_redemption_value', $points);
} elseif ($session->has('point_redemption_value')) {
$points = $session->get('point_redemption_value');
}
$pointRedemption['Config']['Amount']['CurPoint'] = $points;
}
$response = $this->render($urlAvailability, [
'ajaxUrl' => $requestUrl,
'availableArrayHotel' => $AvailabilityArray,
'inlineEngine' => true,
'safeUrl' => $safeUrl,
'cookieLastSearch' => $cookieLastSearch,
'cityName' => $destinationObject->getCity(),
'date1' => date('c', $dateIn),
'date2' => date('c', $dateOut),
'availabilityHasDiscount' => $requestMultiHotelDiscountInfo,
'urlDescription' => $urlDescription,
'pointRedemption' => $pointRedemption,
'pixel_info' => $pixelInfo,
]);
$response->headers->setCookie(new Cookie('_availability_array[hotel]', base64_encode(json_encode($cookieArray)), (time() + 3600 * 24 * 7), '/'));
return $response;
}
}
public function getAvailabilityResultsAction(TwigFolder $twigFolder, SessionInterface $session, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
if ($session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
if (true === $session->has($transactionId.'[hotel][availability_file]')) {
$availFile = $session->get($transactionId.'[hotel][availability_file]');
$response = \simplexml_load_file($availFile);
$agencyFolder = $twigFolder->twigFlux();
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/AjaxAvailability.html.twig'), ['hotels' => $response->Message->OTA_HotelAvailRS]);
} else {
if ($session->has($transactionId.'[hotel][availability_results_retry]')) {
$retry = $session->get($transactionId.'[hotel][availability_results_retry]');
if ($retry < 8) {
$session->set($transactionId.'[hotel][availability_results_retry]', $retry + 1);
return new Response('retry');
} else {
return new Response('error');
}
} else {
$session->set($transactionId.'[hotel][availability_results_retry]', 1);
return new Response('retry');
}
}
} else {
return new Response('error');
}
}
public function availabilitySeoAction(Request $request, RouterInterface $router, $url)
{
$session = $this->session;
$em = $this->managerRegistry;
$seoUrl = $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findOneByUrl('hoteles/'.$url);
if (null != $seoUrl) {
$maskedUrl = $seoUrl->getMaskedurl();
$session->set('maxResults', $request->query->get('maxResults'));
if (false !== strpos($maskedUrl, '?')) {
$parameters = explode('&', substr($maskedUrl, strpos($maskedUrl, '?') + 1));
foreach ($parameters as $parameter) {
$sessionInfo = explode('=', $parameter);
if (2 == sizeof($sessionInfo)) {
$session->set($sessionInfo[0], $sessionInfo[1]);
}
}
$maskedUrl = substr($maskedUrl, 0, strpos($maskedUrl, '?'));
}
if (null != $seoUrl) {
$route = $router->match($maskedUrl);
$route['_route_params'] = [];
foreach ($route as $param => $val) {
// set route params without defaults
if ('_' !== \substr($param, 0, 1)) {
$route['_route_params'][$param] = $val;
}
}
return $this->forward($route['_controller'], $route);
} else {
throw $this->createNotFoundException('La página que solicitaste no existe o se ha movido permanentemente');
}
} else {
throw $this->createNotFoundException('La página que solicitaste no existe o se ha movido permanentemente');
}
}
public function detailAction(Request $fullRequest, \Swift_Mailer $mailer, CouponDiscountService $aviaturCouponDiscount, CustomerMethodPaymentService $customerMethodPayment, TokenStorageInterface $tokenStorage, MultiHotelDiscount $multiHotelDiscount, AviaturWebService $aviaturWebService, AviaturPixeles $aviaturPixeles, PayoutExtraService $payoutExtraService, AuthorizationCheckerInterface $authorizationChecker, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, TwigFolder $twigFolder, ParameterBagInterface $parameterBag, LoginManagerInterface $loginManagerInterface)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$correlationIdSessionName = $parameterBag->get('correlation_id_session_name');
$response = [];
$transactionId = null;
$passangerTypes = [];
$flux = null;
$provider = null;
$responseHotelDetail = [];
$guestsInfo = null;
$fullPricing = [];
$pixel = [];
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$request = $fullRequest->request;
$server = $fullRequest->server;
$domain = $fullRequest->getHost();
$route = $router->match(str_replace($fullRequest->getSchemeAndHttpHost(), '', $fullRequest->getUri()));
$isMulti = false !== strpos($route['_route'], 'multi') ? true : false;
$isFront = $session->has('operatorId');
$detailHasDiscount = false;
$detailHasCoupon = false;
$returnUrl = $twigFolder->pathWithLocale('aviatur_general_homepage');
$isAgent = false;
if (true === $request->has('referer')) {
$returnUrl = $request->get('http_referer');
}
if (true === $request->has('whitemarkDataInfo')) {
$session->set('whitemarkDataInfo', json_decode($request->get('whitemarkDataInfo'), true));
}
if (true === $request->has('userLogin') && '' != $request->get('userLogin') && null != $request->get('userLogin')) {
$user = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneByEmail($request->get('userLogin'));
$this->authenticateUser($user, $loginManagerInterface);
}
if (true === $request->has('transactionID')) {
$transactionId = $request->get('transactionID');
if ($fullRequest->request->has('kayakclickid') || $fullRequest->query->has('kayakclickid')) {
$transactionIdResponse = $aviaturWebService->loginService('SERVICIO_MPT', 'dummy|http://www.aviatur.com.co/dummy/');
if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl, 'Ha ocurrido un error en la validación', 'No se creo Login'));
}
$transactionId = (string) $transactionIdResponse;
}
//Validación para agregar el referer en los hoteles (Temporal)
if (true === $request->has('referer')) {
$referer = $request->get('referer');
$metasearch = $em->getRepository(\Aviatur\GeneralBundle\Entity\Metasearch::class)->findOneByUrl($referer);
if (null != $metasearch) {
$transactionId = $transactionId.'||'.$metasearch->getId();
}
}
if (false !== strpos($transactionId, '||')) {
$explodedTransaction = explode('||', $transactionId);
$transactionId = $explodedTransaction[0];
$request->set('transactionID', $transactionId);
$metaseachId = $explodedTransaction[1];
$session->set('generals[metasearch]', $metaseachId);
$metatransaction = $em->getRepository(\Aviatur\GeneralBundle\Entity\Metatransaction::class)->findOneByTransactionId($transactionId);
if (null == $metatransaction) {
$metasearch = $em->getRepository(\Aviatur\GeneralBundle\Entity\Metasearch::class)->find($metaseachId);
if (null == $metasearch) {
$response['error'] = 'Por favor selecciona nuevamente tu itinerario de viaje';
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl, 'Ha ocurrido un error en la validación', $response['error']));
}
$metatransaction = new Metatransaction();
$metatransaction->setTransactionId((string) $transactionId);
$metatransaction->setDatetime(new \DateTime());
$metatransaction->setIsactive(true);
$metatransaction->setMetasearch($metasearch);
$em->persist($metatransaction);
$em->flush();
}
$d1 = $metatransaction->getDatetime();
$d2 = new \DateTime(date('Y-m-d H:i:s', time() - (15 * 60)));
if (false == $metatransaction->getIsactive()) {
$response['error'] = 'Por favor selecciona nuevamente tu itinerario de viaje';
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl, '', $response['error']));
} elseif ($d1 < $d2) {
$response['error'] = 'Por favor selecciona nuevamente tu itinerario de viaje';
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl, 'Tu consulta fue realizada hace mas de 15 minutos', $response['error']));
} else {
$metatransaction->setIsactive(false);
$em->persist($metatransaction);
$em->flush();
}
} else {
$session->set($transactionIdSessionName, $transactionId);
}
} elseif (true === $session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
}
if (true === $session->has($transactionId.'[hotel][retry]')) {
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
// Parse XML Response stored in Session
$response = simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
$detailHotelRaw = $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay;
$dateIn = strtotime((string) $response->Message->OTA_HotelRoomListRS['StartDate']);
$dateOut = strtotime((string) $response->Message->OTA_HotelRoomListRS['EndDate']);
$postDataJson = $session->get($transactionId.'[hotel][detail_data_hotel]');
$postDataInfo = json_decode($postDataJson);
$passangerInfo = $postDataInfo->PI;
$billingData = $postDataInfo->BD;
$contactData = $postDataInfo->CD;
$hotelInfo = $postDataInfo->HI;
$paymentData = isset($postDataInfo->PD) ? $postDataInfo->PD : '';
foreach ($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate as $roomRatePlan) {
if ($roomRatePlan['RatePlanCode'] == $hotelInfo->ratePlan) {
$roomRate[] = $roomRatePlan;
}
}
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];
}
$detailHotel = [
'dateIn' => $dateIn,
'dateOut' => $dateOut,
'roomInformation' => $rooms,
'dateInStr' => (string) $response->Message->OTA_HotelRoomListRS['StartDate'],
'dateOutStr' => (string) $response->Message->OTA_HotelRoomListRS['EndDate'],
'nights' => floor(($dateOut - $dateIn) / (24 * 60 * 60)),
'adults' => (string) $response->Message->OTA_HotelRoomListRS['Adults'],
'children' => (string) $response->Message->OTA_HotelRoomListRS['Children'],
'rooms' => (string) $response->Message->OTA_HotelRoomListRS['Rooms'],
'roomRates' => $roomRate,
'timeSpan' => $detailHotelRaw->TimeSpan,
'total' => $detailHotelRaw->Total,
'basicInfos' => $detailHotelRaw->BasicPropertyInfo,
'category' => $detailHotelRaw->TPA_Extensions->HotelInfo->Category,
'description' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Description,
'email' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
'services' => $detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service,
'photos' => $detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem,
];
if (isset($response->Message->OTA_HotelRoomListRS['commissionPercentage'])) {
$detailHotel['commissionPercentage'] = (float) $response->Message->OTA_HotelRoomListRS['commissionPercentage'];
}
$typeDocument = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$typeGender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
$repositoryDocumentType = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
$queryDocumentType = $repositoryDocumentType
->createQueryBuilder('p')
->where('p.paymentcode != :paymentcode')
->setParameter('paymentcode', '')
->getQuery();
$documentPaymentType = $queryDocumentType->getResult();
$postData = json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
if (false !== strpos($provider->getName(), 'Juniper')) {
$passangerTypes = [];
for ($i = 1; $i <= $postData['Rooms']; ++$i) {
$passangerTypes[$i] = [
'ADT' => (int) $postData['Adults'.$i],
'CHD' => (int) $postData['Children'.$i],
'INF' => 0,
];
}
} else {
$passangerTypes[1] = [
'ADT' => 1,
'CHD' => 0,
'INF' => 0,
];
}
$paymentMethodAgency = $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency, 'isactive' => 1]);
$paymentOptions = [];
foreach ($paymentMethodAgency as $payMethod) {
$paymentCode = $payMethod->getPaymentMethod()->getCode();
if (!in_array($paymentCode, $paymentOptions) && ('p2p' == $paymentCode || 'cybersource' == $paymentCode)) {
$paymentOptions[] = $paymentCode;
}
}
$banks = [];
if (in_array('pse', $paymentOptions)) {
$banks = $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
}
$cybersource = [];
if (in_array('cybersource', $paymentOptions)) {
$cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource', $paymentOptions)]->getSitecode();
$cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource', $paymentOptions)]->getTrankey();
}
foreach ($paymentOptions as $key => $paymentOption) {
if ('cybersource' == $paymentOption) {
unset($paymentOptions[$key]); // strip from other renderizable payment methods
}
}
$conditions = $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'reservation_conditions_for_hotels');
if (isset($paymentData->cusPOptSelected)) {
//$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData->id);
$customerLogin = $tokenStorage->getToken()->getUser();
if (is_object($customerLogin)) {
$paymentsSaved = $customerMethodPayment->getMethodsByCustomer($customerLogin, false);
}
}
$responseHotelDetail = [
'twig_readonly' => true,
'referer' => $session->get($transactionId.'[availability_url]'),
'passengers' => $passangerInfo ?? null,
'billingData' => $billingData ?? null,
'contactData' => $contactData ?? null,
'doc_type' => $typeDocument,
'gender' => $typeGender,
'hotelProvidersId' => [(string) $provider->getProvideridentifier()],
'detailHotel' => $detailHotel,
'payment_doc_type' => $documentPaymentType,
'services' => $passangerTypes,
'conditions' => $conditions,
'payment_type_form_name' => $provider->getPaymentType()->getTwig(),
'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]),
'inactiveCards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]),
'paymentOptions' => $paymentOptions,
'banks' => $banks,
'cybersource' => $cybersource,
'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
'additional' => base64_encode($transactionId.'/'.$session->get($transactionId.'[hotel]['.$correlationIdSessionName.']')),
];
$responseHotelDetail['baloto'] ?? ($responseHotelDetail['baloto'] = false);
$responseHotelDetail['pse'] ?? ($responseHotelDetail['pse'] = true);
$responseHotelDetail['safety'] ?? ($responseHotelDetail['safety'] = true);
} else {
if (true === $request->has('referer')) {
$session->set($transactionId.'[availability_url]', $request->get('http_referer'));
$session->set($transactionId.'[referer]', $request->get('referer'));
} elseif (true !== $session->has($transactionId.'[availability_url]') || (false !== strpos($session->get($transactionId.'[availability_url]'), 'multi/'))) {
try {
$router_matched = $router->match(parse_url($server->get('HTTP_REFERER'), PHP_URL_PATH));
if (isset($router_matched['rooms'])) {
$session->set($transactionId.'[availability_url]', $server->get('HTTP_REFERER'));
$session->set($transactionId.'[hotel][availability_url]', $server->get('HTTP_REFERER'));
} elseif (('aviatur_hotel_availability_seo' == $router_matched['_route']) || ('aviatur_multi_availability_seo' == $router_matched['_route'])) {
switch ($router_matched['_route']) {
case 'aviatur_hotel_availability_seo': $flux = 'hoteles';
break;
case 'aviatur_multi_availability_seo': $flux = 'multi';
break;
}
$seoUrl = $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findOneByUrl($flux.'/'.$router_matched['url']);
if (null != $seoUrl) {
$maskedUrl = $seoUrl->getMaskedurl();
$parsedUrl = parse_url($server->get('HTTP_REFERER'));
$session->set($transactionId.'[availability_url]', $parsedUrl['scheme'].'://'.$parsedUrl['host'].$maskedUrl);
$session->set($transactionId.'[hotel][availability_url]', $parsedUrl['scheme'].'://'.$parsedUrl['host'].$maskedUrl);
} else {
////////Validar este errrrrooooorrrrr
$session->set($transactionId.'[availability_url]', $server->get('HTTP_REFERER'));
}
} else {
////////Validar este errrrrooooorrrrr
$session->set($transactionId.'[availability_url]', $server->get('HTTP_REFERER'));
}
} catch (\Exception $e) {
////////Validar este errrrrooooorrrrr
$session->set($transactionId.'[availability_url]', $server->get('HTTP_REFERER'));
}
}
if ($session->has('hotelAdapterId')) {
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findOneByProvideridentifier($request->get('providerID'));
} else {
$configsHotelAgency = $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findProviderForHotelsWithAgency($agency);
foreach ($configsHotelAgency as $configHotelAgency) {
if ($request->get('providerID') == $configHotelAgency->getProvider()->getProvideridentifier()) {
$provider = $configHotelAgency->getProvider();
}
}
}
$session->set($transactionId.'[hotel][provider]', $provider->getId());
$correlationID = $request->get('correlationId');
$session->set($transactionIdSessionName, $transactionId);
$session->set($transactionId.'[hotel]['.$correlationIdSessionName.']', $correlationID);
$session->set($transactionId.'[referer]', $server->get('HTTP_REFERER'));
$startDate = $request->get('startDate');
$endDate = $request->get('endDate');
$dateIn = strtotime($startDate);
$dateOut = strtotime($endDate);
$nights = floor(($dateOut - $dateIn) / (24 * 60 * 60));
$searchHotelCodes = ['---', '--'];
$replaceHotelCodes = ['/', '|'];
$hotelCode = explode('-', str_replace($searchHotelCodes, $replaceHotelCodes, $request->get('hotelCode')));
$country = $request->get('country');
$variable = [
'correlationId' => $correlationID,
'start_date' => $startDate,
'end_date' => $endDate,
'hotel_code' => $hotelCode[0],
'country' => $country,
'ProviderId' => $provider->getProvideridentifier(),
];
$hotelModel = new HotelModel();
$xmlRequest = $hotelModel->getXmlDetail();
$message = '';
if ($session->has($transactionId.'[hotel][detail]') && true !== $session->has($transactionId.'[crossed]'.'[url-hotel]')) {
$response = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
if (isset($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->TPA_Extensions->HotelInfo->GuestsInfo)) {
$guestsInfo = $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->TPA_Extensions->HotelInfo->GuestsInfo;
}
} else {
$aviaturWebService->setUrls(json_decode($session->get($domain. '[parameters]')));
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'HotelRoomList', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false);
// $response = simplexml_load_file("C:/wamp/www/aviatur/app/serviceLogs/HotelRoomList/HotelRoomList__static.xml"); ;
if (!isset($response['error'])) {
/* desactivamos al proveedor que esta fallando */
$message = $response->ProviderResults->ProviderResult['Message'];
if (false !== strpos($message, 'El valor no puede ser nulo') || false !== strpos($message, 'Referencia a objeto no establecida') || false !== strpos($message, 'No se puede convertir un objeto')) {
$worngProvider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
$activeWProvider = $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findBy(['provider' => $worngProvider->getId(), 'agency' => $agency]);
$badproviders = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('badProviders');
$mailInfo = '<p>El proveedor '.$worngProvider->getName().' esta presentando problemas y se procede a ser desactivado</p><p>Mensaje de error: '.$message.'</p>';
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo(json_decode($badproviders->getDescription())->email->hoteles)
->setSubject('proveedor con problemas')
->setBody($mailInfo);
$mailer->send($message);
$activeWProvider[0]->setIsactive(0);
$em->persist($activeWProvider[0]);
$em->flush();
}
// $hotelEntity = $em->getRepository(\Aviatur\HotelBundle\Entity\Hotel::class)->findOneByCodhotel($hotelCode[0]);
$markup = $em->getRepository(\Aviatur\HotelBundle\Entity\Markup::class)->find($hotelCode[1]);
// if ($hotelEntity != null) {
// $markupValue = $hotelEntity->getMarkupValue();
// } else {
$markupValue = $markup->getValue();
// }
$markupId = $markup->getId();
$parametersJson = $session->get($domain.'[parameters]');
$parameters = json_decode($parametersJson);
$tax = (float) $parameters->aviatur_payment_iva;
$currency = 'COP';
if (strpos($provider->getName(), '-USD')) {
$currency = 'USD';
}
$currencyCode = (string) $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate->Total['CurrencyCode'];
if ('COP' != $currencyCode && 'COP' == $currency) {
$trm = $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->recentTrm($currencyCode);
$trm = $trm[0]['value'];
} else {
$trm = 1;
}
foreach ($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay as $roomStay) {
$roomStay->BasicPropertyInfo['HotelCode'] .= '-'.$markupId;
foreach ($roomStay->RoomRates->RoomRate as $roomRate) {
if ('N' == $markup->getConfigHotelAgency()->getType()) {
$aviaturMarkup = (float) $roomRate->Total['AmountIncludingMarkup'] * $markupValue / (100 - $markupValue);
} else {
$aviaturMarkup = 0;
}
$roomRate->Total['AmountAviaturMarkup'] = $aviaturMarkup;
if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
$roomRate->Total['AmountAviaturMarkupTax'] = 0;
} else {
$roomRate->Total['AmountAviaturMarkupTax'] = $aviaturMarkup * $tax;
}
$roomRate->Total['AmountIncludingAviaturMarkup'] = round((float) $roomRate->Total['AmountAfterTax'] + $aviaturMarkup + $roomRate->Total['AmountAviaturMarkupTax'], (int) $roomRate->Total['DecimalPlaces']);
$roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round((float) ($aviaturMarkup + (float) $roomRate->Total['AmountIncludingMarkup']) * $trm, (int) $roomRate->Total['DecimalPlaces']);
if ('COP' == $currencyCode) {
$roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'], (int) $roomRate->Total['DecimalPlaces']);
}
if (isset($roomRate->Total['RateOverrideIndicator']) || (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces']))) {
$roomRate->TotalAviatur['AmountTax'] = 0;
} else {
$roomRate->TotalAviatur['AmountTax'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $tax, (int) $roomRate->Total['DecimalPlaces']);
}
$roomRate->TotalAviatur['AmountTotal'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] + $roomRate->TotalAviatur['AmountTax'];
$roomRate->TotalAviatur['calcTripPrice'] = (float) $roomRate->TotalAviatur['AmountTotal'] * $nights;
$roomRate->TotalAviatur['CurrencyCode'] = $currency;
$roomRate->TotalAviatur['Markup'] = $markupValue;
$roomRate->TotalAviatur['MarkupId'] = $markupId;
$roomRate->TotalAviatur['MarkupType'] = $markup->getConfigHotelAgency()->getType();
$roomRate->TotalAviatur['calcBasePrice'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $nights;
if ($isMulti && !$isFront) {
$postData = $request->all();
$postDataCountry = $postData['country'] ?? '';
$detailDiscount = $multiHotelDiscount->setDetailDiscount($transactionId, $postDataCountry, $postData, $agency, $nights);
if ('1' === $detailDiscount['availability_hasdiscount'] && false === $detailDiscount['discount_is_valid']) {
$message = 'Lamentamos informarte que este descuento ya no se encuentra disponible. '
.'Si no estás registrado, te invitamos a hacerlo. Te mantendremos informado de nuestras ofertas. Gracias por viajar con Aviatur.com';
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($session->get($transactionId.'[availability_url]'), 'Descuento caducado', $message));
}
$detailHasDiscount = $detailDiscount['discount_is_valid'];
$roomRateDiscountValues = $multiHotelDiscount->calculateDiscount($roomRate, $nights, $transactionId);
$roomRate->TotalAviatur['calcTripPriceBeforeDiscount'] = $roomRate->TotalAviatur['calcTripPrice'];
$roomRate->TotalAviatur['calcTripPrice'] = $roomRateDiscountValues->calcTripPriceDiscount ?? $roomRate->TotalAviatur['calcTripPrice'];
$roomRate->TotalAviatur['calcBasePriceBeforeDiscount'] = $roomRate->TotalAviatur['calcBasePrice'];
$roomRate->TotalAviatur['calcBasePrice'] = $roomRateDiscountValues->calcTripBaseDiscount ?? $roomRate->TotalAviatur['calcBasePrice'];
$roomRate->TotalAviatur['discountAmount'] = $roomRateDiscountValues->discountTotal ?? 0;
$roomRate->TotalAviatur['AmountIncludingAviaturMarkupBeforeDiscount'] = $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'];
$roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = $roomRateDiscountValues->AmountIncludingAviaturMarkup ?? $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'];
$roomRate->TotalAviatur['calcTripTaxDiscount'] = $roomRateDiscountValues->calcTripTaxDiscount ?? 0;
if ($roomRate->TotalAviatur['AmountTax'] > 0) {
$roomRate->TotalAviatur['AmountTaxBeforeDiscount'] = $roomRate->TotalAviatur['AmountTax'];
$roomRate->TotalAviatur['AmountTax'] = $roomRateDiscountValues->AmountTax ?? $roomRate->TotalAviatur['AmountTax'];
}
}
/* * ************** Validar Sesion Agent Octopus *************** */
$totalcommission = 0;
$hotelCommission = 0;
$commissionActive = null;
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING') && $session->get($transactionId.'_isActiveQse')) {
$response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] = 0;
$agent = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
// if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
if (!empty($agent)) {
$nameProduct = 'hotel';
$productCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agent);
$infoQse = json_decode($agentCommission->getQseproduct());
//TODO: uncomment
// $infoQse = (empty($infoQse)) ? false : (empty($infoQse->$nameProduct)) ? false : $infoQse->$nameProduct;
$productCommissionPercentage = $productCommission->getQsecommissionpercentage();
$qseCommissionPercentage = $productCommission->getQsecommissionpercentage();
$tarifaCommissionPercentage = $productCommission->getTacommissionpercentage();
$hotelCommission = ($infoQse) ? (int) $infoQse-> hotel -> commission_money : 0;
$commissionActive = ($infoQse) ? (int) $infoQse-> hotel -> active : 0;
$commissionPercentage = ($infoQse) ? (float) $infoQse-> hotel -> commission_percentage : 0;
$activeDetail = $agentCommission->getActivedetail();
//************* Amount qse Detalles Hotel ***************\\
$response->Message->OTA_HotelRoomListRS['typeAgency'] = $markup->getConfigHotelAgency()->getType();
$response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] = $roomRate->Total['AmountAviaturMarkup'];
if ('P' == $markup->getConfigHotelAgency()->getType()) {
$commissionFare = round($roomRate->Total['AmountIncludingMarkup'] * ($markupValue / 100));
$response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] = $commissionFare;
}
$response->Message->OTA_HotelRoomListRS['commissionActive'] = $commissionActive;
if ('0' == $commissionActive) {
$response->Message->OTA_HotelRoomListRS['commissionQse'] = round($hotelCommission);
} elseif ('1' == $commissionActive) {
$response->Message->OTA_HotelRoomListRS['commissionQse'] = round($roomRate->Total['AmountIncludingMarkup'] * $commissionPercentage);
}
$response->Message->OTA_HotelRoomListRS['commissionPercentage'] = $productCommissionPercentage;
$response->Message->OTA_HotelRoomListRS['commissionId'] = $agentCommission->getId();
$response->Message->OTA_HotelRoomListRS['activeDetail'] = $activeDetail;
//$roomRate->TotalAviatur['calcBasePrice'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $nights;
$commissionActive = $response->Message->OTA_HotelRoomListRS['commissionActive'];
$productCommissionPercentage = 0;
if (null != $response->Message->OTA_HotelRoomListRS['commissionId']) {
if (null != $commissionActive) {
if ('0' == $commissionActive) {
$totalcommission = round($response->Message->OTA_HotelRoomListRS['commissionQse']);
} elseif ('1' == $commissionActive) {
$totalcommission = round($response->Message->OTA_HotelRoomListRS['commissionQse'] * $nights);
}
}
$productCommissionPercentage = $response->Message->OTA_HotelRoomListRS['commissionPercentage'];
//$totalCommisionFare = 0;
$totalCommisionFare = $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'];
if ('P' == $markup->getConfigHotelAgency()->getType()) {
$totalCommisionFare = round((float) $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] * $nights);
}
}
$valueTax = $tax + 1;
//$totalCommissionPay1 = round(((float) $totalCommisionFare + (float) $totalcommission) / $valueTax);
$totalCommissionPay1 = round((((float) $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] * $nights) / 1.19) * $tarifaCommissionPercentage);
$totalCommissionPay2 = round((((float) $response->Message->OTA_HotelRoomListRS['commissionQse'] * $nights) / 1.19) * $qseCommissionPercentage);
$totalCommissionPay = round($totalCommissionPay1 + $totalCommissionPay2); // Su ganancia
$isAgent = true;
}
}
$fullPricing = [
'total' => ((float) $roomRate->TotalAviatur['AmountTotal'] * $nights) + $totalcommission,
'totalPerNight' => (float) $roomRate->TotalAviatur['AmountTotal'],
'totalWithoutService' => (((float) $roomRate->TotalAviatur['AmountTotal'] - (float) $roomRate->Total['AmountTotal']) * $nights) + $totalcommission,
'currency' => (string) $currency,
];
if ($isAgent) {
$fullPricing['totalCommissionHotel'] = round((float) $response->Message->OTA_HotelRoomListRS['TotalCommissionFare'] * $nights); // Comisión por Tarifa
$fullPricing['totalGananciaHotel'] = round(($fullPricing['totalCommissionHotel'] / 1.19) * $tarifaCommissionPercentage); // Ganacia por tarifa
// $fullPricing['totalCommissionPay'] = $totalCommissionPay;
$fullPricing['markupValue'] = isset($markupValue) ? (float) $markupValue : 0;
if (null != $commissionActive) {
if ('0' == $commissionActive) {
$fullPricing['totalCommissionAgent'] = (float) $response->Message->OTA_HotelRoomListRS['commissionQse'];
} elseif ('1' == $commissionActive) {
$fullPricing['totalCommissionAgent'] = round($response->Message->OTA_HotelRoomListRS['commissionQse'] * $nights);
}
$fullPricing['totalGananciaAgent'] = round(($fullPricing['totalCommissionAgent'] / 1.19) * $qseCommissionPercentage); //Ganacia QSE
}
$fullPricing['totalCommissionPay'] = $fullPricing['totalGananciaHotel'] + $fullPricing['totalGananciaAgent'];
}
if (isset($roomRate->Total->Taxes)) {
$i = 0;
$fullPricing['taxes'] = [];
$fullPricing['taxes'][0] = [];
$fullPricing['taxes'][1] = [];
foreach ($roomRate->Total->Taxes->Tax as $subTax) {
if (isset($subTax['Code'])) {
$fullPricing['taxes'][(int) $subTax['Code']][$i] = [];
$fullPricing['taxes'][(int) $subTax['Code']][$i][] = (string) $subTax['Type'];
$fullPricing['taxes'][(int) $subTax['Code']][$i][] = ((float) $subTax['Amount']) * $nights;
++$i;
}
}
}
$i = 0;
foreach ($roomRate->Rates->Rate as $rate) {
$fullPricing['rooms'][$i] = ((float) $rate->Total['AmountAfterTax']) * $nights;
++$i;
}
$roomRate->TotalAviatur['FullPricing'] = base64_encode(json_encode($fullPricing));
}
}
$guestsInfo = 'S';
if (isset($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->TPA_Extensions->HotelInfo->GuestsInfo)) {
$guestsInfo = $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->TPA_Extensions->HotelInfo->GuestsInfo;
}
$response->Message->OTA_HotelRoomListRS['StartDate'] = $startDate;
$response->Message->OTA_HotelRoomListRS['EndDate'] = $endDate;
$response->Message->OTA_HotelRoomListRS['Adults'] = $request->get('Adults');
$response->Message->OTA_HotelRoomListRS['Children'] = $request->get('Children');
$response->Message->OTA_HotelRoomListRS['Rooms'] = $request->get('Rooms');
$session->set($transactionId.'[hotel][detail]', $response->asXML());
} else {
$responseHotelDetail = $response;
}
}
if (!isset($responseHotelDetail['error'])) {
$detailHotelRaw = $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay;
$httpsPhotos = [];
if (!empty($detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem)) {
foreach ($detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem as $httpPhoto) {
array_push($httpsPhotos, $httpPhoto);
}
}
$postData = $request->all();
$session->set($transactionId.'[hotel][availability_data_hotel]', json_encode($postData));
if (false !== strpos($provider->getName(), 'Juniper') || 'M' == $guestsInfo) {
$passangerTypes = [];
$passangerTypes[1] = [
'ADT' => (int) $request->get('Adults'),
'CHD' => (int) $request->get('Children'),
'INF' => 0,
];
} else {
$passangerTypes[1] = [
'ADT' => 1,
'CHD' => 0,
'INF' => 0,
];
}
$roomRate = [];
/* foreach ($detailHotelRaw->RoomRates->RoomRate as $roomRatePlan) {
$roomRate[] = $roomRatePlan;
}
$services = array();
foreach ($detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service as $service) {
$services[] = $service;
}
$commission = (isset($response->Message->OTA_HotelRoomListRS['commissionPercentage']) ? (float) $response->Message->OTA_HotelRoomListRS['commissionPercentage'] : null ); */
for ($u = 0; $u < (is_countable($detailHotelRaw->RoomRates->RoomRate) ? count($detailHotelRaw->RoomRates->RoomRate) : 0); ++$u) {
if (null != $response->Message->OTA_HotelRoomListRS['commissionId']) {
$qsewithCommission = $detailHotelRaw->RoomRates->RoomRate[$u]->TotalAviatur['calcBasePrice'] + $response->Message->OTA_HotelRoomListRS['commissionQse'];
} else {
$qsewithCommission = $detailHotelRaw->RoomRates->RoomRate[$u]->TotalAviatur['calcBasePrice'];
}
$detailHotelRaw->RoomRates->RoomRate[$u]->TotalAviatur['calcBasePriceQse'] = $qsewithCommission;
//var_dump(json_decode(base64_decode((string) $detailHotelRaw->RoomRates->RoomRate[$u]->TotalAviatur['FullPricing']), true));
}
//die;
foreach ($detailHotelRaw->RoomRates->RoomRate as $roomRatePlan) {
$roomRate[] = $roomRatePlan;
}
$services = [];
if (isset($detailHotelRaw->TPA_Extensions->HotelInfo->Services)) {
foreach ($detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service as $service) {
$services[] = $service;
}
}
//$commission = (isset($response->Message->OTA_HotelRoomListRS['commissionPercentage']) ? (float) $response->Message->OTA_HotelRoomListRS['commissionPercentage'] : null );
if ($isAgent) {
$commission = (float) $response->Message->OTA_HotelRoomListRS['commissionPercentage'];
$commissionQse = (float) $response->Message->OTA_HotelRoomListRS['commissionQse'];
$parametersJson = $session->get($domain.'[parameters]');
$parameters = json_decode($parametersJson);
$tax = (float) $parameters->aviatur_payment_iva;
//$QsetoPay = round(($commissionQse / (1 + $tax)) * $commission);
$QsetoPay = $fullPricing['totalCommissionPay'];
$response->Message->OTA_HotelRoomListRS['QsetoPay'] = $QsetoPay;
}
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);
if ($session->has($transactionId.'external')) {
$childsURL = '';
$routeParsed['scheme'] = 'http';
$routeParsed['host'] = $session->get('domain');
if ($request->get('Children') > 0) {
if ($request->get('Children0') > 0) {
$childsURL .= $request->get('Children0');
}
if ($request->get('Children1') > 0) {
$childsURL .= '-'.$request->get('Children1');
}
if ($request->get('Children2') > 0) {
$childsURL .= '-'.$request->get('Children2');
}
} else {
$childsURL = 'n';
}
$routeParsed['path'] = '/hoteles/'.$request->get('zone').'/'.$startDate.'+'.$endDate.'/'.$request->get('Adults').'+'.$childsURL.'';
$session->set('routePath', $routeParsed['path']);
}
$availabilityUrl = $router->match($routeParsed['path']);
$rooms = [];
$adults = 0;
$childs = 0;
if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
for ($i = 1; $i <= $availabilityUrl['rooms']; ++$i) {
$adults += $availabilityUrl['adult'.$i];
$childrens = [];
if ('n' != $availabilityUrl['child'.$i]) {
$childAgesTemp = explode('-', $availabilityUrl['child'.$i]);
$childs += count($childAgesTemp);
}
}
}
else {
$data = json_decode($session->get($transactionId . '[hotel][availability_data_hotel]'));
if (isset($data->attributes) && null !== json_decode(base64_decode($data->attributes), true)) {
$availabilityData = json_decode(base64_decode($data->attributes), true);
} else {
$availabilityData = json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
}
if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
for ($i = 0; $i < $availabilityData['Rooms']; ++$i) {
$adults += $availabilityData['Adults'.$i] ?? 0;
if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
$childs += $availabilityData['Children'.$i];
}
}
}
}
$detailHotel = [
'dateIn' => $dateIn,
'dateOut' => $dateOut,
'dateInStr' => $startDate,
'dateOutStr' => $endDate,
'nights' => $nights,
'adults' => $request->get('Adults'),
'children' => $request->get('Children'),
'rooms' => $request->get('Rooms') ?? $availabilityUrl['rooms'] ?? $availabilityData['Rooms'] ?? $session->get('AvailabilityArrayhotel')['Rooms'],
'roomInformation' => $rooms,
'roomRates' => $roomRate,
'timeSpan' => $detailHotelRaw->TimeSpan,
'total' => $detailHotelRaw->Total,
'basicInfos' => $detailHotelRaw->BasicPropertyInfo,
'category' => $detailHotelRaw->TPA_Extensions->HotelInfo->Category,
'description' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Description,
'email' => $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
'services' => $services,
'photos' => $httpsPhotos,
];
if ($isAgent) {
$detailHotel['commissionAgentValue'] = $response->Message->OTA_HotelRoomListRS;
}
// END // Collection of informations to show in template (dates, passengers, hotel)
$typeDocument = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$typeGender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
$repositoryDocumentType = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
$queryDocumentType = $repositoryDocumentType
->createQueryBuilder('p')
->where('p.paymentcode != :paymentcode')
->setParameter('paymentcode', '')
->getQuery();
$documentPaymentType = $queryDocumentType->getResult();
$paymentMethodAgency = $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency, 'isactive' => 1]);
$paymentOptions = [];
foreach ($paymentMethodAgency as $payMethod) {
$paymentCode = $payMethod->getPaymentMethod()->getCode();
if (!in_array($paymentCode, $paymentOptions) && 'p2p' == $paymentCode || 'cybersource' == $paymentCode) {
$paymentOptions[] = $paymentCode;
}
}
$banks = [];
if (in_array('pse', $paymentOptions)) {
$banks = $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
}
$cybersource = [];
if (in_array('cybersource', $paymentOptions)) {
$cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource', $paymentOptions)]->getSitecode();
$cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource', $paymentOptions)]->getTrankey();
}
foreach ($paymentOptions as $key => $paymentOption) {
if ('cybersource' == $paymentOption) {
unset($paymentOptions[$key]); // strip from other renderizable payment methods
}
}
$conditions = $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'reservation_conditions_for_hotels');
$pixelInfo = [];
if (!$isFront) {
// PIXELES INFORMATION
$pixel['partner_datalayer'] = [
'event' => 'hotelCheckout',
'dimension1' => isset($detailHotel['basicInfos']->Address->CityName) ? (string) $detailHotel['basicInfos']->Address->CityName : '',
'dimension2' => '',
'dimension3' => $detailHotel['dateInStr'],
'dimension4' => $detailHotel['dateOutStr'],
'dimension5' => 'Checkout Hotel',
'dimension6' => '',
'dimension7' => '',
'dimension8' => '',
'dimension9' => isset($detailHotel['basicInfos']['HotelCode']) ? (string) $detailHotel['basicInfos']['HotelCode'] : '',
'dimension10' => '',
'dimension11' => isset($detailHotel['adults']) ? ($detailHotel['adults'] + $detailHotel['children']) : 0,
'dimension12' => 'Hotel',
'ecommerce' => [
'checkout' => [
'products' => [
'actionField' => "{'step': 1 }",
'name' => isset($detailHotel['basicInfos']['HotelCode']) ? (string) $detailHotel['basicInfos']['HotelCode'] : '',
'price' => '',
'brand' => isset($detailHotel['basicInfos']['HotelName']) ? (string) $detailHotel['basicInfos']['HotelName'] : '',
'category' => 'Hotel',
'variant' => '',
'quantity' => isset($detailHotel['adults']) ? ($detailHotel['adults'] + $detailHotel['children']) : 0,
],
],
],
];
if ($fullRequest->request->has('kayakclickid') || $fullRequest->query->has('kayakclickid')) {
if ($fullRequest->request->has('kayakclickid')) {
$kayakclickid = $fullRequest->request->get('kayakclickid');
} elseif ($fullRequest->query->has('kayakclickid')) {
$kayakclickid = $fullRequest->query->get('kayakclickid');
}
$pixel['kayakclickid'] = $kayakclickid;
$session->set($transactionId.'[hotel][kayakclickid]', $pixel['kayakclickid']);
}
//$pixel['dataxpand'] = true;
$pixelInfo = $aviaturPixeles->verifyPixeles($pixel, 'hotel', 'detail', $agency->getAssetsFolder(), $transactionId);
}
$isNational = true;
if ('CO' != $country) {
$isNational = false;
}
$args = (object) [
'isNational' => $isNational,
'countryCode' => $postDataCountry ?? null,
'passangerTypes' => $passangerTypes,
'destinationArray' => [
'Start' => $detailHotel['dateInStr'],
'End' => $detailHotel['dateOutStr'],
'Code' => $fullRequest->request->get('Destination'),
'passangerTypes' => $passangerTypes,
],
];
if ($isMulti && !$isFront && isset($postDataCountry)) {
$detailCoupon = $aviaturCouponDiscount->loadCoupons($agency, $transactionId, 'hotel', $args);
if ($detailCoupon) {
$detailHasCoupon = true;
$detailHotel['couponInfo'] = [
'title' => $detailCoupon->Title,
'description' => $detailCoupon->Title,
'validateUrl' => $detailCoupon->ValidateURL,
'couponDiscountTotal' => $detailCoupon->CoupontDiscountAmountTotal,
'policy' => $detailCoupon->CouponPolicies,
];
}
}
if (!$session->has($transactionId.'[hotel][args]')) {
$session->set($transactionId.'[hotel][args]', json_encode($args));
}
$payoutExtras = null;
if (!$isFront && !$isMulti) {
$payoutExtras = $payoutExtraService->loadPayoutExtras($agency, $transactionId, 'hotel', $args);
}
$pointRedemption = $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
if (null != $pointRedemption) {
$points = 0;
if ($fullRequest->request->has('pointRedemptionValue')) {
$points = $fullRequest->request->get('pointRedemptionValue');
$session->set('point_redemption_value', $points);
} elseif ($fullRequest->query->has('pointRedeem')) {
$points = $fullRequest->query->get('pointRedeem');
$session->set('point_redemption_value', $points);
} elseif ($session->has('point_redemption_value')) {
$points = $session->get('point_redemption_value');
}
$pointRedemption['Config']['Amount']['CurPoint'] = $points;
}
$pixel = $request->get('pixelInfo'); //cambios fer
$responseHotelDetail = [
'twig_readonly' => false,
'referer' => $session->get($transactionId.'[availability_url]'),
'doc_type' => $typeDocument,
'gender' => $typeGender,
'detailHotel' => $detailHotel,
'payment_doc_type' => $documentPaymentType,
'services' => $passangerTypes,
'conditions' => $conditions,
'hotelProvidersId' => [(string) $provider->getProvideridentifier()],
'payment_type_form_name' => $provider->getPaymentType()->getTwig(),
'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]),
'inactiveCards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]),
'paymentOptions' => $paymentOptions,
'banks' => $banks,
'cybersource' => $cybersource,
'additional' => base64_encode($transactionId.'/'.$session->get($transactionId.'[hotel]['.$correlationIdSessionName.']')),
'payoutExtras' => $payoutExtras,
'pointRedemption' => $pointRedemption,
'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
'pixel_info' => $pixelInfo, //Cambios fer start
'HotelCode' => $request->get('hotelCode'),
'providerID' => $request->get('providerID'),
'correlationId' => $request->get('correlationId'),
'transactionId' => $request->get('transactionID'),
'startDate' => $request->get('startDate'),
'endDate' => $request->get('endDate'),
'country' => $request->get('country'),
'RateHasDiscount' => $request->get('AvailabilityHasDiscount'),
'pixelInfo' => $pixel['partner_datalayer'],
'HotelMinPrice' => $request->get('HotelMinPrice'),
'Rooms' => $request->get('Rooms'),
'Children' => $request->get('Children'),
'Adults' => $request->get('Adults'),
'Destination' => $request->get('Destination'),
'Children0' => $request->get('Children0'),
'Adults0' => $request->get('Adults0'),
'CurrencyCode' => $currencyCode ?? null,
'availableArrayHotel' => ('' != $session->get('AvailabilityArrayhotel')) ? $session->get('AvailabilityArrayhotel') : null,
'Code' => $args->destinationArray['Code'] ?? null,//cambios fer end
];
$responseHotelDetail['baloto'] ?? ($responseHotelDetail['baloto'] = false);
$responseHotelDetail['pse'] ?? ($responseHotelDetail['pse'] = true);
$responseHotelDetail['safety'] ?? ($responseHotelDetail['safety'] = true);
} else {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($returnUrl, 'Ha ocurrido un error inesperado', $responseHotelDetail['error']));
}
}
$route = $router->match(str_replace($fullRequest->getSchemeAndHttpHost(), '', $fullRequest->getUri()));
$isMulti = false !== strpos($route['_route'], 'multi') ? true : false;
if ($isMulti) {
$detailHotel['hasCoupon'] = $detailHasCoupon;
if ($session->get('currentHotelDiscountSession') === $transactionId && !$isFront) {
$detailHotel['discountAmount'] = $session->get($transactionId.'[HotelDiscounts][discountTotal]');
$detailHotel['discountAmountTRM'] = $session->get($transactionId.'[HotelDiscounts][discountAmountTRM]');
$detailHotel['hasDiscount'] = $detailHasDiscount;
$policyText = $session->get($transactionId.'[HotelDiscounts][discountPolicyText]');
$detailHotel['discountPolicyText'] = \str_replace("\r\n", '<br>•', $policyText);
$responseHotelDetail['detailHotel'] = $detailHotel;
}
$context['responseHotelDetail']='responseHotelDetail';
return $this->json($responseHotelDetail, 200, [], $context);
}
$today = date('Y-m-d');
// $diffDays = (strtotime($responseHotelDetail['detailHotel']['dateInStr']) - strtotime($today)) / 86400;
$diffDays = (strtotime($detailHotel['dateInStr']) - strtotime($today)) / 86400;
if ($diffDays > 0) {
$responseHotelDetail['baloto'] = true;
}
$responseHotelDetail['baloto'] ?? ($responseHotelDetail['baloto'] = false);
if (('error' == $responseHotelDetail) || (isset($responseHotelDetail['error']))) {
$session = $session;
$transactionId = $session->get($transactionIdSessionName);
$message = $responseHotelDetail['error'] ?? 'Ha ocurrido un error inesperado';
return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), 'Página no accesible', $message));
} else {
$responseHotelDetail['city']= $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo->Address->CityName->__toString() ?? '';
$responseHotelDetail['nights']=$nights;
$agencyFolder = $twigFolder->twigFlux();
$view = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/detail_info.html.twig');
return $this->render($view, $responseHotelDetail);
}
}
public function detailInvalidAction(Request $request, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, TwigFolder $twigFolder, SessionInterface $session, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$server = $request->server;
if (true === $session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
$referer = $router->match(parse_url($server->get('HTTP_REFERER'), PHP_URL_PATH));
if (true === $session->has($transactionId.'[availability_url]')) {
return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), 'Página no accesible', 'No puedes acceder al detalle sin disponibilidad'));
} elseif (false !== strpos($referer['_controller'], 'availabilityAction')) {
return $this->redirect($aviaturErrorHandler->errorRedirect($server->get('HTTP_REFERER'), '', 'Error en la respuesta de nuestro proveedor de servicios, inténtalo nuevamente'));
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puedes acceder al detalle sin disponibilidad'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puedes acceder al detalle sin disponibilidad'));
}
}
public function prePaymentStep1Action(Request $request, TokenizerService $tokenizerService, CustomerMethodPaymentService $customerMethodPayment, TokenStorageInterface $tokenStorage, AviaturWebService $aviaturWebService, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, AviaturEncoder $aviaturEncoder, TwigFolder $twigFolder, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$correlationIdSessionName = $parameterBag->get('correlation_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
if ($request->isXmlHttpRequest()) {
$request = $request->request;
$quotation = $request->get('QT');
$transactionId = $session->get($transactionIdSessionName);
$billingData = $request->get('BD');
$em = $this->managerRegistry;
$postData = $request->all();
$publicKey = $aviaturEncoder->aviaturRandomKey();
$session->remove('register-extra-data');
if (isset($postData['PD']['card_num'])) {
$postDataInfo = $postData;
if (isset($postDataInfo['PD']['cusPOptSelected'])) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $customerMethodPayment->getMethodsByCustomer($customerLogin, true);
$cardToken = $infoMethodPaymentByClient['info'][$postDataInfo['PD']['cusPOptSelected']]['token'];
$postDataInfo['PD']['card_num'] = $cardToken;
} else {
$postDataInfo['PD']['card_num'] = $tokenizerService->getToken($postData['PD']['card_num']);
}
$postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
}
$encodedInfo = $aviaturEncoder->AviaturEncode(json_encode($postDataInfo ?? $postData), $publicKey);
$formUserInfo = new FormUserInfo();
$formUserInfo->setInfo($encodedInfo);
$formUserInfo->setPublicKey($publicKey);
$em->persist($formUserInfo);
$em->flush();
$session->set($transactionId.'[hotel][user_info]', $formUserInfo->getId());
if ((true !== $session->has($transactionId.'[hotel][retry]')) || (true !== $session->has($transactionId.'[hotel][prepayment_check]'))) {
if (true === $session->has($transactionId.'[hotel][detail]')) {
$isFront = $session->has('operatorId');
//$postData = $request->all();
$session->set($transactionId.'[hotel][detail_data_hotel]', json_encode($postData));
$passangersData = $request->get('PI');
$passangerNames = [];
for ($i = 1; $i <= $passangersData['person_count_1']; ++$i) {
$passangerNames[] = mb_strtolower($passangersData['first_name_1_'.$i]);
$passangerNames[] = mb_strtolower($passangersData['last_name_1_'.$i]);
}
if (($isFront) && ('0' == $quotation['quotation_check'])) {
$nameWhitelist = $em->getRepository(\Aviatur\GeneralBundle\Entity\NameWhitelist::class)->findLikeWhitelist($passangerNames);
if (0 == sizeof($nameWhitelist)) {
$nameBlacklist = $em->getRepository(\Aviatur\GeneralBundle\Entity\NameBlacklist::class)->findLikeBlacklist($passangerNames);
if ((sizeof(preg_grep("/^[a-z- *\.]+$/", $passangerNames)) != (sizeof($passangerNames))) ||
(sizeof($nameBlacklist)) ||
(sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/', $passangerNames)))) {
return $this->json(['error' => 'error', 'message' => 'nombre inválido']);
}
}
}
if ($isFront) {
$customer = null;
$ordersProduct = null;
} else {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
$ordersProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPending($customer);
}
if (null == $ordersProduct) {
$documentTypes = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$arrayDocumentTypes = [];
foreach ($documentTypes as $documentType) {
$arrayDocumentTypes[$documentType->getExternalCode()] = $documentType->getId();
}
$genders = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
$arrayGenders = [];
foreach ($genders as $gender) {
$arrayGenders[$gender->getCode()] = $gender->getExternalCode();
}
$hotelModel = new HotelModel();
$xmlRequest = $hotelModel->getXmlConditions();
$detail = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
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);
if ($session->has($transactionId.'external')) {
$routeParsed['path'] = $session->get('routePath');
}
$availabilityUrl = $router->match($routeParsed['path']);
$adults = 0;
$childs = 0;
if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
for ($i = 1; $i <= $availabilityUrl['rooms']; ++$i) {
$adults += $availabilityUrl['adult'.$i];
$childrens = [];
if ('n' != $availabilityUrl['child'.$i]) {
$childAgesTemp = explode('-', $availabilityUrl['child'.$i]);
$childs += count($childAgesTemp);
}
}
}
else {
$data = json_decode($session->get($transactionId . '[hotel][availability_data_hotel]'));
if (isset($data->attributes) && null !== json_decode(base64_decode($data->attributes), true)) {
$availabilityData = json_decode(base64_decode($data->attributes), true);
} else {
$availabilityData = json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
}
if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
for ($i = 0; $i < $availabilityData['Rooms']; ++$i) {
$adults += $availabilityData['Adults'.$i] ?? 0;
if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
$childs += $availabilityData['Children'.$i];
}
}
}
}
$hotelCode = explode('-', (string) $detail->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo['HotelCode']);
$hotelInformation = $request->get('HI');
$gender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersData['gender_1_1']);
$country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersData['nationality_1_1']);
$session->set($transactionId.'[hotel][retry]', $aviaturPaymentRetryTimes);
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
if (null == $customer && 'Omnibees' == $provider->getName()) {
$inputRequired = 'n/a';
} else {
$inputRequired = null;
}
$variable = [
'correlationId' => $session->get($transactionId.'[hotel]['.$correlationIdSessionName.']'),
'ProviderId' => $provider->getProvideridentifier(),
'StartDate' => (string) $detail->Message->OTA_HotelRoomListRS['StartDate'],
'EndDate' => (string) $detail->Message->OTA_HotelRoomListRS['EndDate'],
'RatePlan' => $hotelInformation['ratePlan'],
'HotelCode' => $hotelCode[0],
'rooms' => $availabilityData['Rooms'] ?? $availabilityUrl['rooms'],
'Adults' => $adults,
'Children' => $childs,
'Usuario' => $session->get('domain'),
'BirthDate' => null == $customer ? '1969-01-01' : $customer->getBirthdate()->format('Y-m-d'),
'Gender' => $gender->getExternalcode(),
'GivenName' => null == $customer ? $billingData['first_name'] : $customer->getFirstname(),
'Surname' => null == $customer ? $billingData['last_name'] : $customer->getLastname(),
'PhoneNumber' => null == $customer ? $billingData['phone'] : $customer->getPhone(),
'Email' => null == $customer ? null : $customer->getEmail(),
'AddressLine' => null == $customer ? $inputRequired : $customer->getAddress(),
'CityName' => null == $customer ? $inputRequired : $customer->getCity()->getDescription(),
'CountryName' => $country->getDescription(),
'DocID' => null == $customer ? $billingData['doc_num'] : $customer->getDocumentnumber(),
];
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'HotelDetail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false);
if (!isset($response['error'])) {
$session->set($transactionId.'[hotel][prepayment]', $response->asXML());
$cancelPenalties = (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->CancelPenalties->CancelPenalty->PenaltyDescription->Text;
$comments = (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->TPA_Extensions->Comments;
$ajaxUrl = $this->generateUrl('aviatur_hotel_prepayment_step_2_secure');
$agencyFolder = $twigFolder->twigFlux();
$info = $this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/policy.html.twig'), ['penalties' => $cancelPenalties, 'comments' => $comments]);
if (($isFront) && ('1' == $quotation['quotation_check'])) {
return $this->json([
'quotationPenalties' => $cancelPenalties,
'quotationComments' => $comments,
'namesClient' => $quotation['quotation_name'],
'lastnamesClient' => $quotation['quotation_lastname'],
'emailClient' => $quotation['quotation_email'],
]);
} elseif (($isFront) && ('0' == $quotation['quotation_check'])) {
return $this->json(['cancelPenalties' => $info, 'ajax_url' => $ajaxUrl]);
} elseif ((!$isFront)) {
return $this->json(['cancelPenalties' => $info, 'ajax_url' => $ajaxUrl]);
}
} else {
$session->remove($transactionId.'[hotel][retry]');
$session->remove($transactionId.'[hotel][prepayment]');
return $this->json(['error' => 'fatal', 'message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', $response['error'])]);
}
} else {
$booking = [];
$cus = [];
foreach ($ordersProduct as $orderProduct) {
$productResponse = $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
$paymentResponse = json_decode($productResponse);
array_push($booking, 'ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId());
if (isset($paymentResponse->x_approval_code)) {
array_push($cus, $paymentResponse->x_approval_code);
} elseif (isset($paymentResponse->createTransactionResult->trazabilityCode)) {
array_push($cus, $paymentResponse->createTransactionResult->trazabilityCode);
}
}
return $this->json([
'error' => 'pending payments',
'message' => 'pending_payments',
'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null,
'cus' => $cus,
]);
}
} else {
return $this->json(['error' => 'fatal', 'message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo')]);
}
} else {
$request = $request->request;
$paymentData = $request->get('PD');
$paymentData = json_decode(json_encode($paymentData));
$json = json_decode($session->get($transactionId.'[hotel][order]'));
$postData = $request->all();
if (!is_null($json)) {
$json->ajax_url = $this->generateUrl('aviatur_hotel_prepayment_step_2_secure');
// reemplazar datos de pago por los nuevos.
$oldPostData = json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
if (isset($paymentData->cusPOptSelected) || isset($paymentData->card_num)) {
if (isset($paymentData->cusPOptSelected)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $customerMethodPayment->getMethodsByCustomer($customerLogin, true);
$card_num_token = $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
} else {
$card_num_token = $tokenizerService->getToken($paymentData->card_num);
}
$card_values = ['card_num_token' => $card_num_token, 'card_num' => $paymentData->card_num];
}
unset($oldPostData->PD);
$oldPostData->PD = $paymentData;
$oldPostData->PD->card_values = $card_values;
$session->set($transactionId.'[hotel][detail_data_hotel]', json_encode($oldPostData));
$response = new Response(json_encode($json));
$response->headers->set('Content-Type', 'application/json');
return $response;
} else {
return $this->json(['error' => 'fatal', 'message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos datos de tu orden, por favor inténtalo nuevamente')]);
}
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado'));
}
}
public function prePaymentStep2Action(Request $request, OrderController $orderController, AuthorizationCheckerInterface $authorizationChecker, AviaturErrorHandler $aviaturErrorHandler, TwigFolder $twigFolder, ManagerRegistry $registry, \Swift_Mailer $mailer, RouterInterface $router, AviaturWebService $aviaturWebService, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$order = [];
if ($request->isXmlHttpRequest()) {
$request = $request->request;
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$billingData = $request->get('BD');
$detailEncodedData = $request->get('DD');
$detailData = explode('/', base64_decode($detailEncodedData['additional']));
$transactionId = $detailData[0];
$session->set($transactionId.'[hotel][prepayment_check]', true);
if (true !== $session->has($transactionId.'[hotel][order]')) {
if (true === $session->has($transactionId.'[hotel][detail]')) {
$session->set($transactionIdSessionName, $transactionId);
$isFront = $session->has('operatorId');
if ($isFront) {
$customer = $billingData;
$customer['isFront'] = true;
$status = 'B2T';
} else {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
$status = 'waiting';
}
if (isset($agency)) {
$productType = $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findByCode('HOTEL');
if ($isFront) {
$orderIdentifier = '{order_product_reservation}';
} else {
$orderIdentifier = '{order_product_num}';
}
$order = $orderController->createAction($agency, $customer, $productType, $orderIdentifier, $status);
$orderId = str_replace('ON', '', $order['order']);
$orderEntity = $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
$agent = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
$detailResponse = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
$orderProductEntity = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find(str_replace('PN', '', $order['products']));
$postData = json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
$hotelInfo = $postData->HI;
foreach ($detailResponse->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate as $roomRatePlan) {
if ($roomRatePlan['RatePlanCode'] == $hotelInfo->ratePlan) {
$roomRate = $roomRatePlan;
}
}
$commissionPay = json_decode($hotelInfo->commissionPay);
//$taAmount = (float) $detailResponse->Message->OTA_HotelRoomListRS['TotalCommissionFare'];
$taAmount = abs((float) $commissionPay->amountTarifa);
//$commissionPercentage = (float) $detailResponse->Message->OTA_HotelRoomListRS['commissionPercentage'];
$nameProduct = 'hotel';
$productCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
$qsePercentage = $productCommission->getQsecommissionpercentage();
$commissionPercentage = $productCommission->getTacommissionpercentage();
//$qseAmount = abs((float) $commissionPay->amountQse - $taAmount);
$qseAmount = abs((float) $commissionPay->amountQse);
$startDate = strtotime((string) $detailResponse->Message->OTA_HotelRoomListRS['StartDate']);
$endDate = strtotime((string) $detailResponse->Message->OTA_HotelRoomListRS['EndDate']);
$datediff = $endDate - $startDate;
$travelDays = floor($datediff / (60 * 60 * 24));
$agentTransaction = new AgentTransaction();
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agent);
$agentTransaction->setOrderProduct($orderProductEntity);
$agentTransaction->setAgent($agent);
$agentTransaction->setAgentCommission($agentCommission);
//$agentTransaction->setCommissionvalue(round((float) ($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $travelDays * (float) $detailResponse->Message->OTA_HotelRoomListRS['commissionPercentage'])));
$agentTransaction->setCommissionvalue(round((float) ($commissionPay->commissionQse)));
$agentTransaction->setAmountQse($qseAmount);
$agentTransaction->setCommissionQse(round((((float) $qseAmount) / 1.19) * $qsePercentage));
$agentTransaction->setAmountTarifa($taAmount);
$agentTransaction->setCommissionTarifa(round((($taAmount) / 1.19) * $commissionPercentage));
$agentTransaction->setAmountProduct($commissionPay->amountProduct);
$agentTransaction->setPercentageTarifa($commissionPay->markupValue);
$em->persist($agentTransaction);
$em->flush();
}
}
$formUserInfo = $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[hotel][user_info]'));
$formUserInfo->setOrder($orderEntity);
$em->persist($formUserInfo);
$em->flush();
if ($isFront) {
$order['url'] = $this->makeReservation($session, $mailer, $aviaturWebService, $aviaturErrorHandler, $router, $registry, $parameterBag, $transactionId, $stateDb = null);
} else {
// Cambiar nombre en condición
if ($agency->getName() === 'QA Aval') {
$order['url'] = $this->generateUrl('tuplus_hotel_payment_secure');
} else {
$order['url'] = $this->generateUrl('aviatur_hotel_payment_secure');
}
}
return $this->json($order);
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró la agencia con el dominio: '.$request->getHost()));
// redireccionar al home y enviar mensaje modal
}
} else {
return $this->json(['error' => 'fatal', 'message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo')]);
}
} else {
// Cambiar nombre en condición
if ($agency->getName() === 'QA Aval') {
$order['url'] = $this->generateUrl('tuplus_hotel_payment_secure');
} else {
$order['url'] = $this->generateUrl('aviatur_hotel_payment_secure');
}
return $this->json($order);
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado'));
}
}
private function makeReservation(SessionInterface $session, \Swift_Mailer $mailer, AviaturWebService $aviaturWebService, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, ManagerRegistry $registry, ParameterBagInterface $parameterBag, $transactionId, $stateDb = null)
{
$correlationIdSessionName = $parameterBag->get('correlation_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$userData = null;
$isFront = $session->has('operatorId');
if ($isFront) {
$usuario = $session->get('operatorId');
$customerModel = new CustomerModel();
$userData = null;
try {
$userData = $aviaturWebService->callWebService('GENERALLAVE', 'dummy|http://www.aviatur.com.co/dummy/', $customerModel->getXmlAgent($usuario));
$session->set($transactionId.'[user]', $userData->asXml());
$userEmail = (string) $userData->CORREO_ELECTRONICO;
} catch (\Exception $e) {
$userEmail = $session->get('domain').'@'.$session->get('domain');
}
} else {
$userEmail = $session->get('domain').'@'.$session->get('domain');
}
$hotelModel = new HotelModel();
$xmlRequestArray = $hotelModel->getXmlReservation();
$detail = \simplexml_load_string((string) $session->get($transactionId.'[hotel][detail]'));
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);
if ($session->has($transactionId.'external')) {
$routeParsed['path'] = $session->get('routePath');
}
$availabilityUrl = $router->match($routeParsed['path']);
$adults = 0;
$childs = 0;
if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
for ($i = 1; $i <= $availabilityUrl['rooms']; ++$i) {
$adults += $availabilityUrl['adult'.$i];
$childrens = [];
if ('n' != $availabilityUrl['child'.$i]) {
$childAgesTemp = explode('-', $availabilityUrl['child'.$i]);
$childs += count($childAgesTemp);
}
}
}
else {
$availabilityData = json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
for ($i = 0; $i < $availabilityData['Rooms']; ++$i) {
$adults += $availabilityData['Adults'.$i] ?? 0;
if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
$childs += $availabilityData['Children'.$i];
}
}
}
}
$hotelCode = explode('-', (string) $detail->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo['HotelCode']);
$postData = json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
$passangersData = $postData->PI;
$hotelInformation = $postData->HI;
$ratePlanCode = $hotelInformation->ratePlan;
$em = $this->managerRegistry;
$gender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersData->gender_1_1);
$country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersData->nationality_1_1);
$session->set($transactionId.'[hotel][retry]', $aviaturPaymentRetryTimes);
if ($isFront) {
$customer = null;
$dbState = 0; //pending of payment with penalty policies autocancelation
} else {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$dbState = (null != $stateDb) ? $stateDb : 2; //pending of payment with same day autocancelation
}
$passangersData->DocType_1_1 = $passangersData->doc_type_1_1;
if (false !== strpos($passangersData->first_name_1_1, '***')) {
$passangersData->first_name_1_1 = $customer->getFirstname();
$passangersData->last_name_1_1 = $customer->getLastname();
$passangersData->phone_1_1 = $customer->getPhone();
$passangersData->email_1_1 = $customer->getEmail();
$passangersData->address_1_1 = $customer->getAddress();
$passangersData->doc_num_1_1 = $customer->getDocumentnumber();
}
$orderProductCode = $session->get($transactionId.'[hotel][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$detailInfo = \simplexml_load_string((string) $session->get($transactionId.'[hotel][detail]'));
$prepaymentInfo = \simplexml_load_string((string) $session->get($transactionId.'[hotel][prepayment]'));
$startDate = strtotime((string) $detailInfo->Message->OTA_HotelRoomListRS['StartDate']);
$endDate = strtotime((string) $detailInfo->Message->OTA_HotelRoomListRS['EndDate']);
$this->generate_email($session, $registry, $orderProduct, $detailInfo, $prepaymentInfo, $startDate, $endDate);
$orderRequestArray = explode('<FILTRO>', str_replace('</FILTRO>', '<FILTRO>', $orderProduct->getAddproductdata()));
$orderRequest = \simplexml_load_string($orderRequestArray[1]);
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
if (null == $customer && 'Omnibees' == $provider->getName()) {
$inputRequired = 'n/a';
} else {
$inputRequired = null;
}
$variable = [
'correlationId' => $session->get($transactionId.'[hotel]['.$correlationIdSessionName.']'),
'ProviderId' => $provider->getProvideridentifier(),
'StartDate' => (string) $detail->Message->OTA_HotelRoomListRS['StartDate'],
'EndDate' => (string) $detail->Message->OTA_HotelRoomListRS['EndDate'],
'RatePlanCode' => $ratePlanCode,
'AmountAfterTax' => (string) $orderRequest->product->cost_data->fare->total_amount,
'CurrencyCode' => false !== strpos($provider->getName(), 'USD') ? 'USD' : 'COP',
'HotelCode' => $hotelCode[0],
'Rooms' => $availabilityData['Rooms'] ?? $availabilityUrl['rooms'],
'Adults' => $adults,
'Children' => $childs,
'Usuario' => $userEmail,
'EstadoBD' => $dbState,
'BirthDate' => null == $customer ? '1980-01-01' : $customer->getBirthdate()->format('Y-m-d'),
'Gender' => $gender->getExternalcode(),
'GivenName' => null == $customer ? $postData->BD->first_name : $customer->getFirstname(),
'Surname' => null == $customer ? $postData->BD->last_name : $customer->getLastname(),
'PhoneNumber' => null == $customer ? $postData->BD->phone : $customer->getPhone(),
'Email' => null == $customer ? null : $customer->getEmail(),
'AddressLine' => null == $customer ? $inputRequired : $customer->getAddress(),
'CityName' => null == $customer ? $inputRequired : $customer->getCity()->getDescription(),
'CountryName' => $country->getDescription(),
'DocID' => null == $customer ? $postData->BD->doc_num : $customer->getDocumentnumber(),
];
// $postDataArray = json_decode($session->get($transactionId . '[hotel][availability_data_hotel]'), true);
$search = [
'{Guest_DocID}',
'{Guest_Name}',
'{Guest_Surname}',
'{Guest_Datebirth}',
'{Guest_Gender}',
'{Guest_Nationality}',
'{Guest_DocType}',
'{Guest_Type}',
'{Guest_Email}',
'{Guest_Phone}',
];
$replace = [];
$xmlRequest = $xmlRequestArray[0];
$xmlRequest .= $xmlRequestArray['RoomType'][0];
$passangersDataArray = json_decode(json_encode($passangersData), true);
$totalGuests = $passangersDataArray['person_count_1']; //$postDataArray['Adults'] + $postDataArray['Children'];
for ($i = 1; $i <= $totalGuests; ++$i) {
$gender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersDataArray['gender_1'.'_'.$i]);
$country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersDataArray['nationality_1'.'_'.$i]);
$replace = [
'{doc_num_1'.'_'.$i.'}',
'{first_name_1'.'_'.$i.'}',
'{last_name_1'.'_'.$i.'}',
'{birthday_1'.'_'.$i.'}',
'{gender_1'.'_'.$i.'}',
'{nationality_1'.'_'.$i.'}',
'{DocType_1'.'_'.$i.'}',
'{passanger_type_1'.'_'.$i.'}',
(1 == $i) ? $passangersDataArray['email_1_1'] : '',
(1 == $i) ? $postData->CD->phone : '',
];
$xmlRequest .= str_replace($search, $replace, $xmlRequestArray['RoomType'][1]);
$passangersDataArray['DocType_1'.'_'.$i] = $passangersDataArray['doc_type_1'.'_'.$i];
$variable['doc_num_1'.'_'.$i] = $passangersDataArray['doc_num_1'.'_'.$i];
$variable['first_name_1'.'_'.$i] = $passangersDataArray['first_name_1'.'_'.$i];
$variable['last_name_1'.'_'.$i] = $passangersDataArray['last_name_1'.'_'.$i];
$variable['birthday_1'.'_'.$i] = $passangersDataArray['birthday_1'.'_'.$i];
$variable['gender_1'.'_'.$i] = $gender->getExternalcode();
$variable['nationality_1'.'_'.$i] = $country->getIatacode();
$variable['DocType_1'.'_'.$i] = $passangersDataArray['doc_type_1'.'_'.$i];
$variable['passanger_type_1'.'_'.$i] = $passangersDataArray['passanger_type_1'.'_'.$i];
}
$xmlRequest .= $xmlRequestArray['RoomType'][2];
$xmlRequest .= $xmlRequestArray[1];
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'HotelRes', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false);
if (isset($response->Message->OTA_HotelResRS->HotelReservations)) {
$reservationId = (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->UniqueID['ID'];
$orderProduct->setEmissiondata($reservationId);
$orderProduct->setUpdatingdate(new \DateTime());
$reservationId2 = (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->ResGlobalInfo->HotelReservationIDs->HotelReservationID['ResID_Value'];
$session->set($transactionId.'[hotel][reservation]', $response->asXml());
$contactNumber = 'No info';
if (isset($response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers) && isset($response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers->ContactNumber['PhoneNumber'])) {
$contactNumber = (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers->ContactNumber['PhoneNumber'];
}
$search = ['{order_product_reservation}', '{order_product_reservation_2}', '{property_name_2}', '{contact_number}'];
$replace = [$reservationId, $reservationId2, (string) $response->Message->OTA_HotelResRS->HotelReservations->HotelReservation->TPA_Extensions->Payable, $contactNumber];
if ('Omnibees' == $provider->getName()) {
$reservation = explode('-', $reservationId);
$search[] = '{incoming_office}';
$replace[] = $reservation[1];
}
$orderXml = str_replace($search, $replace, $orderProduct->getAddProductData());
$orderProduct->setAddProductData($orderXml);
$orderProduct->setBooking($reservationId);
$em->persist($orderProduct);
$em->flush();
if ($isFront) {
try {
$responseOrder = $aviaturWebService->busWebServiceAmadeus(null, null, $orderXml);
} catch (\Exception $e) {
}
}
if ($isFront && isset($postData->HI->refundInfo) && 'NRF' == $postData->HI->refundInfo) {
$toEmails = $userData->CORREO_ELECTRONICO;
$ccMails = ['w_aldana@aviatur.com'];
switch ((string) $provider->getProvideridentifier()) {
case '70'://hotelbeds pruebas
case '42'://hotelbeds produccion
$ccMails[] = 'johanna.briceno@aviatur.com';
break;
case '87'://Expedia pruebas
case '54'://Expedia producción
$ccMails[] = 'luz.ramirez@aviatur.com';
break;
case '102'://Bookohotel pruebas
case '108': //Lots Pruebas
case '62'://Bookohotel producción
case '68'://Lots producción
$ccMails[] = 'madeleine.garcia@aviatur.com';
break;
}
$bccMails = 'errores.prod.web@aviatur.com';
$mailInfo = '<p>Estimado '.$userData->NOMBRE_AGENTE.': </p><p> Teniendo en cuenta que usted acaba de generar un reserva bajo tarifa no reembolsable según las condiciones '
.'del proveedor, usted debió reconfirmar al cliente y generar la factura respectiva de cobro con el fin de evitar entrar en costos '
.'sobre dicha reserva y por lo cual es 100% su aceptación de dicho cobro.</p>';
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($toEmails)
->setCc($ccMails)
->setBcc($bccMails)
->setSubject('Reserva generada en gastos: '.$reservationId2)
->setBody($mailInfo);
$mailer->send($message);
}
if (!$isFront) {
$emailContent = 'Hotel reservation '.$orderProduct->getEmissiondata().', the product id is: '.$orderProduct->getId().', the customer id is: '.$customer->getId().'</b> Email customer new DB: <b>'.$customer->getEmail().'</b>, the info is: '.$orderProduct->getEmail();
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom('noreply@aviatur.com.co')
->setSubject('Hotel Reservation')
->setTo(['soptepagelectronic@aviatur.com', 'soportepagoelectronico@aviatur.com.co'])
->setCc(['supervisorescallcenter@aviatur.com', 'hotelesenlineaaviatur@aviatur.com'])
->setBcc(['notificacionessitioweb@aviatur.com', 'sebastian.huertas@aviatur.com'])
->setBody($emailContent);
$mailer->send($message);
}
if ($isFront) {
return $this->generateUrl('aviatur_hotel_reservation_success_secure');
} else {
// return $this->generateUrl('aviatur_hotel_payment_secure');
return true;
}
} else {
$orderProduct->setEmissiondata('No Reservation');
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$message = 'Ha ocurrido un error realizando la reserva del hotel, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción';
if (isset($response->ProviderResults->ProviderResult['Message']) && isset($response->ProviderResults->ProviderResult['Provider'])) {
if ('71' == $response->ProviderResults->ProviderResult['Provider']) {
$message = $response->ProviderResults->ProviderResult['Message'];
}
}
if (!$isFront) {
$emailContent = '
<b>No se realizó la reserva de hotel, tiene pago aprobado.</b><br/>
Info:<br/>
Referer in posaereos: '.$orderProduct->getBooking().'<br/>
The product id is: '.$orderProduct->getId().'<br/>
The customer id is: '.$customer->getId().'<br/></b>
Email customer DB: <b>'.$customer->getEmail().'</b>,<br/>
The info is: '.$orderProduct->getEmail();
$emailMessage = (new \Swift_Message())
->setContentType('text/html')
->setFrom('noreply@aviatur.com.co')
->setSubject('Hotel reservation failed with payment approved')
->setTo(['soptepagelectronic@aviatur.com', 'soportepagoelectronico@aviatur.com.co'])
->setCc(['supervisorescallcenter@aviatur.com', 'hotelesenlineaaviatur@aviatur.com'])
->setBcc(['notificacionessitioweb@aviatur.com', 'sebastian.huertas@aviatur.com'])
->setBody($emailContent);
$mailer->send($emailMessage);
return false;
}
return $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', $message);
}
}
/**
* Metodo creado para acceder desde la clase HotelTuPlusController.
*/
protected function makeReservationTuPlus(SessionInterface $session, \Swift_Mailer $mailer, AviaturWebService $aviaturWebService, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, ManagerRegistry $registry, ParameterBagInterface $parameterBag, $transactionId, $stateDb = null)
{
return $this->makeReservation($session, $mailer, $aviaturWebService, $aviaturErrorHandler, $router, $registry, $parameterBag, $transactionId, $stateDb);
}
public function paymentAction(Request $request, \Swift_Mailer $mailer, CashController $cashPayController, SafetypayController $safetyPayController, PSEController $psePaymentController,WorldPayController $worldPaymentController ,P2PController $p2pPaymentController, MultiHotelDiscount $multiHotelDiscount, PayoutExtraService $payoutExtraService, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, TwigFolder $twigFolder, ManagerRegistry $registry, SessionInterface $session, ParameterBagInterface $parameterBag, TokenizerService $tokenizerService, CustomerMethodPaymentService $customerMethodPayment, AviaturLogSave $aviaturLogSave, OrderController $orderController)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentOnline = $parameterBag->get('aviatur_payment_online');
$aviaturPaymentOnRequest = $parameterBag->get('aviatur_payment_on_request');
$emailNotification = $parameterBag->get('email_notification');
$orderProduct = [];
$roomRate = [];
$paymentResponse = null;
$return = null;
$emissionData = [];
$response = null;
$array = [];
$em = $this->managerRegistry;
$session = $this->session;
$parameters = json_decode($session->get($request->getHost().'[parameters]'));
$aviaturPaymentIva = (float) $parameters->aviatur_payment_iva;
$transactionId = $session->get($transactionIdSessionName);
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
$providerId = $provider->getProvideridentifier();
$route = $router->match(str_replace($request->getSchemeAndHttpHost(), '', $request->getUri()));
$isMulti = false !== strpos($route['_route'], 'multi') ? true : false;
if ($provider->getPaymentType()->getCode() == $aviaturPaymentOnRequest) {
// pago en destino
return $this->redirect($this->generateUrl('aviatur_hotel_confirmation'));
} elseif ($provider->getPaymentType()->getcode() == $aviaturPaymentOnline) {
// pago online
$detailInfo = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
$prepaymentInfo = \simplexml_load_string($session->get($transactionId.'[hotel][prepayment]'));
$postData = json_decode($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);
if ($session->has($transactionId.'external')) {
$routeParsed['path'] = $session->get('routePath');
}
$availabilityUrl = $router->match($routeParsed['path']);
$hotelName = $detailInfo->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo;
$orderInfo = json_decode($session->get($transactionId.'[hotel][order]'));
$productId = str_replace('PN', '', $orderInfo->products);
$orderProduct[] = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$hotelInfo = $postData->HI;
foreach ($detailInfo->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate as $roomRatePlan) {
if ($roomRatePlan['RatePlanCode'] == $hotelInfo->ratePlan) {
$roomRate = $roomRatePlan;
}
}
$startDate = strtotime((string) $detailInfo->Message->OTA_HotelRoomListRS['StartDate']);
$endDate = strtotime((string) $detailInfo->Message->OTA_HotelRoomListRS['EndDate']);
$destination = $availabilityUrl['destination1'] ?? $availabilityUrl['destination'] ?? json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true)['Destination'];
//Agregar todos los cuartos a la descripción!!!!!!!!!!!!!!!!!
$description = 'Hotel - '.(string) $hotelName['HotelName'].'('.(string) $roomRate->Rates->Rate->RateDescription->Text.' '.(string) $roomRate['RatePlanCategory'].') - '.$destination.'('.date('d/m/Y', $startDate).' - '.date('d/m/Y', $endDate).')';
$datediff = $endDate - $startDate;
$travelDays = floor($datediff / (60 * 60 * 24));
$paymentData = $postData->PD;
// COLLECT INFORMATION TO PERSIST OrderProduct->Email
$this->generate_email($session, $registry, $orderProduct[0], $detailInfo, $prepaymentInfo, $startDate, $endDate);
$discountTransactionID = $session->get('currentHotelDiscountSession');
$discountAmount = 0;
$discountTax = 0;
$_x_tax = 0;
$payoutExtrasValues = null;
if (isset($postData->payoutExtrasSelection) && !$isMulti) {
$payoutExtrasValues = $payoutExtraService->getPayoutExtrasValues($postData->payoutExtrasSelection, $transactionId);
}
if ($transactionId === $discountTransactionID) {
$discountValues = $multiHotelDiscount->getPaymentDiscountValues($transactionId, $roomRate);
$discountAmount = (float) $discountValues->discountAmount;
$discountTax = (float) $discountValues->discountTax;
$_x_tax = (float) $discountValues->x_tax;
}
$minimumAmount = 1000;
if (true === (bool) $session->get($transactionId.'[CouponDiscount][hotel][validationResult]')) {
$discountAmount = (float) $session->get($transactionId.'[CouponDiscount][discountTotal]');
$discountTax = (float) $session->get($transactionId.'[CouponDiscount][discountTax]');
if ((float) $roomRate->TotalAviatur['discountAmount'] > 0) {
$discountTripPrice = ($roomRate->TotalAviatur['calcTripPriceBeforeDiscount'] - $discountAmount) >= $minimumAmount ? ($roomRate->TotalAviatur['calcTripPriceBeforeDiscount'] - $discountAmount) : $minimumAmount;
$baseDiscounted = round($discountTripPrice / (1 + $aviaturPaymentIva));
$tripTaxDiscounted = round($baseDiscounted * $aviaturPaymentIva);
$AmountIncludingAviaturMarkup = $roomRate->TotalAviatur['AmountIncludingAviaturMarkupBeforeDiscount'] - $discountAmount;
} else {
$discountTripPrice = ($roomRate->TotalAviatur['calcTripPriceBeforeDiscount'] - $discountAmount) >= $minimumAmount ? ($roomRate->TotalAviatur['calcTripPrice'] - $discountAmount) : $minimumAmount;
$baseDiscounted = round($discountTripPrice / (1 + $aviaturPaymentIva));
$tripTaxDiscounted = round($baseDiscounted * $aviaturPaymentIva);
}
$_x_tax = $roomRate->TotalAviatur['calcTripTaxDiscount'];
}
$qseAmount = 0;
if (!empty($hotelInfo->qseAmount)) {
$qseAmount = $hotelInfo->qseAmount;
}
if ('p2p' == $paymentData->type || 'world' == $paymentData->type) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
if (false !== strpos($paymentData->address, '***')) {
$paymentData->address = $customer->getAddress();
}
if (false !== strpos($paymentData->phone, '***')) {
$paymentData->phone = $customer->getPhone();
}
if (false !== strpos($paymentData->email, '***')) {
$paymentData->email = $customer->getEmail();
}
$x_amount_total = (float) ($roomRate->TotalAviatur['AmountTotal'] * $travelDays) - $discountAmount;
$x_amount_total = $x_amount_total + $qseAmount;
if ($x_amount_total < $minimumAmount) {
$x_amount_total = $minimumAmount;
}
$x_amount_tax = 0 != (float) $roomRate->TotalAviatur['AmountTax'] ? (float) $x_amount_total * $aviaturPaymentIva : 0;
$x_amount_base = 0 != (float) $roomRate->TotalAviatur['AmountTax'] ? $x_amount_total - $x_amount_tax : 0;
$array = [
'x_currency_code' => (string) $roomRate->TotalAviatur['CurrencyCode'],
'x_amount' => $x_amount_total,
'x_tax' => number_format($x_amount_tax, 2, '.', ''),
'x_amount_base' => number_format($x_amount_base, 2, '.', ''),
//'x_amount_base' => number_format(round((float) ($roomRate->TotalAviatur['AmountTax'] != 0 ? $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $travelDays : 0)), 2, '.', ''),
'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
'x_first_name' => $paymentData->first_name,
'x_last_name' => $paymentData->last_name,
'x_description' => $description,
'x_city' => $customer->getCity()->getIatacode(),
'x_country_id' => $customer->getCountry()->getIatacode(),
'x_cust_id' => $paymentData->doc_type.' '.$paymentData->doc_num,
'x_address' => $paymentData->address,
'x_phone' => $paymentData->phone,
'x_email' => $paymentData->email,
'x_card_num' => $paymentData->card_num,
'x_exp_date' => $paymentData->exp_month.$paymentData->exp_year,
'x_card_code' => $paymentData->card_code,
'x_differed' => $paymentData->differed,
'x_client_id' => $postData->BD->id,
'product_type' => 'hotel',
'productId' => str_replace('PN', '', $orderInfo->products),
'orderId' => str_replace('ON', '', $orderInfo->order),
'franchise' => $paymentData->franquise,
];
if (isset($paymentData->card_values)) {
$array['card_values'] = (array) $paymentData->card_values;
}
if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
foreach ($payoutExtrasValues as $payoutExtraValues) {
$array['x_amount'] += round((float) $payoutExtraValues->values->fare->total);
$array['x_tax'] += round((float) $payoutExtraValues->values->fare->tax);
$array['x_amount_base'] += round((float) $payoutExtraValues->values->fare->base);
}
$array['x_amount'] = $array['x_amount'] + $qseAmount;
}
$payoutExtrasValues = $payoutExtraService->setPayoutExtrasAsProcessed($transactionId);
$array['x_cancelation_date'] = (string) $prepaymentInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->TPA_Extensions->CancellationPolicy['FechaEntradaGasto'];
if (isset($paymentData->cusPOptSelected)) {
$array['isToken'] = (string) $paymentData->card_values->card_num_token;
}
if ('p2p' == $paymentData->type) {
if (isset($paymentData->savePaymProc)) {
$array['x_provider_id'] = 1;
} elseif (isset($paymentData->cusPOptSelected)) {
if (isset($paymentData->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $paymentData->cusPOptSelectedStatus) {
$array['x_provider_id'] = 1;
} else {
$array['x_provider_id'] = 2;
}
} else {
$array['x_provider_id'] = 2;
}
}
}
if ('p2p' == $paymentData->type) {
$paymentResponse = $p2pPaymentController->placetopayAction($parameterBag, $tokenizerService, $customerMethodPayment, $mailer, $aviaturLogSave, $array, $combination = false, $segment = null, false);
$return = $this->redirect($this->generateUrl('aviatur_hotel_payment_p2p_return_url_secure', [], true));
} elseif ('world' == $paymentData->type) {
$array['city'] = $customer->getCity()->getIatacode();
$array['countryCode'] = $customer->getCity()->getCountry()->getIatacode();
$paymentResponse = $worldPaymentController->worldAction($request, $mailer, $aviaturLogSave, $customerMethodPayment, $parameterBag, $array);
$return = $this->redirect($this->generateUrl('aviatur_hotel_payment_world_return_url_secure', [], true));
}
unset($array['x_client_id']);
if (null != $paymentResponse) {
return $return;
} else {
$orderProduct[0]->setStatus('pending');
$em->persist($orderProduct[0]);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '', 'No hay respuesta por parte del servicio de pago, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción'));
}
} elseif ('pse' == $paymentData->type) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$x_amount_total = (float) ($roomRate->TotalAviatur['AmountTotal'] * $travelDays) - $discountAmount;
if ($x_amount_total < $minimumAmount) {
$x_amount_total = $minimumAmount;
}
$x_amount_tax = 0 != (float) $roomRate->TotalAviatur['AmountTax'] ? (float) $x_amount_total * $aviaturPaymentIva : 0;
$x_amount_base = 0 != (float) $roomRate->TotalAviatur['AmountTax'] ? $x_amount_total - $x_amount_tax : 0;
$array = ['x_doc_num' => $customer->getDocumentnumber(),
'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
'x_first_name' => $customer->getFirstname(),
'x_last_name' => $customer->getLastname(),
'x_company' => 'Aviatur',
'x_email' => $customer->getEmail(),
'x_address' => $customer->getAddress(),
'x_city' => $customer->getCity()->getDescription(),
'x_province' => $customer->getCity()->getDescription(),
'x_country' => $customer->getCountry()->getDescription(),
'x_phone' => $customer->getPhone(),
'x_mobile' => $customer->getCellphone(),
'x_bank' => $postData->PD->pse_bank,
'x_type' => $postData->PD->pse_type,
'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
'x_description' => $description,
'x_currency' => (string) $roomRate->TotalAviatur['CurrencyCode'],
'x_total_amount' => $x_amount_total,
'x_tax_amount' => number_format(round($x_amount_tax), 2, '.', ''),
'x_devolution_base' => number_format(round($x_amount_base), 2, '.', ''),
'x_tip_amount' => number_format(round(0), 2, '.', ''),
'product_type' => 'hotel',
];
if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
foreach ($payoutExtrasValues as $payoutExtraValues) {
$array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
$array['x_tax_amount'] += round((float) $payoutExtraValues->values->fare->tax);
$array['x_devolution_base'] += round((float) $payoutExtraValues->values->fare->base);
}
}
$payoutExtrasValues = $payoutExtraService->setPayoutExtrasAsProcessed($transactionId);
$route = $router->match(str_replace($request->getSchemeAndHttpHost(), '', $request->getUri()));
$isMulti = false !== strpos($route['_route'], 'multi') ? true : false;
if ($isMulti) {
return $this->json($array);
}
$array['x_providerId'] = $providerId;
$paymentResponse = $psePaymentController->sendPaymentAction($array, $orderProduct);
if (!isset($paymentResponse->error)) {
switch ($paymentResponse->createTransactionResult->returnCode) {
case 'SUCCESS':
return $this->redirect($paymentResponse->createTransactionResult->bankURL);
case 'FAIL_EXCEEDEDLIMIT':
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Tu reserva fue realizada exitosamente, sin embargo, el monto excede los límites establecidos, comuníate con nosotros a los teléfonos 57 1 5879640 o 57 1 3821616 o vía e-mail al correo soportepagoelectronico@aviatur.com.co para completar tu transacción.'));
case 'FAIL_BANKUNREACHEABLE':
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '', 'Tu entidad financiera no pudo ser contactada para iniciar la transacción, por favor inténtalo nuevamente'));
default:
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '', 'No se pudo crear la transacción con tu banco, por favor inténtalo nuevamente'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), 'Error al procesar el pago', 'Ocurrió un problema al intentar crear tu transacción, '.$paymentResponse->error));
}
} elseif ('safety' == $paymentData->type) {
$orderProductCode = json_decode($session->get($transactionId.'[hotel][order]'));
$transactionUrl = $this->generateUrl('aviatur_payment_safetypay', [], true);
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$productId = str_replace('PN', '', $orderProductCode->products);
$Product = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$x_amount_total = (float) ($roomRate->TotalAviatur['AmountTotal'] * $travelDays) - $discountAmount;
if ($x_amount_total < $minimumAmount) {
$x_amount_total = $minimumAmount;
}
$x_amount_tax = 0 != (float) $roomRate->TotalAviatur['AmountTax'] ? (float) $x_amount_total * $aviaturPaymentIva : 0;
$x_amount_base = 0 != (float) $roomRate->TotalAviatur['AmountTax'] ? $x_amount_total - $x_amount_tax : 0;
$array = ['x_doc_num' => $customer->getDocumentnumber(),
'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
'x_first_name' => $customer->getFirstname(),
'x_last_name' => $customer->getLastname(),
'x_company' => 'Aviatur',
'x_email' => $customer->getEmail(),
'x_address' => $customer->getAddress(),
'x_city' => $customer->getCity()->getDescription(),
'x_province' => $customer->getCity()->getDescription(),
'x_country' => $customer->getCountry()->getDescription(),
'x_phone' => $customer->getPhone(),
'x_mobile' => $customer->getCellphone(),
'x_reference' => $orderInfo->products,
'x_booking' => $Product->getBooking(),
'x_description' => $description,
'x_currency' => (string) $roomRate->TotalAviatur['CurrencyCode'],
'x_total_amount' => $x_amount_total,
'x_tax_amount' => number_format(round($x_amount_tax), 2, '.', ''),
'x_devolution_base' => number_format(round($x_amount_base), 2, '.', ''),
'x_tip_amount' => number_format(round(0), 2, '.', ''),
'x_payment_data' => $paymentData->type,
'x_type_description' => $orderProduct[0]->getDescription(),
];
if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
foreach ($payoutExtrasValues as $payoutExtraValues) {
$array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
$array['x_tax_amount'] += round((float) $payoutExtraValues->values->fare->tax);
$array['x_devolution_base'] += round((float) $payoutExtraValues->values->fare->base);
}
}
$payoutExtrasValues = $payoutExtraService->setPayoutExtrasAsProcessed($transactionId);
$parametMerchant = [
'MerchantSalesID' => $array['x_reference'],
'Amount' => $array['x_total_amount'],
'transactionUrl' => $transactionUrl,
'dataTrans' => $array,
];
$safeTyPay = $safetyPayController->safetyAction($router, $parameterBag, $mailer, $parametMerchant, $array);
if ('ok' == $safeTyPay['status']) {
if ('baloto' == $paymentData->type) {
$cash = '&CountryId=COL&ChannelId=CASH';
$session->set($transactionId.'[hotel][retry]', 0);
return $this->redirect($safeTyPay['response'].$cash);
} else {
return $this->redirect($safeTyPay['response']);
}
} else {
$emissionData->x_booking = $array['x_booking'];
$emissionData->x_first_name = $array['x_first_name'];
$emissionData->x_last_name = $array['x_last_name'];
$emissionData->x_doc_num = $array['x_doc_num'];
$emissionData->x_reference = $array['x_reference'];
$emissionData->x_description = $array['x_description'];
$emissionData->x_total_amount = $array['x_total_amount'];
$emissionData->x_email = $array['x_email'];
$emissionData->x_address = $array['x_address'];
$emissionData->x_phone = $array['x_phone'];
$emissionData->x_type_description = $array['x_type_description'];
$emissionData->x_resultSafetyPay = $safeTyPay;
$mailInfo = print_r($emissionData, true).'<br>'.print_r($response, true);
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($emailNotification)
->setSubject('Error Creación Token SafetyPay'.$emissionData->x_reference)
->setBody($mailInfo);
$mailer->send($message);
return $this->redirect($this->generateUrl('aviatur_hotel_payment_rejected_secure'));
}
} elseif ('cash' == $paymentData->type) {
$x_amount_total = (float) ($roomRate->TotalAviatur['AmountTotal'] * $travelDays) - $discountAmount;
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$agency = $this->agency;
$agencyName = $agency->getOfficeId();
$array['x_officeId'] = $agencyName;
$array['x_doc_num'] = $customer->getDocumentnumber();
$array['x_doc_type'] = $customer->getDocumentType()->getPaymentcode();
$array['x_first_name'] = $customer->getFirstname();
$array['x_last_name'] = $customer->getLastname();
$array['x_company'] = 'Aviatur';
$array['x_email'] = $customer->getEmail();
$array['x_address'] = $customer->getAddress();
$array['x_city'] = $customer->getCity()->getDescription();
$array['x_province'] = $customer->getCity()->getDescription();
$array['x_country'] = $customer->getCountry()->getDescription();
$array['x_phone'] = $customer->getPhone();
$array['x_mobile'] = $customer->getCellphone();
$array['x_payment_data'] = $paymentData->type;
$array['x_type_description'] = $orderProduct[0]->getDescription();
$array['x_reference'] = $orderInfo->products;
$array['x_total_amount'] = $x_amount_total >= 100 ? number_format(round($x_amount_total), 2, '.', '') : 100;
$array['x_currency'] = (string) $roomRate->TotalAviatur['CurrencyCode'];
$array['x_description'] = $description;
$array['x_booking'] = $orderProduct[0]->getBooking();
if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
foreach ($payoutExtrasValues as $payoutExtraValues) {
$array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
}
}
$payoutExtrasValues = $payoutExtraService->setPayoutExtrasAsProcessed($transactionId);
$fecha = $orderProduct[0]->getCreationDate()->format('Y-m-d H:i:s');
$fechalimite = $orderProduct[0]->getCreationDate()->format('Y-m-d 23:40:00');
$nuevafecha = strtotime('+2 hour', strtotime($fecha));
$fechavigencia = date('Y-m-d H:i:s', $nuevafecha);
if (strcmp($fechavigencia, $fechalimite) > 0) {
$fechavigencia = $fechalimite;
}
$array['x_fechavigencia'] = $fechavigencia;
$array['x_transactionId'] = $transactionId;
$retryCount = (int) $session->get($transactionId.'[hotel][retry]');
$route = $router->match(str_replace($request->getSchemeAndHttpHost(), '', $request->getUri()));
$isMulti = false !== strpos($route['_route'], 'multi') ? true : false;
if ($isMulti) {
return $this->json($array);
} elseif ($session->has($transactionId.'[hotel][detail_cash]')) {
$detail_cash = json_decode($session->get($transactionId.'[hotel][detail_cash]'));
if ('error' == $detail_cash->status) {
$cashPay = $cashPayController->cashAction($array);
} else {
$cashPay = json_decode($session->get($transactionId.'[hotel][detail_cash]'));
}
} else {
$cashPay = $cashPayController->cashAction($array);
$session->set($transactionId.'[hotel][detail_cash]', json_encode($cashPay));
}
if ('ok' == $cashPay->status) {
$session->set($transactionId.'[hotel][cash_result]', json_encode($cashPay));
return $this->redirect($this->generateUrl('aviatur_hotel_confirmation_success_secure'));
} else {
$emissionData['x_first_name'] = $array['x_first_name'];
$emissionData['x_last_name'] = $array['x_last_name'];
$emissionData['x_doc_num'] = $array['x_doc_num'];
$emissionData['x_reference'] = $array['x_reference'];
$emissionData['x_description'] = $array['x_description'];
$emissionData['x_total_amount'] = $array['x_total_amount'];
$emissionData['x_email'] = $array['x_email'];
$emissionData['x_address'] = $array['x_address'];
$emissionData['x_phone'] = $array['x_phone'];
$emissionData['x_type_description'] = $array['x_type_description'];
$emissionData['x_error'] = $cashPay->status;
$mailInfo = print_r($emissionData, true).'<br>'.print_r($cashPay, true);
$toEmails = ['soportepagoelectronico@aviatur.com.co', 'soptepagelectronic@aviatur.com', $emailNotification];
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($toEmails)
->setBcc($emailNotification)
->setSubject('Error Creación Transacción Efectivo'.$emissionData['x_reference'])
->setBody($mailInfo);
$mailer->send($message);
$session->set($transactionId.'[hotel][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl('aviatur_hotel_payment_rejected_secure'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '', 'El tipo de pago es invalido'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '', 'El provedor arrojó un método de pago inesperado'));
}
}
public function p2pCallbackAction(OrderController $orderController, ValidateSanctionsRenewal $validateSanctions, TokenStorageInterface $tokenStorage, CustomerMethodPaymentService $customerMethodPayment, AviaturMailer $aviaturMailer, PayoutExtraService $payoutExtraService, AviaturEncoder $aviaturEncoder, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, ParameterBagInterface $parameterBag, AviaturWebService $aviaturWebService, RouterInterface $router, \Swift_Mailer $mailer)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$em = $this->managerRegistry;
$session = $this->session;
$transactionId = $session->get($transactionIdSessionName);
$orderProductCode = $session->get($transactionId.'[hotel][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$decodedRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
if (null != $decodedResponse) {
$agency = $orderProduct->getOrder()->getAgency();
$prepaymentInfo = \simplexml_load_string($session->get($transactionId.'[hotel][prepayment]'));
$twig = '';
$additionalQS = '';
$retryCount = (int) $session->get($transactionId.'[hotel][retry]');
$jsonSendEmail = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('send_email');
if (isset(json_decode($jsonSendEmail->getDescription())->email)) {
$email = json_decode($jsonSendEmail->getDescription())->email->CallBack;
}
$reference = str_replace('{"order":"', '', $orderProductCode);
$reference = str_replace('","products":"', '-', $reference);
$reference = str_replace('"}', '', $reference);
$references = $reference;
$bookings = $orderProduct->getBooking();
switch ($decodedResponse->x_response_code) {
case isset($decodedResponse->x_response_code_cyber) && (2 == $decodedResponse->x_response_code_cyber):
//rechazado cybersource
$parameters = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
if ($parameters) {
if (1 == $parameters->getValue()) {
if (1 == $decodedResponse->x_response_code) {
$postData = json_decode($session->get($transactionId . '[hotel][detail_data_hotel]'));
if (isset($postData->PD->savePaymProc)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPayment->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
if (isset($postData->PD->cusPOptSelected)) {
if (isset($postData->PD->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
$postData->PD->cusPOptSelectedStatus = 'ACTIVE';
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPayment->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
}
}
}
// Aquí NO se hace la reserva en ningún caso
// if (($emissionData != 'No Reservation') && ($emissionData != '') && ($emissionData != null)) {
// $rs = $this->makeReservation($transactionId);
// }
$twig = 'aviatur_hotel_payment_rejected_secure';
// no break
case 3:// pendiente p2p
$twig = '' != $twig ? $twig : 'aviatur_hotel_payment_pending_secure';
$emissionData = 'No Reservation';
$orderProduct->setEmissiondata(json_encode($emissionData));
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$retryCount = 1;
break;
case 0:// error p2p
$twig = 'aviatur_hotel_payment_error_secure';
if (isset($email)) {
$from = $session->get('emailNoReply');
$error = $twig;
$subject = $orderProduct->getDescription().':Error en el proceso de pago de Aviatur';
$body = '</br>El proceso de pago a retornado un error </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
$aviaturMailer->sendEmailGeneral($from, $email, $subject, $body);
}
// no break
case 2:// rechazada p2p
$twig = '' != $twig ? $twig : 'aviatur_hotel_payment_rejected_secure';
if (isset($email)) {
$from = $session->get('emailNoReply');
$error = $twig;
$subject = $orderProduct->getDescription().':Transacción rechazada';
$body = '</br>El pago fue rechazado </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
$aviaturMailer->sendEmailGeneral($from, $email, $subject, $body);
}
break;
case 1:// aprobado p2p
$postData = json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
if (isset($postData->PD->savePaymProc)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPayment->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
if (isset($postData->PD->cusPOptSelected)) {
if (isset($postData->PD->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
$postData->PD->cusPOptSelectedStatus = 'ACTIVE';
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPayment->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
$decodedRequest->product_type = 'hotel';
$decodedResponse->product_type = 'hotel';
$encodedRequest = $aviaturEncoder->AviaturEncode(json_encode($decodedRequest), $orderProduct->getPublicKey());
$encodedResponse = $aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey());
$orderProduct->setPayrequest($encodedRequest);
$orderProduct->setPayresponse($encodedResponse);
$twig = 'aviatur_hotel_payment_success_secure';
if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
$additionalQS = '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->x_amount;
}
//Reemplazar por consumo de reserva!!!!
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
$providerId = $provider->getProvideridentifier();
$orderController->updatePaymentAction($orderProduct, false, null);
$rs = $this->makeReservation($session, $mailer, $aviaturWebService, $aviaturErrorHandler, $router, $registry, $parameterBag, $transactionId, 1);
$reservationInfo = \simplexml_load_string($session->get($transactionId.'[hotel][reservation]'));
if (isset($reservationInfo->Message->OTA_HotelResRS) && isset($reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->ResGlobalInfo->HotelReservationIDs->HotelReservationID['ResID_Value'])) {
$reservationId2 = $reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->ResGlobalInfo->HotelReservationIDs->HotelReservationID['ResID_Value'];
} else {
$reservationId2 = 'PN'.$orderProduct->getId();
}
$orderUpdatePayment = str_replace(
['{web_book_id}', '{hotel_book_id}'],
['PN'.$orderProduct->getId(), (string) $reservationId2],
$orderProduct->getUpdatePaymentData()
);
$orderProduct->setUpdatePaymentData($orderUpdatePayment);
$em->persist($orderProduct);
$em->flush();
break;
}
$payoutExtraService->payoutExtrasCallback($twig, $transactionId, 'hotel', $agency);
$session->set($transactionId.'[hotel][retry]', $retryCount - 1);
$urlResume = $this->generateUrl($twig);
$urlResume .= $additionalQS;
//////// se envia el correo del modulo anti fraude en caso de ser necesario//////////
/*
if ($session->has('Marked_name') && $session->has('Marked_document')) {
$product = 'Hotel';
$validateSanctions->sendMarkedEmail($orderProductCode, $session, $agency, $orderProduct, $transactionId, $product);
}
*/
/* Pero solo si hay condicionados (no bloqueados) y que paguen con Tarjeta */
if ($session->has('Marked_users')) {
$product = 'Hotel';
$validateSanctions->sendMarkedEmail($orderProductCode, $session, $agency, $orderProduct, $transactionId, $product);
}
////////////////////////////////////////////////////////////////////////////////////
return $this->redirect($urlResume);
} else {
$orderProduct->setStatus('pending');
$em->persist($orderProduct);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '', 'No hay respuesta por parte del servicio de pago'));
}
}
public function pseCallbackAction(Request $request, ConfirmationWebservice $hotelConfirmationWebService, PSEController $psePaymentController, OrderController $orderController, PayoutExtraService $payoutExtraService, AviaturEncoder $aviaturEncoder, AviaturErrorHandler $aviaturErrorHandler, TwigFolder $twigFolder, ParameterBagInterface $parameterBag, $transaction)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$status = null;
$twig = null;
$em = $this->managerRegistry;
$session = $this->session;
if ($session->has('agencyId')) {
$agency = $this->agency;
} else {
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1);
}
$paymentMethod = $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethod::class)->findOneByCode('pse');
$paymentMethodAgency = $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findOneBy(['agency' => $agency, 'paymentMethod' => $paymentMethod]);
$tranKey = $paymentMethodAgency->getTrankey();
$decodedUrl = json_decode($aviaturEncoder->AviaturDecode(base64_decode($transaction), $tranKey), true);
$transactionId = ($session->has($transactionIdSessionName)) ? $session->get($transactionIdSessionName) : null;
$orders = $decodedUrl['x_orders'];
if (isset($orders['hotel'])) {
$hotelOrders = explode('+', $orders['hotel']);
$orderProductCode = $hotelOrders[0];
$productId = $hotelOrders[0];
$retryCount = 1;
} else {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontro identificador de la transacción'));
}
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
if (empty($orderProduct)) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró orden asociada a este pago'));
} else {
if ('approved' == $orderProduct->getStatus()) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró información de la transacción'));
}
$agency = $orderProduct->getOrder()->getAgency();
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
if (isset($decodedResponse->createTransactionResult)) {
$pseTransactionId = $decodedResponse->createTransactionResult->transactionID;
$paymentResponse = $psePaymentController->pseCallbackAction($pseTransactionId);
if (!isset($paymentResponse->error)) {
if (!$session->has($transactionId.'[hotel][detail_data_hotel]')) {
$message = 'Una vez el pago sea confirmado recibirá su confirmación de reserva, de no ser así comuníquese con nuestra central de reservas.';
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Gracias por su compra', $message));
}
$decodedResponse->getTransactionInformationResult = $paymentResponse->getTransactionInformationResult;
$orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
if ('SUCCESS' == (string) $paymentResponse->getTransactionInformationResult->returnCode) {
switch ((string) $paymentResponse->getTransactionInformationResult->transactionState) {
case 'OK':
$twig = 'aviatur_hotel_payment_success_secure';
$status = 'approved';
break;
case 'PENDING':
$twig = 'aviatur_hotel_payment_pending_secure';
$status = 'pending';
break;
case 'NOT_AUTHORIZED':
$twig = 'aviatur_hotel_payment_error_secure';
$status = 'rejected';
break;
case 'FAILED':
$twig = 'aviatur_hotel_payment_error_secure';
$status = 'failed';
break;
}
$orderProduct->setStatus($status);
$orderProduct->getOrder()->setStatus($status);
$orderProduct->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$payoutExtraService->payoutExtrasCallback($twig, $transactionId, 'hotel', $agency);
if ('approved' == $status) {
//Reemplazar por consumo de reserva!!!!
if ($session->has($transactionId.'[hotel][provider]')) {
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
$providerId = $provider->getProvideridentifier();
} elseif (isset($decodedUrl['x_providerId'])) {
$providerId = $decodedUrl['x_providerId'];
}
$orderController->updatePaymentAction($orderProduct, false, null);
$request = new \stdClass();
$request->Reserva = (string) $orderProduct->getEmissiondata();
if (isset($providerId) && '58' == $providerId) {
$request->Expediente = 0;
$request->Usuario = 'INTERNET';
}
$hotelConfirmationWebService->callServiceConfirmation('ConfirmarReserva', $request, $orderProduct->getId());
}
} elseif ('FAIL_INVALIDTRAZABILITYCODE' == (string) $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_ACCESSDENIED' == $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_TIMEOUT' == $paymentResponse->getTransactionInformationResult->returnCode) {
echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
transacción <#CUS> .';
$orderProduct->setEmissiondata('error');
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$twig = 'aviatur_hotel_payment_error_secure';
}
if ($session->has($transactionId.'[hotel][retry]')) {
$session->set($transactionId.'[hotel][retry]', $retryCount - 1);
}
return $this->redirect($this->generateUrl($twig));
} else {
$decodedResponse->getTransactionInformationResult = $paymentResponse;
$orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Ocurrió un error al consultar el estado de la transacción'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró información de la transacción'));
}
}
}
public function safetyCallbackOkAction(Request $request, SafetypayController $safetyPayController, ConfirmationWebservice $hotelConfirmationWebService, OrderController $orderController, PayoutExtraService $payoutExtraService, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, AviaturEncoder $aviaturEncoder, TwigFolder $twigFolder, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$correlationIdSessionName = $parameterBag->get('correlation_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$status = null;
$twig = null;
$em = $this->managerRegistry;
$safeTyPay = $safetyPayController->safetyok();
if (true === $session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
if (true === $session->has($transactionId.'[hotel][order]')) {
$orderProductCode = $session->get($transactionId.'[hotel][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$agency = $orderProduct->getOrder()->getAgency();
$decodedRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
$payError = $decodedResponse->payResponse->OperationResponse->ErrorManager->ErrorNumber->{'@content'};
$notifyError = $decodedResponse->notificationResponse->OperationActivityNotifiedResponse->ErrorManager->ErrorNumber->{'@content'};
if (isset($decodedResponse->payResponse->OperationResponse)) {
if (0 == $payError) {
$retryCount = (int) $session->get($transactionId.'[hotel][retry]');
if (0 == $notifyError) {
switch ($payError) {
case 0:
$twig = 'aviatur_hotel_payment_success_secure';
$status = 'approved';
break;
case 2:
$twig = 'aviatur_hotel_payment_error_secure';
$status = 'failed';
break;
}
$orderProduct->setStatus($status);
$orderProduct->getOrder()->setStatus($status);
$orderProduct->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$orderController->updatePaymentAction($orderProduct);
$payoutExtraService->payoutExtrasCallback($twig, $transactionId, 'hotel', $agency);
if (0 == $payError) {
if ('approved' == $status) {
//Reemplazar por consumo de reserva!!!!
$hotelModel = new HotelModel();
$xmlRequestArray = $hotelModel->getXmlReservation();
$xmlRequest = $xmlRequestArray[0].$xmlRequestArray['RoomType'][0].$xmlRequestArray['RoomType'][1].$xmlRequestArray['RoomType'][2].$xmlRequestArray[1];
$detail = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
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']);
$adults = 0;
$childs = 0;
if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
for ($i = 1; $i <= $availabilityUrl['rooms']; ++$i) {
$adults += $availabilityUrl['adult'.$i];
$childrens = [];
if ('n' != $availabilityUrl['child'.$i]) {
$childAgesTemp = explode('-', $availabilityUrl['child'.$i]);
$childs += count($childAgesTemp);
}
}
}
else {
$data = json_decode($session->get($transactionId . '[hotel][availability_data_hotel]'));
if (isset($data->attributes) && null !== json_decode(base64_decode($data->attributes), true)) {
$availabilityData = json_decode(base64_decode($data->attributes), true);
} else {
$availabilityData = json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
}
if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
for ($i = 0; $i < $availabilityData['Rooms']; ++$i) {
$adults += $availabilityData['Adults'.$i] ?? 0;
if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
$childs += $availabilityData['Children'.$i];
}
}
}
}
$hotelCode = explode('-', (string) $detail->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo['HotelCode']);
$postData = json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
$passangersData = $postData->PI;
$hotelInformation = $postData->HI;
$ratePlanCode = $hotelInformation->ratePlan;
$gender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersData->gender_1_1);
$country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersData->nationality_1_1);
$session->set($transactionId.'[hotel][retry]', $aviaturPaymentRetryTimes);
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$passangersData->DocType_1_1 = $passangersData->doc_type_1_1;
if (false !== strpos($passangersData->first_name_1_1, '***')) {
$passangersData->first_name_1_1 = $customer->getFirstname();
$passangersData->last_name_1_1 = $customer->getLastname();
$passangersData->phone_1_1 = $customer->getPhone();
$passangersData->email_1_1 = $customer->getEmail();
$passangersData->address_1_1 = $customer->getAddress();
$passangersData->doc_num_1_1 = $customer->getDocumentnumber();
}
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
$providerId = $provider->getProvideridentifier();
$variable = [
'correlationId' => $session->get($transactionId.'[hotel]['.$correlationIdSessionName.']'),
'ProviderId' => $providerId,
'Guest_DocID' => $passangersData->doc_num_1_1,
'Guest_Name' => $passangersData->first_name_1_1,
'Guest_Surname' => $passangersData->last_name_1_1,
'Guest_Datebirth' => $passangersData->birthday_1_1,
'Guest_Gender' => $gender->getExternalcode(),
'Guest_Nationality' => $country->getIatacode(),
'Guest_DocType' => $passangersData->DocType_1_1,
'StartDate' => (string) $detail->Message->OTA_HotelRoomListRS['StartDate'],
'EndDate' => (string) $detail->Message->OTA_HotelRoomListRS['EndDate'],
'RatePlanCode' => $ratePlanCode,
'AmountAfterTax' => number_format($decodedRequest->totalAmount, 2, ',', ''),
'CurrencyCode' => 'COP',
'HotelCode' => $hotelCode[0],
'Rooms' => $availabilityUrl['rooms'] ?? $availabilityData['Rooms'],
'Adults' => $adults,
'Children' => $childs,
'Usuario' => $session->get('domain').'@'.$session->get('domain'),
'EstadoBD' => 1,
'BirthDate' => $customer->getBirthdate()->format('Y-m-d'),
'Gender' => $gender->getExternalcode(),
'GivenName' => $customer->getFirstname(),
'Surname' => $customer->getLastname(),
'PhoneNumber' => $customer->getPhone(),
'Email' => $customer->getEmail(),
'AddressLine' => $customer->getAddress(),
'CityName' => $customer->getCity()->getDescription(),
'CountryName' => $country->getDescription(),
'DocID' => $customer->getDocumentnumber(),
];
$request = new \stdClass();
$request->Reserva = (string) $orderProduct->getEmissiondata();
if ('58' == $providerId) {
$request->Expediente = 0;
$request->Usuario = 'INTERNET';
}
$response = $hotelConfirmationWebService->callServiceConfirmation('ConfirmarReserva', $request, $orderProduct->getId());
}
}
} else {
echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
transacción <#CUS> .';
$orderProduct->setEmissiondata('error');
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$twig = 'aviatur_hotel_payment_error_secure';
}
$session->set($transactionId.'[hotel][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl($twig));
} else {
$decodedResponse->payResponse->OperationResponse->ListOfOperations = $paymentResponse;
$orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Ocurrió un error al consultar el estado de la transacción'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró información de la transacción, por favor comuniquese con nosotros'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró orden asociada a este pago'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontro identificador de la transacción'));
}
}
public function safetyCallbackErrorAction(AviaturEncoder $aviaturEncoder, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, TwigFolder $twigFolder, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$status = null;
$em = $this->managerRegistry;
$transactionId = $session->get($transactionIdSessionName);
$retryCount = (int) $session->get($transactionId.'[hotel][retry]');
$orderProductCode = $session->get($transactionId.'[hotel][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$payResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
$payRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey()));
$orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($payResponse), $orderProduct->getPublicKey()));
if ('baloto' == $payRequest->dataTransf->x_payment_data) {
$status = 'pending';
$payResponse->dataTransf->x_response_code = 100;
$payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Pending';
} elseif ('safety' == $payRequest->dataTransf->x_payment_data) {
$status = 'rejected';
$payResponse->dataTransf->x_response_code = 100;
$payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Expired';
}
$orderProduct->setStatus($status);
$orderProduct->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setUpdatingdate(new \DateTime());
$order = $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderProduct->getOrder()->getId());
$order->setStatus($status);
$em->persist($order);
$em->persist($orderProduct);
$em->flush();
if (true === $session->has($transactionId.'[hotel][order]')) {
$orderProductCode = $session->get($transactionId.'[hotel][order]');
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró orden asociada a este pago'));
}
$session->set($transactionId.'[hotel][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl('aviatur_hotel_payment_rejected_secure'));
}
public function worldCallbackAction(Request $request, ConfirmationWebservice $hotelConfirmationWebService, OrderController $orderController, PayoutExtraService $payoutExtraService, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, AviaturEncoder $aviaturEncoder, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$correlationIdSessionName = $parameterBag->get('correlation_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$em = $this->managerRegistry;
$transactionId = $session->get($transactionIdSessionName);
$orderProductCode = $session->get($transactionId.'[hotel][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$decodedRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
if (null != $decodedResponse) {
$agency = $orderProduct->getOrder()->getAgency();
$prepaymentInfo = \simplexml_load_string($session->get($transactionId.'[hotel][prepayment]'));
$twig = 'aviatur_hotel_payment_rejected_secure';
$retryCount = (int) $session->get($transactionId.'[hotel][retry]');
if (isset($decodedResponse->x_response_code_cyber) && (2 == $decodedResponse->x_response_code_cyber)) {
$decodedResponse->x_response_code_case = 99;
} else {
if (isset($decodedResponse->resultado->reply->orderStatus->payment->lastEvent)) {
$decodedResponse->x_response_code_case = (string) $decodedResponse->resultado->reply->orderStatus->payment->lastEvent;
} elseif (isset($decodedResponse->resultado->reply->orderStatusEvent->payment->lastEvent)) {
$decodedResponse->x_response_code_case = 'REFUSED';
} elseif (isset($decodedResponse->resultado->reply->error)) {
$decodedResponse->x_response_code_case = 'REFUSED';
}
}
switch ($decodedResponse->x_response_code_case) {
case 99:
$twig = 'aviatur_hotel_payment_rejected_secure';
break;
case 'ERROR':
$twig = 'aviatur_hotel_payment_error_secure';
break;
case 'AUTHORISED':
$decodedRequest->product_type = 'hotel';
$decodedResponse->product_type = 'hotel';
$encodedRequest = $aviaturEncoder->AviaturEncode(json_encode($decodedRequest), $orderProduct->getPublicKey());
$encodedResponse = $aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey());
$orderProduct->setPayrequest($encodedRequest);
$orderProduct->setPayresponse($encodedResponse);
$twig = 'aviatur_hotel_payment_success_secure';
//Reemplazar por consumo de reserva!!!!
$hotelModel = new HotelModel();
$xmlRequestArray = $hotelModel->getXmlReservation();
$detail = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
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']);
$adults = 0;
$childs = 0;
if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
for ($i = 1; $i <= $availabilityUrl['rooms']; ++$i) {
$adults += $availabilityUrl['adult'.$i];
$childrens = [];
if ('n' != $availabilityUrl['child'.$i]) {
$childAgesTemp = explode('-', $availabilityUrl['child'.$i]);
$childs += count($childAgesTemp);
}
}
}
else {
$data = json_decode($session->get($transactionId . '[hotel][availability_data_hotel]'));
if (isset($data->attributes) && null !== json_decode(base64_decode($data->attributes), true)) {
$availabilityData = json_decode(base64_decode($data->attributes), true);
} else {
$availabilityData = json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
}
if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
for ($i = 0; $i < $availabilityData['Rooms']; ++$i) {
$adults += $availabilityData['Adults'.$i] ?? 0;
if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
$childs += $availabilityData['Children'.$i];
}
}
}
}
$hotelCode = explode('-', (string) $detail->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo['HotelCode']);
$postData = json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
$passangersData = $postData->PI;
$hotelInformation = $postData->HI;
$ratePlanCode = $hotelInformation->ratePlan;
$gender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersData->gender_1_1);
$country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersData->nationality_1_1);
$session->set($transactionId.'[hotel][retry]', $aviaturPaymentRetryTimes);
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$passangersData->DocType_1_1 = $passangersData->doc_type_1_1;
if (false !== strpos($passangersData->first_name_1_1, '***')) {
$passangersData->first_name_1_1 = $customer->getFirstname();
$passangersData->last_name_1_1 = $customer->getLastname();
$passangersData->phone_1_1 = $customer->getPhone();
$passangersData->email_1_1 = $customer->getEmail();
$passangersData->address_1_1 = $customer->getAddress();
$passangersData->doc_num_1_1 = $customer->getDocumentnumber();
}
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->find($session->get($transactionId.'[hotel][provider]'));
$providerId = $provider->getProvideridentifier();
$variable = [
'correlationId' => $session->get($transactionId.'[hotel]['.$correlationIdSessionName.']'),
'ProviderId' => $providerId,
'StartDate' => (string) $detail->Message->OTA_HotelRoomListRS['StartDate'],
'EndDate' => (string) $detail->Message->OTA_HotelRoomListRS['EndDate'],
'RatePlanCode' => $ratePlanCode,
'AmountAfterTax' => number_format($decodedRequest->x_amount, 2, ',', ''),
'CurrencyCode' => 'COP',
'HotelCode' => $hotelCode[0],
'Rooms' => $availabilityUrl['rooms'] ?? $availabilityData['Rooms'],
'Adults' => $adults,
'Children' => $childs,
'Usuario' => $session->get('domain').'@'.$session->get('domain'),
'EstadoBD' => 1,
'BirthDate' => $customer->getBirthdate()->format('Y-m-d'),
'Gender' => $gender->getExternalcode(),
'GivenName' => $customer->getFirstname(),
'Surname' => $customer->getLastname(),
'PhoneNumber' => $customer->getPhone(),
'Email' => $customer->getEmail(),
'AddressLine' => $customer->getAddress(),
'CityName' => $customer->getCity()->getDescription(),
'CountryName' => $country->getDescription(),
'DocID' => $customer->getDocumentnumber(),
];
$search = [
'{Guest_DocID}',
'{Guest_Name}',
'{Guest_Surname}',
'{Guest_Datebirth}',
'{Guest_Gender}',
'{Guest_Nationality}',
'{Guest_DocType}',
'{Guest_Type}',
'{Guest_Email}',
'{Guest_Phone}',
];
$replace = [];
$xmlRequest = $xmlRequestArray[0];
$xmlRequest .= $xmlRequestArray['RoomType'][0];
$passangersDataArray = json_decode(json_encode($passangersData), true);
$totalGuests = $passangersDataArray['person_count_1']; //$postDataArray['Adults'] + $postDataArray['Children'];
for ($i = 1; $i <= $totalGuests; ++$i) {
$gender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findOneByCode($passangersDataArray['gender_1'.'_'.$i]);
$country = $em->getRepository(\Aviatur\GeneralBundle\Entity\Country::class)->findOneByIatacode($passangersDataArray['nationality_1'.'_'.$i]);
$replace = [
'{doc_num_1'.'_'.$i.'}',
'{first_name_1'.'_'.$i.'}',
'{last_name_1'.'_'.$i.'}',
'{birthday_1'.'_'.$i.'}',
'{gender_1'.'_'.$i.'}',
'{nationality_1'.'_'.$i.'}',
'{DocType_1'.'_'.$i.'}',
'{passanger_type_1'.'_'.$i.'}',
(1 == $i) ? $passangersDataArray['email_1_1'] : '',
(1 == $i) ? $postData->CD->phone : '',
];
$xmlRequest .= str_replace($search, $replace, $xmlRequestArray['RoomType'][1]);
$passangersDataArray['DocType_1'.'_'.$i] = $passangersDataArray['doc_type_1'.'_'.$i];
$variable['doc_num_1'.'_'.$i] = $passangersDataArray['doc_num_1'.'_'.$i];
$variable['first_name_1'.'_'.$i] = $passangersDataArray['first_name_1'.'_'.$i];
$variable['last_name_1'.'_'.$i] = $passangersDataArray['last_name_1'.'_'.$i];
$variable['birthday_1'.'_'.$i] = $passangersDataArray['birthday_1'.'_'.$i];
$variable['gender_1'.'_'.$i] = $gender->getExternalcode();
$variable['nationality_1'.'_'.$i] = $country->getIatacode();
$variable['DocType_1'.'_'.$i] = $passangersDataArray['DocType_1'.'_'.$i];
$variable['passanger_type_1'.'_'.$i] = $passangersDataArray['passanger_type_1'.'_'.$i];
}
$xmlRequest .= $xmlRequestArray['RoomType'][2];
$xmlRequest .= $xmlRequestArray[1];
$orderController->updatePaymentAction($orderProduct, false, null);
$request = new \stdClass();
$request->Reserva = (string) $orderProduct->getEmissiondata();
if ('58' == $providerId) {
$request->Expediente = 0;
$request->Usuario = 'INTERNET';
}
$response = $hotelConfirmationWebService->callServiceConfirmation('ConfirmarReserva', $request, $orderProduct->getId());
break;
case 'REFUSED':
$twig = 'aviatur_hotel_payment_rejected_secure';
break;
default:
$twig = 'aviatur_hotel_payment_pending_secure';
$emissionData = 'No Reservation';
$orderProduct->setEmissiondata(json_encode($emissionData));
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$retryCount = 1;
break;
}
$payoutExtraService->payoutExtrasCallback($twig, $transactionId, 'hotel', $agency);
$session->set($transactionId.'[hotel][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl($twig));
} else {
$orderProduct->setStatus('pending');
$em->persist($orderProduct);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_hotel_retry_secure'), '', 'No hay respuesta por parte del servicio de pago'));
}
}
public function paymentOutputAction(Request $request, ExceptionLog $exceptionLog, \Swift_Mailer $mailer, AviaturPixeles $aviaturPixeles, Pdf $pdf, AuthorizationCheckerInterface $authorizationChecker, RouterInterface $router, AviaturEncoder $aviaturEncoder, TwigFolder $twigFolder, ParameterBagInterface $parameterBag)
{
$projectDir = $parameterBag->get('kernel.project_dir');
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$emailNotification = $parameterBag->get('email_notification');
$clientFranquice = [];
$paymentResume = [];
$voucherFile = null;
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$transactionId = $session->get($transactionIdSessionName);
$travellerInfo = json_decode($session->get($transactionId.'[hotel][detail_data_hotel]'));
if ($session->has($transactionId.'[crossed]'.'[url-hotel]') && !$session->has($transactionId.'[multi]'.'[validation]')) {
$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);
if ($session->has($transactionId.'external')) {
$routeParsed['path'] = $session->get('routePath');
}
$availabilityUrl = $router->match($routeParsed['path']);
$traveller = [];
$traveller['firstName'] = $travellerInfo->PI->first_name_1_1;
$traveller['lastName'] = $travellerInfo->PI->last_name_1_1;
if (false !== strpos($traveller['firstName'], '*')) {
$postDataJson = $session->get($transactionId.'[hotel][detail_data_hotel]');
$paymentData = json_decode($postDataJson);
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->BD->id);
$traveller['firstName'] = $customer->getFirstname();
$traveller['lastName'] = $customer->getLastname();
}
$orderProductCode = $session->get($transactionId.'[hotel][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$emailData = json_decode($orderProduct->getEmail(), true);
if ($session->has($transactionId.'[hotel][reservation]')) {
$reservationInfo = \simplexml_load_string($session->get($transactionId.'[hotel][reservation]'));
$reservationId = (string) $reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->UniqueID['ID'];
$reservationId2 = (string) $reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->ResGlobalInfo->HotelReservationIDs->HotelReservationID['ResID_Value'];
$traveller['ReservationID'] = $reservationId;
$traveller['HotelReservationID'] = $reservationId2;
if (('' == $emailData['journeySummary']['phone']) && isset($reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers) && isset($reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers->ContactNumber['PhoneNumber'])) {
$emailData['journeySummary']['phone'] = (string) $reservationInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->BasicPropertyInfo->ContactNumbers->ContactNumber['PhoneNumber'];
}
} else {
$traveller['ReservationID'] = null;
}
$rooms = [];
$response = \simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
foreach ($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate as $roomRatePlan) {
if ($roomRatePlan['RatePlanCode'] == $travellerInfo->HI->ratePlan) {
$i = 1;
foreach ($roomRatePlan->Rates->Rate as $roomRateText) {
for ($j = 0; $j < ((int) $roomRateText['NumberOfUnits']); ++$j) {
$rooms[$j + $i]['text'] = (string) $roomRateText->RateDescription->Text;
break;
}
$i = $i + $j;
}
$rooms[1]['roomRates'] = $roomRatePlan;
$rooms[1]['fullPricing'] = json_decode(base64_decode((string) $roomRatePlan->TotalAviatur['FullPricing']), true);
}
}
$adults = 0;
$childs = 0;
// Implementar logica para obtener el numero de adultos y niños en Tu Plus
if (!$agency->getName() === 'QA Aval') {
if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
for ($i = 1; $i <= $availabilityUrl['rooms']; ++$i) {
$adults += $availabilityUrl['adult' . $i];
$childrens = [];
if ('n' != $availabilityUrl['child' . $i]) {
$childAgesTemp = explode('-', $availabilityUrl['child' . $i]);
$childs += count($childAgesTemp);
}
}
} else {
$availabilityData = json_decode($session->get($transactionId . '[hotel][availability_data_hotel]'), TRUE);
if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
for ($i = 0; $i < $availabilityData['Rooms']; ++$i) {
$adults += $availabilityData['Adults' . $i] ?? 0;
if (isset($availabilityData['Children' . $i]) && $availabilityData['Children' . $i] > 0) {
$childs += $availabilityData['Children' . $i];
}
}
}
}
} else {
for ($i = 1; $i <= $availabilityUrl['rooms']; $i++) {
if ($availabilityUrl['child' . $i] == "n") {
$rooms[$i]['child'] = 0;
} else {
$rooms[$i]['child'] = substr_count($availabilityUrl['child' . $i], '-') + 1;
$rooms[$i]['childAges'] = $availabilityUrl['child' . $i];
}
$rooms[$i]['adult'] = $availabilityUrl['adult' . $i];
}
}
$postDataJson = $session->get($transactionId.'[hotel][detail_data_hotel]');
$paymentData = json_decode($postDataJson);
$opRequestInitial = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$opRequest = $opRequestInitial->multi_transaction_hotel ?? $opRequestInitial;
$opResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
//Destroy session URL TripAdvisor
if ($session->has($transactionId.'external')) {
$session->remove($transactionId.'external');
}
if ((null != $opRequest) && (null != $opResponse)) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->BD->id);
if (isset($opResponse->x_description)) {
$paymentResume = [
'transaction_state' => $opResponse->x_response_code,
'ta_transaction_state' => $opResponse->x_ta_response_code,
'id' => $orderProduct->getBooking(),
'id_context' => $opRequest->x_invoice_num,
'total_amount' => $opResponse->x_amount,
'currency' => $opResponse->x_bank_currency,
'amount' => 0 != $opRequest->x_amount_base ? $opRequest->x_amount_base : $opResponse->x_amount,
'iva' => $opRequest->x_tax,
'ip_address' => $opRequest->x_customer_ip,
'bank_name' => $opResponse->x_bank_name,
'cuotas' => $opRequest->x_differed,
'card_num' => '************'.substr($opRequest->x_card_num, strlen($opRequest->x_card_num) - 4),
'reference' => $opResponse->x_transaction_id,
'auth' => $opResponse->x_approval_code,
'transaction_date' => $opResponse->x_transaction_date,
'description' => $opResponse->x_description,
'reason_code' => $opResponse->x_response_reason_code,
'reason_description' => $opResponse->x_response_reason_text,
'client_names' => $opResponse->x_first_name.' '.$opResponse->x_last_name,
'client_email' => $opResponse->x_email,
];
} elseif (isset($opRequest->dataTransf)) {
if (isset($opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'})):
$state = $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'};
if (102 == $state):
$state = 1;
$reason_description = 'SafetyPay recibe la confirmación del pago de un Banco Asociado'; elseif (101 == $state):
$state = 2;
$reason_description = 'Transacción creada';
endif;
$paymentResume = [
'transaction_state' => $state,
'id' => $orderProduct->getBooking(),
'currency' => $opRequest->dataTransf->x_currency,
'total_amount' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:Amount'},
'amount' => null,
'iva' => null,
'ip_address' => $opRequest->dataTransf->dirIp,
'airport_tax' => null,
'reference' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:MerchantSalesID'},
'auth' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationID'},
'transaction_date' => $opResponse->payResponse->OperationResponse->ResponseDateTime,
'description' => $opRequest->dataTransf->x_description,
'reason_code' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'},
'reason_description' => $reason_description,
'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
'client_email' => $opRequest->dataTransf->x_email,
'x_payment_data' => $opRequest->dataTransf->x_payment_data,
'client_franquice' => ['description' => 'SafetyPay'],
]; else:
$paymentResume = [
'transaction_state' => 2,
'id' => $orderProduct->getBooking(),
'currency' => $opRequest->dataTransf->x_currency,
'total_amount' => $opRequest->dataTransf->x_total_amount,
'amount' => null,
'iva' => null,
'ip_address' => $opRequest->dataTransf->dirIp,
'airport_tax' => null,
'reference' => $opRequest->dataTransf->x_reference,
'auth' => null,
'transaction_date' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:RequestDateTime'},
'description' => $opRequest->dataTransf->x_description,
'reason_code' => 101,
'reason_description' => 'Transacción creada',
'x_payment_data' => $opRequest->dataTransf->x_payment_data,
'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
'client_email' => $opRequest->dataTransf->x_email,
];
endif;
if ('baloto' == $opRequest->dataTransf->x_payment_data) {
$paymentResume['transaction_state'] = 3;
}
} elseif (isset($opRequest->infoCash)) {
$paymentResume = [
'transaction_state' => 2,
'id' => $orderProduct->getBooking(),
'id_context' => $opRequest->infoCash->x_reference,
'currency' => $opRequest->infoCash->x_currency,
'total_amount' => $opRequest->infoCash->x_total_amount,
'client_franquice' => ['description' => 'Efectivo'],
'amount' => null,
'iva' => null,
'ip_address' => $opRequest->infoCash->dirIp,
'airport_tax' => null,
'reference' => $opRequest->infoCash->x_reference,
'auth' => null,
'transaction_date' => $opRequest->infoCash->x_fechavigencia,
'description' => $opRequest->infoCash->x_description,
'reason_code' => 101,
'reason_description' => 'Transacción creada',
'client_names' => $opRequest->infoCash->x_first_name.' '.$opRequest->infoCash->x_last_name,
'client_email' => $opRequest->infoCash->x_email,
'fecha_vigencia' => $opRequest->infoCash->x_fechavigencia,
];
$cash_result = json_decode($session->get($transactionId.'[hotel][cash_result]'));
$paymentResume['transaction_state'] = 3;
if ('' == $cash_result) {
$paymentResume['transaction_state'] = 2;
}
} else {
$bank_info = $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findOneByCode($opRequest->bankCode);
$bank_name = $bank_info->getName();
$clientFranquice['description'] = 'PSE';
$paymentResume = [
'transaction_state' => $opResponse->getTransactionInformationResult->responseCode,
'id' => $orderProduct->getBooking(),
'id_context' => $opRequest->reference,
'currency' => $opRequest->currency,
'total_amount' => $opRequest->totalAmount,
'amount' => $opRequest->devolutionBase,
'iva' => $opRequest->taxAmount,
'ip_address' => $opRequest->ipAddress,
'bank_name' => $bank_name,
'client_franquice' => $clientFranquice,
'reference' => $opResponse->createTransactionResult->transactionID,
'auth' => $opResponse->getTransactionInformationResult->trazabilityCode,
'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate,
'description' => $opRequest->description,
'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode,
'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText,
'client_names' => $opRequest->payer->firstName.' '.$opRequest->payer->lastName,
'client_email' => $opRequest->payer->emailAddress,
];
}
} else {
$customer = null;
$paymentResume['id'] = $orderProduct->getBooking();
}
if (isset($opRequest->redemptionPoints)) {
$paymentResume['pointsRedemption'] = $opRequest->redemptionPoints;
}
if (isset($opRequest->onlyRedemption)) {
$paymentResume['onlyRedemption'] = true;
}
$paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
if (false !== strpos($paymentData->BD->first_name, '***')) {
$facturationResume = [
'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
'customer_address' => $customer->getAddress(),
'customer_doc_num' => $customer->getDocumentnumber(),
'customer_phone' => $customer->getPhone(),
'customer_email' => $customer->getEmail(),
];
} else {
$facturationResume = [
'customer_names' => $paymentData->BD->first_name.' '.$paymentData->BD->last_name,
'customer_address' => $paymentData->BD->address ?? null,
'customer_doc_num' => $paymentData->BD->doc_num,
'customer_phone' => $paymentData->BD->phone,
'customer_email' => $paymentData->BD->email ?? null,
];
}
$clientFranquice = '';
$retryCount = (int) $session->get($transactionId.'[hotel][retry]');
if ($session->has($transactionId.'[user]')) {
$responseOrder = \simplexml_load_string($session->get($transactionId.'[user]'));
} else {
$responseOrder = null;
}
$emailData += [
'retry_count' => $retryCount,
'paymentResume' => $paymentResume,
'currency' => isset($paymentResume['currency']) ? $paymentResume['currency'] : '',
'facturationResume' => $facturationResume,
'agencyData' => $emailData['agencyData'],
'journeySummary' => $emailData['journeySummary'],
'transactionID' => $transactionId,
'rooms' => $rooms,
'traveller' => $traveller,
'ratePlan' => $travellerInfo->HI->ratePlan,
'agent' => $responseOrder,
];
//validacion de parametros vacios usando en twig
$emailData["paymentResume"]["reason_description"] = isset($emailData["paymentResume"]["reason_description"]) ? $emailData["paymentResume"]["reason_description"] : "";
$emailData["paymentResume"]["auth"] = isset($emailData["paymentResume"]["auth"]) ? $emailData["paymentResume"]["auth"] : "";
$emailData["paymentResume"]["reason_code"] = isset($emailData["paymentResume"]["reason_code"]) ? $emailData["paymentResume"]["reason_code"] : "";
$emailData["paymentResume"]["reference"] = isset($emailData["paymentResume"]["reference"]) ? $emailData["paymentResume"]["reference"] : "";
$emailData["paymentResume"]["total_amount"] = isset($emailData["paymentResume"]["total_amount"]) ? $emailData["paymentResume"]["total_amount"] : "";
$emailData["paymentResume"]["currency"] = isset($emailData["paymentResume"]["currency"]) ? $emailData["paymentResume"]["currency"] : "";
$orderProduct->setEmail(json_encode($emailData));
$em->persist($orderProduct);
$em->flush();
$isFront = $session->has('operatorId');
$pixelInfo = [];
$routeName = $request->get('_route');
if (!$isFront) {
// PIXELES INFORMATION
if (!$session->has('operatorId') && 1 == $paymentResume['transaction_state']) {
$pixel = json_decode($session->get($transactionId.'[pixeles_info]'), true);
$pixel['partner_datalayer']['event'] = 'hotelPurchase';
if (!isset($emailData['rooms'][1]['child'], $emailData['rooms'][1]['adult'])){
$quantity = json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
}
$products = [
'actionField' => "{'id': '".$paymentResume['id_context']."', 'affiliation': 'Portal Web', 'revenue': '".$paymentResume['total_amount']."', 'tax':'".$paymentResume['iva']."', 'coupon': ''}",
'name' => $emailData['journeySummary']['hotelName'],
'price' => $paymentResume['total_amount'],
'brand' => $emailData['journeySummary']['hotelName'],
'category' => 'Hotel',
'variant' => $emailData['rooms'][1]['text'] ?? '',
'quantity' => isset($emailData['rooms'][1]['child'], $emailData['rooms'][1]['adult'])
? ($emailData['rooms'][1]['child'] + $emailData['rooms'][1]['adult'])
: (($quantity['Children'] ?? 0) + ($quantity['Adults'] ?? 0)),
];
unset($pixel['partner_datalayer']['ecommerce']['checkout']);
$pixel['partner_datalayer']['ecommerce']['purchase']['products'] = $products;
//$pixel['dataxpand'] = true;
//$pixel['pickback'] = true;
if ($session->get($transactionId.'[hotel][kayakclickid]')) {
$pixel['kayakclickid'] = $session->get($transactionId.'[hotel][kayakclickid]');
if (isset($pixel['kayakclickid']) && 'aviatur_hotel_payment_success_secure' == $routeName) {
$kayakclickid = [
'kayakclickid' => $pixel['kayakclickid'],
'price' => $paymentResume['total_amount'],
'currency' => $paymentResume['currency'],
'confirmation' => $paymentResume['id_context'],
'rand' => microtime(true),
];
$pixel['kayakclickid'] = $kayakclickid;
}
}
$pixelInfo = $aviaturPixeles->verifyPixeles($pixel, 'hotel', 'resume', $agency->getAssetsFolder(), false);
}
}
$agencyFolder = $twigFolder->twigFlux();
$urlResume = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/resume.html.twig');
$emailData['journeySummary']['infoDataFlight'] = json_decode($session->get($transactionId.'[crossed]'.'[infoDataFlight]'), true);
/* * *
* Agente Octopus
* Cambiar logo Correo Gracias por su compra.
*/
$isAgent = false;
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
$agent = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
$isAgent = true;
$agent = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
$idAgentLogo = $agent->getId();
$folderImg = 'assets/octopus_assets/img/custom/logoAgent/'.$idAgentLogo.'.png';
$domain = 'https://'.$agency->getDomain();
$folderLogoAgent = $domain.'/'.$folderImg;
if (file_exists($folderImg)) {
$emailData['imgLogoAgent'] = $folderLogoAgent;
}
}
}
if ((('aviatur_hotel_payment_success_secure' == $routeName) || ('aviatur_hotel_reservation_success_secure' == $routeName)) && !$session->has($transactionId.'[multi][detail_cash]')) {
$voucherFile = $projectDir.'/app/serviceLogs/HotelVoucher/ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId().'_'.$transactionId.'.pdf';
if (!file_exists($voucherFile)) {
$bccMails = [$agency->getMailvouchers()];
if (!$isFront) {
$emissionData = $orderProduct->getEmissiondata();
if (('No Reservation' != $emissionData) && ('' != $emissionData) && (null != $emissionData)) {
$setTo = (null == $customer) ? null : $customer->getEmail();
} else {
$setTo = 'soptepagelectronic@aviatur.com';
}
if ($session->has('whitemark')) {
if ('' != $session->get('whitemarkMail')) {
$bccMails[] = $session->get('whitemarkMail');
$bccMails[] = 'sebastian.huertas@aviatur.com';
}
}
try {
$infoPdfHotel = ['retry_count' => $retryCount,
'paymentResume' => $paymentResume,
'facturationResume' => $facturationResume,
'agencyData' => $emailData['agencyData'],
'journeySummary' => $emailData['journeySummary'],
'transactionID' => $transactionId,
'rooms' => $rooms,
'traveller' => $traveller,
'agent' => $responseOrder,
'pdfGenerator' => true,
// dd($rooms),
];
if ($isAgent) {
$infoPdfHotel['imgLogoAgent'] = $emailData['imgLogoAgent'];
}
$pdf->generateFromHtml(
$this->renderView($urlResume, $infoPdfHotel),
$voucherFile
);
$bccMails[] = 'supervisorescallcenter@aviatur.com';
$setSubject = 'Gracias por su compra';
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
->setBcc($bccMails)
->setSubject($session->get('agencyShortName').' - '.$setSubject)
->attach(\Swift_Attachment::fromPath($voucherFile))
->setBody(
$this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
);
} catch (\Exception $e) {
$bccMails[] = 'lida.lugo@aviatur.com';
$emissionData = $orderProduct->getEmissiondata();
if (('No Reservation' != $emissionData) && ('' != $emissionData) && (null != $emissionData)) {
$setTo = (null == $customer) ? null : $customer->getEmail();
} else {
$setTo = 'soptepagelectronic@aviatur.com';
}
$setSubject = 'Gracias por su compra';
if (file_exists($voucherFile)) {
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
->setBcc($bccMails)
->setSubject($session->get('agencyShortName').' - '.$setSubject)
->attach(\Swift_Attachment::fromPath($voucherFile))
->setBody(
$this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
);
} else {
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
->setBcc($bccMails)
->setSubject($session->get('agencyShortName').' - '.$setSubject)
->setBody(
$this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
);
}
}
} else {
$bccMails[] = 'lida.lugo@aviatur.com';
$setTo = isset($responseOrder->CORREO_ELECTRONICO) ? (string) $responseOrder->CORREO_ELECTRONICO : null;
$setSubject = 'Gracias por tu reserva';
$emailData['front'] = true;
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
->setBcc($bccMails)
->setSubject($session->get('agencyShortName').' - '.$setSubject)
->setBody(
$this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
);
}
try {
$mailer->send($message);
$session->set($transactionId.'[emission_email]', 'emailed');
/*
* Agente Octopus
* Email de la reserva del agente hijo enviado al agente Padre Octopus.
*/
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
$agent = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
$request = $request;
$parent = $agent->getparentAgent();
if (0 != $parent) {
$myParent = $em->createQuery('SELECT a,b FROM AviaturAgentBundle:Agent a JOIN a.customer b WHERE a.id= :idAgent');
$myParent = $myParent->setParameter('idAgent', $parent);
$parentInfo = $myParent->getResult();
$emailParent = $parentInfo[0]->getCustomer()->getEmail();
$emailData['infoSubAgent'] = ['nameSubAgent' => strtoupper($agent->getCustomer()->__toString()), 'emailSubAgent' => strtoupper($agent->getCustomer()->getEmail())];
$messageAgent = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo([$agent->getCustomer()->getEmail(), $emailParent])
->setBcc($bccMails)
->setSubject($session->get('agencyShortName').' - Gracias por su compra - '.$customer->getFirstname().' '.$customer->getLastname().' Vendedor - '.$agent->getCustomer()->getFirstName().' '.$agent->getCustomer()->getLastName())
->setBody(
$this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
);
$mailer->send($messageAgent);
} else {
$messageAgent = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($agent->getCustomer()->getEmail())
->setBcc($bccMails)
->setSubject($session->get('agencyShortName').' - Gracias por su compra - '.$customer->getFirstname().' '.$customer->getLastname().' Vendedor - '.$agent->getCustomer()->getFirstName().' '.$agent->getCustomer()->getLastName())
->setBody(
$this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/email.html.twig'), $emailData)
);
$mailer->send($messageAgent);
}
}
}
} catch (Exception $ex) {
$exceptionLog->log(
var_dump($message),
$ex
);
}
}
// END Send confirmation email if success
}
$route = $router->match(str_replace($request->getSchemeAndHttpHost(), '', $request->getUri()));
$isMulti = false !== strpos($route['_route'], 'multi') ? true : false;
if ($isMulti) {
if ($session->has($transactionId.'[multi][cash_result]')) {
$paymentResume['transaction_state'] = 3;
}
return $this->json([
'retry_count' => $retryCount,
'paymentResume' => $paymentResume,
'facturationResume' => $facturationResume,
'agencyData' => $emailData['agencyData'],
'journeySummary' => $emailData['journeySummary'],
'transactionID' => $transactionId,
'rooms' => $rooms,
'traveller' => $traveller,
'agent' => $responseOrder,
]);
}
// delete items for geNerate other reservation of hotel after crossed sale
if (isset($paymentResume['transaction_state']) && 1 == $paymentResume['transaction_state'] && $session->has($transactionId.'[crossed]'.'[url-hotel]')) {
$session->remove($transactionId.'[hotel]'.'[retry]');
$session->remove($transactionId.'[hotel]'.'[prepayment_check]');
$session->remove($transactionId.'[hotel]'.'[order]');
}
if ($session->has($transactionId.'[hotel][cash_result]')) {
$paymentResume['cash_result'] = json_decode($session->get($transactionId.'[hotel][cash_result]'));
}
if (isset($paymentResume['id_context'])) {
$voucherFile = $projectDir.'/app/serviceLogs/CashTransaction/ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
if (file_exists($voucherFile)) {
$paymentResume['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
}
}
if (($session->has($transactionId.'[hotel][cash_result]') && !$isMulti) && !$session->has($transactionId.'[emission_baloto_email]')) {
$paymentResume['exportPDF'] = true;
$paymentResume['infos'][0]['agencyData'] = $emailData['agencyData'];
$paymentResume['infos'][0]['paymentResume']['id'] = $paymentResume['id_context'];
$paymentResume['infos'][0]['paymentResume']['total_amount'] = $paymentResume['total_amount'];
$paymentResume['infos'][0]['paymentResume']['fecha_vigencia'] = $paymentResume['fecha_vigencia'];
$paymentResume['infos'][0]['paymentResume']['description'] = $paymentResume['description'];
$ruta = '@AviaturTwig/'.$agencyFolder.'/General/Templates/email_cash.html.twig';
if (!file_exists($voucherFile)) {
$pdf->generateFromHtml($this->renderView($twigFolder->twigExists($ruta), $paymentResume), $voucherFile);
$paymentResume['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
}
$clientEmail = $paymentResume['client_email'];
$setTo = ['soportepagoelectronico@aviatur.com.co', 'soptepagelectronic@aviatur.com', $clientEmail];
$paymentResume['exportPDF'] = false;
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
->setBcc($emailNotification)
->setSubject($session->get('agencyShortName').' - '.'Transacción Efectivo Creada '.$paymentResume['id_context'])
->attach(\Swift_Attachment::fromPath($voucherFile))
->setBody(
$this->renderView($twigFolder->twigExists($ruta), $paymentResume)
);
try {
$mailer->send($message);
$session->set($transactionId.'[emission_baloto_email]', 'emailed');
} catch (Exception $ex) {
$exceptionLog->log(var_dump($message), $ex);
}
}
return $this->render($urlResume, [
'retry_count' => $retryCount,
'paymentResume' => $paymentResume,
'facturationResume' => $facturationResume,
'agencyData' => $emailData['agencyData'],
'journeySummary' => $emailData['journeySummary'],
'transactionID' => $transactionId,
'rooms' => $rooms,
'traveller' => $traveller,
'agent' => $responseOrder,
'pixel_info' => $pixelInfo,
]);
}
public function confirmationAction(SessionInterface $session, AviaturXsltRender $renderxslt, TwigFolder $twigFolder, ManagerRegistry $registry, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$em = $this->managerRegistry;
$transactionId = $session->get($transactionIdSessionName);
$response = $session->get($transactionId.'[rates]');
$xml = simplexml_load_string((string) $response)->TotalAviatur;
$postDataJson = $session->get($transactionId.'[hotel][detail_data_hotel]');
$postData = json_decode($postDataJson);
$docType = '';
$docNumber = '';
$names = '';
$lastNames = '';
$address = '';
$phone = '';
$email = '';
if (strpos($postData->BD->first_name, '***') > 0) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$docType = $customer->getDocumentType()->getExternalcode();
$docNumber = $customer->getDocumentnumber();
$names = $customer->getFirstname();
$lastNames = $customer->getLastname();
$address = $customer->getAddress();
$phone = $customer->getPhone();
$email = $customer->getEmail();
} else {
$docType = $postData->BD->doc_type;
$docNumber = $postData->BD->doc_num;
$names = $postData->BD->first_name;
$lastNames = $postData->BD->last_name;
$address = $postData->BD->address;
$phone = $postData->BD->phone;
$email = $postData->BD->email;
}
$iataOrigin = (string) $xml->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'];
$iataDestinity = (string) $xml->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'];
$from = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($iataOrigin);
$to = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findOneByIatacode($iataDestinity);
$plantilla = $renderxslt->render($xml->asXML(), 'Hotel', 'Resume');
$agencyFolder = $twigFolder->twigFlux();
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/confirmation.html.twig'), [
'from_iata' => $iataOrigin,
'to_iata' => $iataDestinity,
'from' => $from->getDescription(),
'to' => $to->getDescription(),
'template' => $plantilla,
'docType' => $docType,
'docNumber' => $docNumber,
'names' => $names,
'lastNames' => $lastNames,
'address' => $address,
'phone' => $phone,
'email' => $email,
'total_amount' => (string) $xml['TotalAmount'],
'currency_code' => (string) $xml['CurrencyCode'],
]);
}
public function metasearchAvailabilityAction(Request $request, SessionInterface $session, ManagerRegistry $registry, AuthorizationCheckerInterface $authorizationChecker, ParameterBagInterface $parameterBag, $token)
{
$projectDir = $parameterBag->get('kernel.project_dir');
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturServiceWebInvoker = $parameterBag->get('aviatur_service_web_invoker');
$aviaturServiceWebRequestId = $parameterBag->get('aviatur_service_web_request_id');
$AvailabilityArray = [];
$providers = [];
$makeLogin = null;
$options = [];
$starttime = microtime(true);
$em = $this->managerRegistry;
$metasearch = $em->getRepository(\Aviatur\GeneralBundle\Entity\Metasearch::class)->findOneByToken($token);
if (null != $metasearch) {
$fullRequest = $request;
$session = $fullRequest->getSession();
$agency = $metasearch->getAgency();
$tempRequest = explode('<OTA_HotelAvailRQ', file_get_contents('php://input'));
$tempRequest = explode('</OTA_HotelAvailRQ', $tempRequest[1]);
$request = '<OTA_HotelAvailRQ'.$tempRequest[0].'</OTA_HotelAvailRQ>';
$xmlRequestObject = simplexml_load_string($request);
$rooms = 0;
$child1 = null;
$adult2 = null;
$child2 = null;
$adult3 = null;
$child3 = null;
$services = [];
foreach ($xmlRequestObject->AvailRequestSegments->AvailRequestSegment->RoomStayCandidates->RoomStayCandidate as $roomStay) {
++$rooms;
${'adult'.$rooms} = 0;
$childArray = [];
$services[$rooms]['adults'] = 0;
$services[$rooms]['childrens'] = [];
foreach ($roomStay->GuestCounts->GuestCount as $guestCount) {
if (!isset($guestCount['Age'])) {
${'adult'.$rooms} += (int) $guestCount['Count'];
$services[$rooms]['adults'] = ${'adult'.$rooms};
} else {
$childArray[] = (string) $guestCount['Age'];
${'child'.$rooms} = implode('-', $childArray);
$services[$rooms]['childrens'] = $childArray;
}
}
}
$destination = (string) $xmlRequestObject->AvailRequestSegments->AvailRequestSegment->HotelSearchCriteria->Criterion->HotelRef['HotelCityCode'];
$date1 = (string) $xmlRequestObject->AvailRequestSegments->AvailRequestSegment->StayDateRange['Start'];
$date2 = (string) $xmlRequestObject->AvailRequestSegments->AvailRequestSegment->StayDateRange['End'];
$destinationObject = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($destination);
if (null != $destinationObject) {
$AvailabilityArray['cityName'] = $destinationObject->getCity();
$AvailabilityArray['countryCode'] = $destinationObject->getCountrycode();
} else {
$response = new \SimpleXMLElement('<Response></Response>');
$response->addChild('error', 'La ciudad ingresada no es válida');
}
if ($destinationObject) {
$currency = 'COP';
if ($session->has('hotelAdapterId')) {
$providers = explode(';', $session->get('hotelAdapterId'));
$providerObjects = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findByProvideridentifier($providers);
$configsHotelAgency = $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findBy(['provider' => $providerObjects, 'agency' => $agency]);
} else {
$configsHotelAgency = $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findProviderForHotelsWithAgency($agency);
}
if ($configsHotelAgency) {
$providers = [];
foreach ($configsHotelAgency as $configHotelAgency) {
$providers[] = $configHotelAgency->getProvider()->getProvideridentifier();
if (strpos($configHotelAgency->getProvider()->getName(), '-USD')) {
$currency = 'USD';
}
}
} else {
$response = new \SimpleXMLElement('<Response></Response>');
$response->addChild('error', 'No se encontró agencias para consultar disponibilidad.');
}
$hotelModel = new HotelModel();
$xmlTemplate = $hotelModel->getXmlAvailability();
$xmlRequest = $xmlTemplate[0];
$provider = implode(';', $providers);
$requestLanguage = mb_strtoupper($fullRequest->getLocale());
$variable = [
'ProviderId' => $provider,
'date1' => $date1,
'date2' => $date2,
'destination' => $destination,
'country' => $destinationObject->getCountrycode(),
'language' => $requestLanguage,
'currency' => $currency,
'userIp' => $fullRequest->getClientIp(),
'userAgent' => $fullRequest->headers->get('User-Agent'),
];
$i = 1;
foreach ($services as $room) {
$xmlRequest .= str_replace('templateAdults', 'adults_'.$i, $xmlTemplate[1]);
$j = 1;
foreach ($room['childrens'] as $child) {
$xmlRequest .= str_replace('templateChild', 'child_'.$i.'_'.$j, $xmlTemplate[2]);
$variable['child_'.$i.'_'.$j] = $child;
++$j;
}
$variable['adults_'.$i] = $room['adults'];
$xmlRequest .= $xmlTemplate[3];
++$i;
}
$xmlRequest .= $xmlTemplate[4];
$transactionIdResponse = $aviaturWebService->loginService('SERVICIO_MPT', 'dummy|http://www.aviatur.com.co/dummy/', $variable['ProviderId']);
if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
$response = new \SimpleXMLElement('<Response></Response>');
$response->addChild('error', 'Estamos experimentando dificultades técnicas en este momento.');
$aviaturErrorHandler->errorRedirect('', 'Error MPA', 'No se creo Login!');
}
$transactionId = (string) $transactionIdResponse;
$variable['transaction'] = $transactionId;
$session->set($transactionIdSessionName, $transactionId);
$metatransaction = new Metatransaction();
$metatransaction->setTransactionId((string) $transactionId);
$metatransaction->setDatetime(new \DateTime());
$metatransaction->setIsactive(true);
$metatransaction->setMetasearch($metasearch);
$em->persist($metatransaction);
$em->flush();
$preResponse = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'HotelAvail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false);
if (isset($preResponse['error'])) {
if (false === strpos($preResponse['error'], '66002')) {
$aviaturErrorHandler->errorRedirect($fullRequest->server->get('REQUEST_URI'), 'Error disponibilidad hoteles', $preResponse['error']);
}
$preResponse = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'HotelAvail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, $makeLogin);
if (isset($preResponse['error'])) {
if (false === strpos($preResponse['error'], '66002')) {
$aviaturErrorHandler->errorRedirect($fullRequest->server->get('REQUEST_URI'), 'Error disponibilidad hoteles', $preResponse['error']);
}
$response = new \SimpleXMLElement('<Response></Response>');
$response->addChild('error', $preResponse['error']);
}
} elseif (empty((array) $preResponse->Message)) {
$aviaturErrorHandler->errorRedirect($fullRequest->server->get('REQUEST_URI'), 'Error disponibilidad hoteles', $preResponse->Message);
$response = new \SimpleXMLElement('<Response></Response>');
$response->addChild('error', 'No hemos encontrado información para el destino solicitado.');
}
if (!isset($response)) {
$searchImages = ['hotelbeds.com/giata/small', '/100x100/', '_tn.jpg', '<p><b>Ubicación del establecimiento</b> <br />'];
$replaceImages = ['hotelbeds.com/giata', '/200x200/', '.jpg', ''];
$response = simplexml_load_string(str_replace($searchImages, $replaceImages, $preResponse->asXML()));
$response->Message->OTA_HotelAvailRS['StartDate'] = $date1;
$response->Message->OTA_HotelAvailRS['EndDate'] = $date2;
$response->Message->OTA_HotelAvailRS['Country'] = $variable['country'];
$configHotelAgencyIds = [];
foreach ($configsHotelAgency as $configHotelAgency) {
$configHotelAgencyIds[] = $configHotelAgency->getId();
$providerOfConfig[$configHotelAgency->getId()] = $configHotelAgency->getProvider()->getProvideridentifier();
$typeOfConfig[$configHotelAgency->getId()] = $configHotelAgency->getType();
}
$markups = $em->getRepository(\Aviatur\HotelBundle\Entity\Markup::class)->getMarkups($configHotelAgencyIds, $destinationObject->getId());
$domain = $fullRequest->getHost();
$parametersJson = $session->get($domain.'[parameters]');
$parameters = json_decode($parametersJson);
$tax = (float) $parameters->aviatur_payment_iva;
$currencyCode = (string) $response->Message->OTA_HotelAvailRS->RoomStays->RoomStay->RoomRates->RoomRate->Total['CurrencyCode'];
if ('COP' != $currencyCode && 'COP' == $currency) {
$trm = $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->recentTrm($currencyCode);
$trm = $trm[0]['value'];
} else {
$trm = 1;
}
$key = 0;
$searchHotelCodes = ['|', '/'];
$replaceHotelCodes = ['--', '---'];
//load discount info if applicable
//$aviaturLogSave->logSave(print_r($session, true), 'Bpcs', 'availSession');
foreach ($response->Message->OTA_HotelAvailRS->RoomStays->RoomStay as $roomStay) {
$roomStay['Show'] = '1';
$roomStay->BasicPropertyInfo['HotelCode'] = str_replace($searchHotelCodes, $replaceHotelCodes, (string) $roomStay->BasicPropertyInfo['HotelCode']);
$hotelCode = $roomStay->BasicPropertyInfo['HotelCode'];
$hotelEntity = $em->getRepository(\Aviatur\HotelBundle\Entity\Hotel::class)->findOneByCodhotel($hotelCode);
$hotel = $hotelEntity ? $hotelEntity->getId() : null;
$roomRate = $roomStay->RoomRates->RoomRate;
$i = 0;
$markup = false;
while (!$markup) {
if (($markups[$i]['hotel_id'] == $hotel || null == $markups[$i]['hotel_id']) && ($providerOfConfig[$markups[$i]['config_hotel_agency_id']] == (string) $roomStay->TPA_Extensions->HotelInfo->providerID)) {
// if ($hotelEntity != null) {
// $markups[$i]['value'] = $hotelEntity->getMarkupValue();
// }
if ('N' == $typeOfConfig[$markups[$i]['config_hotel_agency_id']]) {
$aviaturMarkup = (float) $roomRate->Total['AmountIncludingMarkup'] * $markups[$i]['value'] / (100 - $markups[$i]['value']);
} else {
$aviaturMarkup = 0;
}
$roomRate->Total['AmountAviaturMarkup'] = $aviaturMarkup;
if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
$roomRate->Total['AmountAviaturMarkupTax'] = 0;
} else {
$roomRate->Total['AmountAviaturMarkupTax'] = $aviaturMarkup * $tax;
}
$roomRate->Total['AmountIncludingAviaturMarkup'] = round((float) $roomRate->Total['AmountAfterTax'] + $aviaturMarkup + $roomRate->Total['AmountAviaturMarkupTax'], (int) $roomRate->Total['DecimalPlaces']);
$roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round(((float) $aviaturMarkup + (float) $roomRate->Total['AmountIncludingMarkup']) * $trm, (int) $roomRate->Total['DecimalPlaces']);
if ('COP' == $currencyCode) {
$roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'], (int) $roomRate->Total['DecimalPlaces']);
}
if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
$roomRate->TotalAviatur['AmountTax'] = 0;
} else {
$roomRate->TotalAviatur['AmountTax'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $tax, (int) $roomRate->Total['DecimalPlaces']);
}
$roomRate->TotalAviatur['AmountTotal'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] + $roomRate->TotalAviatur['AmountTax'];
$roomRate->TotalAviatur['CurrencyCode'] = $currency;
$roomRate->TotalAviatur['Markup'] = $markups[$i]['value'];
$roomStay->BasicPropertyInfo['HotelCode'] .= '-'.$markups[$i]['id'];
$roomRate->TotalAviatur['MarkupId'] = $markups[$i]['id'];
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING') && $session->get($transactionId.'_isActiveQse')) {
$agent = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
if (!empty($agent) && $agent->getAgency()->getId() === $agency->getId()) {
/* * revisar */
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agent);
$commissionPercentage = $agentCommission->getHotelcommission();
$roomRate->TotalAviatur['AgentComission'] = round($commissionPercentage * $roomRate->TotalAviatur['AmountIncludingAviaturMarkup']);
}
}
if (false == $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING')) {
$roomRate->TotalAviatur['submitBuy'] = '1';
}
$markup = true;
}
++$i;
}
$roomStay->TPA_Extensions->HotelInfo->Category['Code'] = (int) $roomStay->TPA_Extensions->HotelInfo->Category['Code'];
$dividerStar = explode(' ', $roomStay->TPA_Extensions->HotelInfo->Category['CodeDetail']);
$roomStay->TPA_Extensions->HotelInfo->Category['CodeDetail'] = (int) $dividerStar[0].' '.$dividerStar[1];
$options[$key]['amount'] = (float) $roomStay->RoomRates->RoomRate->TotalAviatur['AmountTotal'];
$options[$key]['xml'] = $roomStay->asXml();
++$key;
}
usort($options, fn($a, $b) => $a['amount'] - $b['amount']);
$responseXml = explode('<RoomStay>', str_replace(['</RoomStay>', '<RoomStay InfoSource="B2C" Show="1">', '<RoomStay InfoSource="B2C" Show="0">'], '<RoomStay>', $response->asXml()));
$orderedResponse = $responseXml[0];
foreach ($options as $option) {
$orderedResponse .= $option['xml'];
}
$orderedResponse .= $responseXml[sizeof($responseXml) - 1];
$response = \simplexml_load_string($orderedResponse);
$response->Version = ('' != $response->Version) ? $response->Version : '2.0';
$response->Language = ('' != $response->Language) ? $response->Language : 'es';
$response->ResponseType = ('' != $response->ResponseType) ? $response->ResponseType : 'XML';
$response->ExecutionMessages->Fecha ??= date('d/m/Y H:i:s');
$response->ExecutionMessages->Servidor ??= 'MPB';
$response->Message->OTA_HotelAvailRS['Version'] = '';
$response->Message->OTA_HotelAvailRS['SequenceNmbr'] = '1';
$response->Message->OTA_HotelAvailRS['CorrelationID'] = '';
$response->Message->OTA_HotelAvailRS['TransactionIdentifier'] = $transactionId.'||'.$metasearch->getId();
$response->Message->OTA_HotelAvailRS['TransactionID'] = $transactionId.'||'.$metasearch->getId();
$endtime = microtime(true);
$response->ExecutionMessages->TiempoEjecucion = $endtime - $starttime;
}
} elseif (isset($xmlResponse['error'])) {
$response = new \SimpleXMLElement('<Response></Response>');
$response->addChild('error', $xmlResponse['error']);
} else {
$response = new \SimpleXMLElement('<Response></Response>');
$response->addChild('error', 'Respuesta vacia del servicio');
}
} else {
$feeVariables = null;
$xmlResponse = null;
$aviaturErrorHandler->errorRedirect(json_encode($feeVariables), '', 'Claves Invalidas');
$response = new \SimpleXMLElement('<Response></Response>');
$response->addChild('error', 'Invalid Keys');
}
$path = $projectDir.'/app/xmlService/aviaturResponse.xml';
$arrayIndex = [
'{xmlBody}',
'{service}',
'{invoker}',
'{provider}',
'{requestId}',
];
$arrayValues = [
str_replace('<?xml version="1.0"?>', '', $response->asXML()),
'SERVICIO_MPT',
$aviaturServiceWebInvoker,
'dummy|http://www.aviatur.com.co/dummy/',
$aviaturServiceWebRequestId,
];
$xmlBase = simplexml_load_file($path)->asXML();
$metaResponse = str_replace($arrayIndex, $arrayValues, $xmlBase);
return new Response($metaResponse, Response::HTTP_OK, ['content-type' => 'text/xml']);
}
public function generate_email(SessionInterface $session, ManagerRegistry $registry, $orderProduct, $detailInfo, $prepaymentInfo, $startDate, $endDate)
{
$em = $registry->getManager();
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$agencyData = [
'agency_name' => $agency->getName(),
'agency_nit' => $agency->getNit(),
'agency_phone' => $agency->getPhone(),
'agency_email' => $agency->getMailContact(),
];
$emailInfos = $detailInfo->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo;
$emailInfos2 = $detailInfo->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->TPA_Extensions->HotelInfo;
$i = 0;
$pictures = [];
foreach ($emailInfos2->MultimediaDescription->ImageItems->ImageItem as $picture) {
if ($i < 3) {
$pictures[] = (string) $picture->ImageFormat->URL;
}
++$i;
}
if (0 == sizeof($pictures)) {
$domain = 'https://'.$agency->getDomain();
$pictures[0] = $domain.'/assets/aviatur_assets/img/error/noHotelPicture.jpg';
}
$cancelPolicies = (string) $prepaymentInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->RoomStays->RoomStay->CancelPenalties->CancelPenalty->PenaltyDescription->Text;
$checkinInstructions = (string) $prepaymentInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->TPA_Extensions->Comments;
$payable = (string) $prepaymentInfo->Message->OTA_HotelResRS->HotelReservations->HotelReservation->TPA_Extensions->Payable;
$journeySummary = [
'hotelName' => (string) $emailInfos['HotelName'],
'stars' => (string) $emailInfos2->Category['Code'],
'startDate' => $startDate,
'endDate' => $endDate,
'address' => (string) $emailInfos->Address->AddressLine.', '.(string) $emailInfos->Address->CityName,
'phone' => (string) $emailInfos->ContactNumbers->ContactNumber['PhoneNumber'],
'email' => (string) $emailInfos2->Email,
'pictures' => $pictures,
'latitude' => (string) $emailInfos->Position['Latitude'],
'longitude' => (string) $emailInfos->Position['Longitude'],
'cancelPolicies' => $cancelPolicies,
'checkinInstructions' => $checkinInstructions,
'payable' => $payable,
];
$emailData = [
'agencyData' => $agencyData,
'journeySummary' => $journeySummary,
];
$orderProduct->setEmail(json_encode($emailData));
$em->persist($orderProduct);
$em->flush();
}
public function indexAction(Request $fullRequest, AuthorizationCheckerInterface $authorizationChecker, PaginatorInterface $knpPaginator, AviaturErrorHandler $aviaturErrorHandler, TwigFolder $twigFolder, $page, $active, $search = null)
{
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$routeParams = $fullRequest->attributes->get('_route_params');
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), $routeParams);
$agencyId = $session->get('agencyId');
$agencyFolder = $twigFolder->twigFlux();
if ($fullRequest->isXmlHttpRequest()) {
$query = $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.id = :id AND a.isactive = 1 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
$query = $query->setParameter('agency', $agency);
$query = $query->setParameter('id', $search);
$queryIn = $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.id = :id AND a.isactive = 0 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
$queryIn = $queryIn->setParameter('agency', $agency);
$queryIn = $queryIn->setParameter('id', $search);
$path = '/Hotel/Hotel/Ajaxindex_content.html.twig';
$urlReturn = '@AviaturTwig/'.$agencyFolder.$path;
if ('activo' == $active) {
$articulos = $query->getResult();
} elseif ('inactivo' == $active) {
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_CREATE_'.$agencyId) || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_EDIT_'.$agencyId) || $authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
$articulos = $queryIn->getResult();
} else {
return $this->redirect($twigFolder->pathWithLocale('aviatur_general_homepage'));
}
}
$actualArticles = [];
foreach ($articulos as $articulo) {
$description = json_decode($articulo->getDescription(), true);
if ($description && is_array($description)) {
$actualArticles[] = $articulo;
$type = $description['type2'];
}
}
if (empty($actualArticles)) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/', '', 'No existen contenidos para esta agencia.'));
}
$cantdatos = count($actualArticles);
$cantRegis = 10;
$totalRegi = ceil($cantdatos / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($actualArticles, $fullRequest->query->get('page', $page), $cantRegis);
if (isset($type)) {
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $pagination, 'page' => $page, 'active' => $active, 'totalRegi' => $totalRegi, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type]);
} else {
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $pagination, 'page' => $page, 'active' => $active, 'totalRegi' => $totalRegi, 'ajaxUrl' => $requestUrl]);
}
} else {
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/index_hotel.html.twig'), ['agencyId' => $agencyId]);
}
}
public function listAction(Request $fullRequest, AuthorizationCheckerInterface $authorizationChecker, PaginatorInterface $knpPaginator, AviaturErrorHandler $aviaturErrorHandler, TwigFolder $twigFolder, $page, $active, $type)
{
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$routeParams = $fullRequest->attributes->get('_route_params');
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), $routeParams);
$agencyId = $session->get('agencyId');
$agencyFolder = $twigFolder->twigFlux();
$query = $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.isactive = 1 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
$query = $query->setParameter('agency', $agency);
$queryIn = $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.isactive = 0 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
$queryIn = $queryIn->setParameter('agency', $agency);
$path = '/Hotel/Hotel/index_content.html.twig';
$urlReturn = '@AviaturTwig/'.$agencyFolder.$path;
$booking = false;
$configHotelAgency = $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findBy(['agency' => $agencyId]);
foreach ($configHotelAgency as $agency) {
if ('B' == $agency->getType()) {
$booking = true;
$domain = $agency->getWsUrl();
}
}
if ($session->has('operatorId')) {
$operatorId = $session->get('operatorId');
}
$colombia = [];
$america = [];
$oceania = [];
$europa = [];
$africa = [];
$asia = [];
$destino = [];
$cantRegis = 9;
if ('activo' == $active) {
$articulos = $query->getResult();
} elseif ('inactivo' == $active) {
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_CREATE_'.$agencyId) || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_EDIT_'.$agencyId) || $authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
$articulos = $queryIn->getResult();
foreach ($articulos as $articulo) {
$description = json_decode($articulo->getDescription(), true);
if ($description && is_array($description)) {
if (isset($description['type']) && 'hoteles' == $description['type']) {
if (isset($description['type2'])) {
if ('colombia' == $description['type2']) {
$colombia[] = $articulo;
}
if ('america' == $description['type2']) {
$america[] = $articulo;
}
if ('oceania' == $description['type2']) {
$oceania[] = $articulo;
}
if ('europa' == $description['type2']) {
$europa[] = $articulo;
}
if ('africa' == $description['type2']) {
$africa[] = $articulo;
}
if ('asia' == $description['type2']) {
$asia[] = $articulo;
}
if ('destino' == $description['type2']) {
$destino[] = $articulo;
}
}
}
}
}
if (empty($colombia) && empty($america) && empty($oceania) && empty($europa) && empty($africa) && empty($asia)) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/', '', 'No existen contenidos para esta agencia.'));
}
/* Redireccion hoteles por division */
if ('colombia' == $type) {
$cantDestinosC = count($colombia);
$totalDestinosC = ceil($cantDestinosC / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($colombia, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'SMR';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $colombia, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosC, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('america' == $type) {
$cantDestinosA = count($america);
$totalDestinosA = ceil($cantDestinosA / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($america, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'MIA';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $america, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosA, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('oceania' == $type) {
$cantDestinosO = count($oceania);
$totalDestinosO = ceil($cantDestinosO / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($oceania, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'SYD';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $oceania, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosO, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('europa' == $type) {
$cantDestinosE = count($europa);
$totalDestinosE = ceil($cantDestinosE / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($europa, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'MAD';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $europa, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosE, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('africa' == $type) {
$cantDestinosAF = count($africa);
$totalDestinosAF = ceil($cantDestinosAF / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($africa, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'CAI';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $africa, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosAF, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('asia' == $type) {
$cantDestinosAS = count($asia);
$totalDestinosAS = ceil($cantDestinosAS / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($asia, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'TYO';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $asia, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosAS, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('destino' == $type) {
$cantDestinosD = count($destino);
$totalDestinosD = ceil($cantDestinosD / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($destino, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'SMR';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $destino, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosD, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
} else {
return $this->redirect($twigFolder->pathWithLocale('aviatur_general_homepage'));
}
}
foreach ($articulos as $articulo) {
$description = json_decode($articulo->getDescription(), true);
if ($description && is_array($description)) {
if (isset($description['type']) && 'hoteles' == $description['type']) {
if (isset($description['type2'])) {
if ('colombia' == $description['type2']) {
$colombia[] = $articulo;
}
if ('america' == $description['type2']) {
$america[] = $articulo;
}
if ('oceania' == $description['type2']) {
$oceania[] = $articulo;
}
if ('europa' == $description['type2']) {
$europa[] = $articulo;
}
if ('africa' == $description['type2']) {
$africa[] = $articulo;
}
if ('asia' == $description['type2']) {
$asia[] = $articulo;
}
if ('destino' == $description['type2']) {
$destino[] = $articulo;
}
}
}
}
}
if (empty($colombia) && empty($america) && empty($oceania) && empty($europa) && empty($africa) && empty($asia)) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/', '', 'No existen contenidos para esta agencia.'));
}
/* Redireccion hoteles según división */
if ('colombia' == $type) {
$cantDestinosC = count($colombia);
$totalDestinosC = ceil($cantDestinosC / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($colombia, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'SMR';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $colombia, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosC, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('america' == $type) {
$cantDestinosA = count($america);
$totalDestinosA = ceil($cantDestinosA / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($america, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'MIA';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $america, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosA, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('oceania' == $type) {
$cantDestinosO = count($oceania);
$totalDestinosO = ceil($cantDestinosO / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($oceania, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'SYD';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $oceania, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosO, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('europa' == $type) {
$cantDestinosE = count($europa);
$totalDestinosE = ceil($cantDestinosE / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($europa, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'MAD';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $europa, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosE, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('africa' == $type) {
$cantDestinosAF = count($africa);
$totalDestinosAF = ceil($cantDestinosAF / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($africa, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'CAI';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $africa, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosAF, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('asia' == $type) {
$cantDestinosAS = count($asia);
$totalDestinosAS = ceil($cantDestinosAS / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($asia, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'TYO';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $asia, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosAS, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
if ('destino' == $type) {
$cantDestinosD = count($destino);
$totalDestinosD = ceil($cantDestinosD / $cantRegis);
$paginator = $knpPaginator;
$pagination = $paginator->paginate($asia, $fullRequest->query->get('page', $page), $cantRegis);
$cookieArray = [];
$cookieArray['destination'] = 'SMR';
if (isset($cookieArray['destination']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
return $this->render($twigFolder->twigExists($urlReturn), ['articulo' => $destino, 'page' => $page, 'active' => $active, 'totalRegi' => $totalDestinosD, 'ajaxUrl' => $requestUrl, 'typeArticle' => $type, 'params' => $routeParams, 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
}
public function viewAction(TwigFolder $twigFolder, $id)
{
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$agencyId = $session->get('agencyId');
$articulo = $em->getRepository(\Aviatur\ContentBundle\Entity\Content::class)->findByAgencyTypeNull($session->get('agencyId'), $id, '%\"hoteles\"%');
$promoType = '';
if (isset($articulo[0]) && (null != $articulo[0])) {
$agencyFolder = $twigFolder->twigFlux();
$description = json_decode($articulo[0]->getDescription(), true);
// determine content type based on eventual json encoded description
$HotelesPromoList = $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromoList::class)->findOneBy(['type' => 'hoteles-destino'.$promoType, 'agency' => $agency]);
if (null != $HotelesPromoList) {
$HotelPromoList = $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromo::class)->findByHomePromoList($HotelesPromoList, ['date' => 'DESC']);
} else {
$HotelPromoList = [];
}
$booking = false;
$configHotelAgency = $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findBy(['agency' => $agencyId]);
foreach ($configHotelAgency as $agency) {
if ('B' == $agency->getType()) {
$booking = true;
$domain = $agency->getWsUrl();
}
}
if ($session->has('operatorId')) {
$operatorId = $session->get('operatorId');
}
// determine content type based on eventual json encoded description
if ($description && is_array($description)) {
if (isset($description['type']) && 'hoteles' == $description['type']) {
// eg: {"type":"hoteles","type2":"nuevo|colombia|america|oceania|europa|africa|asia" , "description":"texto", "origin1":"BOG", "destination1":"MDE", "date1":"2016-11-18", "date2":"2016-11-25", "adults":"2", "children":"", "infants":""}
$cookieArrayH = [];
$cookieArray = [];
foreach ($description as $key => $value) {
$cookieArrayH[$key] = $value;
}
if (isset($cookieArrayH['origin1']) && (preg_match('/^[A-Z]{3}$/', $cookieArrayH['origin1']) || 'A28' == $cookieArrayH['origin1'] || 'A01' == $cookieArrayH['origin1'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArrayH['origin1']]);
$cookieArray['destinationLabel'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['destinationLabel'] = '';
}
$cookieArray['destination'] = $cookieArrayH['origin1'];
$cookieArray['adults'] = '';
$cookieArray['children'] = '';
$cookieArray['childAge'] = '';
$cookieArray['date1'] = '';
$cookieArray['date2'] = '';
$cookieArray['description'] = $cookieArrayH['description'];
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/view_content.html.twig'), ['articulo' => $articulo[0], 'cookieLastSearch' => $cookieArray, 'booking' => $booking, 'hotelPromos' => $HotelPromoList, 'promoType' => 'hoteles-destino', 'domain' => $domain ?? null, 'agencyId' => $agencyId ?? null, 'operatorId' => $operatorId ?? null]);
}
} else {
throw $this->createNotFoundException('Contenido no encontrado');
}
} else {
throw $this->createNotFoundException('Contenido no encontrado');
}
}
public function searchHotelsAction(Request $request)
{
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
if ($request->isXmlHttpRequest()) {
$term = $request->query->get('term');
$url = $request->query->get('url');
$queryIn = $em->createQuery('SELECT a.id, a.title, a.url, a.description, a.isactive FROM AviaturContentBundle:Content a WHERE a.title LIKE :title AND a.description LIKE :description AND (a.agency = :agency OR a.agency IS NULL)');
$queryIn = $queryIn->setParameter('title', '%'.$term.'%');
$queryIn = $queryIn->setParameter('description', '%\"hoteles\"%');
$queryIn = $queryIn->setParameter('agency', $agency);
$articulos = $queryIn->getResult();
$type = '';
$json_template = '<value>:<label>*';
$json = '';
if ($articulos) {
foreach ($articulos as $contenidos) {
$description = json_decode($contenidos['description'], true);
if (null == $description || is_array($description)) {
if (isset($description['type'])) {
$type = $description['type'];
}
}
$json .= str_replace(['<value>', '<label>'], [$contenidos['id'].'|'.$type.'|'.$contenidos['url'], $contenidos['title']], $json_template);
}
$json = \rtrim($json, '-');
} else {
$json = 'NN:No hay Resultados';
}
$response = \rtrim($json, '*');
return new Response($response);
} else {
return new Response('Acceso Restringido');
}
}
public function quotationAction(Request $fullRequest, AviaturLogSave $aviaturLogSave, AviaturWebService $aviaturWebService, AviaturErrorHandler $aviaturErrorHandler, \Swift_Mailer $mailer, ExceptionLog $exceptionLog, Pdf $pdf, RouterInterface $router, TwigFolder $twigFolder, ManagerRegistry $registry, ParameterBagInterface $parameterBag)
{
$projectDir = $parameterBag->get('kernel.project_dir');
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$codImg = null;
$session = $this->session;
$agency = $this->agency;
$transactionId = $session->get($transactionIdSessionName);
$prepaymentInfo = \simplexml_load_string($session->get($transactionId.'[hotel][prepayment]'));
$agencyFolder = $twigFolder->twigFlux();
$response = simplexml_load_string($session->get($transactionId.'[hotel][detail]'));
$additionalUserFront = simplexml_load_string($session->get('front_user_additionals'));
$detailHotelRaw = $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay;
$locationHotel = $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->BasicPropertyInfo->Position;
$dateIn = strtotime((string) $response->Message->OTA_HotelRoomListRS['StartDate']);
$dateOut = strtotime((string) $response->Message->OTA_HotelRoomListRS['EndDate']);
$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 = [];
$adults = 0;
$childs = 0;
if (isset($availabilityUrl['rooms']) && $availabilityUrl['rooms'] > 0) {
for ($i = 1; $i <= $availabilityUrl['rooms']; ++$i) {
$adults += $availabilityUrl['adult'.$i];
$childrens = [];
if ('n' != $availabilityUrl['child'.$i]) {
$childAgesTemp = explode('-', $availabilityUrl['child'.$i]);
$childs += count($childAgesTemp);
}
}
}
else {
$data = json_decode($session->get($transactionId . '[hotel][availability_data_hotel]'));
if (isset($data->attributes) && null !== json_decode(base64_decode($data->attributes), true)) {
$availabilityData = json_decode(base64_decode($data->attributes), true);
} else {
$availabilityData = json_decode($session->get($transactionId.'[hotel][availability_data_hotel]'), true);
}
if (isset($availabilityData['Rooms']) && $availabilityData['Rooms'] > 0) {
for ($i = 0; $i < $availabilityData['Rooms']; ++$i) {
$adults += $availabilityData['Adults'.$i] ?? 0;
if (isset($availabilityData['Children'.$i]) && $availabilityData['Children'.$i] > 0) {
$childs += $availabilityData['Children'.$i];
}
}
}
}
$detailHotel = [
'dateIn' => $dateIn,
'dateOut' => $dateOut,
'roomInformation' => $rooms,
'dateInStr' => (string) $response->Message->OTA_HotelRoomListRS['StartDate'],
'dateOutStr' => (string) $response->Message->OTA_HotelRoomListRS['EndDate'],
'nights' => floor(($dateOut - $dateIn) / (24 * 60 * 60)),
'adults' => (string) $response->Message->OTA_HotelRoomListRS['Adults'],
'children' => (string) $response->Message->OTA_HotelRoomListRS['Children'],
'rooms' => (string) $response->Message->OTA_HotelRoomListRS['Rooms'] ?? $availabilityData['Rooms'] ?? $availabilityUrl['rooms'],
'timeSpan' => $detailHotelRaw->TimeSpan,
'basicInfos' => $detailHotelRaw->BasicPropertyInfo,
'total' => $detailHotelRaw->Total,
'category' => $detailHotelRaw->TPA_Extensions->HotelInfo->Category,
'description' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Description,
'email' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
'services' => $detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service,
'photos' => $detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem,
'agentName' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
'agentMail' => $additionalUserFront->CORREO_ELECTRONICO,
'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL,
'prepaymentsInfo' => $prepaymentInfo,
'namesClient' => $fullRequest->request->get('quotationName'),
'lastnamesClient' => $fullRequest->request->get('quotationLastname'),
'emailClient' => $fullRequest->request->get('quotationEmail'),
'priceTotalQuotation' => $fullRequest->request->get('quotationPriceTotal'),
'priceCurrency' => $fullRequest->request->get('quotationCurrency'),
'typeRoom' => $fullRequest->request->get('typeRoom'),
'infoTerms' => $fullRequest->request->get('quotationTerms'),
'infoComments' => $fullRequest->request->get('quotationComments'),
'longitude' => $locationHotel['Longitude'],
'latitude' => $locationHotel['Latitude'],
];
//'src/Aviatur/TwigBundle/Resources/views/aviatur/Flux/Hotel/Hotel/quotation.html.twig'
$html = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/quotation.html.twig');
$namefilepdf = 'Aviatur_cotizacion_hotel_'.$transactionId.'.pdf';
$voucherCruiseFile = $projectDir.'/app/quotationLogs/hotelQuotation/'.$namefilepdf.'.pdf';
if ('N' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
$codImg = $additionalUserFront->EMPRESA;
} elseif ('S' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
$codImg = $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
}
$imgAgency = 'assets/common_assets/img/offices/'.$codImg.'.png';
if (!file_exists($imgAgency)) {
$codImg = 10;
}
$subject = 'Cotización de Hotel';
try {
if (!file_exists($voucherCruiseFile)) {
$pdf->setOption('page-size', 'Legal');
$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);
$pdf->generateFromHtml($this->renderView($html, [
'dateIn' => $dateIn,
'dateOut' => $dateOut,
'roomInformation' => $rooms,
'dateInStr' => (string) $response->Message->OTA_HotelRoomListRS['StartDate'],
'dateOutStr' => (string) $response->Message->OTA_HotelRoomListRS['EndDate'],
'nights' => floor(($dateOut - $dateIn) / (24 * 60 * 60)),
'adults' => (string) $response->Message->OTA_HotelRoomListRS['Adults'],
'children' => (string) $response->Message->OTA_HotelRoomListRS['Children'],
'rooms' => (string) $response->Message->OTA_HotelRoomListRS['Rooms'],
'timeSpan' => $detailHotelRaw->TimeSpan,
'basicInfos' => $detailHotelRaw->BasicPropertyInfo,
'total' => $detailHotelRaw->Total,
'category' => $detailHotelRaw->TPA_Extensions->HotelInfo->Category,
'description' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Description,
'email' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
'services' => $detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service,
'photos' => $detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem,
'agentName' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
'agentMail' => $additionalUserFront->CORREO_ELECTRONICO,
'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL,
'prepaymentsInfo' => $prepaymentInfo,
'namesClient' => $fullRequest->request->get('quotationName'),
'lastnamesClient' => $fullRequest->request->get('quotationLastname'),
'emailClient' => $fullRequest->request->get('quotationEmail'),
'priceTotalQuotation' => $fullRequest->request->get('quotationPriceTotal'),
'priceCurrency' => $fullRequest->request->get('quotationCurrency'),
'typeRoom' => $fullRequest->request->get('typeRoom'),
'infoTerms' => $fullRequest->request->get('quotationTerms'),
'infoComments' => $fullRequest->request->get('quotationComments'),
'longitude' => $locationHotel['Longitude'],
'latitude' => $locationHotel['Latitude'],
'codImg' => $codImg,
]), $voucherCruiseFile);
}
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($additionalUserFront->CORREO_ELECTRONICO)
->setSubject($session->get('agencyShortName').' - '.$subject)
->attach(\Swift_Attachment::fromPath($voucherCruiseFile))
->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Bus/Default/quotation_email_body.html.twig'), [
'nameAgent' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
'codImg' => $codImg,
]), 'text/html');
} catch (\Exception $ex) {
if (file_exists($voucherCruiseFile)) {
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($additionalUserFront->CORREO_ELECTRONICO)
->setSubject($session->get('agencyShortName').' - '.$subject)
->attach(\Swift_Attachment::fromPath($voucherCruiseFile))
->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Bus/Default/quotation_email_body.html.twig'), [
'nameAgent' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
'codImg' => $codImg,
]), 'text/html');
} else {
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($additionalUserFront->CORREO_ELECTRONICO)
->setBcc(['sebastian.huertas@aviatur.com'])
->setSubject($session->get('agencyShortName').' - '.$subject)
->setBody('No se generó la cotización del hotel.');
}
}
try {
$mailer->send($messageEmail);
} catch (Exception $ex) {
$exceptionLog->log(var_dump('aviatur_cotizacion_hotel_'.$transactionId), $ex);
}
unlink($voucherCruiseFile);
$this->saveInformationCGS($aviaturLogSave, $aviaturWebService, $aviaturErrorHandler, $registry, $detailHotel, $additionalUserFront, $agency);
//($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Agent/Default/menu_agent.html.twig'), ['agent' => $nombreagente, 'email' => $emailuser, 'adminAgent' => $adminAgent])
$factor = [
'dateIn' => $dateIn,
'dateOut' => $dateOut,
'roomInformation' => $rooms,
'dateInStr' => (string) $response->Message->OTA_HotelRoomListRS['StartDate'],
'dateOutStr' => (string) $response->Message->OTA_HotelRoomListRS['EndDate'],
'nights' => floor(($dateOut - $dateIn) / (24 * 60 * 60)),
'adults' => (string) $response->Message->OTA_HotelRoomListRS['Adults'],
'children' => (string) $response->Message->OTA_HotelRoomListRS['Children'],
'rooms' => (string) $response->Message->OTA_HotelRoomListRS['Rooms'],
'timeSpan' => $detailHotelRaw->TimeSpan,
'basicInfos' => $detailHotelRaw->BasicPropertyInfo,
'total' => $detailHotelRaw->Total,
'category' => $detailHotelRaw->TPA_Extensions->HotelInfo->Category,
'description' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Description,
'email' => (string) $detailHotelRaw->TPA_Extensions->HotelInfo->Email,
'services' => $detailHotelRaw->TPA_Extensions->HotelInfo->Services->Service,
'photos' => $detailHotelRaw->TPA_Extensions->HotelInfo->MultimediaDescription->ImageItems->ImageItem,
'agentName' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
'agentMail' => $additionalUserFront->CORREO_ELECTRONICO,
'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL,
'prepaymentsInfo' => $prepaymentInfo,
'namesClient' => $fullRequest->request->get('quotationName'),
'lastnamesClient' => $fullRequest->request->get('quotationLastname'),
'emailClient' => $fullRequest->request->get('quotationEmail'),
'priceTotalQuotation' => $fullRequest->request->get('quotationPriceTotal'),
'priceCurrency' => $fullRequest->request->get('quotationCurrency'),
'typeRoom' => $fullRequest->request->get('typeRoom'),
'infoTerms' => $fullRequest->request->get('quotationTerms'),
'infoComments' => $fullRequest->request->get('quotationComments'),
'longitude' => $locationHotel['Longitude'],
'latitude' => $locationHotel['Latitude'],
'codImg' => $codImg,
];
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Hotel/Hotel/quotation.html.twig'),$factor);
}
public function saveInformationCGS(AviaturLogSave $aviaturLogSave, AviaturWebService $aviaturWebService, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, $data, $customer, $agency)
{
$parametersLogin = $this->managerRegistry->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findParameters($agency, 'aviatur_service_login_cgs');
$urlLoginCGS = $parametersLogin[0]['value'];
$parametersProduct = $this->managerRegistry->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findParameters($agency, 'aviatur_service_hotel_cgs');
$urlAddProductHotel = $parametersProduct[0]['value'];
/*
* get token api autentication
*/
$userLoginCGS = $aviaturWebService->encryptUser(trim(strtolower($customer->CODIGO_USUARIO)), 'AviaturCGSMTK');
$jsonReq = json_encode(['username' => $userLoginCGS]);
//print_r(json_encode($data)); die;
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $urlLoginCGS,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $jsonReq,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
],
]);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if (200 != $httpcode) {
$aviaturLogSave->logSave('HTTPCODE: '.$httpcode.' Error usuario: '.strtolower($customer->CODIGO_USUARIO), 'CGS', 'CGSHOTEL_ERRORLOGIN');
$aviaturLogSave->logSave(print_r($response, true), 'CGS', 'responseHotelCGS');
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/hoteles', 'Error Login', 'Error Login'));
} else {
$tokenInfoApiQuotation = json_decode($response);
$tokenApiQuotation = $tokenInfoApiQuotation->TOKEN;
}
ini_set('xdebug.var_display_max_depth', '-1');
ini_set('xdebug.var_display_max_children', '-1');
ini_set('xdebug.var_display_max_data', '-1');
//var_dump($data['priceTotalQuotation']); die;
/**
* Begin API data send.
*/
$ages = '';
$roms = '';
$roms_collection = '';
$separate = '';
for ($i = 1; $i <= (is_countable($data['roomInformation']) ? count($data['roomInformation']) : 0); ++$i) {
$ages = '';
for ($a = 0; $a < (is_countable($data['roomInformation'][$i]['child']) ? count($data['roomInformation'][$i]['child']) : 0); ++$a) {
if (0 !== $a) {
$ages .= ','.'"'.$data['roomInformation'][$i]['child'][$a].'"';
} else {
$ages .= '"'.$data['roomInformation'][$i]['child'][$a].'"';
}
}
if (1 !== $i) {
$separate = ',';
} else {
$separate = '';
}
$roms .= $separate.'{
"adultOcupancy": '.$data['roomInformation'][$i]['adult'].',
"availCount": null,
"boardCode": null,
"boardName": null,
"boardShortName": null,
"boardType": null,
"cancellationPolicies": [
{
"amount": null,
"dateFrom": "'.$data['prepaymentsInfo']['Message']['OTA_HotelResRS']['HotelReservations']['RoomStays']['TPA_Extensions']['CancellationPolicy']['FechaEntradaGasto'].'",
"respaldoFechaSalida": "'.$data['dateOutStr'].'",
"time": "'.$data['prepaymentsInfo']['Message']['OTA_HotelResRS']['HotelReservations']['RoomStays']['TPA_Extensions']['CancellationPolicy']['HoraFechaEntradaGasto'].'"
}
],
"childAges": [
'.$ages.'
],
"childOcupancy": '.(is_countable($data['roomInformation'][$i]['child']) ? count($data['roomInformation'][$i]['child']) : 0).',
"onRequest": null,
"price": null,
"roomCharacteristic": null,
"roomCharacteristicCode": null,
"roomCode": null,
"roomCount": null,
"roomType": null,
"shrui": null
}';
}
$data_send = '{
"customer":{
"billingInformations":[
{
"active": true,
"agencyContact": "string",
"city": "'.$data['basicInfos']->Address->CityName.'",
"colony": "string",
"country": "string",
"dateCreated": "2020-05-21T23:20:30.441Z",
"email": "string",
"extNumber": "string",
"id": 0,
"intNumber": "string",
"lastUpdated": "2020-05-21T23:20:30.441Z",
"official": "string",
"phone": {
"active": true,
"dateCreated": "2020-05-21T23:20:30.441Z",
"id": 0,
"lastUpdated": "2020-05-21T23:20:30.441Z",
"number": "string",
"type": "string",
"version": 0
},
"postalCode": "string",
"representation": "string",
"rfc": "string",
"state": "string",
"status": "string",
"street": "string",
"taxRegime": "string",
"version": 0
}
],
"birthDate":"true",
"city": "'.$data['basicInfos']->Address->CityName.'",
"dateCreated":"0001-01-01T00:00:00",
"dateOfBirth":"0001-01-01T00:00:00",
"document":null,
"emails":[
{
"active": true,
"dateCreated": "'.date('Y-m-d').'",
"emailAddress": "'.$data['emailClient'].'",
"id": 0,
"lastUpdated": "'.date('Y-m-d').'",
"version": 0
}
],
"exchangeRateInformations":null,
"firstName":"'.$data['namesClient'].'",
"fullName":"'.$data['namesClient'].' '.$data['lastnamesClient'].'",
"gender":null,
"id":null,
"idAccount":null,
"idIntelisis":null,
"idUserOwner":null,
"identify":null,
"interestsForExpo":null,
"lastName":"'.$data['lastnamesClient'].'",
"lastUpdated":"0001-01-01T00:00:00",
"mothersName":null,
"phones":[
{
"active":false,
"dateCreated":"0001-01-01T00:00:00",
"id":0,
"lastUpdated":"0001-01-01T00:00:00",
"number":null,
"type":null,
"version":0
}
],
"typeContact":null
},
"quote":null,
"selectedProduct":{
"associatedProductIndex":null,
"category": "'.$data['category']['Code'].'",
"complementProductList": null,
"deleteInfo":null,
"description":"'.$data['description'].'",
"packageName":"'.$data['basicInfos']['HotelName'].'",
"discount":null,
"emit":false,
"fareData":{
"aditionalFee":0.0,
"airpotService":null,
"baseFare":'.str_replace('.', '', $data['priceTotalQuotation']).',
"cO":0.0,
"commission":0.0,
"commissionPercentage":0.0,
"complements":null,
"currency":{
"type":"'.$data['priceCurrency'].'"
},
"equivFare":0.0,
"iva":0.0,
"otherDebit":null,
"otherTax":null,
"price":'.str_replace('.', '', $data['priceTotalQuotation']).',
"providerPrice":0.0,
"qSe":0.0,
"qSeIva":0.0,
"qse":null,
"revenue":0.0,
"serviceCharge":0.0,
"sureCancel":null,
"tA":0.0,
"taIva":0.0,
"tax":0.0,
"total":'.str_replace('.', '', $data['priceTotalQuotation']).',
"yQ":0.0,
"yQiva":0.0
},
"foodPlan":null,
"hotelDetail":{
"nightCount": '.$data['nights'].',
"roomCount": '.$data['rooms'].'
},
"index":null,
"itinerary": {
"availToken": null,
"category": null,
"cdChain": null,
"code": "'.$data['prepaymentsInfo']['Message']['HotelReservations']['HotelReservation']['RoomStays']['RoomStay']['BasicPropertyInfo']['HotelCode'].'",
"codeCurrency": "'.$data['prepaymentsInfo']['Message']['HotelReservations']['HotelReservation']['RoomStays']['RoomStay']['Total']['CurrencyCode'].'",
"contractIncommingOffice": null,
"contractName": null,
"dateFrom": "'.$data['prepaymentsInfo']['Message']['HotelReservations']['HotelReservation']['RoomStays']['RoomStay']['TimeSpan']['End'].'",
"dateTo": "'.$data['prepaymentsInfo']['Message']['HotelReservations']['HotelReservation']['RoomStays']['RoomStay']['TimeSpan']['Start'].'",
"echoToken": null,
"issueFrom": null,
"issueTo": null,
"location": [
],
"nbChain": null,
"nuStars": "'.$data['category']['Code'].'",
"pointOfInterest": null,
"promo": null,
"rooms": [
'.$roms.'
],
"topSale": null,
"txDescription": "'.$data['description'].'",
"txDestination": "'.$data['basicInfos']->Address->CityName.'",
"txImage": "'.$data['photos']['ImageFormat']['URL'].'",
"txIssues": null,
"txName": "'.$data['prepaymentsInfo']['Message']['HotelReservations']['HotelReservation']['RoomStays']['RoomStay']['BasicPropertyInfo']['HotelName'].'",
"txPrice": "'.$data['priceTotalQuotation'].'",
"txZone": null
},
"locatorList":[
],
"passengerDataList":[
{
"age":"0",
"birthday":"1899-12-31T19:00:00-05:00",
"fareData":{
"aditionalFee":0.0,
"airpotService":null,
"baseFare":0.0,
"cO":0.0,
"commission":0.0,
"commissionPercentage":0.0,
"complements":null,
"currency":null,
"equivFare":0.0,
"iva":0.0,
"otherDebit":null,
"otherTax":null,
"price":0.0,
"providerPrice":0.0,
"qSe":0.0,
"qSeIva":0.0,
"qse":null,
"revenue":0.0,
"serviceCharge":0.0,
"sureCancel":null,
"tA":0.0,
"taIva":0.0,
"tax":0.0,
"total": '.str_replace('.', '', $data['priceTotalQuotation']).',
"yQ":0.0,
"yQiva":0.0
},
"gender":"",
"id":"",
"lastName":"",
"mail":"",
"mothersName":"",
"name":"",
"passengerCode":{
"accountCode":"",
"promo":false,
"realType":"ADT",
"type":"ADT"
},
"passengerContact":null,
"passengerInsuranceInfo":null,
"phone":null
}
],
"priority":"",
"productType":{
"description":"Hotel",
"typeProduct":"Hotel"
},
"quoteHost":null,
"reservationInfo":null,
"reserveProductLogList":null,
"roomType": null,
"route":{
"arrivalDate": "'.$data['dateOutStr'].'",
"arrivalDateString": "'.$data['dateOutStr'].'",
"arrivalDescription": "'.$data['basicInfos']->Address->CityName.'",
"arrivalIATA": null,
"departureDate": "'.$data['dateInStr'].'",
"departureDateString": "'.$data['dateInStr'].'",
"departureDescription": null,
"departureIATA": null,
"destination": "'.$data['basicInfos']->Address->CityName.'",
"flightTime": null,
"origin": null,
"providerCode": null,
"subRoutes": null
},
"savedPassenger":false,
"searchHost":null,
"selected":false,
"serviceProvider": {
"code": "'.$data['prepaymentsInfo']['ProviderResults']['ProviderResult']['Provider'].'"
},
"stayTime":null
},
"quote": {"channel":"B2C WEB"}
}';
$authorization = 'Authorization: Bearer '.$tokenApiQuotation;
//API URL
$url = $urlAddProductHotel;
//create a new cURL resource
$ch = curl_init($url);
//setup request to send json via POST
$payload = $data_send;
//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'accept: application/json',
'authorization: Bearer '.$tokenApiQuotation,
'content-type: application/json',
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute the POST request
$result = curl_exec($ch);
//close CURL resource
curl_close($ch);
/*
* End API data send
*/
}
public function consultRoommlistAction(Request $fullRequest, AviaturWebService $aviaturWebService, RouterInterface $router)
{
$provider = null;
$fullPricing = null;
$request = $fullRequest->request;
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$domain = $fullRequest->getHost();
$route = $router->match(str_replace($fullRequest->getSchemeAndHttpHost(), '', $fullRequest->getUri()));
$isMulti = false !== strpos($route['_route'], 'multi') ? true : false;
$isFront = $session->has('operatorId');
$configsHotelAgency = $em->getRepository(\Aviatur\HotelBundle\Entity\ConfigHotelAgency::class)->findProviderForHotelsWithAgency($agency);
$validate = true;
$inputsRequest = ['correlationId', 'startDate', 'endDate', 'providerID', 'hotelCode', 'country'];
foreach ($inputsRequest as $input) {
if (!$request->get($input)) {
$validate = false;
}
}
if (!$validate) {
return $this->redirect($this->generateUrl('aviatur_search_hotels'));
}
foreach ($configsHotelAgency as $configHotelAgency) {
if ($request->get('providerID') == $configHotelAgency->getProvider()->getProvideridentifier()) {
$provider = $configHotelAgency->getProvider();
}
}
$correlationID = $request->get('correlationId');
$startDate = $request->get('startDate');
$endDate = $request->get('endDate');
$dateIn = strtotime($startDate);
$dateOut = strtotime($endDate);
$nights = floor(($dateOut - $dateIn) / (24 * 60 * 60));
$searchHotelCodes = ['---', '--'];
$replaceHotelCodes = ['/', '|'];
$hotelCode = explode('-', str_replace($searchHotelCodes, $replaceHotelCodes, $request->get('hotelCode')));
$country = $request->get('country');
$variable = [
'correlationId' => $correlationID,
'start_date' => $startDate,
'end_date' => $endDate,
'hotel_code' => $hotelCode[0],
'country' => $country,
'ProviderId' => $provider->getProvideridentifier(),
];
$hotelModel = new HotelModel();
$xmlRequest = $hotelModel->getXmlDetail();
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'HotelRoomList', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false);
if (!isset($response['error'])) {
$markup = $em->getRepository(\Aviatur\HotelBundle\Entity\Markup::class)->find($hotelCode[1]);
$markupValue = $markup->getValue();
$markupId = $markup->getId();
$parametersJson = $session->get($domain.'[parameters]');
$parameters = json_decode($parametersJson);
$tax = (float) $parameters->aviatur_payment_iva;
$currency = 'COP';
if (strpos($provider->getName(), '-USD')) {
$currency = 'USD';
}
$currencyCode = (string) $response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay->RoomRates->RoomRate->Total['CurrencyCode'];
if ('COP' != $currencyCode && 'COP' == $currency) {
$trm = $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->recentTrm($currencyCode);
$trm = $trm[0]['value'];
} else {
$trm = 1;
}
$count = 0;
foreach ($response->Message->OTA_HotelRoomListRS->HotelRoomLists->HotelRoomList->RoomStays->RoomStay as $key => $roomStay) {
$roomStay->BasicPropertyInfo['HotelCode'] .= '-'.$markupId;
foreach ($roomStay->RoomRates->RoomRate as $roomRate) {
if (0 == $count) {
if ('N' == $markup->getConfigHotelAgency()->getType()) {
$aviaturMarkup = (float) $roomRate->Total['AmountIncludingMarkup'] * $markupValue / (100 - $markupValue);
} else {
$aviaturMarkup = 0;
}
$roomRate->Total['AmountAviaturMarkup'] = $aviaturMarkup;
if (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces'])) {
$roomRate->Total['AmountAviaturMarkupTax'] = 0;
} else {
$roomRate->Total['AmountAviaturMarkupTax'] = $aviaturMarkup * $tax;
}
$roomRate->Total['AmountIncludingAviaturMarkup'] = round((float) $roomRate->Total['AmountAfterTax'] + $aviaturMarkup + $roomRate->Total['AmountAviaturMarkupTax'], (int) $roomRate->Total['DecimalPlaces']);
$roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round((float) ($aviaturMarkup + (float) $roomRate->Total['AmountIncludingMarkup']) * $trm, (int) $roomRate->Total['DecimalPlaces']);
if ('COP' == $currencyCode) {
$roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'], (int) $roomRate->Total['DecimalPlaces']);
}
if (isset($roomRate->Total['RateOverrideIndicator']) || (round($roomRate->Total['AmountIncludingMarkup'], (int) $roomRate->Total['DecimalPlaces']) == round($roomRate->Total['AmountAfterTax'], (int) $roomRate->Total['DecimalPlaces']))) {
$roomRate->TotalAviatur['AmountTax'] = 0;
} else {
$roomRate->TotalAviatur['AmountTax'] = round($roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] * $tax, (int) $roomRate->Total['DecimalPlaces']);
}
$roomRate->TotalAviatur['AmountTotal'] = (float) $roomRate->TotalAviatur['AmountIncludingAviaturMarkup'] + $roomRate->TotalAviatur['AmountTax'];
$fullPricing = [
'total' => (float) $roomRate->TotalAviatur['AmountTotal'] * $nights,
'totalPerNight' => (float) $roomRate->TotalAviatur['AmountTotal'],
];
$roomRate->TotalAviatur['FullPricing'] = base64_encode(json_encode($fullPricing));
}
++$count;
}
}
} else {
$fullPricing = [
'total' => (float) 0,
'totalPerNight' => 0,
];
}
return $this->json($fullPricing);
}
protected function authenticateUser(UserInterface $user, LoginManager $loginManager)
{
try {
$loginManager->loginUser(
'main',
$user
);
} catch (AccountStatusException $ex) {
// We simply do not authenticate users which do not pass the user
// checker (not enabled, expired, etc.).
}
}
/**
* Sobrescribe el método 'json' de la clase 'AbstractController'.
*
* @param mixed $data Los datos a serializar en json.
* @param int $status El código de estado de la respuesta HTTP.
* @param array $headers Un array de encabezados de respuesta HTTP.
* @param array $context Opciones para el contexto del serializador.
*
* @return JsonResponse
*/
public function json($data, int $status = 200, array $headers = [], array $context = []): JsonResponse
{
if (! isset($context['responseHotelDetail'])) {
$jsonResponse=parent::json($data, $status, $headers, $context);
} else {
$isSerializableValidResponse=TRUE;
if ($this->multiCustomUtils->isObjectInArray($data)) {
$isSerializableValidResponse=FALSE;
}
if ($isSerializableValidResponse) {
$jsonResponse=parent::json($data, $status, $headers, $context);
} else {
$jsonResponse= new JsonResponse($data);
}
}
return $jsonResponse;
}
/**
* Obtiene las coordenadas (latitud y longitud) para un código IATA.
*
* @param string $iata Código IATA de la ciudad.
* @return array|null Array con 'latitude' y 'longitude', o null si no se encuentra.
* @throws \InvalidArgumentException Si el código IATA es inválido.
*/
public function getCoordinatesByIata(string $iata): ?array
{
// Validar que el código IATA no sea vacío ni inválido.
if (empty($iata) || !preg_match('/^[A-Z]{3}$/', $iata)) {
throw new \InvalidArgumentException('El código IATA proporcionado no es válido.');
}
$em = $this->managerRegistry;
// Obtener el repositorio basado en la entidad SearchCities.
$repositorySearchCities = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class);
// Buscar la ciudad por su código IATA.
$city = $repositorySearchCities->findOneBy(['iata' => $iata]);
// Si no se encuentra la ciudad, retornar null.
if (!$city) {
return null;
}
// Decodificar el JSON almacenado en el campo 'coordinates'.
try {
$coordinates = json_decode($city->getCoordinates(), true, 512, JSON_THROW_ON_ERROR);
$city = $city->getCity();
// $country = $city->getCountryCode();
} catch (\JsonException $e) {
// Si el JSON está mal formado, arrojar una excepción o manejar el error.
throw new \RuntimeException('Error al decodificar el campo coordinates: ' . $e->getMessage());
}
// Verificar que latitud y longitud estén presentes en el JSON decodificado.
if (!isset($coordinates['latitude'], $coordinates['longitude'])) {
throw new \RuntimeException('El JSON no contiene los campos requeridos: latitude y longitude.');
}
// Retornar la latitud y longitud.
return [
'latitude' => $coordinates['latitude'],
'longitude' => $coordinates['longitude'],
'city' => $city,
'country' => 'co',
];
}
/**
* @Route("/build-url/{iata}/{checkIn}+{checkOut}/{adults}+{children}", name="redirect_to_coordinates")
*
* @param string $iata Código IATA de la ciudad.
* @param string $checkIn Fecha de entrada en formato YYYY-MM-DD.
* @param string $checkOut Fecha de salida en formato YYYY-MM-DD.
* @param string $adults Número de adultos.
* @param string $children Número de niños o "n" si no hay niños.
*
* @return RedirectResponse
*/
public function redirectToCoordinates(
string $iata,
string $checkIn,
string $checkOut,
string $adults,
string $children
): RedirectResponse {
try {
$coordinates = $this->getCoordinatesByIata($iata);
$latitude = 0;
$longitude = 0;
$url = 'https://api.opencagedata.com/geocode/v1/json';
$params = [
//'key' => 'd4ea2db24f6448dcbb1551c3546851d6', // dev
'key' => 'd7c38ad65c694ffc82d29a4987e3f056', // prod
'q' => $coordinates['city'],
'no_annotations' => 1
];
$queryString = http_build_query($params);
$requestUrl = $url . '?' . $queryString;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $requestUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
} else {
$data = json_decode($response, true);
if (!empty($data['results']) && isset($data['results'][0]['geometry'])) {
$firstResult = $data['results'][0]['geometry'];
$latitude = $firstResult['lat'];
$longitude = $firstResult['lng'];
$city = $data['results'][0]['components']['_normalized_city'];
$country = $data['results'][0]['components']['country_code'];
} else {
echo "No se encontraron resultados.\n";
}
}
curl_close($ch);
$coordinateString = "{$latitude},{$longitude}";
$destination = sprintf('%s(%s)', $city, $country);
$destinationUrl = sprintf(
'/hoteles/avail/%s/%s/%s+%s/room=1&adults=%s&children=%s',
rawurlencode($destination), // Codificar el destino.
$coordinateString,
$checkIn,
$checkOut,
$adults,
$children
);
// Redirigir a la nueva URL.
return $this->redirect($destinationUrl);
} catch (\InvalidArgumentException $e) {
// Manejar errores de validación del código IATA.
return $this->json(['error' => $e->getMessage()], 400);
} catch (\RuntimeException $e) {
// Manejar otros errores como coordenadas no encontradas o JSON inválido.
return $this->json(['error' => $e->getMessage()], 500);
}
}
}