<?php
namespace Aviatur\PackageBundle\Controller;
use Aviatur\AgentBundle\Entity\AgentTransaction;
use Aviatur\CustomerBundle\Models\CustomerModel;
use Aviatur\DocumentationBundle\Models;
use Aviatur\GeneralBundle\Entity\FormUserInfo;
use Aviatur\PackageBundle\Models\PackageModel;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Aviatur\TwigBundle\Services\TwigFolder;
use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
use Aviatur\GeneralBundle\Services\ExceptionLog;
use Aviatur\GeneralBundle\Services\AviaturWebService;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Aviatur\PackageBundle\Services\SearchPackageCookie;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Aviatur\GeneralBundle\Services\AviaturLoginService;
use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
use Aviatur\GeneralBundle\Services\AviaturEncoder;
use Aviatur\GeneralBundle\Controller\OrderController;
use Aviatur\PaymentBundle\Controller\SafetypayController;
use Aviatur\PaymentBundle\Controller\P2PController;
use Aviatur\PaymentBundle\Controller\PSEController;
use Aviatur\PaymentBundle\Services\TokenizerService;
use Aviatur\CustomerBundle\Services\ValidateSanctions;
use Aviatur\GeneralBundle\Services\AviaturMailer;
use Aviatur\GeneralBundle\Services\AviaturLogSave;
use Knp\Snappy\Pdf;
class DefaultController extends AbstractController
{
/**
* @var \Doctrine\Persistence\ObjectManager
*/
protected $managerRegistry;
/**
* @var SessionInterface
*/
protected $session;
protected $agency;
public function __construct(ManagerRegistry $registry, SessionInterface $session)
{
$this->managerRegistry = $registry->getManager();
$this->session = $session;
$this->agency = $this->managerRegistry->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
}
public function searchAction()
{
return $this->redirect(
$this->generateUrl(
'aviatur_search_package',
[]
)
);
}
public function availabilitySeoAction(Request $request, RouterInterface $router, $url)
{
$em = $this->managerRegistry;
$session = $this->session;
$seoUrl = $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findOneByUrl('paquetes/' . $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 solicito no existe o se ha movido permanentemente');
}
} else {
throw $this->createNotFoundException('La página que solicito no existe o se ha movido permanentemente');
}
}
public function availabilityAction(Request $request, SearchPackageCookie $searchPackageCookie, AuthorizationCheckerInterface $authorizationChecker, AviaturWebService $aviaturWebService, ExceptionLog $exceptionLog, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, ParameterBagInterface $parameterBag, TwigFolder $twigFolder, $package, $description)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$channel = [];
$Chanels = null;
$xmlTemplate = [];
$providers = [];
$domain = null;
$urlDescription = [];
$em = $this->managerRegistry;
$fullRequest = $request;
$session = $this->session;
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
$agency = $this->agency;
$configPackageAgency = $em->getRepository(\Aviatur\PackageBundle\Entity\ConfigPackageAgency::class)->findProviderForPackagesWithAgency($agency);
$valueReservation = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_payment_package');
$agencyFolder = $twigFolder->twigFlux();
$packageModel = new PackageModel();
if (!$configPackageAgency || !isset($configPackageAgency[0])) {
return $aviaturErrorHandler->errorRedirectNoEmail('/buscar/paquetes', 'Resultados de búsqueda', 'No podemos realizar la consulta ya que, no existe un proveedor configurado para este servicio');
}
$channel['channel'] = $configPackageAgency[0]->getChannel();
$OfficeId = explode('-', $configPackageAgency[0]->getOfficeid());
$channel['officeId'] = $OfficeId[1];
$date = date('Y-m-d');
if ('especializado' === $package && 'Turismo-vacaciones' === $description) {
$package = 'personalizada';
$description = 'vacaciones';
}
$newDescription = explode('/', $description);
$descriptions = [$newDescription];
$count = count($newDescription);
switch ($channel['channel']) {
case 1:
// canal de venta Aviatur.com (público)
$Chanels = '<Channels>
<Channel>
<Id>'.$channel['channel'].'</Id>
<OfficeId/>
</Channel>
</Channels>';
break;
case 2:
// canal de venta página web agencia de la organización (privado)
$Chanels = '<Channels>
<Channel>
<Id>3</Id>
<OfficeId>'.$channel['officeId'].'</OfficeId>
</Channel>
</Channels>';
break;
case 3:
// canal de venta página web agencia de la organización (privado mas público)
$Chanels = '<Channels>
<Channel>
<Id>1</Id>
<OfficeId/>
</Channel>
<Channel>
<Id>3</Id>
<OfficeId>'.$channel['officeId'].'</OfficeId>
</Channel>
</Channels>';
break;
case 4:
// canal de venta Marcas Blancas (público)
$Chanels = '<Channels>
<Channel>
<Id>4</Id>
<OfficeId/>
</Channel>
</Channels>';
break;
case 6:
// canal de venta Marcas Blancas (público)
$Chanels = '<Channels>
<Channel>
<Id>6</Id>
<OfficeId/>
</Channel>
</Channels>';
break;
}
if ('especializado' == $package) {
$xmlTemplate = $packageModel->getAvailabilityFavorite($Chanels);
} elseif ('personalizada' == $package) {
$descriptions[0] = str_replace('-', ' ', $descriptions[0]);
$xmlTemplate = $packageModel->getXmlAvailability($count, $descriptions[0], $Chanels);
}
$xmlRequest = $xmlTemplate[0];
if ($fullRequest->isXmlHttpRequest()) {
if ($configPackageAgency) {
$providers[] = $configPackageAgency[0]->getProvider()->getProvideridentifier();
} else {
$exceptionLog->log('Error Fatal', 'No se encontró la agencia segun el dominio: '.$domain, null, false);
return new Response('No se encontraron agencias para consultar disponibilidad.');
}
$provider = implode(';', $providers);
$description = str_replace('-', ' ', $description);
$variable = [
'ProviderId' => $provider,
'package' => $package,
'description' => $description,
'date' => $date,
];
$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.');
}
$transactionId = (string) $transactionIdResponse;
$variable['transactionId'] = $transactionId;
$session->set($transactionIdSessionName, $transactionId);
$session->set($transactionId.'[availability_url]', $requestUrl);
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'PkgAvail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false, $variable['transactionId']);
if (isset($response['error'])) {
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'PkgAvail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, true);
//$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgAvail__RS.xml')));
if (isset($response['error'])) {
if ('No se encontro información para la búsqueda seleccionada.' != $response['error']) {
$aviaturErrorHandler->errorRedirect($requestUrl, 'Error disponibilidad buscador', $response['error']);
}
return new Response($response['error']);
}
} elseif (!isset($response->Message->OTA_PkgAvailRS)) {
echo 'No hay información';
die;
$aviaturErrorHandler->errorRedirect($requestUrl, 'Error disponibilidad hoteles', $response->Message);
return new Response('No hemos encontrado información para el destino solicitado.');
}
$searchImages = ['http://static.aviatur.com/images'];
$replaceImages = ['https://static.aviatur.com/images'];
$response = simplexml_load_string(str_replace($searchImages, $replaceImages, $response->asXML()));
$packages = null;
$ProductInfo = null;
//$isAgent = false;
$nameProduct = 'package';
$productCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
$productCommission2 = (array) $productCommission;
if (($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_WAITING')) && (is_countable($productCommission2) ? count($productCommission2) : 0) > 0) {
$user = $this->getUser();
$agent = $user->getAgent();
$agency = $this->agency;
if (!empty($agent)) {
$nameProduct = 'package';
$productCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
$tarifaCommissionPercentage = $productCommission->getTacommissionpercentage();
$isAgent = true;
}
}
foreach ($response->Message->OTA_PkgAvailRS->Package as $packages) {
$packages->TPA_Extensions->ProductInfo->Description = htmlspecialchars_decode($packages->TPA_Extensions->ProductInfo->Description);
$hoy = date('Y-m-d');
$fecha_actual = strtotime($hoy);
$fecha_final = isset($packages) ? strtotime($packages->TPA_Extensions->ProductInfo->VigenciaFinal) : null;
if (isset($isAgent) && $isAgent) {
$packages->TPA_Extensions->ProductInfo->ActiveAgent = $isAgent;
$packages->TPA_Extensions->ProductInfo->ComisionPay = round((float) $packages->TPA_Extensions->ProductInfo->Comision * $tarifaCommissionPercentage);
}
if ($fecha_actual < $fecha_final) {
switch ($valueReservation->getValue()) {
case 0:
if ('false' === (string) $packages->TPA_Extensions->ProductInfo->FormaVenta) {
//Only Products OFF LINE
$ProductInfo[] = $packages;
}
break;
case 1:
if ('false' === (string) $packages->TPA_Extensions->ProductInfo->FormaVenta || 'true' === (string) $packages->TPA_Extensions->ProductInfo->FormaVenta) {
//Products OFF LINE and Products ON LINE
$ProductInfo[] = $packages;
}
break;
}
}
}
$variable['TransactionIdentifier'] = (string) $response->Message->OTA_PkgAvailRS['TransactionIdentifier'];
$urlAvailability = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/AjaxAvailability.html.twig');
return $this->render($urlAvailability, [
'ProductsInfo' => $ProductInfo,
'variable' => $variable,
'packages'=> $packages->TPA_Extensions->ProductInfo->ComisionPay,
]);
} else {
if ($configPackageAgency) {
$providers[] = $configPackageAgency[0]->getProvider()->getProvideridentifier();
} else {
$exceptionLog->log('Error Fatal', 'No se encontró la agencia segun el dominio: '.$domain, null, false);
return new Response('No se encontraron agencias para consultar disponibilidad.');
}
$provider = implode(';', $providers);
$cookieArray = [
'ProviderId' => $provider,
'package' => $package,
'description' => $description,
// 'date' => $date,
];
$urlAvailability = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/availability.html.twig');
if ($agency->getDomainsecure() == $agency->getDomain()) {
$safeUrl = 'https://'.$agency->getDomain();
} else {
$safeUrl = 'https://'.$agency->getDomainsecure();
}
$cookieLastSearch = $searchPackageCookie->searchPackageCookie(['package' => base64_encode(json_encode($cookieArray))]);
$availableArrayPackage = $cookieArray;
if ('personalizada' == $availableArrayPackage['package']) {
$availableArrayPackage['label'] = 'Búsqueda personalizada';
} else {
$descriptionE = trim($availableArrayPackage['description'], '-');
$availableArrayPackage['description'] = str_replace('-', ' ', $descriptionE);
$availableArrayPackage['label'] = 'Plan especializado';
}
$pointRedemption = $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
$seoUrl = $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
$urlDescription['url'] = null != $seoUrl ? '/'.$seoUrl[0]->getUrl() : $requestUrl;
$response = $this->render($urlAvailability, [
'ajaxUrl' => $requestUrl,
'availableArrayPackage' => $availableArrayPackage,
'inlineEngine' => true,
'safeUrl' => $safeUrl,
'cookieLastSearch' => $cookieLastSearch,
'pointRedemption' => $pointRedemption,
'urlDescription' => $urlDescription,
'ispackage' => true,
]);
$response->headers->setCookie(new Cookie('_availability_array[package]', base64_encode(json_encode($cookieArray)), (time() + 3600 * 24 * 7), '/'));
return $response;
}
}
public function detailAction(Request $request, RouterInterface $router, AuthorizationCheckerInterface $authorizationChecker,AviaturWebService $aviaturWebService, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, ParameterBagInterface $parameterBag, TwigFolder $twigFolder, $name, $id)
{
$correlationIdSessionName = $parameterBag->get('correlation_id_session_name');
$urlDescription = [];
$em = $this->managerRegistry;
$isAgent = false;
$fullRequest = $request;
$request = $fullRequest->request;
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
$session = $this->session;
$agency = $this->agency;
$agencyFolder = $twigFolder->twigFlux();
$values = explode('-', $id);
$packageCode = $values[0];
$TipoProducto = $values[2];
$valueReservation = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_payment_package');
$UrlHomologation = $em->getRepository(\Aviatur\GeneralBundle\Entity\urlHomologation::class)->findOneByOldUrl(trim('paquetes/detalle/'.$id.'/'.$name));
if (!empty($UrlHomologation)) {
return $this->redirect('/'.$UrlHomologation->getNewUrl());
}
if (true === $request->has('whitemarkDataInfo')) {
$session->set('whitemarkDataInfo', json_decode($request->get('whitemarkDataInfo'), true));
}
if ($request->has('correlationID')) {
$correlationId = $request->get('correlationID');
$session->set($correlationIdSessionName, $correlationId);
} else {
$correlationId = '';
}
$configPackageAgency = $em->getRepository(\Aviatur\PackageBundle\Entity\ConfigPackageAgency::class)->findProviderForPackagesWithAgency($agency);
$provider = $configPackageAgency[0]->getProvider();
$variable = [
'date' => date('Y-m-d'),
'packageCode' => $packageCode,
'nights' => $values[1],
'TipoProducto' => $values[2],
'correlationId' => $correlationId,
'ProviderId' => $provider->getProviderIdentifier(),
];
$packageModel = new PackageModel();
$xmlTemplate = $packageModel->getXmlDetail();
$xmlRequest = $xmlTemplate;
if ($request->has('transactionID')) {
$variable['transactionId'] = $request->get('transactionID');
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'PkgDetail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false, $variable['transactionId']);
//$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgDetail__RS.xml')));
if (isset($response['error'])) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/paquetes', 'Resultados de búsqueda', $response['error']));
}
$transactionId = $variable['transactionId'];
} else {
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'PkgDetail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, true);
//$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgDetail__RS.xml')));
if (isset($response['error'])) {
$response['error'] = 'No se encontró información para la búsqueda seleccionada. Por favor, realice otra consulta.';
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/paquetes', 'Resultados de búsqueda', $response['error']));
}
$transactionId = $response->Message->OTA_PkgAvailRS['TransactionIdentifier'];
}
if(empty($response))
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/paquetes', 'Resultados de búsqueda', 'No se encontró información para la búsqueda seleccionada. Por favor, realice otra consulta.'));
$nameProduct = 'package';
$productCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
$productCommission2 = (array)$productCommission;
$session->set($transactionId . '_isActiveQse', ((is_countable($productCommission2) ? count($productCommission2) : 0) > 0) ? true : false);
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId . '_isActiveQse')) {
$user = $this->getUser();
$agent = $user->getAgent();
$agency = $this->agency;
if (!empty($agent)) {
$emailuser = $user->getemail();
$idagent = $agent[0]->getid();
$nombreagente = $user->getFirstname().' '.$user->getLastname();
$agencyFolder = $twigFolder->twigFlux();
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($idagent);
$infoQse = json_decode($agentCommission->getQseproduct());
$infoQseNameProduct = empty($infoQse->$nameProduct) ? false : $infoQse->$nameProduct;
$infoQse = empty($infoQse) ? false : $infoQseNameProduct;
$productCommissionPercentage = $productCommission->getQsecommissionpercentage();
$packageCommission = ($infoQse) ? (int) $infoQse->commission_money : 0;
$packageCommissionPercentage = ($infoQse) ? (float) $infoQse->commission_percentage : 0;
$commissionActive = ($infoQse) ? (int) $infoQse->active : 0;
$isAgent = true;
} else {
$session->set($transactionId.'_isActiveQse', false);
}
}
$searchImages = ['http://static.aviatur.com/images'];
$replaceImages = ['https://static.aviatur.com/images'];
$response = simplexml_load_string(str_replace($searchImages, $replaceImages, $response->asXML()));
if (!$session->has($transactionId.'[package_detail_url]')) {
$session->set($transactionId.'[package_detail_url]', $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params')));
}
if ($request->has('package')) {
$package = $request->get('package');
$description = $request->get('description');
$requestUrl = $router->generate(
'aviatur_package_availability',
[
'package' => $package,
'description' => str_replace(' ', '-', $description), ]
);
$session->set($transactionId.'[mpt]', $requestUrl);
}
$referer = explode('/', $fullRequest->server->get('HTTP_REFERER'));
// if (isset($referer) && count($referer) > 4) {
// $description = $referer[5];
// } else {
// }
$description = '';
if (!isset($response->Message) || !isset($response->Message->OTA_PkgAvailRS) || !isset($response->Message->OTA_PkgAvailRS->Package) || empty($response->Message)) {
return $this->redirect($aviaturErrorHandler->errorRedirect($fullRequest->server->get('HTTP_REFERER'), '', 'Error en la respuesta de nuestro proveedor'));
}
$infoPackage = $response->Message->OTA_PkgAvailRS->Package->asXml();
$codeCity = (string) $response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->CodeCiudad;
$searchCity = $em->getRepository(\Aviatur\GeneralBundle\Entity\City::class)->findCityByIata($codeCity);
if (empty($searchCity)) {
$nameCity = $codeCity;
} else {
$nameCity = $searchCity[0]->getDescription();
}
$session->set($transactionId.'[mpt][infoPackage]', $infoPackage);
$salidaPackage = [];
if (!isset($response)) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_package_detail_secure'), '', 'No hay información'));
} elseif (is_object($response->Message->OTA_PkgAvailRS->Package)) {
if ('true' == $response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->FormaVenta) {
$session->set($transactionId.'[mpt]'.'[FormaVenta]', 'true');
} else {
$session->set($transactionId.'[mpt]'.'[FormaVenta]', 'false');
}
foreach ($response->Message->OTA_PkgAvailRS->Package as $information) {
$CostName = $information->TPA_Extensions->ProductInfo->UnitCostName;
$night = 'noche';
$ocupation = 'ocupaci';
$verificationNight = strrpos($CostName, $night);
$verificationOcupation = strrpos($CostName, $ocupation);
if (false === $verificationNight && false === $verificationOcupation) {
//Unidad de Costo por Estadia
$UnitCostValue = 0;
} elseif (false !== $verificationNight && false === $verificationOcupation) {
//Unidad de Costo por Noche
$UnitCostValue = 1;
} else {
//Unidad de Costo por Ocupacion
$UnitCostValue = 2;
}
$count = 0;
foreach ($information->Cautions as $travelerInformation) {
foreach ($travelerInformation as $caution) {
$info = explode('</Caution>', str_replace($caution['ID'].'">', '</Caution>', $caution->asXml()));
$caution['Info'] = isset($info[1]) ? htmlspecialchars_decode($info[1]) : '';
$infoDocumentation[$count]['ID'] = (string) $caution['ID'];
$infoDocumentation[$count]['INFO'] = (string) $caution['Info'];
++$count;
}
}
$session->set($transactionId.'[mpt][infoCaution]', json_encode($infoDocumentation));
$rangeDates = [];
foreach ($information->TPA_Extensions->ProductInfo->Salidas->Salida as $salidas) {
$salidaPackage[] = (string) $salidas['DepartureArrivalDate'];
$beginDateTemp = new \DateTime((string) $salidas['BeginDate']);
$endDateTemp = new \DateTime((string) $salidas['EndDate']);
$endDateTemp->modify('-'.((int) $information->TPA_Extensions->ProductInfo->Noches - 1).' day');
$intervalTemp = new \DateInterval('P1D');
$periodTemp = new \DatePeriod($beginDateTemp, $intervalTemp, $endDateTemp);
foreach ($periodTemp as $dateTemp) {
if ($dateTemp->format('Y-m-d') > date('Y-m-d', strtotime(date('Y-m-d').'+ '.$information->TPA_Extensions->ProductInfo->DiasAntesReserva.' days'))) {
$rangeDates[] = $dateTemp->format('Y-m-d');
}
}
}
$salidaPackage = array_unique($salidaPackage);
$rangeDates = array_unique($rangeDates);
if ('' != $salidaPackage[0]) {
$salidaPackage = array_intersect($rangeDates, $salidaPackage);
} else {
$salidaPackage = $rangeDates;
}
$DestinationCode = $information->TPA_Extensions->ProductInfo->CodePais;
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_package_detail_secure'), '', 'No hay información'));
}
$cautionsTotal = count($response->Message->OTA_PkgAvailRS->Package->Cautions->Caution);
if ($configPackageAgency[0]->getTourismRegister()) {
$response->Message->OTA_PkgAvailRS->Package->Cautions->Caution[$cautionsTotal]['ID'] = 'responsability_clausule';
$searchData = ['{agency_name}', '{agency_nit}', '{agency_rnt}'];
$replaceData = [$agency->getName(), $agency->getNit(), $configPackageAgency[0]->getTourismRegister()];
$responsability_clausule = str_replace($searchData, $replaceData, $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'responsability_clausule'));
$response->Message->OTA_PkgAvailRS->Package->Cautions->Caution[$cautionsTotal]['Info'] = $responsability_clausule;
$minor_trip = str_replace($searchData, $replaceData, $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'minor_trip'));
$response->Message->OTA_PkgAvailRS->Package->Cautions->Caution[($cautionsTotal + 1)]['ID'] = 'minor_trip';
$response->Message->OTA_PkgAvailRS->Package->Cautions->Caution[($cautionsTotal + 1)]['Info'] = $minor_trip;
}
$startDate = (string) $response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->VigenciaInicial;
$Accommodation = $response->Message->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation;
if ('19982' === $packageCode || '19989' === $packageCode || '19983' === $packageCode) {
$session->remove('promotionalCodePackage_code');
}
$urlDetail = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/package_detail.html.twig');
$valuePromo = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('promo_banca_mpt');
$seoUrl = $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
$urlDescription['url'] = null != $seoUrl ? '/'.$seoUrl[0]->getUrl() : $requestUrl;
$twigVariables = [
'promo' => json_decode($valuePromo->getValue(), true),
'DestinationCode' => $DestinationCode,
'CiudadDestino' => $nameCity,
'nights' => $variable['nights'],
'count' => count($Accommodation),
'date' => $startDate,
'packageCode' => $packageCode,
'TipoProducto' => $TipoProducto,
'days' => null,
'salida' => null,
'description' => strtolower($description),
'UnitCostValue' => $UnitCostValue,
'transactionId' => $transactionId,
'correlationId' => $correlationId,
'ProviderId' => $provider->getProvideridentifier(),
'urlDescription' => $urlDescription,
// 'QSE' => $infoQse->commission_money,
'FormaVentaButton' => ('true' == (string) $response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->FormaVenta && 0 == $valueReservation->getValue()) ? false : true,
];
if ($session->has($transactionId.'[availability_url]')) {
$twigVariables['referer'] = $session->get($transactionId.'[availability_url]');
}
if ($agency->getDomainsecure() == $agency->getDomain() && '443' != $agency->getCustomport()) {
$safeUrl = 'https://'.$agency->getDomain();
} else {
$safeUrl = 'https://'.$agency->getDomainsecure();
}
return $this->render($urlDetail, ['ProductsDetail' => $response->Message, 'salidaPackage' => $salidaPackage, 'variables' => $twigVariables, 'safeUrl' => $safeUrl]);
}
public function redirectDetailAction(Request $request, AviaturWebService $aviaturWebService, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, TwigFolder $twigFolder, $id)
{
$em = $this->managerRegistry;
$fullRequest = $request;
$request = $fullRequest->request;
$session = $this->session;
$agency = $this->agency;
$agencyFolder = $twigFolder->twigFlux();
$values = explode('-', $id);
$packageCode = $values[0];
$TipoProducto = $values[2];
$configPackageAgency = $em->getRepository(\Aviatur\PackageBundle\Entity\ConfigPackageAgency::class)->findProviderForPackagesWithAgency($agency);
$provider = $configPackageAgency[0]->getProvider();
$variable = [
'date' => date('Y-m-d'),
'packageCode' => $packageCode,
'nights' => $values[1],
'TipoProducto' => $values[2],
'ProviderId' => $provider->getProviderIdentifier(),
];
$packageModel = new PackageModel();
$xmlTemplate = $packageModel->getXmlDetail();
$xmlRequest = $xmlTemplate;
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'PkgDetail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, true);
//$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgDetail__RS.xml')));
if (isset($response['error']) || empty($response)) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/paquetes', 'Resultados de búsqueda', $response['error']));
}
$searchImages = ['http://static.aviatur.com/images'];
$replaceImages = ['https://static.aviatur.com/images'];
$response = simplexml_load_string(str_replace($searchImages, $replaceImages, $response->asXML()));
$transactionId = $response->Message->OTA_PkgAvailRS['TransactionIdentifier'];
if (!$session->has($transactionId.'[package_detail_url]')) {
$session->set($transactionId.'[package_detail_url]', $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params')));
}
$namePackage = mb_strtolower($response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->ProductName, 'UTF-8');
$namePackage = trim($namePackage);
$caracteresEspeciales = [',', ' - ', ' - ', '- ', ' -', ' - ', ' – ', '– ', ' –', ' – ', ' – ', '. ', '.', '...', '!', '¡', '!!', '¡¡', '#', '$', '%', '&', '(', ')', '*', '/', 'á', 'é', 'í', 'ó', 'ú', 'ñ', ' ', ' '];
$caracteres = ['', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '', '', '', '', '', '', ' porciento', 'y', '', '', '', '', 'a', 'e', 'i', 'o', 'u', 'n', '-', '-'];
$namePackageURL = str_replace($caracteresEspeciales, $caracteres, $namePackage);
return $this->redirectToRoute('aviatur_package_detail_secure', ['id' => $id, 'name' => $namePackageURL], 301);
}
public function cautionsAsyncAction(Request $request, AviaturWebService $aviaturWebService, ExceptionLog $exceptionLog, ParameterBagInterface $parameterBag, $id)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$providers = [];
if ($request->isXmlHttpRequest()) {
$domain = str_replace('www.', '', $request->getHost());
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$configPackageAgency = $em->getRepository(\Aviatur\PackageBundle\Entity\ConfigPackageAgency::class)->findProviderForPackagesWithAgency($agency);
$transactionId = $session->get($transactionIdSessionName);
$correlationId = $request->get('correlationId');
if ($configPackageAgency) {
$providers[] = $configPackageAgency[0]->getProvider()->getProvideridentifier();
} else {
$exceptionLog->log('Error Fatal', 'No se encontró la agencia segun el dominio: '.$domain, null, false);
return new Response('No se encontraron agencias para consultar disponibilidad.');
}
$provider = implode(';', $providers);
$values = explode('-', $id);
$OriginDate = date('Y-m-d');
$variable = [
'date' => $OriginDate,
'packageCode' => $values[0],
'transactionId' => $transactionId,
'correlationId' => $correlationId,
'ProviderId' => $provider,
'nights' => $values[1],
'TipoProducto' => $values[2],
];
$packageModel = new PackageModel();
$xmlTemplate = $packageModel->getXmlDetail();
$xmlRequest = $xmlTemplate;
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'PkgDetail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false, $variable['transactionId']);
//$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgDetail__RS.xml')));
if (!isset($response->Message) || !isset($response->Message->OTA_PkgAvailRS) || !isset($response->Message->OTA_PkgAvailRS->Package) || empty($response->Message)) {
return $this->json(['error' => 'Error en la respuesta de nuestro proveedor']);
} elseif (!isset($response) || !is_object($response->Message->OTA_PkgAvailRS->Package)) {
return $this->json(['error' => 'No hay información']);
} else {
$searchImages = ['http://static.aviatur.com/images'];
$replaceImages = ['https://static.aviatur.com/images'];
$response = simplexml_load_string(str_replace($searchImages, $replaceImages, $response->asXML()));
$cautions = [];
foreach ($response->Message->OTA_PkgAvailRS->Package->Cautions->Caution as $caution) {
if (\strlen((string) $caution)) {
switch ((string) $caution['ID'][0]) {
// map cautions to an array limited to six items
case 'ContentInclude':
$cautions['Included'][] = (string) $caution;
break;
case 'ContentNoInclude':
$cautions['NotIncluded'][] = (string) $caution;
break;
case 'Itinerary':
$cautions['Itinerary'][] = (string) $caution;
break;
case 'TravelerInformation':
case 'Observations':
$cautions['InfoTraveler'][] = (string) $caution;
break;
case 'AditionalNotes':
if ($session->has('operatorId')) {
$cautions['InfoAgent'][] = (string) $caution;
}
break;
case 'PaymentPolicy':
case 'CancellationRestrictionPolicy':
$cautions['Policy'][] = (string) $caution;
break;
case 'Conditions':
$cautions['Conditions'][] = (string) $caution;
break;
}
}
}
$count = 0;
if (isset($response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->RutasAereas->Ruta)) {
$cautions['TitulosRutas'] = [
'Origin' => 'Origen',
'Destination' => 'Destino',
'Airline' => 'Aerolinea',
'Flight' => 'Vuelo',
'DateFlight' => 'Fecha de Vuelo',
'DepartureHour' => 'Hora de Salida',
'DateFlightArrival' => 'Llegada de vuelo',
'ArriveHour' => 'Hora de llegada',
'Baggage' => 'Equipaje',
];
foreach ($response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->RutasAereas as $rutas) {
foreach ($rutas->Ruta as $ruta) {
$cautions['Rutas'][0][$count]['Origin'] = isset($ruta->Origin) ? (string) $ruta->Origin : (string) '';
$cautions['Rutas'][0][$count]['Destination'] = isset($ruta->Destination) ? (string) $ruta->Destination : (string) '';
$cautions['Rutas'][0][$count]['Airline'] = isset($ruta->Airline) ? (string) $ruta->Airline : (string) '';
$cautions['Rutas'][0][$count]['Flight'] = isset($ruta->Flight) ? (string) $ruta->Flight : (string) '';
$cautions['Rutas'][0][$count]['DateFlight'] = isset($ruta->DateFlight) ? (string) $ruta->DateFlight : (string) '';
$cautions['Rutas'][0][$count]['DepartureHour'] = isset($ruta->DepartureHour) ? (string) $ruta->DepartureHour.' '.$ruta->DepartureMinute : (string) '';
$cautions['Rutas'][0][$count]['DateFlightArrival'] = isset($ruta->DateFlightArrival) ? (string) $ruta->DateFlightArrival : (string) '';
$cautions['Rutas'][0][$count]['ArriveHour'] = isset($ruta->Baggage) ? (string) $ruta->ArriveHour.' '.$ruta->ArriveMinute : (string) '';
$cautions['Rutas'][0][$count]['Baggage'] = isset($ruta->Baggage) ? (string) $ruta->Baggage : (string) '';
++$count;
}
}
} elseif (isset($response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->RutasItinerarios->RutaItinerario)) {
$count = 0;
$Itinerary = [];
foreach ($response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->RutasItinerarios->RutaItinerario as $itinerarios) {
$Itinerary['Itinerarios'][0][$count]['Dia'] = isset($itinerarios->Dia) ? (string) rtrim($itinerarios->Dia) : (string) '';
$Itinerary['Itinerarios'][0][$count]['NombreDia'] = isset($itinerarios->NombreDia) ? rtrim((string) $itinerarios->NombreDia) : (string) '';
$Itinerary['Itinerarios'][0][$count]['HoraInicial'] = isset($itinerarios->HoraInicial) ? rtrim((string) $itinerarios->HoraInicial) : (string) '';
$Itinerary['Itinerarios'][0][$count]['HoraFinal'] = isset($itinerarios->HoraFinal) ? rtrim((string) $itinerarios->HoraFinal) : (string) '';
$Itinerary['Itinerarios'][0][$count]['Observacion'] = isset($itinerarios->Observacion) ? rtrim((string) $itinerarios->Observacion) : (string) '';
++$count;
}
$cautions['Itinerary'][1] = $Itinerary;
} else {
$cautions['Rutas'][0][0] = (string) '';
}
if ($configPackageAgency[0]->getTourismRegister()) {
$cautions['Policy'][] = (string) $response->Message->OTA_PkgAvailRS->Package->TPA_Extensions->ProductInfo->ResponsibilityPolicy[0];
}
return $this->json($cautions);
}
} else {
return new Response('Acceso Restringido');
}
}
public function ExportPdfAction(Request $request, ManagerRegistry $registry, PDF $pdf, ParameterBagInterface $parameterBag)
{
$projectDir = $parameterBag->get('kernel.project_dir');
$em = $this->managerRegistry;
$fullRequest = $request;
$request = $fullRequest->request;
$session = $this->session;
$server = $fullRequest->server;
$domain = $fullRequest->getHost();
$packageModel = new PackageModel();
$xmlTemplate = $packageModel->getResponse();
$xmlRequest = $xmlTemplate;
$response = simplexml_load_string($xmlRequest);
foreach ($response->Message->OTA_PkgAvailRS->Package as $information) {
foreach ($information->Cautions->Caution as $travelerInformation) {
$infoHtml[] = $travelerInformation->asXml();
}
}
$urlResume = 'AviaturPackageBundle:Default:resumePdf.html.twig';
$archive = $request->get('transactionId');
$voucherFile = $projectDir.'/app/serviceLogs/PackagePDF/'.$archive.'.pdf';
$pdf->generateFromHtml(
$this->renderView(
$urlResume,
['Package' => $response->Message->OTA_PkgAvailRS->Package, 'travelerInformation' => $infoHtml]
),
$voucherFile
);
die;
}
public function infoHotelAction(Request $request, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, TwigFolder $twigFolder, AuthorizationCheckerInterface $authorizationChecker, AviaturWebService $aviaturWebService)
{
$arrayCommission = [];
$tarifaCommissionPercentage = null;
$commissionActive = null;
$packageCommission = null;
$packageCommissionPercentage = null;
$isAgent = false;
$em = $this->managerRegistry;
$session = $this->session;
$parameterTax = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_payment_iva');
$aviaturPaymentIva = $parameterTax->getValue();
$fullRequest = $request;
$request = $fullRequest->request;
$agencyFolder = $twigFolder->twigFlux();
$dateStart = $request->get('dateStart');
$dateEnd = $request->get('dateEnd');
$packageCode = $request->get('packageCode');
$nights = $request->get('nights');
$TipoProducto = $request->get('TipoProducto');
$transactionID = $request->get('transactionId');
$correlationID = $request->get('correlationId');
$ProviderId = $request->get('ProviderId');
$UnitCostValue = $request->get('UnitCostValue');
$VigenciaFinal = $request->get('VigenciaFinal');
$detailXml = simplexml_load_string($session->get($transactionID.'[mpt][infoPackage]'));
if (0 == $UnitCostValue) {
$salida = strtotime('+'.$nights.'day ', strtotime($dateStart));
$salida = date('Y-m-d', $salida);
$days = $nights;
} elseif (1 == $UnitCostValue || 2 == $UnitCostValue) {
$salida = $dateEnd;
$segundos = strtotime($dateEnd) - strtotime($dateStart);
$days = (string) intval($segundos / 60 / 60 / 24);
}
$maxAditionals = (int) intval((strtotime($VigenciaFinal) - strtotime($dateEnd)) / 60 / 60 / 24);
$variable = [
'dateStart' => $dateStart,
'dateEnd' => $dateEnd,
'packageCode' => $packageCode,
'transactionId' => $transactionID,
'correlationId' => $correlationID,
'nights' => $nights,
'TipoProducto' => $TipoProducto,
'ProviderId' => $ProviderId,
];
$packageModel = new PackageModel();
// $xmlTemplate = $packageModel->getXmlDetail();
$xmlTemplate = $packageModel->getXmlFares();
$xmlRequest = $xmlTemplate;
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'PkgFares', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false, $variable['transactionId']);
//$response = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\PkgFares__RS.xml')));
// $transactionId = $session->get($transactionIdSessionName);
$transactionId = (string) $response->Message->OTA_PkgAvailRS['TransactionIdentifier'];
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
$nameProduct = 'package';
$productCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
$user = $this->getUser();
$emailuser = $user->getemail();
$agent = $user->getAgent();
if (!empty($agent[0])) {
$idagent = $agent[0]->getid();
$nombreagente = $user->getFirstname().' '.$user->getLastname();
$agencyFolder = $twigFolder->twigFlux();
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($idagent);
$infoQse = json_decode($agentCommission->getQseproduct());
$infoQseNameProduct = empty($infoQse->$nameProduct) ? false : $infoQse->$nameProduct;
$infoQse = empty($infoQse) ? false : $infoQseNameProduct;
$tarifaCommissionPercentage = $productCommission->getTacommissionpercentage();
$productCommissionPercentage = $productCommission->getQsecommissionpercentage();
$packageCommission = ($infoQse) ? (int) $infoQse->commission_money : 0;
$packageCommissionPercentage = ($infoQse) ? (float) $infoQse->commission_percentage : 0;
$commissionActive = ($infoQse) ? (int) $infoQse->active : 0;
$activeDetail = $agentCommission->getActivedetail();
$isAgent = true;
}
}
if (!isset($response) || isset($response['error'])) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_package_detail_secure'), '', 'No hay información'));
} else {
$serviceResponse = $response->Message->OTA_PkgAvailRS->Package;
$infoHotel = $response->Message->asXml();
$session->set($transactionID.'[mpt]'.'[InfoHotel]', $infoHotel);
$session->set($transactionID.'[mpt]'.'[ValueOptionals]', 0);
$session->set($transactionID.'[mpt]'.'[ValueSelection]', 0);
$session->set($transactionID.'[mpt]'.'[PriceOptionals]', 0);
$i = 0;
$j = 0;
$count = 0;
$error = 0;
$datesRoom = null;
$newDates = null;
$addDates = null;
$caracteres = ["'"];
if (!isset($detailXml->TPA_Extensions->ProductInfo->Description)) {
return $aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad');
}
$newDescription = str_replace($caracteres, '', strip_tags($detailXml->TPA_Extensions->ProductInfo->Description));
$datesTransaction = [
'UnitCostValue' => $UnitCostValue,
'days' => $days,
'entrada' => $dateStart,
'salida' => $dateEnd,
'IdPackage' => (string) $response->Message->OTA_PkgAvailRS->Package['ID'],
'ProductName' => (string) $detailXml->TPA_Extensions->ProductInfo->ProductName,
'Description' => $newDescription,
'CodeCiudad' => (string) $detailXml->TPA_Extensions->ProductInfo->CodeCiudad,
'TipoProducto' => (string) $detailXml->TPA_Extensions->ProductInfo->TipoProducto,
'CurrencyCode' => (string) $detailXml->TPA_Extensions->ProductInfo->CurrencyCode,
'FormaVenta' => (string) $detailXml->TPA_Extensions->ProductInfo->FormaVenta,
'UnitCostName' => (string) $detailXml->TPA_Extensions->ProductInfo->UnitCostName,
'ClaseServicio' => (string) $detailXml->TPA_Extensions->ProductInfo->ClaseServicio,
'Email' => (string) $detailXml->TPA_Extensions->ProductInfo->Email,
];
/* * ******************** Commision Por Tarifa *************************** */
$arrayCommission['isAgent'] = $isAgent;
if ($isAgent) {
$arrayCommission['commissionFarePay'] = round((float) $detailXml->TPA_Extensions->ProductInfo->Comision * $tarifaCommissionPercentage);
$arrayCommission['commissionActive'] = $commissionActive;
$arrayCommission['commissionAgent'] = ('0' == $commissionActive) ? $packageCommission : $packageCommissionPercentage;
$arrayCommission['commissionClaseServicio'] = $detailXml->TPA_Extensions->ProductInfo->ClaseServicio.'-'.(1 + $aviaturPaymentIva);
$arrayCommission['commissionActiveDetail'] = $activeDetail;
}
$datesTransaction['commissionInfo'] = $arrayCommission;
$totalTransaction = json_encode($datesTransaction);
$session->set($transactionID.'[mpt][totalTransaction]', $totalTransaction);
$datesRoom['datesTransaction'] = $datesTransaction;
$datesRoom['ServiciosOpcionales'] = $detailXml->TPA_Extensions->ProductInfo->CantidadServiciosOpcionales;
foreach ($detailXml->Cautions as $travelerInformation) {
foreach ($travelerInformation as $caution) {
$info = explode('</Caution>', str_replace($caution['ID'].'">', '</Caution>', $caution->asXml()));
$caution['Info'] = isset($info[1]) ? htmlspecialchars_decode($info[1]) : '';
$infoHtml = $travelerInformation;
$travelerInformation = $infoHtml;
}
}
foreach ($response->Message->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation as $Accommodation) {
$datesRoom['HotelCode'][$i][$j] = $Accommodation->Identity['HotelCode'];
$datesRoom['HotelName'][$i][$j] = $Accommodation->Identity['HotelName'];
$datesRoom['BrandCode'][$i][$j] = $Accommodation->Identity['BrandCode'];
foreach ($Accommodation->RoomProfiles->RoomProfile as $RoomProfile) {
$datesRoom['dateValidation'][$j] = $RoomProfile['EffectiveDate'].'*'.$RoomProfile['ExpireDate'].'*'.$RoomProfile['RoomTypeCode'];
$roomDate = explode('*', $datesRoom['dateValidation'][$j]);
$fechaIni = strtotime($roomDate[0]);
$fechaFin = strtotime($roomDate[1]);
if (strtotime($dateStart) >= $fechaIni && strtotime($salida) <= $fechaFin && (int) $RoomProfile['CotQuantity'] <= $days) {
$Rph = $RoomProfile['RPH'];
$AmountCHD[$i][$j] = 0;
$AmountADT[$i][$j] = 0;
$RangeCHD[$i][$j] = 0;
$datesRoom['ADN'][$i][$j] = 0;
$datesRoom['ADF'][$i][$j] = 0;
$datesRoom['ANF'][$i][$j] = 0;
$datesRoom['ADD'][$i][$j] = 0;
$datesRoom['AAN'][$i][$j] = 0;
$datesRoom['AFN'][$i][$j] = 0;
$AmountCHD[$i][$j] = 0;
$AmountCHN[$i][$j] = 0;
$AmountCHF[$i][$j] = 0;
$AmountCFN[$i][$j] = 0;
$FreeChildFlag = $RoomProfile['FreeChildFlag'];
$MinOccupancy = $RoomProfile['MinOccupancy'];
$MaxOccupancy = $RoomProfile['MaxOccupancy'];
$RoomTypeCode = (int) $RoomProfile['RoomTypeCode'];
$datesRoom['dateRoom'][$i][$RoomTypeCode] = $RoomProfile;
foreach ($RoomProfile->Prices->Price as $Amount) {
/* ----- DATOS ADULTOS ------ */
//Adulto
if ('ADT' == $Amount['PriceQualifier']) {
$AmountADT[$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
$RangeADT[$i][$j] = $Amount['RangeMinimum'].'|'.$Amount['RangeMaximum'];
}
//Adulto Noche Adicional
if ('ADN' == $Amount['PriceQualifier']) {
$datesRoom['ADN'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
}
//Adulto Fin de semana
if ('ADF' == $Amount['PriceQualifier']) {
$datesRoom['ADF'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
}
//Adulto Noche Adicional Fin de semana
if ('ANF' == $Amount['PriceQualifier']) {
$datesRoom['ANF'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
}
/* ----- DATOS ADULTOS ADICIONALES------ */
//Persona Adicional
if ('ADD' == $Amount['PriceQualifier']) {
$datesRoom['ADD'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
}
//Noche Adicional - Persona Adicional
if ('AAN' == $Amount['PriceQualifier']) {
$datesRoom['AAN'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
}
//Noche Adicional Adulto fin de semana
if ('AFN' == $Amount['PriceQualifier']) {
$datesRoom['AFN'][$i][$j] = $Amount['Amount'].'|'.$Amount['WeekDay'];
}
/* ----- DATOS CHILDREN ------ */
//Children
if ('CHD' == $Amount['PriceQualifier']) {
$newDates = $Amount['Age'].'-'.$Amount['AgeQualifyingCode'].'-'.$Amount['Amount'];
$AmountCHD[$i][$j] = $AmountCHD[$i][$j].'|'.$newDates;
$RangeCHD[$i][$j] = $Amount['RangeMinimum'].'|'.$Amount['RangeMaximum'];
}
//Noche Adicional Niño
if ('CHN' == $Amount['PriceQualifier']) {
$addDates = $Amount['Age'].'-'.$Amount['AgeQualifyingCode'].'-'.$Amount['Amount'];
$AmountCHN[$i][$j] = $AmountCHN[$i][$j].'|'.$addDates;
}
//Fin de semana Niño
if ('CHF' == $Amount['PriceQualifier']) {
$addDates = $Amount['Age'].'-'.$Amount['AgeQualifyingCode'].'-'.$Amount['Amount'];
$AmountCHF[$i][$j] = $AmountCHF[$i][$j].'|'.$addDates;
}
//Noche Adicional fin de semana Niño
if ('CFN' == $Amount['PriceQualifier']) {
$addDates = $Amount['Age'].'-'.$Amount['AgeQualifyingCode'].'-'.$Amount['Amount'];
$AmountCFN[$i][$j] = $AmountCFN[$i][$j].'|'.$addDates;
}
}
$dateRoomTrans[$i][$j] = $RoomProfile['MinOccupancy'].'*'.
$RoomProfile['MaxOccupancy'].'*'.
$AmountADT[$i][$j].'*'.
$datesRoom['ADN'][$i][$j].'*'.
$datesRoom['ADF'][$i][$j].'*'.
$datesRoom['ANF'][$i][$j].'*'.
$datesRoom['ADD'][$i][$j].'*'.
$datesRoom['AAN'][$i][$j].'*'.
$datesRoom['AFN'][$i][$j].'*'.
$AmountCHD[$i][$j].'*'.
$AmountCHN[$i][$j].'*'.
$AmountCHF[$i][$j].'*'.
$AmountCFN[$i][$j].'*'.
$RangeADT[$i][$j].'*'.
$RangeCHD[$i][$j].'*'.
$RoomTypeCode.'*'.
$Rph;
$datesRoom['dateRoomTrans'][$i][] = $dateRoomTrans[$i][$j];
++$count;
}
++$j;
}
++$i;
}
if (0 == $count) {
$error = 1;
}
$datesOptionals = $session->get($transactionID.'[mpt]'.'[ValueOptionals]');
$url = $session->get($transactionID.'[mpt]');
$urlDetail = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Includes/package_infoHotel.html.twig');
$twigVariables = [
'referer' => $url,
'nights' => $variable['nights'],
'count' => is_countable($response->Message->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation) ? count($response->Message->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation) : 0,
'dateStart' => $dateStart,
'dateEnd' => $dateEnd,
'datesRoom' => $datesRoom,
'packageCode' => $packageCode,
'TipoProducto' => $TipoProducto,
'transactionId' => $transactionID,
'ProviderId' => $ProviderId,
'error' => $error,
'datesOptionals' => $datesOptionals,
'maxAditionals' => ($maxAditionals > 0) ? ($maxAditionals > 6) ? 6 : $maxAditionals : 0,
];
return $this->render($urlDetail, ['totalTransaction' => $totalTransaction, 'response' => $serviceResponse, 'datesRoom' => $datesRoom, 'variables' => $twigVariables]);
}
}
public function InfoHotelErrorAction(Request $request, AviaturErrorHandler $aviaturErrorHandler, TwigFolder $twigFolder, RouterInterface $router, 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 puede acceder al detalle sin disponibilidad'));
} elseif (true === $session->has($transactionId.'[package_detail_url]')) {
return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[package_detail_url]'), 'Página no accesible', 'No puede 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éntelo nuevamente'));
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
}
public function OptionalsAction(Request $request, TwigFolder $twigFolder, AviaturWebService $aviaturWebService)
{
$fullRequest = $request;
$request = $fullRequest->request;
$session = $this->session;
$agencyFolder = $twigFolder->twigFlux();
$date = $request->get('date');
$destionation = $request->get('destionation');
$TipoProducto = $request->get('TipoProducto');
$transactionID = $request->get('transactionId');
$ProviderId = $request->get('ProviderId');
$salida = $request->get('salida');
$variable = [
'date' => $date,
'destination' => $destionation,
'transactionId' => $transactionID,
'TipoProducto' => $TipoProducto,
'ProviderId' => $ProviderId,
'salida' => $salida,
];
$packageModel = new PackageModel();
$xmlTemplate = $packageModel->getOptionals();
$xmlRequest = $xmlTemplate;
$salidaOpcionals = null;
$count = 0;
$totalTransaction = $session->get($transactionID.'[mpt][totalTransaction]');
$ValueSelection = $session->get($transactionID.'[mpt][ValueSelection]');
$response = $aviaturWebService->callWebServiceAmadeus('SERVICIO_MPT', 'PkgOptions', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, false, $variable['transactionId']);
if (!isset($response->Message) || empty($response->Message)) {
$response = "<font color='red'>Ha ocurrido un error inesperado en la consulta de Opcionales</font>";
$infoOptionals = $response;
} else {
$infoOptionals = $response->Message->OTA_PkgAvailRS->asXml();
}
$session->set($transactionID.'[mpt]'.'[infoOptionals]', $infoOptionals);
if (isset($response->Message->OTA_PkgAvailRS->Package)) {
$searchImages = ['http://static.aviatur.com/images'];
$replaceImages = ['https://static.aviatur.com/images'];
$response = simplexml_load_string(str_replace($searchImages, $replaceImages, $response->asXML()));
foreach ($response->Message->OTA_PkgAvailRS->Package as $information) {
foreach ($information->TPA_Extensions->ServiciosOpcionales->TravelerInformation as $travelerInformation) {
$infoHtml = $travelerInformation->asXml();
$infoPrint = $travelerInformation;
$travelerInformation->html = $infoHtml;
$travelerInformation->htmlPrint = $travelerInformation;
}
foreach ($information->TPA_Extensions->ServiciosOpcionales->TarifasServiciosOpc->Tarifas as $dataInfo) {
++$count;
}
$BeginDate = $information->DateRange['Start'];
$EndDate = $information->DateRange['End'];
$salidaOpcionals = date('Y/m/d', strtotime($BeginDate)).'*'.date('Y/m/d', strtotime($EndDate));
}
} else {
$response = "<font color='red'>Ha ocurrido un error inesperado en la consulta de Opcionales</font>";
}
$urlDetail = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/optionals.html.twig');
return $this->render($urlDetail, ['totalTransaction' => $totalTransaction, 'countInfo' => $count, 'salidaOpcionals' => $salidaOpcionals, 'ProductsDetail' => $response, 'variables' => ['ValueSelection' => $ValueSelection, 'date' => $date, 'destionation' => $destionation, 'TipoProducto' => $TipoProducto, 'transactionId' => $transactionID, 'ProviderId' => $ProviderId]]);
}
public function OptionalsErrorAction(Request $request, AviaturErrorHandler $aviaturErrorHandler, TwigFolder $twigFolder, SessionInterface $session, RouterInterface $router, 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 puede 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éntelo nuevamente'));
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
}
public function AditionalPriceAction(Request $fullRequest)
{
$Amount = null;
$request = $fullRequest->request;
$session = $this->session;
$infoTransaction = $request->get('infoTransaction');
$transactionID = $request->get('transactionId');
if ('optionals' == $infoTransaction) {
$TotalvalueOptionals = $request->get('Totalvalue');
$totalValuesOptionals = $request->get('totalValues');
if ('0' == $TotalvalueOptionals || '' == $TotalvalueOptionals) {
$session->set($transactionID.'[mpt]'.'[ValueOptionals]', '');
$session->set($transactionID.'[mpt]'.'[PriceOptionals]', '');
$Amount = $request->get('Amount');
} else {
$session->set($transactionID.'[mpt]'.'[ValueOptionals]', $totalValuesOptionals);
$session->set($transactionID.'[mpt]'.'[PriceOptionals]', $TotalvalueOptionals);
$Amount = $request->get('Amount');
}
} elseif ('transaction' == $infoTransaction) {
$Amount = $request->get('Amount');
$session->set($transactionID.'[mpt]'.'[ValueSelection]', $Amount);
}
return new Response($Amount);
}
public function AditionalsPriceErrorAction(Request $request, RouterInterface $router, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, TwigFolder $twigFolder, 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 puede 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éntelo nuevamente'));
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
}
public function documentationAction(Request $fullRequest, AviaturWebService $aviaturWebService, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, TwigFolder $twigFolder)
{
$request = $fullRequest->request;
$codeCountry = $request->get('codeCountry');
$documentationModel = new Models\DocumentationModel();
$xmlTemplate = $documentationModel->getXml($codeCountry);
$agencyFolder = $twigFolder->twigFlux();
$response = $aviaturWebService->callWebService('GENERALLAVE', 'dummy|http://www.aviatur.com.co/dummy/', $xmlTemplate);
if (isset($response->RESULTADO)) {
$response = 'No se encuentra Información del país seleccionado';
}
$urlDetail = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/package_Documentation.html.twig');
return $this->render($urlDetail, ['response' => $response]);
}
public function documentationErrorAction(Request $request, TwigFolder $twigFolder, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, 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 puede 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éntelo nuevamente'));
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
}
public function formreservaAction(AviaturWebService $aviaturWebService, AviaturLogSave $aviaturLogSave, CustomerMethodPaymentService $customerMethodPaymentService, Request $request, AviaturLoginService $aviaturLoginService, TokenStorageInterface $tokenStorage, AuthorizationCheckerInterface $authorizationChecker, TwigFolder $twigFolder, ManagerRegistry $registry, ParameterBagInterface $parameterBag, AviaturErrorHandler $aviaturErrorHandler)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$transactionId = null;
$room = [];
$AddPerson = [];
$AditionalRoom = [];
$personTotal = [];
$codigoHotel = [];
$codigoRoom = [];
$codigoBrand = [];
$typeRoom = [];
$categoryRoom = [];
$codeBooking = [];
$adtCant = [];
$chdCant = [];
$aditionalPerson = [];
$totalTarifas = [];
$tarifaReal = [];
$TotalValor = [];
$tarifaCommissionPercentage = null;
$commissionActive = null;
$packageCommissionPercentage = null;
$productCommissionPercentage = null;
$exchangeValues = null;
$typePerson = [];
$detail_data_package = null;
$isAgent = false;
$em = $this->managerRegistry;
$parameterTax = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_payment_iva');
$aviaturPaymentIva = $parameterTax->getValue();
$fullRequest = $request;
$session = $this->session;
$productInfo = new PackageModel();
$agency = $this->agency;
$request = $fullRequest->request;
$domain = $fullRequest->getHost();
$routeName = $fullRequest->get('_route');
$agencyFolder = $twigFolder->twigFlux();
$typeGender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
$typeDocument = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$conditions = $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'reservation_conditions');
if (true === $request->has('transactionId')) {
$transactionId = $request->get('transactionId');
$session->set($transactionIdSessionName, $transactionId);
$session->set($transactionId.'[mpt]'.'[request]', $request);
} elseif (true === $session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
$request = $session->get($transactionId.'[mpt]'.'[request]');
}
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
$nameProduct = 'package';
$productCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
$user = $this->getUser();
$emailuser = $user->getemail();
$agent = $user->getAgent();
if (!empty($agent[0])) {
$idagent = $agent[0]->getid();
$nombreagente = $user->getFirstname().' '.$user->getLastname();
$agencyFolder = $twigFolder->twigFlux();
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($idagent);
$infoQse = json_decode($agentCommission->getQseproduct());
$infoQseNameProduct = empty($infoQse->$nameProduct) ? false : $infoQse->$nameProduct;
$infoQse = empty($infoQse) ? false : $infoQseNameProduct;
$tarifaCommissionPercentage = $productCommission->getTacommissionpercentage();
$productCommissionPercentage = $productCommission->getQsecommissionpercentage();
$packageCommission = ($infoQse) ? (int) $infoQse->commission_money : 0;
$packageCommissionPercentage = ($infoQse) ? (float) $infoQse->commission_percentage : 0;
$commissionActive = ($infoQse) ? (int) $infoQse->active : 0;
$activeDetail = $agentCommission->getActivedetail();
$isAgent = true;
}
}
if ('aviatur_package_retry_secure' == $routeName) {
$reintento = true;
$twig_readonly = true;
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findOneByProvideridentifier($session->get($transactionId.'[mpt][provider]'));
$ValuePrestador = $session->get($transactionId.'[mpt][ValuePrestador]');
$detail = $session->get($transactionId.'[mpt]'.'[detail]');
$TotalADT = $detail->get('TotalADT');
$TotalCHD = $detail->get('TotalCHD');
$parameters = $detail->get('parameters');
$detail_data_package = json_decode($session->get($transactionId.'[mpt]'.'[detail_data_package]'));
$billingData = $detail_data_package->BD;
$infopassenger = $detail_data_package->PI;
$paymentData = $detail_data_package->PD;
$contactData = $detail_data_package->CD;
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($detail_data_package->BD->id);
if (isset($paymentData->cusPOptSelected) && true === $aviaturLoginService->validActiveSession()) {
$customerLogin = $tokenStorage->getToken()->getUser();
if (is_object($customerLogin)) {
$paymentsSaved = $customerMethodPaymentService->getMethodsByCustomer($customerLogin, false);
}
}
} else {
$TotalADT = $request->get('TotalADT');
$TotalCHD = $request->get('TotalCHD');
$parameters = $request->get('parameters');
$reintento = false;
$twig_readonly = false;
$infopassenger = '';
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findOneByProvideridentifier($request->get('ProviderId'));
if (isset($provider)) {
$session->set($transactionId.'[mpt]'.'[provider]', $provider->getProvideridentifier());
$session->set($transactionId.'[mpt][detail]', $request);
$session->set($transactionId.'[mpt]'.'[TotalADT]', $TotalADT);
$session->set($transactionId.'[mpt]'.'[TotalCHD]', $TotalCHD);
$ValuePrestador = substr($request->get('ValuePrestador'), 1);
$session->set($transactionId.'[mpt]'.'[ValuePrestador]', $ValuePrestador);
if (0 == $session->get($transactionId.'[mpt]'.'[ValueOptionals]')) {
$session->set($transactionId.'[mpt]'.'[infoOptionals]', null);
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
}
$aviaturLogSave->logSave(print_r($request, true), 'PkgRequestDetail', 'RQ', $transactionId);
$datesTransaction = json_decode($session->get($transactionId.'[mpt][totalTransaction]'), true);
$infoHotel = simplexml_load_string($session->get($transactionId.'[mpt][InfoHotel]'));
$infopackage = simplexml_load_string($session->get($transactionId.'[mpt][infoPackage]'));
$paymentOptions = [];
$cybersource = [];
$banks = [];
$isPaymentOnline = 'true' == $infopackage->TPA_Extensions->ProductInfo->FormaVenta;
if ($isPaymentOnline) {
$paymentMethodAgency = $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency, 'isactive' => 1]);
foreach ($paymentMethodAgency as $payMethod) {
$paymentCode = $payMethod->getPaymentMethod()->getCode();
if (!in_array($paymentCode, $paymentOptions)) {
if ('p2p' == $paymentCode || 'cybersource' == $paymentCode) {
$paymentOptions[] = $paymentCode;
}
}
}
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
}
}
if (in_array('pse', $paymentOptions)) {
$banks = $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
}
}
$tarifas = [
'AmountADT' => 0,
'AmountADN' => 0,
'AmountADF' => 0,
'AmountANF' => 0,
'AmountADD' => 0,
'AmountAAN' => 0,
'AmountAFN' => 0,
'AmountCHD' => 0,
'AmountCHN' => 0,
'AmountCHF' => 0,
'AmountCFN' => 0,
];
$WeekDay = [
'ADT' => 0,
'ADN' => 0,
'ADF' => 0,
'ANF' => 0,
'ADD' => 0,
'AAN' => 0,
'AFN' => 0,
'CHD' => 0,
'CHN' => 0,
'CHF' => 0,
'CFN' => 0,
];
$ageMinCHD = null;
$ageMaxCHD = null;
$ChdValues = null;
$ageMinCHN = null;
$ageMaxCHN = null;
$ChnValues = null;
$ageMinCHF = null;
$ageMaxCHF = null;
$ChfValues = null;
$ageMinCFN = null;
$ageMaxCFN = null;
$CfnValues = null;
$subTotal = 0;
$Amount = 0;
$CantADT = 0;
$CantCHD = 0;
$ChdAmount = 0;
$ChnAmount = 0;
$TotalDays = $datesTransaction['days'];
$UnitCostValue = $datesTransaction['UnitCostValue'];
$UnitCostName = $datesTransaction['UnitCostName'];
$countFestivos = 0;
$selectValue = null;
$AmountTotal = 0;
$Name = $ValuePrestador;
$search = '|';
$verification = strpos($Name, $search);
/* Cuenta los fines de semana */
$fecha1 = $datesTransaction['entrada'];
$fecha2 = $datesTransaction['salida'];
$PriceOptionals = $session->get($transactionId.'[mpt]'.'[PriceOptionals]');
$AmountBaby = 0;
if (false === $verification) {
$datePrestador = $ValuePrestador;
$prestadorValue = explode('*', $datePrestador);
$CodeRoom = $prestadorValue[0];
$BrandCode = $prestadorValue[1];
$CodeHotel = $prestadorValue[2];
$RoomType = $prestadorValue[3];
$RoomCategory = $prestadorValue[4];
$BookingCode = $prestadorValue[5];
$iteration = $prestadorValue[6];
$cantADT = $prestadorValue[7];
$cantCHD = $prestadorValue[8];
$TotalPerson = $cantADT + $cantCHD;
$room[] = $prestadorValue[9];
$PersonAdd = $prestadorValue[10];
$AddPerson[] = $PersonAdd;
$AditionalRoom[] = $room;
$personTotal[] = $TotalPerson;
$codigoHotel[] = $CodeHotel;
$codigoRoom[] = $CodeRoom;
$codigoBrand[] = $BrandCode;
$typeRoom[] = $RoomType;
$categoryRoom[] = $RoomCategory;
$codeBooking[] = $BookingCode;
$adtCant[] = $cantADT;
$chdCant[] = $cantCHD;
$ADTotal = $parameters['adults_'.$iteration];
$CHDTotal = $parameters['children_'.$iteration];
$CantADT = $ADTotal + $CantADT;
$CantCHD = $CHDTotal + $CantCHD;
if (isset($AditionalRoom[0][0])) {
$final = strtotime('+'.$AditionalRoom[0][0].'day', strtotime($fecha2));
$final = date('Y-m-d', $final);
$fecha2 = $final;
}
if (empty($parameters['roomAditional_'.$iteration])) {
$parameters['roomAditional_'.$iteration] = 0;
}
if (empty($parameters['personAditional_'.$iteration])) {
$parameters['personAditional_'.$iteration] = 0;
}
$age = explode(',', $parameters['room_'.$iteration.'_childage']);
for ($i = 1; $i <= $CHDTotal; ++$i) {
$selectValue[] = (string) $age[$i - 1];
}
$roomAditional = $parameters['roomAditional_'.$iteration];
$personAditional = $parameters['personAditional_'.$iteration];
$aditionalPerson[] = $personAditional;
foreach ($infoHotel->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation as $Accommodations) {
$BrandCode = $Accommodations->Identity['BrandCode'];
$HotelCode = $Accommodations->Identity['HotelCode'];
if ($HotelCode == $CodeHotel) {
foreach ($Accommodations->RoomProfiles->RoomProfile as $RoomProfiles) {
$RoomTypeCode = $RoomProfiles['RoomTypeCode'];
if ($RoomTypeCode == $CodeRoom) {
$BrandName[] = isset($Accommodations->Identity['BrandName']) ? (int) $Accommodations->Identity['BrandName'] : '';
foreach ($RoomProfiles->Prices->Price as $RoomProfile) {
/* Calculo de Tarifa Adulto */
if ('ADT' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountADT'] = (int) $RoomProfile['Amount'];
$WeekDay['ADT'] = $RoomProfile['WeekDay'];
$tarifas['ADTotal'] = $ADTotal;
$tarifas['CountADT'] = (int) $RoomProfile['Count'];
}
if ('ADN' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountADN'] = (int) $RoomProfile['Amount'];
$WeekDay['ADN'] = $RoomProfile['WeekDay'];
$tarifas['CountADN'] = (int) $RoomProfile['Count'];
}
if ('ADF' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountADF'] = (int) $RoomProfile['Amount'];
$WeekDay['ADF'] = $RoomProfile['WeekDay'];
$tarifas['CountADF'] = (int) $RoomProfile['Count'];
}
if ('ANF' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountANF'] = (int) $RoomProfile['Amount'];
$WeekDay['ANF'] = $RoomProfile['WeekDay'];
$tarifas['CountANF'] = (int) $RoomProfile['Count'];
}
if ('ADD' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountADD'] = (int) $RoomProfile['Amount'];
$WeekDay['ADD'] = $RoomProfile['WeekDay'];
$tarifas['CountADD'] = (int) $RoomProfile['Count'];
}
if ('AAN' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountAAN'] = (int) $RoomProfile['Amount'];
$WeekDay['AAN'] = $RoomProfile['WeekDay'];
$tarifas['CountAAN'] = (int) $RoomProfile['Count'];
}
if ('AFN' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountAFN'] = (int) $RoomProfile['Amount'];
$WeekDay['AFN'] = $RoomProfile['WeekDay'];
$tarifas['CountAFN'] = (int) $RoomProfile['Count'];
}
if ('CHD' == $RoomProfile['PriceQualifier']) {
$ageMinCHD[] = (string) $RoomProfile['Age'];
$ageMaxCHD[] = (string) $RoomProfile['AgeQualifyingCode'];
$ChdValues[] = (string) $RoomProfile['Amount'];
$ChdAmount = $RoomProfile['Amount'];
$WeekDay['CHD'] = $RoomProfile['WeekDay'];
$tarifas['CHDTotal'] = $CHDTotal;
$tarifas['ageMinCHD'] = (int) $RoomProfile['Age'];
$tarifas['ageMaxCHD'] = (int) $RoomProfile['AgeQualifyingCode'];
$tarifas['CountCHD'] = (int) $RoomProfile['Count'];
}
if ('CHN' == $RoomProfile['PriceQualifier']) {
$ageMinCHN[] = (string) $RoomProfile['Age'];
$ageMaxCHN[] = (string) $RoomProfile['AgeQualifyingCode'];
$ChnValues[] = (string) $RoomProfile['Amount'];
$ChnAmount = $RoomProfile['Amount'];
$WeekDay['CHN'] = $RoomProfile['WeekDay'];
$tarifas['CountCHN'] = (int) $RoomProfile['Count'];
}
if ('CHF' == $RoomProfile['PriceQualifier']) {
$ageMinCHF[] = (string) $RoomProfile['Age'];
$ageMaxCHF[] = (string) $RoomProfile['AgeQualifyingCode'];
$ChfValues[] = (string) $RoomProfile['Amount'];
$WeekDay['CHF'] = $RoomProfile['WeekDay'];
$tarifas['CountCHF'] = (int) $RoomProfile['Count'];
}
if ('CFN' == $RoomProfile['PriceQualifier']) {
$ageMinCFN[] = (string) $RoomProfile['Age'];
$ageMaxCFN[] = (string) $RoomProfile['AgeQualifyingCode'];
$CfnValues[] = (string) $RoomProfile['Amount'];
$WeekDay['CFN'] = $RoomProfile['WeekDay'];
$tarifas['CountCFN'] = (int) $RoomProfile['Count'];
}
}
}
}
}
}// End Foreach
if (0 == $UnitCostValue) {
/* si Unidad de costo = 0 la tarifa es por estadia */
$TotalDays = 1;
} elseif (2 == $UnitCostValue) {
/* si Unidad de costo = 2 la tarifa es por ocupación */
$ADTotal = 1;
if ($CHDTotal > 0) {
$CHDTotal = 1;
}
}
if ($tarifas['AmountADF'] > 0) {
/* -------------------- Cálculo cuando hay tarifa fin de semana -------------------------- */
$Amount = $this->calculoTarifaFinDeSemana($roomAditional, $personAditional, $fecha1, $fecha2, $ADTotal, $CHDTotal, $tarifas, $WeekDay, $ageMinCHD, $ageMaxCHD, $ChdValues, $selectValue, $ageMinCHN, $ageMaxCHN, $ChnValues, $ageMinCHF, $ageMaxCHF, $ChfValues, $ageMinCFN, $ageMaxCFN, $CfnValues, $UnitCostValue, $datesTransaction['days']);
$totalTarifas[] = $Amount['tarifas'];
$tarifaReal[] = $Amount['tarifaReal'];
$Amount = $Amount['SubTotal'];
} else {
/* -------------------- Cálculo cuando NO hay tarifa fin de semana -------------------------- */
$subTotal = $tarifas['AmountADT'] * $ADTotal * $TotalDays;
$AmountBaby = 0;
if ($ChdAmount > 0) {
$tarifas['AmountCHD'] = $this->AmountCHD($AmountBaby, $selectValue, $ageMinCHD, $ageMaxCHD, $tarifas['AmountADT'], $ChdValues);
$subTotal = $subTotal + ($tarifas['AmountCHD'] * $TotalDays);
}
if ($ChnAmount > 0) {
$tarifas['AmountCHN'] = $this->AmountCHD($AmountBaby, $selectValue, $ageMinCHN, $ageMaxCHN, $tarifas['AmountADN'], $ChnValues);
}
$totalTarifas[] = $tarifas;
$Amount = $this->calculoTarifa($subTotal, $TotalDays, $tarifas, $roomAditional, $personAditional, $ADTotal, $CHDTotal, $datesTransaction['days']);
$tarifaReal[] = $Amount['tarifaReal'];
$Amount = $Amount['SubTotal'];
}
$TotalValor[] = $Amount;
$Amount = $Amount + $PriceOptionals;
} else {
$prestador = explode('|', $ValuePrestador);
foreach ($prestador as $datePrestador) {
$prestadorValue = explode('*', $datePrestador);
$CodeRoom = $prestadorValue[0];
$BrandCode = $prestadorValue[1];
$CodeHotel = $prestadorValue[2];
$RoomType = $prestadorValue[3];
$RoomCategory = $prestadorValue[4];
$BookingCode = $prestadorValue[5];
$iteration = $prestadorValue[6];
$cantADT = $prestadorValue[7];
$cantCHD = $prestadorValue[8];
$TotalPerson = $cantADT + $cantCHD;
$room[] = $prestadorValue[9];
$PersonAdd = $prestadorValue[10];
$AddPerson[] = $PersonAdd;
$AditionalRoom[] = $room;
$personTotal[] = $TotalPerson;
$codigoHotel[] = $CodeHotel;
$codigoRoom[] = $CodeRoom;
$codigoBrand[] = $BrandCode;
$typeRoom[] = $RoomType;
$categoryRoom[] = $RoomCategory;
$codeBooking[] = $BookingCode;
$adtCant[] = $cantADT;
$chdCant[] = $cantCHD;
$ChdValues = [];
$ChnValues = [];
$ChfValues = [];
$CfnValues = [];
$ADTotal = $parameters['adults_'.$iteration];
$CHDTotal = $parameters['children_'.$iteration];
if (isset($AditionalRoom[0][0])) {
$final = strtotime('+'.$AditionalRoom[0][0].'day', strtotime($fecha2));
$final = date('Y-m-d', $final);
$fecha2 = $final;
}
$CantADT = $ADTotal + $CantADT;
$CantCHD = $CHDTotal + $CantCHD;
if (empty($parameters['roomAditional_'.$iteration])) {
$parameters['roomAditional_'.$iteration] = 0;
}
if (empty($parameters['personAditional_'.$iteration])) {
$parameters['personAditional_'.$iteration] = 0;
}
$selectValue = null;
$age = explode(',', $parameters['room_'.$iteration.'_childage']);
for ($i = 1; $i <= $CHDTotal; ++$i) {
$selectValue[] = (string) $age[$i - 1];
}
$roomAditional = $parameters['roomAditional_'.$iteration];
$personAditional = $parameters['personAditional_'.$iteration];
$aditionalPerson[] = $personAditional;
foreach ($infoHotel->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation as $Accommodations) {
$BrandCode = $Accommodations->Identity['BrandCode'];
$HotelCode = $Accommodations->Identity['HotelCode'];
if ($HotelCode == $CodeHotel) {
$BrandName[] = (int) $Accommodations->Identity['BrandName'];
foreach ($Accommodations->RoomProfiles->RoomProfile as $RoomProfiles) {
$RoomTypeCode = $RoomProfiles['RoomTypeCode'];
if ($RoomTypeCode == $CodeRoom) {
foreach ($RoomProfiles->Prices->Price as $RoomProfile) {
/* Calculo de Tarifa Adulto */
if ('ADT' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountADT'] = (int) $RoomProfile['Amount'];
$WeekDay['ADT'] = $RoomProfile['WeekDay'];
$tarifas['ADTotal'] = $ADTotal;
$tarifas['CountADT'] = (int) $RoomProfile['Count'];
}
if ('ADN' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountADN'] = (int) $RoomProfile['Amount'];
$WeekDay['ADN'] = $RoomProfile['WeekDay'];
$tarifas['CountADN'] = (int) $RoomProfile['Count'];
}
if ('ADF' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountADF'] = (int) $RoomProfile['Amount'];
$WeekDay['ADF'] = $RoomProfile['WeekDay'];
$tarifas['CountADF'] = (int) $RoomProfile['Count'];
}
if ('ANF' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountANF'] = (int) $RoomProfile['Amount'];
$WeekDay['ANF'] = $RoomProfile['WeekDay'];
$tarifas['CountANF'] = (int) $RoomProfile['Count'];
}
if ('ADD' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountADD'] = (int) $RoomProfile['Amount'];
$WeekDay['ADD'] = $RoomProfile['WeekDay'];
$tarifas['CountADD'] = (int) $RoomProfile['Count'];
}
if ('AAN' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountAAN'] = (int) $RoomProfile['Amount'];
$WeekDay['AAN'] = $RoomProfile['WeekDay'];
$tarifas['CountAAN'] = (int) $RoomProfile['Count'];
}
if ('AFN' == $RoomProfile['PriceQualifier']) {
$tarifas['AmountAFN'] = (int) $RoomProfile['Amount'];
$WeekDay['AFN'] = $RoomProfile['WeekDay'];
$tarifas['CountAFN'] = (int) $RoomProfile['Count'];
}
if ('CHD' == $RoomProfile['PriceQualifier']) {
$ageMinCHD[] = (string) $RoomProfile['Age'];
$ageMaxCHD[] = (string) $RoomProfile['AgeQualifyingCode'];
$ChdValues[] = (string) $RoomProfile['Amount'];
$ChdAmount = $RoomProfile['Amount'];
$tarifas['CHDTotal'] = $CHDTotal;
$tarifas['ageMinCHD'] = (int) $RoomProfile['Age'];
$tarifas['ageMaxCHD'] = (int) $RoomProfile['AgeQualifyingCode'];
$tarifas['CountCHD'] = (int) $RoomProfile['Count'];
}
if ('CHN' == $RoomProfile['PriceQualifier']) {
$ageMinCHN[] = (string) $RoomProfile['Age'];
$ageMaxCHN[] = (string) (int) $RoomProfile['AgeQualifyingCode'];
$ChnValues[] = (string) (int) $RoomProfile['Amount'];
$ChnAmount = $RoomProfile['Amount'];
$WeekDay['CHN'] = $RoomProfile['WeekDay'];
$tarifas['CountCHN'] = (int) $RoomProfile['Count'];
}
if ('CHF' == $RoomProfile['PriceQualifier']) {
$ageMinCHF[] = (string) $RoomProfile['Age'];
$ageMaxCHF[] = (string) $RoomProfile['AgeQualifyingCode'];
$ChfValues[] = (string) $RoomProfile['Amount'];
$WeekDay['CHF'] = $RoomProfile['WeekDay'];
$tarifas['CountCHN'] = (int) $RoomProfile['Count'];
}
if ('CFN' == $RoomProfile['PriceQualifier']) {
$ageMinCFN[] = (string) $RoomProfile['Age'];
$ageMaxCFN[] = (string) $RoomProfile['AgeQualifyingCode'];
$CfnValues[] = (string) $RoomProfile['Amount'];
$WeekDay['CFN'] = $RoomProfile['WeekDay'];
$tarifas['CountCFN'] = (int) $RoomProfile['Count'];
}
}
}
}
}
}// End Foreach
if (0 == $UnitCostValue) {
/* si Unidad de costo = 0 la tarifa es por estadia */
$TotalDays = 1;
} elseif (2 == $UnitCostValue) {
/* si Unidad de costo = 2 la tarifa es por ocupación */
$ADTotal = 1;
if ($CHDTotal > 0) {
$CHDTotal = 1;
}
}
if ($tarifas['AmountADF'] > 0) {
/* -------------------- Cálculo cuando hay tarifa fin de semana -------------------------- */
$SubTotal = $this->calculoTarifaFinDeSemana($roomAditional, $personAditional, $fecha1, $fecha2, $ADTotal, $CHDTotal, $tarifas, $WeekDay, $ageMinCHD, $ageMaxCHD, $ChdValues, $selectValue, $ageMinCHN, $ageMaxCHN, $ChnValues, $ageMinCHF, $ageMaxCHF, $ChfValues, $ageMinCFN, $ageMaxCFN, $CfnValues, $UnitCostValue, $datesTransaction['days']);
$totalTarifas[] = $SubTotal['tarifas'];
$tarifaReal[] = $SubTotal['tarifaReal'];
$SubTotal = $SubTotal['SubTotal'];
} else {
/* -------------------- Cálculo cuando NO hay tarifa fin de semana -------------------------- */
$subTotal = $tarifas['AmountADT'] * $ADTotal * $TotalDays;
$AmountBaby = 0;
if ($ChdAmount > 0) {
$tarifas['AmountCHD'] = 0;
$tarifas['AmountCHD'] = $this->AmountCHD($AmountBaby, $selectValue, $ageMinCHD, $ageMaxCHD, $tarifas['AmountADT'], $ChdValues);
$subTotal = $subTotal + ($tarifas['AmountCHD'] * $TotalDays);
}
if ($ChnAmount > 0) {
$tarifas['AmountCHN'] = $this->AmountCHD($AmountBaby, $selectValue, $ageMinCHN, $ageMaxCHN, $tarifas['AmountADN'], $ChnValues);
}
$SubTotal = $this->calculoTarifa($subTotal, $TotalDays, $tarifas, $roomAditional, $personAditional, $ADTotal, $CHDTotal, $datesTransaction['days']);
$totalTarifas[] = $tarifas;
$tarifaReal[] = $SubTotal['tarifaReal'];
$SubTotal = $SubTotal['SubTotal'];
}
$Amount = $Amount + $SubTotal;
$ValorTotal[] = $SubTotal;
$TotalValor = $ValorTotal;
}
$Amount = $Amount + $PriceOptionals;
}
if (isset($AditionalRoom)) {
$keys = array_pop($AditionalRoom);
$keys2 = max($keys);
$final = strtotime('+'.$keys2.'day', strtotime($datesTransaction['salida']));
$final = date('Y-m-d', $final);
$datesTransaction['salida'] = $final;
}
$arrayCommissionAgent = [$isAgent];
/* * ***************************** Commission Agent *********************** */
if ($isAgent) {
$commissionFare = round((float) $infopackage->TPA_Extensions->ProductInfo->Comision * $tarifaCommissionPercentage);
$claseServicio = $infopackage->TPA_Extensions->ProductInfo->ClaseServicio;
$totalAmount = ('N' == $claseServicio) ? (float) $Amount / (float) (1 + $aviaturPaymentIva) : $Amount;
//$totalAmount=round($totalAmount);
$commissionFareAll = round($totalAmount * ((float) $infopackage->TPA_Extensions->ProductInfo->Comision / 100));
$commissionFare = round($totalAmount * ($commissionFare / 100));
$agentCommission = $packageCommission;
$textCommission = 'QSE($)';
if ('1' == $commissionActive) {
$agentCommission = round($totalAmount * $packageCommissionPercentage);
$textCommission = 'QSE(%)';
}
$Amount += (float) $agentCommission;
$valueQsePay = round(($agentCommission / (1 + $aviaturPaymentIva)) * $productCommissionPercentage);
$commissionPay = $commissionFare + $valueQsePay;
$info_product = [
'amountQse' => (float) $agentCommission,
'commissionQse' => (float) $valueQsePay,
'amountTa' => (float) $commissionFareAll,
'commissionTa' => (float) $commissionFare,
'amountProduct' => round((float) $Amount) - (float) $agentCommission - (float) $commissionFareAll,
'amountFare' => round((float) $Amount) - (float) $agentCommission,
'percentageTarifa' => isset($infopackage->TPA_Extensions->ProductInfo->Comision) ? (float) $infopackage->TPA_Extensions->ProductInfo->Comision : 0,
];
$arrayCommissionAgent = [$isAgent, $commissionFare, $agentCommission, $textCommission, $commissionPay, $activeDetail, $info_product];
}
$infoDates = [
'TotalADT' => $CantADT,
'TotalCHD' => $CantCHD,
'Amount' => $Amount,
'transactionId' => $transactionId,
'datesTransaction' => $datesTransaction,
'BrandCode' => $codigoBrand,
'BrandName' => $BrandName,
'HotelCode' => $codigoHotel,
'CodeRoom' => $codigoRoom,
'typeRoom' => $typeRoom,
'categoryRoom' => $categoryRoom,
'codeBooking' => $codeBooking,
'adtCant' => $adtCant,
'chdCant' => $chdCant,
'personTotal' => $personTotal,
'personAditional' => $aditionalPerson,
'AditionalRoom' => $room,
'CantAditionalRoom' => $room,
'AddPerson' => $AddPerson,
'ValorTotal' => $TotalValor,
'totalTarifas' => $totalTarifas,
'tarifaReal' => $tarifaReal,
'reintento' => $reintento,
'optionals' => '',
'infopassenger' => $infopassenger,
'requestInformation' => $request->get('parameters'),
];
if ($isAgent) {
$infoDates['commissionAgent'] = $arrayCommissionAgent;
}
if ('COP' != mb_strtoupper($infoDates['datesTransaction']['CurrencyCode']) && 'true' == $infoDates['datesTransaction']['FormaVenta']) {
$hoy = date('Y-m-d');
$xmlTemplate = $productInfo->getTasaCambio($hoy);
$aviaturLogSave->logSave(print_r($xmlTemplate, true), 'TASAS_CAMBIO', 'RQ');
$financial = $aviaturWebService->callWebService('GENERALLAVE', 'dummy|http://www.aviatur.com.co/dummy/', $xmlTemplate);
$aviaturLogSave->logSave(print_r($financial, true), 'TASAS_CAMBIO', 'RS');
$validate = false;
foreach ($financial->MENSAJE->TASAS_CAMBIO->ELEMENTO_TASA_CAMBIO as $tasa) {
if ('COP' == mb_strtoupper($tasa->MONEDA_DESTINO) && mb_strtoupper($infoDates['datesTransaction']['CurrencyCode']) == $tasa->MONEDA_ORIGEN && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
$financialValue = (int) $tasa->VALOR;
$exchangeValues = [
'MONEDA_ORIGEN' => (string) $tasa->MONEDA_ORIGEN,
'TIPO_TASA_CAMBIO' => (string) $tasa->TIPO_TASA_CAMBIO,
];
$validate = true;
}
}
if (!$validate) {
$hoy = date('Y-m-d', strtotime('-1 day', strtotime(date('Y-m-d'))));
$xmlTemplate = $productInfo->getTasaCambio($hoy);
$financial = $aviaturWebService->callWebService('GENERALLAVE', 'dummy|http://www.aviatur.com.co/dummy/', $xmlTemplate);
foreach ($financial->MENSAJE->TASAS_CAMBIO->ELEMENTO_TASA_CAMBIO as $tasa) {
if ('COP' == mb_strtoupper($tasa->MONEDA_DESTINO) && mb_strtoupper($infoDates['datesTransaction']['CurrencyCode']) == $tasa->MONEDA_ORIGEN && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
$financialValue = (int) $tasa->VALOR;
$exchangeValues = [
'MONEDA_ORIGEN' => (string) $tasa->MONEDA_ORIGEN,
'TIPO_TASA_CAMBIO' => (string) $tasa->TIPO_TASA_CAMBIO,
];
}
}
}
if (!isset($financialValue) || !is_numeric($financialValue)) {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_search_package'), '', 'Error en la conversión de moneda'));
} else {
$infoDates['AmountTotal'] = $infoDates['Amount'] * $financialValue;
$session->set('[mpt][finantial_rate]', $financialValue);
$session->set($transactionId.'[mpt][exchangeValues]', json_encode($exchangeValues));
}
} else {
$infoDates['AmountTotal'] = $infoDates['Amount'];
}
$typePerson[1] = [
'ADT' => $CantADT,
'CHD' => $CantCHD,
'INF' => 0,
];
$urlDetail = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Package/Default/detail.html.twig');
$infoOptionals = simplexml_load_string($session->get($transactionId.'[mpt]'.'[infoOptionals]'));
$ValueOptionals = $session->get($transactionId.'[mpt]'.'[ValueOptionals]');
$optionalsValue = explode('*', substr($ValueOptionals, 0, -1));
if (0 != $ValueOptionals) {
$optionalsValue = explode('*', substr($ValueOptionals, 0, -1));
foreach ($optionalsValue as $optional) {
$optionals = explode('|', $optional);
$fareID = $optionals[5];
$fecha = $optionals[1];
$cantidad = $optionals[2];
foreach ($infoOptionals->Package as $tarifas) {
$tarifas->TPA_Extensions->ServiciosOpcionales->TravelerInformation = null;
$tarifas->TPA_Extensions->ServiciosOpcionales->LongDescription = null;
foreach ($tarifas->TPA_Extensions->ServiciosOpcionales->TarifasServiciosOpc->Tarifas as $tarifa) {
if ($fareID == $tarifa->FareId) {
$ProductName = $tarifas->TPA_Extensions->ServiciosOpcionales->ProductName;
$infoDates['optionals']['ProductName'][] = $ProductName;
$infoDates['optionals']['infOptional'][] = base64_encode($tarifas);
$infoDates['optionals']['FechaInicio'][] = $fecha;
$infoDates['optionals']['cantSelection'][] = $cantidad;
$infoDates['optionals']['FareSale'][] = $tarifa->FareSale;
$infoDates['optionals']['Axis1Attribute'][] = $tarifa->Axis1Attribute;
}
}
}
}
}
$referer = $session->get($transactionId.'[package_detail_url]');
$session->set($transactionId.'[mpt][infoDates]', json_encode($infoDates));
$repositoryDocumentType = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
$queryDocumentType = $repositoryDocumentType
->createQueryBuilder('p')
->where('p.paymentcode != :paymentcode')
->setParameter('paymentcode', '')
->getQuery();
$documentPaymentType = $queryDocumentType->getResult();
$twigVariables = [
'referer' => $referer,
'FormaVenta' => (string) $infopackage->TPA_Extensions->ProductInfo->FormaVenta,
'banks' => $banks,
'cybersource' => $cybersource,
'contactData' => $contactData ?? null,
'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findAll(),
'twig_readonly' => $twig_readonly,
'paymentOptions' => $paymentOptions,
'infoDates' => $infoDates,
'doc_type' => $typeDocument,
'billingData' => $billingData ?? null,
'services' => $typePerson,
'gender' => $typeGender,
'conditions' => $conditions,
'payment_type_form_name' => $provider->getPaymentType()->getTwig(),
'payment_doc_type' => $documentPaymentType,
'infoPackage' => $infopackage,
'passengers' => $detail_data_package->PI ?? null,
'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
];
return $this->render($urlDetail, $twigVariables);
}
public function prePaymentStep1Action(Request $request, TokenizerService $aviaturTokenizer, AviaturEncoder $aviaturEncoder, CustomerMethodPaymentService $customerMethodPaymentService, TokenStorageInterface $tokenStorage, TwigFolder $twigFolder, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
if ($request->isXmlHttpRequest()) {
$request = $request->request;
$transactionId = $session->get($transactionIdSessionName);
$billingData = $request->get('BD');
$em = $this->managerRegistry;
$postData = $request->all();
$publicKey = $aviaturEncoder->aviaturRandomKey();
if (isset($postData['PD']['card_num'])) {
$postDataInfo = $postData;
if (isset($postDataInfo['PD']['cusPOptSelected'])) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $customerMethodPaymentService->getMethodsByCustomer($customerLogin, true);
$cardToken = $infoMethodPaymentByClient['info'][$postDataInfo['PD']['cusPOptSelected']]['token'];
$postDataInfo['PD']['card_num'] = $cardToken;
$postData['PD']['card_num'] = $cardToken;
} else {
$postDataInfo['PD']['card_num'] = $aviaturTokenizer->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.'[mpt][user_info]', $formUserInfo->getId());
if ((true !== $session->has($transactionId.'[mpt][retry]')) || (true !== $session->has($transactionId.'[mpt][prepayment_check]'))) {
if (true === $session->has($transactionId.'[mpt][detail]')) {
//$postData = $request->all();
$session->set($transactionId.'[mpt][detail_data_package]', 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]);
}
$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']);
}
}
$isFront = $session->has('operatorId');
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();
}
$session->set($transactionId.'[mpt][retry]', $aviaturPaymentRetryTimes);
$detail = $session->get($transactionId.'[mpt][detail]');
$session->set($transactionId.'[mpt][prepayment]', $detail);
$cancelPenalties = (string) '';
$ajaxUrl = $this->generateUrl('aviatur_package_prepayment_step_2_secure');
return $this->json(['cancelPenalties' => $cancelPenalties, 'ajax_url' => $ajaxUrl]);
} 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,
'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 {
$paymentData = $request->get('PD');
$paymentData = json_decode(json_encode($paymentData));
$json = json_decode($session->get($transactionId.'[mpt][order]'));
if (!is_null($json)) {
$json->ajax_url = $this->generateUrl('aviatur_package_prepayment_step_2_secure');
// reemplazar datos de pago por los nuevos.
$oldPostData = json_decode($session->get($transactionId.'[mpt][detail_data_package]'));
if (isset($paymentData->cusPOptSelected) || isset($paymentData->card_num)) {
if (isset($paymentData->cusPOptSelected)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $customerMethodPaymentService->getMethodsByCustomer($customerLogin, true);
$card_num_token = $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
} else {
$card_num_token = $aviaturTokenizer->getToken($paymentData->card_num);
}
$card_values = ['card_num_token' => $card_num_token, 'card_num' => $paymentData->card_num];
}
unset($oldPostData->PD);
$oldPostData->PD = $paymentData;
if (isset($card_num_token)) {
$oldPostData->PD->card_values = $card_values;
}
$session->set($transactionId.'[mpt][detail_data_package]', 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 vuelve a intentarlo')]);
}
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado'));
}
}
public function prePaymentStep2Action(Request $request, OrderController $aviaturOrderController, AuthorizationCheckerInterface $authorizationChecker, TwigFolder $twigFolder, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, ManagerRegistry $registry, 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');
$transactionId = $session->get($transactionIdSessionName);
$session->set($transactionId.'[mpt][prepayment_check]', true);
$infoDates = json_decode($session->get($transactionId.'[mpt][infoDates]'), true);
if (true !== $session->has($transactionId.'[mpt][order]')) {
if (true === $session->has($transactionId.'[mpt][detail]')) {
$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('MPT');
if ($isFront) {
$orderIdentifier = '{order_product_reservation}';
} else {
$orderIdentifier = '{order_product_num}';
}
$order = $aviaturOrderController->createAction($agency, $customer, $productType, $orderIdentifier, $status);
$orderId = str_replace('ON', '', $order['order']);
$orderEntity = $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
$formUserInfo = $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[mpt][user_info]'));
$formUserInfo->setOrder($orderEntity);
$em->persist($formUserInfo);
$em->flush();
// Agent Transaction, Save commission QSE or Percentage
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
$orderProductCode = $session->get($transactionId.'[mpt][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$agentId = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agentId);
$arrayInfo = $infoDates['commissionAgent'];
$agentTransaction = new AgentTransaction();
$agentTransaction->setAgent($agentId);
$agentTransaction->setAgentCommission($agentCommission);
$agentTransaction->setOrderProduct($orderProduct);
$agentTransaction->setCommissionvalue(round((float) ($arrayInfo[4])));
$agentTransaction->setAmountQse($arrayInfo[6]['amountQse']);
$agentTransaction->setCommissionQse($arrayInfo[6]['commissionQse']);
$agentTransaction->setAmountTarifa($arrayInfo[6]['amountTa']);
$agentTransaction->setCommissionTarifa($arrayInfo[6]['commissionTa']);
$agentTransaction->setAmountProduct($arrayInfo[6]['amountProduct']);
$agentTransaction->setPercentageTarifa($arrayInfo[6]['percentageTarifa']);
$em->persist($agentTransaction);
$em->flush();
}
if ($isFront) {
$order['url'] = $this->makeReservation($transactionId);
} else {
$order['url'] = $this->generateUrl('aviatur_package_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()));
}
} 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 {
$order['url'] = $this->generateUrl('aviatur_package_payment_secure');
return $this->json($order);
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado'));
}
}
public function paymentAction(Request $request, PSEController $aviaturPsePaymentController, P2PController $aviaturP2pPaymentController, \Swift_Mailer $mailer, SafetypayController $aviaturSafetypayController, TwigFolder $twigFolder, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag,OrderController $aviaturOrderController)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$emailNotification = $parameterBag->get('email_notification');
$orderProduct = [];
$emissionData = null;
$response = null;
$em = $this->managerRegistry;
$transactionId = $session->get($transactionIdSessionName);
$postData = json_decode($session->get($transactionId.'[mpt][detail_data_package]'));
$orderInfo = json_decode($session->get($transactionId.'[mpt][order]'));
$infoDates = json_decode($session->get($transactionId.'[mpt][infoDates]'), true);
$infoPackage = simplexml_load_string((string) $session->get($transactionId.'[mpt][infoPackage]'));
$productId = str_replace('PN', '', $orderInfo->products);
$orderProduct[] = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$paymentData = $postData->PD;
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$x_total_amount = (int) $infoDates['AmountTotal'];
$parameters = json_decode($session->get($request->getHost().'[parameters]'));
$aviaturPaymentIva = (float) $parameters->aviatur_payment_iva;
$x_amount_base = $x_total_amount / (1 + $aviaturPaymentIva);
$x_amount_iva = $x_amount_base * $aviaturPaymentIva;
if ('p2p' == $paymentData->type) {
$array = [
'x_currency_code' => (string) 'COP',
'x_amount' => number_format(round((float) ($x_total_amount)), 0, '.', ''),
'x_tax' => number_format(round((float) ($x_amount_iva)), 2, '.', ''),
'x_amount_base' => number_format(round((float) ($x_amount_base)), 2, '.', ''),
'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
'x_first_name' => $customer->getFirstname(),
'x_last_name' => $customer->getLastname(),
'x_description' => 'Paquete - '.$infoDates['datesTransaction']['Description'],
'x_cust_id' => $customer->getDocumentType()->getPaymentcode().' '.$customer->getDocumentnumber(),
'x_address' => $customer->getAddress(),
'x_phone' => $customer->getPhone(),
'x_email' => $customer->getEmail(),
'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' => 'mpt',
];
if (isset($paymentData->card_values)) {
$array['card_values'] = (array) $paymentData->card_values;
}
if (isset($paymentData->cusPOptSelected)) {
$array['isToken'] = (string) $paymentData->card_values->card_num_token;
}
if (isset($postData->PD->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;
}
}
$paymentResponse = $aviaturP2pPaymentController->placetopayAction($array);
unset($array['x_client_id']);
if (null != $paymentResponse) {
return $this->redirect($this->generateUrl('aviatur_package_payment_p2p_return_url_secure', [], true));
} else {
$orderProduct[0]->setStatus('pending');
$em->persist($orderProduct[0]);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_package_retry_secure'), '', 'No hay respuesta por parte del servicio de pago, por favor intente nuevamente o comuníquese con nosotros para finalizar su transacción'));
}
} elseif ('pse' == $paymentData->type) {
$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' => $paymentData->pse_bank,
'x_type' => $paymentData->pse_type,
'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
'x_description' => 'Paquete - '.$infoDates['datesTransaction']['Description'],
'x_currency' => (string) 'COP',
'x_total_amount' => number_format(round((float) ($x_total_amount)), 0, '.', ''),
'x_tax_amount' => number_format(round((float) ($x_amount_iva)), 2, '.', ''),
'x_devolution_base' => number_format(round((float) ($x_amount_base)), 2, '.', ''),
'x_tax' => number_format(round((float) (0)), 2, '.', ''),
'x_tip_amount' => number_format(round((float) (0)), 2, '.', ''),
'product_type' => 'mpt',
];
$route = $router->match(str_replace($request->getSchemeAndHttpHost(), '', $request->getUri()));
$isMulti = false !== strpos($route['_route'], 'multi') ? true : false;
if ($isMulti) {
return $this->json($array);
}
$paymentResponse = $aviaturPsePaymentController->sendPaymentAction( $request,$session,$router,$parameterBag,$mailer,$aviaturOrderController,$array, $orderProduct);
if (!isset($paymentResponse->error)) {
switch ($paymentResponse->createTransactionResult->returnCode) {
case 'SUCCESS':
return $this->redirect($paymentResponse->createTransactionResult->bankURL);
case 'FAIL_EXCEEDEDLIMIT':
return $this->redirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '');
case 'FAIL_BANKUNREACHEABLE':
return $this->redirect($this->generateUrl('aviatur_package_retry_secure'), '');
default:
return $this->redirect($this->generateUrl('aviatur_package_retry_secure'), '');
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_package_retry_secure'), 'Error al procesar el pago', 'Ocurrió un problema al intentar crear su transacción, '.$paymentResponse->error));
}
} elseif ('safety' == $paymentData->type) {
$transactionUrl = $this->generateUrl('aviatur_payment_safetypay', [], true);
$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' => $request->get('PlanID'),
'x_description' => 'Paquete - '.$infoDates['datesTransaction']['Description'],
'x_currency' => 'COP',
'x_total_amount' => number_format(round((float) ($x_total_amount)), 2, '.', ''),
'x_tax_amount' => number_format(round((float) (0)), 2, '.', ''),
'x_devolution_base' => number_format(round((float) (0)), 2, '.', ''),
'x_tip_amount' => number_format(round(0), 2, '.', ''),
'x_payment_data' => $paymentData->type,
'x_type_description' => 'package',
];
$parametMerchant = [
'MerchantSalesID' => $array['x_reference'],
'Amount' => $array['x_total_amount'],
'transactionUrl' => $transactionUrl,
'dataTrans' => $array,
];
$safeTyPay = $aviaturSafetypayController->safetyAction($router, $parameterBag, $mailer, $parametMerchant, $array);
if ('ok' == $safeTyPay['status']) {
if ('baloto' == $paymentData->type) {
$cash = '&CountryId=COL&ChannelId=CASH';
$session->set($transactionId.'[mpt][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 AssistCard'.$emissionData->x_reference)
->setBody($mailInfo);
$mailer->send($message);
return $this->redirect($this->generateUrl('aviatur_package_payment_rejected_secure'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_package_retry_secure'), '', 'El tipo de pago es inválido'));
}
}
public function p2pCallbackAction(AviaturMailer $aviaturMailer, AviaturEncoder $aviaturEncoder, ValidateSanctions $aviaturValidateSanctions, OrderController $aviaturOrderController, CustomerMethodPaymentService $customerMethodPaymentService, SessionInterface $session, TokenStorageInterface $tokenStorage, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, ParameterBagInterface $parameterBag,Request $request, \Swift_Mailer $mailer,AuthorizationCheckerInterface $authorizationChecker,TwigFolder $twigFolder,Pdf $pdf,AviaturLogSave $aviaturLogSave)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$postData = null;
$em = $this->managerRegistry;
$transactionId = $session->get($transactionIdSessionName);
$orderProductCode = $session->get($transactionId.'[mpt][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()));
$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();
if (null != $decodedResponse) {
$agency = $orderProduct->getOrder()->getAgency();
$twig = '';
$retryCount = (int) $session->get($transactionId.'[mpt][retry]');
$this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,false);
if (!isset($decodedResponse->x_response_code)) {
$twig = 'aviatur_package_payment_rejected_secure';
} else {
if (isset($decodedResponse->x_response_code_cyber) && (2 == $decodedResponse->x_response_code_cyber)) {
$decodedResponse->x_response_code_case = 99;
} else {
$decodedResponse->x_response_code_case = $decodedResponse->x_response_code;
}
switch ($decodedResponse->x_response_code_case) {
case 99:
//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) {
if (isset($postData->PD->cusPOptSelected)) {
if (isset($postData->PD->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
$postData->PD->cusPOptSelectedStatus = 'ACTIVE';
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPaymentService->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
if (isset($postData->PD->savePaymProc)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPaymentService->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
}
$twig = 'aviatur_package_payment_rejected_secure';
// no break
case 3:// pendiente p2p
$twig = '' != $twig ? $twig : 'aviatur_package_payment_pending_secure';
$updateOrder = $aviaturOrderController->updatePaymentAction($orderProduct);
$retryCount = 1;
break;
case 0:// error p2p
$twig = 'aviatur_package_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_package_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
$updateOrder = $aviaturOrderController->updatePaymentAction($orderProduct);
$transactionId = $session->get($transactionIdSessionName);
$postData = json_decode($session->get($transactionId.'[mpt][detail_data_package]'));
if (isset($postData->PD->cusPOptSelected)) {
if (isset($postData->PD->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
$postData->PD->cusPOptSelectedStatus = 'ACTIVE';
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPaymentService->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
if (isset($postData->PD->savePaymProc)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPaymentService->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
$twig = 'aviatur_package_payment_success_secure';
//Reemplazar por consumo de reserva!!!!
$aviaturOrderController->updatePaymentAction($orderProduct, false, null);
$response = $this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,true);
$result = json_decode($response->getContent(), true);
$session->set($transactionId.'[mpt][retry]', $aviaturPaymentRetryTimes);
break;
}
}
$session->set($transactionId.'[mpt][retry]', $retryCount - 1);
//////// se envia el correo del modulo anti fraude en caso de ser necesario//////////
if ($session->has('Marked_name') && $session->has('Marked_document')) {
$product = 'Vacaciones';
$aviaturValidateSanctions->sendMarkedEmail($orderProductCode, $session, $agency, $orderProduct, $transactionId, $product);
}
////////////////////////////////////////////////////////////////////////////////////
return $this->redirect($this->generateUrl($twig));
} else {
$orderProduct->setStatus('pending');
$em->persist($orderProduct);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_package_retry_secure'), '', 'No hay respuesta por parte del servicio de pago'));
}
}
public function pseCallbackAction(AviaturEncoder $aviaturEncoder, PSEController $aviaturPsePaymentController, OrderController $aviaturOrderController, SessionInterface $session, TwigFolder $twigFolder, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, ParameterBagInterface $parameterBag, $transaction,Request $request,\Swift_Mailer $mailer, AuthorizationCheckerInterface $authorizationChecker, Pdf $pdf,AviaturLogSave $aviaturLogSave)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$status = null;
$twig = null;
$em = $this->managerRegistry;
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['mpt'])) {
$mptOrders = explode('+', $orders['mpt']);
$orderProductCode = $mptOrders[0];
$productId = $mptOrders[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'));
} else {
$agency = $orderProduct->getOrder()->getAgency();
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
if (isset($decodedResponse->createTransactionResult)) {
$this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,false);
$pseTransactionId = $decodedResponse->createTransactionResult->transactionID;
$paymentResponse = $aviaturPsePaymentController->pseCallbackAction( $aviaturOrderController,$pseTransactionId);
if (!isset($paymentResponse->error)) {
if (!$session->has($transactionId.'[mpt][resumeView]')) {
$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_package_payment_success_secure';
$status = 'approved';
break;
case 'PENDING':
$twig = 'aviatur_package_payment_pending_secure';
$status = 'pending';
break;
case 'NOT_AUTHORIZED':
$twig = 'aviatur_package_payment_error_secure';
$status = 'rejected';
break;
case 'FAILED':
$twig = 'aviatur_package_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();
if ('approved' == $status) {
//Reemplazar por consumo de reserva!!!!
$aviaturOrderController->updatePaymentAction($orderProduct, false, null);
$response = $this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,true);
$result = json_decode($response->getContent(), true);
$session->set($transactionId.'[mpt][retry]', $aviaturPaymentRetryTimes);
}
return $this->redirect($this->generateUrl($twig));
} 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 más tarde para verificar si 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 preguntar por el estado de la
transacción <#CUS> .';
$orderProduct->setEmissiondata('error');
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$twig = 'aviatur_package_payment_error_secure';
}
if ($session->has($transactionId.'[mpt][retry]')) {
$session->set($transactionId.'[mpt][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(AviaturEncoder $aviaturEncoder, SafetypayController $aviaturSafetypayController, OrderController $aviaturOrderController, SessionInterface $session, TwigFolder $twigFolder, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, ParameterBagInterface $parameterBag,Request $request,\Swift_Mailer $mailer,AuthorizationCheckerInterface $authorizationChecker,Pdf $pdf,AviaturLogSave $aviaturLogSave)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$status = null;
$twig = null;
$em = $this->managerRegistry;
$safeTyPay = $aviaturSafetypayController->safetyok();
if (true === $session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
if (true === $session->has($transactionId.'[mpt][order]')) {
$orderProductCode = $session->get($transactionId.'[mpt][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()));
$payError = $decodedResponse->payResponse->OperationResponse->ErrorManager->ErrorNumber->{'@content'};
$notifyError = $decodedResponse->notificationResponse->OperationActivityNotifiedResponse->ErrorManager->ErrorNumber->{'@content'};
if (isset($decodedResponse->payResponse->OperationResponse)) {
$response = $this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,true);
if (0 == $payError) {
$retryCount = (int) $session->get($transactionId.'[mpt][retry]');
if (0 == $notifyError) {
switch ($payError) {
case 0:
$twig = 'aviatur_package_payment_success_secure';
$status = 'approved';
break;
case 2:
$twig = 'aviatur_package_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();
$aviaturOrderController->updatePaymentAction($orderProduct);
if (0 == $payError) {
if ('approved' == $status) {
//Reemplazar por consumo de reserva!!!!
$response = $this->createOrderPackageAction($request,$mailer,$aviaturOrderController,$aviaturEncoder,$authorizationChecker,$twigFolder,$aviaturErrorHandler,$session,$registry,$parameterBag,$pdf,$aviaturLogSave,true);
$result = json_decode($response->getContent(), true);
$session->set($transactionId.'[mpt][retry]', $aviaturPaymentRetryTimes);
if ('Ok' != $result['Estado'][0]) {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Hubo un error en la creación de la reserva, comuníquese con nosotros por favor'));
}
}
}
} 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 más tarde para verificar si 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 preguntar por el estado de la
transacción <#CUS> .';
$orderProduct->setEmissiondata('error');
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$twig = 'aviatur_package_payment_error_secure';
}
$session->set($transactionId.'[mpt][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, SessionInterface $session, TwigFolder $twigFolder, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$status = null;
$em = $this->managerRegistry;
$transactionId = $session->get($transactionIdSessionName);
$retryCount = (int) $session->get($transactionId . '[mpt][retry]');
$orderProductCode = json_decode($session->get($transactionId . '[mpt][order]'));
$productId = str_replace('PN', '', $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 . '[mpt][order]')) {
$orderProductCode = $session->get($transactionId . '[mpt][order]');
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró orden asociada a este pago'));
}
$session->set($transactionId . '[mpt][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl('aviatur_package_payment_rejected_secure'));
}
public function paymentOutputAction(Request $request, AviaturEncoder $aviaturEncoder, TwigFolder $twigFolder, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag, AviaturLogSave $aviaturLogSave)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$clientFranquice = [];
$paymentResume = [];
header('Content-Type: text/html;charset=utf-8');
$em = $this->managerRegistry;
$transactionId = $session->get($transactionIdSessionName);
$infoDates = json_decode($session->get($transactionId . '[mpt]' . '[infoDates]'), true);
$detail = $session->get($transactionId . '[mpt]' . '[detail]');
$detail_data_package = json_decode($session->get($transactionId . '[mpt]' . '[detail_data_package]'));
$orderProductCode = json_decode($session->get($transactionId . '[mpt]' . '[order]'));
$ProductInfo = json_decode($session->get($transactionId . '[mpt]' . '[ProductInfo]'), true);
$resumeView = json_decode($session->get($transactionId . '[mpt]' . '[resumeView]'), true);
$infoClient = json_decode($session->get($transactionId . '[mpt]' . '[infoClient]'));
$infoSelection = json_decode($session->get($transactionId . '[mpt]' . '[infoSelection]'));
$infoOptionals = json_decode($session->get($transactionId . '[mpt]' . '[optionalSelection]'));
$InfoHotel = $session->get($transactionId . '[mpt][InfoHotel]');
$ProductInfo ?? null;
$resumeView ?? null;
$agency = $this->agency;
$agencyData = [
'agency_name' => $agency->getName(),
'agency_nit' => $agency->getNit(),
'agency_phone' => $agency->getPhone(),
'agency_email' => $agency->getMailContact(),
];
$product = simplexml_load_string(html_entity_decode($ProductInfo));
$productId = str_replace('PN', '', $orderProductCode->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$opRequestInitial = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$opRequest = $opRequestInitial->multi_transaction_hotel ?? $opRequestInitial;
$opResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
if (isset($opResponse->x_franchise) && ('' != $opResponse->x_franchise)) {
$franquiceCode = str_replace(['CR_', 'RM_', 'CDNSA'], ['', '', 'CS'], $opResponse->x_franchise);
$clientFranquice = $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findOneByPaymentgatewaycode($franquiceCode);
} else {
$clientFranquice['description'] = 'error';
}
$paymentData = $detail_data_package->BD;
$emailData = json_decode($orderProduct->getEmail(), true);
if ((null != $opRequest) && (null != $opResponse)) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->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,
'client_franquice' => ['description' => @$clientFranquice->getDescription()],
'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'],
'id_context' => $orderProductCode->order . '-' . $orderProductCode->products,
];
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;
}
} 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 ?? $opResponse->createTransactionResult->responseReasonCode,
'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 ?? $opResponse->createTransactionResult->trazabilityCode,
'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate ?? '',
'description' => $opRequest->description,
'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode ?? $opResponse->createTransactionResult->responseReasonCode,
'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText ?? $opResponse->createTransactionResult->responseReasonText,
'client_names' => $opRequest->payer->firstName . ' ' . $opRequest->payer->lastName,
'client_email' => $opRequest->payer->emailAddress,
];
}
} else {
$customer = null;
$paymentResume['id'] = $orderProduct->getBooking();
}
$paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
if (false !== strpos($paymentData->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->first_name . ' ' . $paymentData->last_name,
'customer_address' => $paymentData->address ?? null,
'customer_doc_num' => $paymentData->doc_num,
'customer_phone' => $paymentData->phone,
'customer_email' => $paymentData->email ?? null,
];
}
if (false !== strpos($detail_data_package->PI->first_name_1_1, '***')) {
$detail_data_package->PI->first_name_1_1 = $customer->getFirstname();
$detail_data_package->PI->last_name_1_1 = $customer->getLastname();
$detail_data_package->PI->email_1_1 = $customer->getEmail();
$detail_data_package->PI->address_1_1 = $customer->getAddress();
$detail_data_package->CD->phone = $customer->getPhone();
}
$clientFranquice = '';
$retryCount = (int) $session->get($transactionId . '[mpt][retry]');
$agencyFolder = $twigFolder->twigFlux();
$routeName = $request->get('_route');
$info_travelers = $detail_data_package->PI;
$emailData = [
'product' => $product,
'retry_count' => $retryCount,
'paymentResume' => $paymentResume,
'agencyData' => $agencyData,
'order' => $orderProductCode->order,
'products' => $orderProductCode->products,
'Name' => $infoDates['datesTransaction']['Description'],
'info_travelers' => (array) $detail_data_package->PI,
'contact_phone' => $detail_data_package->CD->phone,
'transactionID' => $transactionId,
'infoClient' => $facturationResume,
'dateEntry' => $infoDates['datesTransaction']['entrada'],
'dateEnd' => $infoDates['datesTransaction']['salida'],
'total_amount' => $infoDates['Amount'],
'resumeView' => $resumeView,
];
$urlResume = $twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/package/Default/resume.html.twig');
$renderResumeView = $emailData;
if ('jetset_semana' === $agency->getAssetsFolder()) {
$urlReturn = $this->CallAPI($session, $aviaturLogSave, $registry, 'GET', $transactionId);
$renderResumeView['urlReturn'] = $urlReturn ?? null;
}
$renderResumeView['infos'][0] = $emailData;
$setResume = $this->render($urlResume, $renderResumeView);
$orderProduct->setEmail(json_encode($renderResumeView));
$orderProduct->setResume($setResume);
$bookinData = json_decode($session->get($transactionId . '[mpt][resumeView]'), true);
if (isset($bookinData['Estado'][0]) && 'OK' == mb_strtoupper($bookinData['Estado'][0])) {
$emissionData = json_decode($orderProduct->getEmissionData(), true);
$emissionData['emission'] = $bookinData['message'][0];
$orderProduct->setEmissionData(json_encode($emissionData));
}
$em->persist($orderProduct);
$em->flush();
return $setResume;
}
public function createOrderPackageAction(Request $request, \Swift_Mailer $mailer, OrderController $aviaturOrderController, AviaturEncoder $aviaturEncoder, AuthorizationCheckerInterface $authorizationChecker, TwigFolder $twigFolder, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag, Pdf $pdf, AviaturLogSave $aviaturLogSave, $emission = true, AviaturWebService $aviaturWebService)
{
$env = $parameterBag->get('kernel.environment');
$projectDir = $parameterBag->get('kernel.project_dir');
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$emailNotification = $parameterBag->get('email_notification');
$packageCommissionPercentage = null;
$infoRoom = [];
$arrayAdult = [];
$emissionData = [];
$agentId = null;
$agentCommission = null;
$fullRequest = $request;
$isAgent = false;
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$request = $fullRequest->request;
$transactionId = $session->get($transactionIdSessionName);
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId . '_isActiveQse')) {
$nameProduct = 'package';
$user = $this->getUser();
$emailuser = $user->getemail();
$agent = $user->getAgent();
if (!empty($agent[0])) {
$idagent = $agent[0]->getid();
$nombreagente = $user->getFirstname() . ' ' . $user->getLastname();
$agencyFolder = $twigFolder->twigFlux();
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($idagent);
$infoQse = json_decode($agentCommission->getQseproduct());
$infoQseNameProduct = empty($infoQse->$nameProduct) ? false : $infoQse->$nameProduct;
$infoQse = empty($infoQse) ? false : $infoQseNameProduct;
$idAgentCommision = $agentCommission->getId();
$packageCommissionPercentage = (($infoQse) ? (float) $infoQse->commission_percentage : 0) * 100;
$agentId = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
// $parameters = json_decode($session->get($request->getHost() . '[parameters]')); // Como se tenía antes
$parameters = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_payment_iva');
$aviaturPaymentIva = (float) $parameters->getValue();
$isAgent = true;
}
}
$agencyFolder = $twigFolder->twigFlux();
$productInfo = new PackageModel();
$configPackageAgency = $em->getRepository(\Aviatur\PackageBundle\Entity\ConfigPackageAgency::class)->findOneByAgency($agency);
$hotelsInfo = simplexml_load_string($session->get($transactionId . '[mpt][InfoHotel]'));
$infopackage = simplexml_load_string($session->get($transactionId . '[mpt][infoPackage]'));
$OfficeId = $configPackageAgency->getOfficeID();
if ('wmcorona' == $configPackageAgency->getAgency()->getAssetsFolder()) {
$OfficeId = $configPackageAgency->getAgency()->getOfficeID();
}
$toMails = explode(';', $configPackageAgency->getMails());
$resumeView = '';
$infoDates = json_decode($session->get($transactionId . '[mpt][infoDates]'), true);
$urlResume = $twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Package/Default/email.html.twig');
$data_package = json_decode($session->get($transactionId . '[mpt][detail_data_package]'));
$data = $session->get($transactionId . '[mpt][detail]');
$ProviderId = $session->get($transactionId . '[mpt][provider]');
$environment = $env;
$adults = null;
$children = null;
$adultsInfo = null;
$getInfoPrestador = null;
$getPrestadorOptional = null;
$infoOptional = null;
$cliente = null;
if ($fullRequest->isXmlHttpRequest()) {
$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]);
}
$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)))
) {
$resumeView = ['Estado' => ['ERROR'], 'Description' => 'Nombre Inválido', 'message' => 'Nombre Inválido'];
$arraydecode = json_encode($resumeView);
$response = new Response($arraydecode);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
// pago Offline
/* Datos de Pasajeros Adultos */
$passengerADT = $request->get('PI');
/* Datos de Cliente */
$passengerCLI = $request->get('BD');
/* Datos de Prestador */
$informationPrestador = [
'IdHotelCode' => json_decode($request->get('HotelCode')),
'IdPrestador' => json_decode($request->get('HotelCode')),
'IdBrandName' => json_decode($request->get('BrandName')),
'IdPrestadorNew' => json_decode($request->get('BrandCode')),
'TipoHabitacion' => json_decode($request->get('typeRoom')),
'CategoriaHabitacion' => json_decode($request->get('categoryRoom')),
'CantidadAdultos' => json_decode($request->get('adtCant')),
'CantidadNiños' => json_decode($request->get('chdCant')),
'AditionalRoom' => json_decode($request->get('AditionalRoom')),
'personTotal' => json_decode($request->get('personTotal')),
'ValorTotal' => json_decode($request->get('ValorTotal')),
'TotalADT' => json_decode($request->get('TotalADT')),
'personAditional' => $infoDates['personAditional'],
'codeBooking' => $infoDates['codeBooking'],
'TotalCHD' => json_decode($request->get('TotalCHD')),
'totalTarifas' => json_decode($request->get('totalTarifas')),
'tarifaReal' => json_decode($request->get('tarifaReal')),
'optionals' => json_decode($request->get('optionals')),
];
$transaction = json_decode($request->get('Transaction'), true);
$TotalADT = json_decode($request->get('TotalADT'));
$TotalCHD = json_decode($request->get('TotalCHD'));
$amount = (int) $request->get('Amount');
$HotelCode = json_decode($request->get('HotelCode'));
$typeRoom = is_countable(json_decode($request->get('typeRoom'))) ? count(json_decode($request->get('typeRoom'))) : 0;
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($passengerCLI['id']);
if (isset($customer) && 0 == $customer->getAviaturClientId()) {
$this->createCustomer($parameterBag, $aviaturWebService, $mailer, $session, $registry, $customer);
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($passengerCLI['id']);
}
$fromCurrency = $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata($transaction['CurrencyCode']);
} else {
// pago Online
/* Datos de Pasajeros Adultos */
$passengerADT = (array) $data_package->PI;
/* Datos de Cliente */
$passengerCLI = $data_package->BD;
/* Datos de Prestador */
$informationPrestador = [
'IdHotelCode' => $infoDates['HotelCode'],
'IdPrestador' => $infoDates['HotelCode'],
'IdBrandName' => $infoDates['BrandName'],
'IdPrestadorNew' => $infoDates['BrandCode'],
'TipoHabitacion' => $infoDates['typeRoom'],
'CategoriaHabitacion' => $infoDates['categoryRoom'],
'CantidadAdultos' => $infoDates['adtCant'],
'CantidadNiños' => $infoDates['chdCant'],
'AditionalRoom' => $infoDates['AditionalRoom'],
'CantAditionalRoom' => $infoDates['CantAditionalRoom'],
'personAditional' => $infoDates['personAditional'],
'codeBooking' => $infoDates['codeBooking'],
'AddPerson' => $infoDates['AddPerson'],
'personTotal' => $infoDates['personTotal'],
'ValorTotal' => $infoDates['ValorTotal'],
'TotalADT' => $infoDates['TotalADT'],
'TotalCHD' => $infoDates['TotalCHD'],
'totalTarifas' => $infoDates['totalTarifas'],
'tarifaReal' => $infoDates['tarifaReal'],
'optionals' => $infoDates['optionals'],
];
$transaction = $infoDates['datesTransaction'];
$TotalADT = $infoDates['TotalADT'];
$TotalCHD = $infoDates['TotalCHD'];
$amount = $infoDates['Amount'];
$HotelCode = $infoDates['HotelCode'];
$typeRoom = is_countable($infoDates['typeRoom']) ? count($infoDates['typeRoom']) : 0;
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($data_package->BD->id);
if (isset($customer) && 0 == $customer->getAviaturClientId()) {
$this->createCustomer($parameterBag, $aviaturWebService, $mailer, $session, $registry, $customer);
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($data_package->BD->id);
}
$fromCurrency = $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata($transaction['CurrencyCode']);
}
if ($isAgent) {
$qseAmount = $infoDates['commissionAgent'][2];
$qseText = ('QSE (%)' == $infoDates['commissionAgent'][3]) ? 'QSE (' . $packageCommissionPercentage . '%)' : $infoDates['commissionAgent'][3];
}
if (false !== strpos($passengerADT['first_name_1_1'], '***')) {
$passengerADT['first_name_1_1'] = $customer->getFirstname();
$passengerADT['last_name_1_1'] = $customer->getLastname();
$passengerADT['email_1_1'] = $customer->getEmail();
$passengerADT['address_1_1'] = $customer->getAddress();
}
$cliente = [
'Id' => $customer->getAviaturclientid(),
'Name' => $customer->getFirstname(),
'Last_name' => $customer->getLastname(),
'address' => $customer->getAddress(),
'phone' => $customer->getPhone(),
'email' => $customer->getEmail(),
'doc_num' => $customer->getDocumentNumber(),
];
if ('aviatur' === $agency->getAssetsFolder()) {
if (false !== strpos($transaction['ProductName'], 'Crucero')) {
$toMails = null;
$toMails[] = 'julieth.cotrino@aviatur.com';
} /* elseif (mb_strtoupper((string) $infopackage->TPA_Extensions->ProductInfo->ClaseServicio) == 'I') {
$toMails[] = 'j_uriza@aviatur.com';
$toMails[] = 'operadorbogint@aviatur.com';
$toMails[] = 'cc_diaz@aviatur.com';
} elseif (mb_strtoupper((string) $infopackage->TPA_Extensions->ProductInfo->ClaseServicio) == 'N') {
$toMails[] = 'operadorbognal@aviatur.com';
$toMails[] = 'f_arias@aviatur.com';
} */
}
if ($session->has($transactionId . '[mpt][exchangeValues]')) {
$trm = $session->get('[mpt][finantial_rate]');
} else {
$trm = 1;
}
$AmountTotal = $infoDates['AmountTotal'];
$infoProducto = [
'ProductId' => $transaction['IdPackage'],
'ProductName' => $transaction['ProductName'],
'LongDescription' => $transaction['Description'],
'CiudadDestino' => $transaction['CodeCiudad'],
'UnitCostValue' => $transaction['UnitCostValue'],
'UnitCostName' => $transaction['UnitCostName'],
'CodeIATA' => $transaction['CurrencyCode'],
'CurrencyName' => $fromCurrency->getDescription(),
'Noches' => $transaction['days'],
'FechaInicial' => str_replace('/', '-', $transaction['entrada']),
'FechaFinal' => str_replace('/', '-', $transaction['salida']),
'TipoProducto' => $transaction['TipoProducto'],
'CurrencyCodeEx' => $transaction['CurrencyCode'],
'CurrencyNameEx' => $fromCurrency->getDescription(),
'TasaCambioEx' => ('COP' == $transaction['CurrencyCode']) ? 1 : $trm,
'ProviderId' => $ProviderId,
'TipoVenta' => $transaction['FormaVenta'],
'SesionId' => $transactionId,
'Ref_externa' => null,
];
if ($session->has('whitemark')) {
$infoProducto['Ref_externa'] = $session->get('whitemark');
}
$ProductInfo = $productInfo->getInfoProducto($infoProducto);
$ProductInfo = preg_replace('/&(?!#?[a-z0-9]+;)/', 'y', $ProductInfo);
/* ---------------- informacion del prestador ------------ */
for ($j = 0; $j < $typeRoom; ++$j) {
if ('undefined' == $informationPrestador['AditionalRoom'][$j] || 'null' == $informationPrestador['AditionalRoom'][$j]) {
$informationPrestador['AditionalRoom'][$j] = 'false';
}
$infoRoom[$j] = [
'IdHotelCode' => $informationPrestador['IdHotelCode'][$j],
'IdPrestador' => (1 == $informationPrestador['IdPrestadorNew'][$j]) ? $informationPrestador['IdBrandName'][$j] : $informationPrestador['IdPrestador'][$j],
'IdPrestadorNew' => 0,
'TipoHabitacion' => $informationPrestador['TipoHabitacion'][$j],
'CategoriaHabitacion' => $informationPrestador['CategoriaHabitacion'][$j],
'CantidadNiños' => $informationPrestador['CantidadNiños'][$j],
'CantidadAdultos' => $informationPrestador['CantidadAdultos'][$j],
'NumeroPasajeros' => $informationPrestador['personTotal'][$j],
'AceptaAdicional' => (0 != $informationPrestador['personAditional'][$j]) ? 'true' : 'false',
'ValorTotal' => $informationPrestador['ValorTotal'][$j],
'totalTarifas' => (array) $informationPrestador['totalTarifas'][$j],
'tarifaReal' => (array) $informationPrestador['tarifaReal'][$j],
'CodeIATA' => $transaction['CurrencyCode'],
'LifeTimeId' => $informationPrestador['codeBooking'][$j],
];
}
$uniqueHotel = array_unique($HotelCode);
$arrayTarifa = [];
$ValueOptionals = $session->get($transactionId . '[mpt]' . '[ValueOptionals]');
$optionals = explode('*', substr($ValueOptionals, 0, -1));
$infoOptionals = simplexml_load_string($session->get($transactionId . '[mpt]' . '[infoOptionals]'));
$contador = 0;
foreach ($uniqueHotel as $keyNew => $value_array) {
$IdPrestadorNew = $infoRoom[$keyNew]['IdPrestadorNew'];
$getInfoPrestador[$keyNew] = '<objPrestadores_RQ>' . $productInfo->getObjPrestadores_RQ($infoRoom[$keyNew]) . '<Acomodacion>';
foreach ($infoRoom as $keyRoom => $value_room) {
if ($uniqueHotel[$keyNew] == $infoRoom[$keyRoom]['IdHotelCode']) {
$TipoHabitacion = $infoRoom[$keyRoom]['TipoHabitacion'];
$CategoriaHabitacion = $infoRoom[$keyRoom]['CategoriaHabitacion'];
$CodeIATA = $infoRoom[$keyRoom]['CodeIATA'];
//$getInfoPrestador[$keyNew] .= "<objAcomodacion_RQ>" . $productInfo->getObjAcomodacion_RQ($infoRoom[$keyRoom]) . "<Tarifas>";
$getInfoPrestador[$keyNew] .= '<objAcomodacion_RQ>' . $productInfo->getObjAcomodacion_RQ($infoRoom[$keyRoom]);
if ($isAgent) {
$baseQse = round($qseAmount / (1 + $aviaturPaymentIva));
$taxQse = round($qseAmount - $baseQse);
$arrayQSE = [
'CodigoFee' => 'GV057',
'BaseFee' => (int) $baseQse,
'PorcentajeIVA' => ($aviaturPaymentIva * 100),
'TaxFee' => (int) $taxQse,
'TotalFee' => (int) $qseAmount,
];
$getInfoPrestador[$keyNew] .= '<objFee_RQ>' . $productInfo->getObjValorQse($arrayQSE) . '</objFee_RQ>';
}
$getInfoPrestador[$keyNew] .= '<Tarifas>';
$array = json_decode(json_encode($value_room['totalTarifas']), true);
$arrayReal = json_decode(json_encode($value_room['tarifaReal']), true);
$ADTotal = $array['ADTotal'];
if (isset($array['CHDTotal'])) {
$CHDTotal = $array['CHDTotal'];
if (0 != $array['CHDTotal']) {
$Age = $array['ageMinCHD'];
$AgeEnd = $array['ageMaxCHD'];
}
}
foreach ($arrayReal as $keyRate => $Rate) {
$dateVar = $keyRate;
$arrayTarifa = null;
if (0 != $Rate && false === strpos($dateVar, 'DAYS')) {
if (isset($arrayReal['DAYS_' . $dateVar]) && 0 != $arrayReal['DAYS_' . $dateVar]) {
if ('ADT' == $dateVar || 'ADN' == $dateVar || 'ADF' == $dateVar || 'ANF' == $dateVar || 'ADD' == $dateVar || 'AAN' == $dateVar || 'AFN' == $dateVar) {
$NroPersonas = ('ADD' == $dateVar || 'AAN' == $dateVar || 'AFN' == $dateVar) ? 1 : $ADTotal;
$arrayTarifa = [
'FareId' => $array['Count' . $dateVar],
'TipoPersona' => $dateVar,
'Valor' => $Rate,
'Noches' => $arrayReal['DAYS_' . $dateVar],
'NroPersonas' => $NroPersonas,
];
}
if ('CHD' == $dateVar || 'CHN' == $dateVar || 'CHF' == $dateVar || 'CFN' == $dateVar) {
$NroPersonas = $CHDTotal;
$arrayTarifa = [
'FareId' => $array['Count' . $dateVar],
'TipoPersona' => $dateVar,
'Valor' => (int) ($Rate / $NroPersonas),
'NroPersonas' => $NroPersonas,
'Noches' => $arrayReal['DAYS_' . $dateVar],
'Age' => (int) $Age,
'AgeEnd' => (int) $AgeEnd,
];
}
$getInfoPrestador[$keyNew] .= '<objTarifas_RQ>' . $productInfo->getObjTarifas_RQ($arrayTarifa) . '</objTarifas_RQ>';
}
}
}
$getInfoPrestador[$keyNew] .= '</Tarifas></objAcomodacion_RQ>';
}
}
$getInfoPrestador[$keyNew] .= '</Acomodacion></objPrestadores_RQ>';
}
$infoPrestador = implode('', $getInfoPrestador);
/* ------------------ Informacion de los opcionales -------------- */
if (0 != $ValueOptionals) {
foreach ($optionals as $valueOptionals) {
$dateOptionals = explode('|', $valueOptionals);
foreach ($infoOptionals->Package as $Opcionales) {
foreach ($Opcionales->TPA_Extensions->ServiciosOpcionales as $ServiciosOpcionales) {
foreach ($ServiciosOpcionales->TarifasServiciosOpc->Tarifas as $Tarifas) {
if ($Tarifas->FareId == $dateOptionals[5]) {
$arrayPrestador[] = [
'IdPrestadorNew' => $IdPrestadorNew,
'IdPrestador' => (int) $Tarifas->IdPrestador,
];
$getPrestadorOptional[] = '<objPrestadores_RQ>' . $productInfo->getObjPrestadores_RQ($arrayPrestador[$contador]) . '<Acomodacion>';
$PrestadorAcomodacion[] = [
'TipoHabitacion' => $TipoHabitacion,
'CategoriaHabitacion' => $CategoriaHabitacion,
'CantidadNiños' => 0,
'CantidadAdultos' => $dateOptionals[2],
'AceptaAdicional' => (string) ($Tarifas->Additional > 0) ? 'true' : 'false',
'NumeroPasajeros' => $dateOptionals[2],
'CodeIATA' => $CodeIATA,
'ValorTotal' => (int) $Tarifas->FareSale,
];
$getPrestadorOptional[] .= '<objAcomodacion_RQ>' . $productInfo->getObjAcomodacion_RQ($PrestadorAcomodacion[$contador]);
if ($isAgent) {
$baseQse = round($qseAmount / (1 + $aviaturPaymentIva));
$taxQse = round($qseAmount - $baseQse);
$arrayQSE = [
'CodigoFee' => 'GV057',
'BaseFee' => (int) $baseQse,
'PorcentajeIVA' => $aviaturPaymentIva * 100,
'TaxFee' => (int) $taxQse,
'TotalFee' => (int) $qseAmount,
];
$getPrestadorOptional[] .= '<objFee_RQ>' . $productInfo->getObjValorQse($arrayQSE) . '</objFee_RQ>';
}
$getPrestadorOptional[] .= '<Tarifas>';
$arrayOptionals = [
'FareId' => (int) $Tarifas->FareId,
'TipoPersona' => $Tarifas->TypeOfPerson,
'Valor' => (int) $Tarifas->FareSale,
'Noches' => $transaction['days'],
'NroPersonas' => $dateOptionals[2],
];
$getPrestadorOptional[] .= '<objTarifas_RQ>' . $productInfo->getObjTarifas_RQ($arrayOptionals) . '</objTarifas_RQ>';
++$contador;
}
}
}
}
$getPrestadorOptional[] .= '</Tarifas></objAcomodacion_RQ>';
$getPrestadorOptional[] .= '</Acomodacion></objPrestadores_RQ>';
}
$infoOptional = implode('', $getPrestadorOptional);
$infoPrestador = $infoPrestador . $infoOptional;
}
$prestadorInfo = '<Prestador>' . $infoPrestador . '</Prestador>';
$infoClient = $productInfo->getInfoClient($cliente);
/* ------------------ Informacion de los pasajeros -------------- */
for ($i = 1; $i <= ($TotalADT + $TotalCHD); ++$i) {
if ('ADT' == $passengerADT['passanger_type_1_' . $i]) {
if (335 == $passengerADT['gender_1_' . $i]) {
$type = 'M';
} else {
$type = 'F';
}
$arrayAdult[$i] = [
'Passenger_number' => $i,
'Type' => $type,
'First_name' => $passengerADT['first_name_1_' . $i],
'First_last_name' => $passengerADT['last_name_1_' . $i],
'Document_type' => $passengerADT['doc_type_1_' . $i],
'Document_id' => $passengerADT['doc_type_1_' . $i],
'Document_number' => $passengerADT['doc_num_1_' . $i],
'Nationality' => $passengerADT['nationality_1_' . $i],
'birthday' => $passengerADT['birthday_1_' . $i],
];
$adults = $productInfo->getInfoPassengers($arrayAdult[$i]) . $adults;
}
}
$adultsInfo = '<Pasajeros>' . $adults . '</Pasajeros>';
$arrayChildren = null;
for ($j = 1; $j <= ($TotalADT + $TotalCHD); ++$j) {
if ('CHD' == $passengerADT['passanger_type_1_' . $j]) {
if (335 == $passengerADT['gender_1_' . $j]) {
$type = 'M';
} else {
$type = 'F';
}
$arrayChildren[$j] = [
'Passenger_number' => $j,
'Type' => $type,
'First_name' => $passengerADT['first_name_1_' . $j],
'First_last_name' => $passengerADT['last_name_1_' . $j],
'Document_type' => $passengerADT['doc_type_1_' . $j],
'Document_id' => $passengerADT['doc_type_1_' . $j],
'Document_number' => $passengerADT['doc_num_1_' . $j],
'Nationality' => $passengerADT['nationality_1_' . $j],
'birthday' => $passengerADT['birthday_1_' . $j],
];
$children = $productInfo->getInfoPassengers($arrayChildren[$j]) . $children;
}
}
if ($TotalCHD > 0) {
$infoPasseenger = '<Pasajeros>' . $adults . $children . '</Pasajeros>';
} else {
$infoPasseenger = '<Pasajeros>' . $adults . '</Pasajeros>';
}
$infoVendedor = $productInfo->getInfoVendedor($OfficeId);
$xmlTemplateHead = "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"
. '<soap:Body>';
$xmlTemplateBody = utf8_encode("<CrearSolicitudPaquetes xmlns='http://www.aviatur.com.co/'>"
. '<Request>'
. $ProductInfo
. $prestadorInfo
. $infoClient
. $infoPasseenger
. $infoVendedor
. '</Request>'
. '</CrearSolicitudPaquetes>');
$xmlTemplatefooter = '</soap:Body>'
. '</soap:Envelope>';
$emissionData['xml'] = $xmlTemplateBody;
$emissionData['agencyId'] = $session->get('agencyId');
$emissionData['infoDates'] = $infoDates;
$DataEmail = [
'ProductInfo' => simplexml_load_string(utf8_encode($ProductInfo)),
'clientInformation' => ['infoClient' => simplexml_load_string($infoClient), 'documentNumber' => $customer->getDocumentNumber(), 'address' => $customer->getAddress(), 'phone' => $customer->getPhone(), 'email' => $customer->getEmail()],
'informationPrestador' => $informationPrestador,
'passengerADT' => $arrayAdult,
'passengerCHD' => $arrayChildren,
'amount' => $amount,
'AmountTotal' => $AmountTotal,
];
$emissionData['emailData'] = $DataEmail;
if ($session->has($transactionId . '[mpt][order]')) {
$orderProductCode = $session->get($transactionId . '[mpt][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$orderProduct->setEmissiondata(json_encode($emissionData));
$em->persist($orderProduct);
$em->flush();
}
$response = true;
if (true === $emission) {
$this->CallAPI($session, $aviaturLogSave, $registry, 'POST', $transactionId);
$objectTemplate = \simplexml_load_string($xmlTemplateBody);
$urlEmission = $configPackageAgency->getWsUrl();
$client = new \SoapClient($urlEmission . '?wsdl', ['trace' => 1]);
try {
$aviaturLogSave->logSave(print_r($xmlTemplateHead . $xmlTemplateBody . $xmlTemplatefooter, true), 'CrearSolicitudPaquetes', 'RQ', $transactionId);
$response = $client->__doRequest($xmlTemplateHead . $xmlTemplateBody . $xmlTemplatefooter, $urlEmission, 'http://www.aviatur.com.co/CrearSolicitudPaquetes', 1);
//$response = str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\wamp\www\serviciosquemadosaviatur\package\CrearSolicitudPaquetes__RS.xml'));
$aviaturLogSave->logSave(print_r($response, true), 'CrearSolicitudPaquetes', 'RS', $transactionId);
$xml = str_replace('<', '<', $response);
$xml = str_replace('>', '>', $xml);
$xml = str_replace('<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>', '', $xml);
$xml = str_replace('</soap:Body></soap:Envelope>', '', $xml);
$xmlResponse = \simplexml_load_string($xml);
$estado = (string) $xmlResponse->CrearSolicitudPaquetesResult->RESPUESTA->ESTADO;
$descriptionError = (string) $xmlResponse->CrearSolicitudPaquetesResult->RESPUESTA->DESC_ERROR;
$respuesta = (string) $xmlResponse->CrearSolicitudPaquetesResult->RESPUESTA->MESSAGE;
$soapFault = false;
} catch (\SoapFault $e) {
var_dump($e->faultcode);
var_dump($e->faultstring);
$soapFault = true;
$descriptionError = 'Error de servicio';
$estado = 'ERROR';
$respuesta = 'ERROR';
}
if (null == $customer) {
$clientInformation = ['infoClient' => simplexml_load_string($infoClient), 'documentNumber' => $passengerCLI['doc_num'], 'address' => $passengerCLI['address'], 'phone' => $passengerCLI['phone'], 'email' => $passengerCLI['email']];
} else {
$clientInformation = ['infoClient' => simplexml_load_string($infoClient), 'documentNumber' => $customer->getDocumentNumber(), 'address' => $customer->getAddress(), 'phone' => $customer->getPhone(), 'email' => $customer->getEmail()];
}
$resumeView = ['Estado' => $estado, 'Description' => $descriptionError, 'message' => $respuesta];
$session->set($transactionId . '[mpt][resumeView]', json_encode($resumeView));
$session->set($transactionId . '[mpt][ProductInfo]', json_encode(utf8_encode($ProductInfo)));
$session->set($transactionId . '[mpt][infoClient]', json_encode($clientInformation));
$session->set($transactionId . '[mpt][infoSelection]', json_encode($informationPrestador));
$session->set($transactionId . '[mpt][optionalSelection]', json_encode($informationPrestador['optionals']));
$hotelInfo = '';
$emailData = [
'resumeView' => $resumeView,
'ProductInfo' => simplexml_load_string(utf8_encode($ProductInfo)),
'clientInformation' => $clientInformation,
'informationPrestador' => $informationPrestador,
'optionals' => $informationPrestador['optionals'],
'passengerADT' => $arrayAdult,
'passengerCHD' => $arrayChildren,
'amount' => $amount,
'AmountTotal' => $AmountTotal,
'agencyData' => $agency,
];
if ($isAgent) {
$emailData['qseAmount'] = $qseAmount;
$emailData['qseText'] = $qseText;
}
if ($session->has($transactionId . '[mpt]' . '[infoCaution]')) {
$emailData['infoCaution'] = json_decode($session->get($transactionId . '[mpt]' . '[infoCaution]'));
}
foreach ($emailData['informationPrestador']['IdPrestador'] as $idprestador) {
foreach ($hotelsInfo->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation as $hotelInfo) {
if ($idprestador == $hotelInfo->Identity['HotelCode']) {
$emailData['informationPrestador']['nameHotel'][] = $hotelInfo->Identity['HotelName'];
}
}
}
$postData = $request->all();
$publicKey = $aviaturEncoder->aviaturRandomKey();
$encodedInfo = $aviaturEncoder->AviaturEncode(json_encode($postData), $publicKey);
$formUserInfo = new FormUserInfo();
$formUserInfo->setInfo($encodedInfo);
$formUserInfo->setPublicKey($publicKey);
$em->persist($formUserInfo);
$em->flush();
$session->set($transactionId . '[mpt][user_info]', $formUserInfo->getId());
if ('false' == (string) $infopackage->TPA_Extensions->ProductInfo->FormaVenta) {
if (true !== $session->has($transactionId . '[mpt][order]')) {
if (true === $session->has($transactionId . '[mpt][detail]')) {
$session->set($transactionId . '[mpt][detail_data_package]', json_encode($postData));
$billingData = $request->get('BD');
$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('MPT');
if ($isFront) {
$orderIdentifier = '{order_product_reservation}';
} else {
$orderIdentifier = '{order_product_num}';
}
$order = $aviaturOrderController->createAction($agency, $customer, $productType, $orderIdentifier, $status);
$orderId = str_replace('ON', '', $order['order']);
$orderEntity = $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
$formUserInfo = $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId . '[mpt][user_info]'));
$formUserInfo->setOrder($orderEntity);
$em->persist($formUserInfo);
$em->flush();
/*
* Agent Octopus
* Agent Transaction, Save commission QSE or Percentage
*/
if ($isAgent) {
$orderProductCode = $session->get($transactionId . '[mpt][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$arrayInfo = $infoDates['commissionAgent'];
$agentTransaction = new AgentTransaction();
$agentTransaction->setAgent($agentId);
$agentTransaction->setAgentCommission($agentCommission);
$agentTransaction->setOrderProduct($orderProduct);
$agentTransaction->setCommissionvalue(round((float) ($arrayInfo[4])));
$agentTransaction->setAmountQse($arrayInfo[6]['amountQse']);
$agentTransaction->setCommissionQse($arrayInfo[6]['commissionQse']);
$agentTransaction->setAmountTarifa($arrayInfo[6]['amountTa']);
$agentTransaction->setCommissionTarifa($arrayInfo[6]['commissionTa']);
$agentTransaction->setAmountProduct($arrayInfo[6]['amountProduct']);
$agentTransaction->setPercentageTarifa($arrayInfo[6]['percentageTarifa']);
$em->persist($agentTransaction);
$em->flush();
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró la agencia con el dominio: ' . $request->getHost()));
}
} else {
return $this->json(['error' => 'fatal', 'message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId . '[availability_url]'), '', 'No encontramos información del detalle de su búsqueda, por favor vuelva a intentarlo')]);
}
}
$arraydecode = json_encode($resumeView);
$response = new Response($arraydecode);
$response->headers->set('Content-Type', 'application/json');
} else {
$response = $this->redirect($this->generateUrl('aviatur_package_resume_secure'));
}
$orderProductCode = $session->get($transactionId . '[mpt][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
if ($session->has('promotionalCodePackage_code') && '0' !== $session->get('promotionalCodePackage_code')) {
$promotionalCodePackage = $em->getRepository(\Aviatur\PackageBundle\Entity\PromotionalCodePackage::class)->findOneByCode($session->get('promotionalCodePackage_code'));
if ($promotionalCodePackage) {
$promotionalCodePackage->setOrderproductid($orderProduct->getId());
}
}
if ('dev' != $environment && isset($infopackage->TPA_Extensions->ProductInfo->Email) && !empty($infopackage->TPA_Extensions->ProductInfo->Email)) {
foreach (explode(';', $infopackage->TPA_Extensions->ProductInfo->Email) as $emails) {
$toMails[] = $emails;
}
}
$bccMails = [$emailNotification];
if ($session->has('whitemark')) {
if ('' != $session->get('whitemarkMail')) {
$bccMails[] = $session->get('whitemarkMail');
$bccMails[] = 'agenciasenlinea@aviatur.com';
$bccMails[] = 'sebastian.huertas@aviatur.com';
}
} else {
$bccMails[] = $agency->getMailcontact();
$bccMails[] = 'soptepagelectronic@aviatur.com';
}
if ('ERROR' == $estado || $soapFault) {
$status = 'waiting';
if ('true' == (string) $infopackage->TPA_Extensions->ProductInfo->FormaVenta) {
$status = 'approved';
}
$toMails = $bccMails;
$mailInfo = print_r($descriptionError, true) . '<br>' . print_r($objectTemplate, true);
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($toMails)
->setBcc([$emailNotification, 'sebastian.huertas@aviatur.com'])
->setSubject('Error al Crear Paquete ' . $orderProductCode)
->setBody($mailInfo);
$mailer->send($messageEmail);
$OrderIdAviatur = 'ErrorToCreate';
$Productidaviatur = $OrderIdAviatur;
} else {
if ($session->has($transactionId . '[mpt][order]') && !empty($orderProductCode)) {
$emailData['resumeView']['message'] = $emailData['resumeView']['message'] . ' - ' . json_decode($orderProductCode)->products;
}
/**
* Agente Octopus
* Cambiar logo Correo Gracias por tu compra.
*/
$isAgent = false;
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
$user = $this->getUser();
$agent = $user->getAgent();
$agency = $this->agency;
if (!empty($agent[0]) && $agent[0]->getAgency()->getId() === $agency->getId()) {
$planSepare = $request->get('PS');
if (isset($planSepare['slPlanSepare']) && 'on' == $planSepare['slPlanSepare']) {
$emailData['planSepare'] = true;
}
$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;
}
}
}
$emissionData['emission'] = $respuesta;
$this->CallAPI($session, $aviaturLogSave, $registry, 'CONT', $transactionId);
$status = 'approved_package';
if ('true' == (string) $infopackage->TPA_Extensions->ProductInfo->FormaVenta) {
$status = 'approved';
}
$packageFile = $projectDir . '/serviceLogs/packageReservation/' . $respuesta . '.pdf';
$pdf->generateFromHtml($this->renderView($urlResume, $emailData), $packageFile, ['encoding' => 'utf-8']);
$mailInfo = print_r($descriptionError, true) . '<br>' . print_r($objectTemplate, true);
$subject = $orderProduct->getOrder()->getAgency()->getName();
if ($session->has('whitemark')) {
$subject = 'Marca Blanca ' . $session->get('whitemarkName');
}
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($cliente['email'])
->setCC($toMails)
->setBcc($bccMails)
->attach(\Swift_Attachment::fromPath($packageFile))
->setSubject($subject . ' Reserva de Paquete Creada ' . $respuesta)
->setBody($this->renderView($urlResume, $emailData));
$mailer->send($messageEmail);
unlink($packageFile);
$respuestas = explode('-', $respuesta);
$OrderIdAviatur = isset($respuestas[0]) ? trim($respuestas[0]) : '';
$Productidaviatur = isset($respuestas[1]) ? trim($respuestas[1]) : '';
/*
* Agente Octopus
* Email de la reserva del agente hijo enviado al agente Padre Octopus.
*/
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
$user = $this->getUser();
$agent = $user->getAgent();
$agency = $this->agency;
if (!empty($agent[0]) && $agent[0]->getAgency()->getId() === $agency->getId()) {
$agent = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
$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($subject . ' - Reserva de Paquete Creada - ' . $respuesta . ' ' . $customer->getFirstname() . ' ' . $customer->getLastname() . ' Vendedor - ' . $agent->getCustomer()->getFirstName() . ' ' . $agent->getCustomer()->getLastName())
->setBody($this->renderView($urlResume, $emailData));
$mailer->send($messageAgent);
} else {
$messageAgent = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($agent->getCustomer()->getEmail())
->setBcc($bccMails)
->setSubject($subject . ' - Reserva de Paquete Creada - ' . $respuesta . ' ' . $customer->getFirstname() . ' ' . $customer->getLastname() . ' Vendedor - ' . $agent->getCustomer()->getFirstName() . ' ' . $agent->getCustomer()->getLastName())
->setBody($this->renderView($urlResume, $emailData));
$mailer->send($messageAgent);
}
}
}
}
$orderProduct->setEmissiondata(json_encode($emissionData));
$orderProduct->getOrder()->setStatus($status);
$orderProduct->setStatus($status);
$orderProduct->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setOrderIdAviatur($OrderIdAviatur);
$orderProduct->setProductidaviatur($Productidaviatur);
$em->persist($orderProduct);
$em->flush();
}
return $response;
}
public function createOrderPackageErrorAction(Request $request, TwigFolder $twigFolder, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, 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 puede 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éntelo nuevamente'));
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Página no accesible', 'No puede acceder al detalle sin disponibilidad'));
}
}
public function resumeAction(TwigFolder $twigFolder, ManagerRegistry $registry, ParameterBagInterface $parameterBag, AviaturLogSave $aviaturLogSave)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
header('Content-Type: text/html;charset=utf-8');
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$transactionId = $session->get($transactionIdSessionName);
$agencyFolder = $twigFolder->twigFlux();
$resumeTrans = json_decode($session->get($transactionId . '[mpt]' . '[resumeView]'));
$ProductInfo = json_decode($session->get($transactionId . '[mpt]' . '[ProductInfo]'));
$infoClient = json_decode($session->get($transactionId . '[mpt]' . '[infoClient]'));
$infoSelection = json_decode($session->get($transactionId . '[mpt]' . '[infoSelection]'));
$infoOptionals = json_decode($session->get($transactionId . '[mpt]' . '[optionalSelection]'));
$orderProductCode = json_decode($session->get($transactionId . '[mpt]' . '[order]'));
if ('jetset_semana' === $agency->getAssetsFolder()) {
$urlReturn = $this->CallAPI($session, $aviaturLogSave, $registry, 'GET', $transactionId);
}
$productId = str_replace('PN', '', $orderProductCode->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$resumeView = [
'Estado' => $resumeTrans->Estado,
'Description' => $resumeTrans->Description,
'message' => $resumeTrans->message . ' - ' . $orderProductCode->products,
'ProductInfo' => simplexml_load_string(html_entity_decode($ProductInfo)),
'infoClient' => $infoClient,
'infoOptionals' => $infoOptionals,
'infoSelection' => $infoSelection,
'agencyData' => $agency,
'urlReturn' => $urlReturn ?? null,
];
$resumeView['InfoHotel'] = simplexml_load_string($session->get($transactionId . '[mpt]' . '[InfoHotel]'));
foreach ($resumeView['infoSelection']->IdPrestador as $idprestador) {
foreach ($resumeView['InfoHotel']->OTA_PkgAvailRS->Package->ItineraryItems->ItineraryItem->Accommodation as $hotelInfo) {
if ($idprestador == $hotelInfo->Identity['HotelCode']) {
$resumeView['infoSelection']->nameHotel[] = $hotelInfo->Identity['HotelName'];
$resumeView['infoSelection']->categoria[] = $hotelInfo->TPA_Extensions->HotelInfo->Category->CodeDetail;
$resumeView['infoSelection']->Latitude[] = $hotelInfo->TPA_Extensions->HotelInfo->Latitude;
$resumeView['infoSelection']->Longitude[] = $hotelInfo->TPA_Extensions->HotelInfo->Longitude;
$resumeView['infoSelection']->Zone[] = $hotelInfo->TPA_Extensions->HotelInfo->Zone;
$resumeView['infoSelection']->Multimedia[] = $hotelInfo->TPA_Extensions->HotelInfo->Multimedia->ImageItems->ImageItem;
}
}
}
$urlResume = $twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Package/Default/resume_content.html.twig');
$setResume = $this->render($urlResume, $resumeView);
$orderProduct->setEmail(json_encode($resumeView));
$orderProduct->setResume($setResume);
$bookinData = json_decode($session->get($transactionId . '[mpt][resumeView]'), true);
if (isset($bookinData['Estado'][0]) && 'OK' == mb_strtoupper($bookinData['Estado'][0])) {
$emissionData = json_decode($orderProduct->getEmissionData(), true);
$emissionData['emission'] = $bookinData['message'][0];
$orderProduct->setEmissionData(json_encode($emissionData));
}
$em->persist($orderProduct);
$em->flush();
return $setResume;
}
/* Funcion que calcula el numero de Festivos entre dos fechas */
public function CountFestivos($fecha1, $fecha2, $weekDay)
{
$fecha1 = strtotime($fecha1);
$fecha2 = strtotime($fecha2);
$DayWeek = explode('-', $weekDay);
$countFestivos = 0;
for ($fecha1; $fecha1 < $fecha2; $fecha1 = strtotime('+1 day ' . date('Y-m-d', $fecha1))) {
for ($i = 0; $i < sizeof($DayWeek); ++$i) {
if (7 == $DayWeek[$i]) {
$DayWeek[$i] = 0;
}
if (date('w', $fecha1) == $DayWeek[$i]) {
++$countFestivos;
}
}
}
return $countFestivos;
}
public function viewConditionsAction(Request $request, TwigFolder $twigFolder, SessionInterface $session)
{
$fullRequest = $request;
$request = $fullRequest->request;
$transactionID = $request->get('transactionId');
$response = simplexml_load_string($session->get($transactionID . '[mpt]' . '[InfoHotel]'));
$agencyFolder = $twigFolder->twigFlux();
foreach ($response->OTA_PkgAvailRS->Package as $information) {
foreach ($information->Cautions as $travelerInformation) {
foreach ($travelerInformation as $caution) {
$info = explode('</Caution>', str_replace($caution['ID'] . '">', '</Caution>', $caution->asXml()));
$caution['Info'] = isset($info[1]) ? htmlspecialchars_decode($info[1]) : '';
$infoHtml = $travelerInformation;
$travelerInformation = $infoHtml;
}
}
}
$urlDetail = $twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Package/Includes/package_conditions.html.twig');
return $this->render($urlDetail, ['ProductsDetail' => $response, 'conditions' => true]);
}
public function viewConditionsErrorAction(Request $request, TwigFolder $twigFolder, AviaturErrorHandler $aviaturErrorHandler, RouterInterface $router, 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'));
}
}
/* Función que calcula el valor que factura los niños segun la edad */
public function AmountCHD($AmountBaby, $selectValue, $ageMin, $ageMax, $AmountADT, $CHDValue)
{
$AmountChdTotal = 0;
$newCHDValue = 0;
if ($selectValue !== null) {
for ($i = 0; $i < sizeof($selectValue); ++$i) {
if (null != $ageMin || null != $ageMax) {
if ($selectValue[$i] < min($ageMin)) {
//echo $selectValue[$i] . "***fuera por rango minimo***0****" . "2.1<br>";
$AmountChdTotal = $AmountChdTotal + $AmountBaby;
} elseif ($selectValue[$i] > max($ageMax)) {
//echo $selectValue[$i] . "***fuera por rango maximo****" . $AmountADT . "****" . "2.2<br>";
$AmountChdTotal = $AmountChdTotal + $AmountADT;
} else {
for ($j = 0; $j < sizeof($ageMin); ++$j) {
if ($selectValue[$i] >= $ageMin[$j] && $selectValue[$i] <= $ageMax[$j]) {
if ((is_countable($CHDValue) ? count($CHDValue) : 0) > 1) {
$newCHDValue = $CHDValue[$j];
} else {
$newCHDValue = $CHDValue[0];
}
$AmountChdTotal = $AmountChdTotal + $newCHDValue;
//echo $selectValue[$i] . "En el rango***" . $ageMin[$j] . "***" . $ageMax[$j] . "****" . $AmountChdTotal . "****" .$CHDValue[$j]. "<br>";
break;
}
}
}
}
}
}
return $AmountChdTotal;
}
/* Función que calcula el valor total de la tarifa */
public function calculoTarifa($subTotal, $TotalDays, $tarifas, $roomAditional, $personAditional, $ADTotal, $CHDTotal, $nights)
{
$tarifaReal = [];
$TotalADN = 0;
$TotalADD = 0;
$TotalAAN = 0;
$AmountChn = 0;
$tarifaReal['CantADT'] = $ADTotal;
$tarifaReal['CantCHD'] = $CHDTotal;
$tarifaReal['CantNights'] = $TotalDays;
$tarifaReal['aditionalRoom'] = $roomAditional;
$tarifaReal['aditionalPerson'] = $personAditional;
$tarifaReal['ADT'] = ($TotalDays > 1) ? (int) ($tarifas['AmountADT']) : (int) ($tarifas['AmountADT']) / $nights;
$tarifaReal['DAYS_ADT'] = $nights;
if ($CHDTotal > 0) {
$tarifaReal['CHD'] = ($TotalDays > 1) ? (int) ($tarifas['AmountCHD']) : (int) ($tarifas['AmountCHD']) / $nights;
$tarifaReal['DAYS_CHD'] = $nights;
}
if ($roomAditional > 0 && $personAditional > 0) {
$TotalADN = $tarifas['AmountADN'] * $roomAditional * $ADTotal;
$tarifaReal['ADN'] = $tarifas['AmountADN'];
$tarifaReal['DAYS_ADN'] = $roomAditional;
$TotalADD = $tarifas['AmountADD'] * $TotalDays;
$tarifaReal['ADD'] = $tarifas['AmountADD'];
$tarifaReal['DAYS_ADD'] = $TotalDays;
$TotalAAN = $tarifas['AmountAAN'] * $roomAditional;
$tarifaReal['AAN'] = $tarifas['AmountAAN'];
$tarifaReal['DAYS_AAN'] = $roomAditional;
$subTotal = $subTotal + $TotalADN + $TotalADD + $TotalAAN;
if ($CHDTotal > 0) {
$AmountChn = $tarifas['AmountCHN'] * $roomAditional * 1;
$tarifaReal['CHN'] = $tarifas['AmountCHN'];
$tarifaReal['DAYS_CHN'] = $roomAditional;
$subTotal = $subTotal + $AmountChn;
}
} elseif ($roomAditional > 0 && 0 == $personAditional) {
$TotalADN = $tarifas['AmountADN'] * $roomAditional * $ADTotal;
$tarifaReal['ADN'] = $tarifas['AmountADN'];
$tarifaReal['DAYS_ADN'] = $roomAditional;
$subTotal = $subTotal + $TotalADN;
if ($CHDTotal > 0) {
$AmountChn = $tarifas['AmountCHN'] * $roomAditional * 1;
$tarifaReal['CHN'] = $tarifas['AmountCHN'];
$tarifaReal['DAYS_CHN'] = $roomAditional;
$subTotal = $subTotal + $AmountChn;
}
} elseif (0 == $roomAditional && $personAditional > 0) {
$TotalADD = $tarifas['AmountADD'] * $TotalDays;
$tarifaReal['ADD'] = $tarifas['AmountADD'];
$tarifaReal['DAYS_ADD'] = $TotalDays;
$subTotal = $subTotal + $TotalADD;
}
$result = ['SubTotal' => $subTotal, 'tarifas' => $tarifas, 'tarifaReal' => $tarifaReal];
return $result;
}
public function calculoValor($cantidad, $tarifa, $dayType, $UnitCostValue, $nights)
{
$total = 0;
$total = $cantidad * $tarifa * $dayType;
if (0 == $UnitCostValue) {
$total = $total / $nights;
}
return $total;
}
public function calculoTarifaFinDeSemana($roomAditional, $personAditional, $fecha1, $fecha2, $CantADT, $CHDTotal, $tarifas, $WeekDay, $ageMinCHD, $ageMaxCHD, $ChdValues, $selectValue, $ageMinCHN, $ageMaxCHN, $ChnValues, $ageMinCHF, $ageMaxCHF, $ChfValues, $ageMinCFN, $ageMaxCFN, $CfnValues, $UnitCostValue, $nights)
{
$tarifaReal = [];
$AmountBaby = 0;
$countHabiles = $this->CountFestivos($fecha1, $fecha2, substr($WeekDay['ADT'], 0, -1));
$countFestivos = $this->CountFestivos($fecha1, $fecha2, $WeekDay['ADF']);
$tarifaADT = $this->calculoValor($CantADT, $tarifas['AmountADT'], $countHabiles, $UnitCostValue, $nights);
$tarifaReal['ADT'] = ($tarifaADT / $CantADT) / ((0 == $countHabiles) ? 1 : $countHabiles);
$tarifaReal['DAYS_ADT'] = $countHabiles;
$tarifaADF = $this->calculoValor($CantADT, $tarifas['AmountADF'], $countFestivos, $UnitCostValue, $nights);
$tarifaReal['ADF'] = ($tarifaADF / $CantADT) / ((0 == $countFestivos) ? 1 : $countFestivos);
$tarifaReal['DAYS_ADF'] = $countFestivos;
$SubTotal = $tarifaADT + $tarifaADF;
if ($CHDTotal > 0) {
$AmountCHD = $this->AmountCHD($AmountBaby, $selectValue, $ageMinCHD, $ageMaxCHD, $tarifas['AmountADT'], $ChdValues);
$tarifas['AmountCHD'] = $AmountCHD;
$tarifaCHD = $this->calculoValor(1, $AmountCHD, $countHabiles, $UnitCostValue, $nights);
$tarifaReal['CHD'] = ($tarifaCHD / $CHDTotal) / ((0 == $countHabiles) ? 1 : $countHabiles);
$tarifaReal['DAYS_CHD'] = $countHabiles;
$AmountCHF = $this->AmountCHD($AmountBaby, $selectValue, $ageMinCHF, $ageMaxCHF, $tarifas['AmountADT'], $ChfValues);
$tarifaCHF = $this->calculoValor(1, $AmountCHF, $countFestivos, $UnitCostValue, $nights);
$tarifaReal['CHF'] = ($tarifaCHF / $CHDTotal) / ((0 == $countFestivos) ? 1 : $countFestivos);
$tarifaReal['DAYS_CHF'] = $countFestivos;
$TotalCHD = $tarifaCHD + $tarifaCHF;
$tarifas['AmountCHF'] = $AmountCHF;
$SubTotal = $SubTotal + $TotalCHD;
}
$newFechaIni = $fecha2;
$newFechaFin = strtotime('+' . $roomAditional . ' day', strtotime($newFechaIni));
$newFechaFin = date('Y-m-d', $newFechaFin);
$HabilesAditional = $this->CountFestivos($newFechaIni, $newFechaFin, substr($WeekDay['ADN'], 0, -1));
$FestivosAditional = $this->CountFestivos($newFechaIni, $newFechaFin, $WeekDay['ADF']);
$AditionalPerson = 1;
if ($roomAditional > 0 && $personAditional > 0) {
$HabilesPersonAdd = $this->CountFestivos($fecha1, $fecha2, substr($WeekDay['ADD'], 0, -1));
$FestivosPersonAdd = $this->CountFestivos($fecha1, $fecha2, $WeekDay['AFN']);
$tarifaADN = $this->calculoValor($CantADT, $tarifas['AmountADN'], $HabilesAditional, 1, $roomAditional);
$tarifaReal['ADN'] = ($tarifaADN / $CantADT) / ((0 == $HabilesAditional) ? 1 : $HabilesAditional);
$tarifaReal['DAYS_ADN'] = $HabilesAditional;
$tarifaANF = $this->calculoValor($CantADT, $tarifas['AmountANF'], $FestivosAditional, 1, $roomAditional);
$tarifaReal['ANF'] = ($tarifaANF / $CantADT) / ((0 == $FestivosAditional) ? 1 : $FestivosAditional);
$tarifaReal['DAYS_ANF'] = $FestivosAditional;
$tarifaADD = $AditionalPerson * $tarifas['AmountADD'];
$tarifaReal['ADD'] = $tarifas['AmountADD'];
$tarifaReal['DAYS_ADD'] = $HabilesPersonAdd;
$tarifaAAN = $AditionalPerson * $tarifas['AmountAAN'] * $HabilesAditional;
$tarifaReal['AAN'] = $tarifas['AmountAFN'];
$tarifaReal['DAYS_AAN'] = $HabilesAditional;
$tarifaAFN = $AditionalPerson * $tarifas['AmountAFN'] * $FestivosAditional;
$tarifaReal['AFN'] = $tarifas['AmountAFN'];
$tarifaReal['DAYS_AFN'] = $FestivosAditional;
$SubTotal = $SubTotal + $tarifaADN + $tarifaANF + $tarifaADD + $tarifaAAN + $tarifaAFN;
if ($CHDTotal > 0) {
$AmountCHN = $this->AmountCHD($AmountBaby, $selectValue, $ageMinCHN, $ageMaxCHN, $tarifas['AmountADN'], $ChnValues);
$tarifas['AmountCHN'] = $AmountCHN;
$tarifaCHN = $this->calculoValor(1, $AmountCHN, $HabilesAditional, 1, $roomAditional);
$tarifaReal['CHN'] = ($tarifaCHN / $CHDTotal) / ((0 == $HabilesAditional) ? 1 : $HabilesAditional);
$tarifaReal['DAYS_CHN'] = $HabilesAditional;
$AmountCFN = $this->AmountCHD($AmountBaby, $selectValue, $ageMinCFN, $ageMaxCFN, $tarifas['AmountADN'], $CfnValues);
$tarifas['AmountCFN'] = $AmountCFN;
$tarifaCFN = $this->calculoValor(1, $AmountCFN, $FestivosAditional, 1, $roomAditional);
$tarifaReal['CFN'] = ($tarifaCFN / $CHDTotal) / ((0 == $FestivosAditional) ? 1 : $FestivosAditional);
$tarifaReal['DAYS_CFN'] = $FestivosAditional;
$TotalCHN = $tarifaCHN + $tarifaCFN;
$SubTotal = $SubTotal + $TotalCHN;
}
} elseif ($roomAditional > 0 && 0 == $personAditional) {
$tarifaADN = $this->calculoValor($CantADT, $tarifas['AmountADN'], $HabilesAditional, 1, $roomAditional);
$tarifaReal['ADN'] = ($tarifaADN / $CantADT) / ((0 == $HabilesAditional) ? 1 : $HabilesAditional);
$tarifaReal['DAYS_ADN'] = $HabilesAditional;
$tarifaANF = $this->calculoValor($CantADT, $tarifas['AmountANF'], $FestivosAditional, 1, $roomAditional);
$tarifaReal['ANF'] = ($tarifaANF / $CantADT) / ((0 == $FestivosAditional) ? 1 : $FestivosAditional);
$tarifaReal['DAYS_ANF'] = $FestivosAditional;
$SubTotal = $SubTotal + $tarifaADN + $tarifaANF;
if ($CHDTotal > 0) {
$AmountCHN = $this->AmountCHD($AmountBaby, $selectValue, $ageMinCHN, $ageMaxCHN, $tarifas['AmountADN'], $ChnValues);
$tarifas['AmountCHN'] = $AmountCHN;
$tarifaCHN = $this->calculoValor(1, $AmountCHN, $HabilesAditional, 1, $roomAditional);
$tarifaReal['CHN'] = ($tarifaCHN / $CHDTotal) / ((0 == $HabilesAditional) ? 1 : $HabilesAditional);
$tarifaReal['DAYS_CHN'] = $HabilesAditional;
$AmountCFN = $this->AmountCHD($AmountBaby, $selectValue, $ageMinCFN, $ageMaxCFN, $tarifas['AmountADN'], $CfnValues);
$tarifas['AmountCFN'] = $AmountCFN;
$tarifaCFN = $this->calculoValor(1, $AmountCFN, $FestivosAditional, 1, $roomAditional);
$tarifaReal['CFN'] = ($tarifaCFN / $CHDTotal) / ((0 == $FestivosAditional) ? 1 : $FestivosAditional);
$tarifaReal['DAYS_CFN'] = $FestivosAditional;
$TotalCHN = $tarifaCHN + $tarifaCFN;
$SubTotal = $SubTotal + $TotalCHN;
}
} elseif (0 == $roomAditional && $personAditional > 0) {
$HabilesPersonAdd = $this->CountFestivos($fecha1, $fecha2, substr($WeekDay['ADD'], 0, -1));
$FestivosPersonAdd = $this->CountFestivos($fecha1, $fecha2, $WeekDay['AFN']);
$tarifaADD = $AditionalPerson * $tarifas['AmountADD'] * $HabilesPersonAdd;
$tarifaReal['AAN'] = $tarifas['AmountAFN'];
$tarifaReal['DAYS_AAN'] = $HabilesPersonAdd;
$SubTotal = $SubTotal + $tarifaADD;
}
$result = ['SubTotal' => $SubTotal, 'tarifas' => $tarifas, 'tarifaReal' => $tarifaReal];
return $result;
}
public function processLegalPersonalities(ManagerRegistry $registry, $customer)
{
$em = $this->managerRegistry;
$documentNumber = (string) $customer->getDocumentNumber();
$documentType = (string) $customer->getDocumentType()->getId();
$personType = (string) $customer->getPersonType();
if (('8' === $documentNumber[0] || '9' === $documentNumber[0]) && 10 === strlen($documentNumber)) {
if ('3' !== $documentType || '7' !== $personType) {
$customer->setDocumentType($em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->find(3));
$customer->setPersonType(7);
$em->flush();
return true;
}
}
return false;
}
public function createCustomer(ParameterBagInterface $parameterBag, AviaturWebService $aviaturWebService, \Swift_Mailer $mailer, SessionInterface $session, ManagerRegistry $registry, $customer)
{
$providerService = $parameterBag->get('provider_service');
$webmasterEmail = $parameterBag->get('webmaster_email');
$output = null;
$em = $this->managerRegistry;
$docType = $customer->getDocumentType()->getExternalcode();
$docNumber = $customer->getDocumentNumber();
$customerModel = new CustomerModel();
$xmlRequest = $customerModel->getXmlFindUser($docType, $docNumber, '0926EB', 'BOGVU2900');
$responseCustomer = $aviaturWebService->busWebServiceAmadeus('GENERALLAVE', $providerService, $xmlRequest);
if ('FALLO' == $responseCustomer->RESULTADO) {
$emailTo = $webmasterEmail;
$xmlRequest = $customerModel->getXmlRegister($customer, 1);
$responseCustomer = $aviaturWebService->busWebServiceAmadeus('GENERALLAVE', $providerService, $xmlRequest);
if ('FALLO' == $responseCustomer->RESULTADO) {
if (!$this->processLegalPersonalities($registry, $customer)) {
$emailContent = 'id customer new DB:' . $customer->getId() . '</b> Email customer new DB: <b>' . $customer->getEmail() . '</b> Service Response: ' . print_r($responseCustomer, true);
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setSubject('updateCustomerCommand Error 1')
->setTo($emailTo)
->setBody($emailContent);
$mailer->send($message);
} else {
$output->writeln('Customer id[' . $customer->getId() . '] updated: documentType=3 - personType=7');
}
} elseif (isset($responseCustomer->SALIDAS->ELEMENTO_SALIDA_B2C->ID_CLIENTE)) {
$responseId = (string) $responseCustomer->SALIDAS->ELEMENTO_SALIDA_B2C->ID_CLIENTE;
}
if (isset($responseId) && (null != (string) $responseId)) {
$customer->setAviaturClientId((string) $responseId);
$em->persist($customer);
$em->flush();
} else {
$emailContent = 'id customer new DB:' . $customer->getId() . '</b> Email customer new DB: <b>'
. $customer->getEmail() . '</b> Service Response: ' . print_r($responseCustomer, true)
. '<br><pre>' . htmlspecialchars(print_r($xmlRequest, true)) . '</pre>';
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setSubject('updateCustomerCommand Error 2')
->setTo($emailTo)
->setBody($emailContent);
$mailer->send($message);
}
}
}
public function CallAPI(SessionInterface $session, AviaturLogSave $aviaturLogSave, ManagerRegistry $registry, $method, $transactionId)
{
$data = null;
$response = [];
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$infopackage = simplexml_load_string((string) $session->get($transactionId . '[mpt][infoPackage]'));
if (isset($infopackage->TPA_Extensions->ProductInfo->CargosYServicios->CargoYServicio['ThirdPartyId']) && '607' == (string) $infopackage->TPA_Extensions->ProductInfo->CargosYServicios->CargoYServicio['ThirdPartyId'] && $session->has($transactionId . '[mpt]' . '[detail_data_package]')) {
$detail_data_package = json_decode($session->get($transactionId . '[mpt]' . '[detail_data_package]'), true);
$infoDates = json_decode($session->get($transactionId . '[mpt][infoDates]'), true);
if (false !== strpos($detail_data_package['PI']['first_name_1_1'], '***')) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneBy(['documentnumber' => $detail_data_package['PI']['doc_num_1_1']]);
$detail_data_package['PI']['first_name_1_1'] = $customer->getFirstname();
$detail_data_package['PI']['last_name_1_1'] = $customer->getLastname();
$detail_data_package['PI']['address_1_1'] = $customer->getAddress();
$detail_data_package['PI']['email_1_1'] = $customer->getEmail();
}
$users = [];
for ($i = 0; $i < $detail_data_package['PI']['person_count_1']; ++$i) {
$users[$i]['name'] = $detail_data_package['PI']['first_name_1_' . ($i + 1)] . ' ' . $detail_data_package['PI']['last_name_1_' . ($i + 1)];
if (isset($detail_data_package['PI']['email_1_' . ($i + 1)])) {
$users[$i]['email'] = $detail_data_package['PI']['email_1_' . ($i + 1)];
}
}
$aviatur_payment_jet_set_api = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('jet_set_url');
$urls = json_decode($aviatur_payment_jet_set_api->getDescription(), true);
$url = $urls[$aviatur_payment_jet_set_api->getValue()][$method];
$curl = curl_init();
switch ($method) {
case 'POST':
curl_setopt($curl, CURLOPT_POST, 1);
$data = json_encode([
'idProducto' => (int) $infopackage['ID'],
'ProductName' => (string) $infopackage->TPA_Extensions->ProductInfo->ProductName,
'Description' => (string) $infopackage->TPA_Extensions->ProductInfo->Description,
'total' => $infoDates['AmountTotal'],
'cantidad' => $detail_data_package['PI']['person_count_1'],
'usuarios' => $users,
]);
if ($data) {
$aviaturLogSave->logSave(print_r($data, true), $agency->getAssetsFolder(), $method . ' RQ');
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
break;
case 'PUT':
curl_setopt($curl, CURLOPT_PUT, 1);
break;
case 'GET':
$data = base64_encode(json_encode([
'idProducto' => (int) $infopackage['ID'],
'ProductName' => (string) $infopackage->TPA_Extensions->ProductInfo->ProductName,
'Description' => (string) $infopackage->TPA_Extensions->ProductInfo->Description,
'total' => $infoDates['AmountTotal'],
'cantidad' => $detail_data_package['PI']['person_count_1'],
'usuarios' => $users,
]));
return $url . '?ProductInfo=' . $data;
case 'CONT':
curl_setopt($curl, CURLOPT_POST, 1);
$data = json_encode([
'idProducto' => (int) $infopackage['ID'],
]);
if ($data) {
$aviaturLogSave->logSave(print_r($data, true), $agency->getAssetsFolder(), $method . ' RQ');
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
break;
default:
if ($data) {
$url = sprintf('%s?%s', $url, http_build_query($data));
}
}
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
if (false === curl_exec($curl)) {
$response['error'] = curl_error($curl);
} else {
$response = curl_exec($curl);
}
curl_close($curl);
$aviaturLogSave->logSave(print_r($response, true), $agency->getAssetsFolder(), $method . ' RS');
}
return $response ?? false;
}
public function consultPromoCodeAction(Request $request, SessionInterface $session, ManagerRegistry $registry)
{
$em = $this->managerRegistry;
$fullRequest = $request;
$code = $fullRequest->request->get('code');
$promotionalCodePackage = $em->getRepository(\Aviatur\PackageBundle\Entity\PromotionalCodePackage::class)->findOneBy([
'code' => $code,
'orderproductid' => null,
]);
if (!($promotionalCodePackage)) {
$session->remove('promotionalCodePackage_code');
return $this->json(['response' => '0', 'text' => 'nonExistentCode']);
} else {
$session->set('promotionalCodePackage_code', $code);
return $this->json(['response' => '2', 'text' => 'availableCode', 'packageCode' => $promotionalCodePackage->getPackagecode()]);
}
}
}