<?php
namespace Aviatur\CarBundle\Controller;
use Aviatur\AgencyBundle\Entity\Agency;
use Aviatur\CarBundle\Entity\ConfigCarAgency;
use Aviatur\CarBundle\Entity\DirectRoutesCar;
use Aviatur\CarBundle\Entity\ProviderCarCode;
use Aviatur\CarBundle\Models\CarModel;
use Aviatur\CarBundle\Services\AviaturCarService;
use Aviatur\CarBundle\Services\SearchCarCookie;
use Aviatur\CustomerBundle\Entity\Customer;
use Aviatur\CustomerBundle\Entity\DocumentType;
use Aviatur\CustomerBundle\Entity\Gender;
use Aviatur\CustomerBundle\Services\ValidateSanctions;
use Aviatur\GeneralBundle\Controller\OrderController;
use Aviatur\GeneralBundle\Entity\Card;
use Aviatur\GeneralBundle\Entity\City;
use Aviatur\GeneralBundle\Entity\Country;
use Aviatur\GeneralBundle\Entity\FormUserInfo;
use Aviatur\GeneralBundle\Entity\HistoricalInfo;
use Aviatur\GeneralBundle\Entity\NameBlacklist;
use Aviatur\GeneralBundle\Entity\NameWhitelist;
use Aviatur\GeneralBundle\Entity\Order;
use Aviatur\GeneralBundle\Entity\OrderProduct;
use Aviatur\GeneralBundle\Entity\Parameter;
use Aviatur\GeneralBundle\Entity\PaymentMethod;
use Aviatur\GeneralBundle\Entity\PaymentMethodAgency;
use Aviatur\GeneralBundle\Entity\PointRedemption;
use Aviatur\GeneralBundle\Entity\SeoUrl;
use Aviatur\GeneralBundle\Services\AviaturEncoder;
use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
use Aviatur\GeneralBundle\Services\AviaturLogSave;
use Aviatur\GeneralBundle\Services\AviaturMailer;
use Aviatur\GeneralBundle\Services\AviaturWebService;
use Aviatur\GeneralBundle\Services\ExceptionLog;
use Aviatur\GeneralBundle\Services\PayoutExtraService;
use Aviatur\MpaBundle\Entity\Provider;
use Aviatur\PackageBundle\Models\PackageModel;
use Aviatur\PaymentBundle\Controller\CashController;
use Aviatur\PaymentBundle\Controller\P2PController;
use Aviatur\PaymentBundle\Controller\PSEController;
use Aviatur\PaymentBundle\Controller\SafetypayController;
use Aviatur\PaymentBundle\Controller\WorldPayController;
use Aviatur\PaymentBundle\Entity\PseBank;
use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
use Aviatur\PaymentBundle\Services\TokenizerService;
use Aviatur\SearchBundle\Entity\SearchAirports;
use Aviatur\TwigBundle\Services\TwigFolder;
use Doctrine\Persistence\ManagerRegistry;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Security\LoginManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Knp\Snappy\AbstractGenerator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Knp\Snappy\Pdf;
class DefaultController extends AbstractController
{
public function searchAction()
{
return $this->redirect(
$this->generateUrl(
'aviatur_search_cars',
[]
)
);
}
/**
* @param Request $request
* @param ManagerRegistry $managerRegistry
* @param AviaturErrorHandler $errorHandler
* @param AviaturWebService $webService
* @param TwigFolder $twigFolder
* @param ExceptionLog $exceptionLog
* @param SearchCarCookie $carCookie
* @param string $origin
* @param string $destination
* @param string $date1
* @param string $date2
*
* @return Response
*/
public function availabilityAction(Request $request, ManagerRegistry $managerRegistry, AviaturErrorHandler $errorHandler, AviaturWebService $webService, TwigFolder $twigFolder, ExceptionLog $exceptionLog, SearchCarCookie $carCookie, $origin, $destination, $date1, $date2)
{
$urlDescription = [];
$em = $managerRegistry->getManager();
$session = $request->getSession();
$agency = $em->getRepository(Agency::class)->find($session->get('agencyId'));
$fullRequest = $request;
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
$seoUrl = $em->getRepository(SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
$urlDescription['url'] = null != $seoUrl ? '/'.$seoUrl[0]->getUrl() : $requestUrl;
$sameOrigin = false;
if ('' == $destination) {
$destination = $origin;
$sameOrigin = true;
}
$pickUpDate = strtotime(false !== strpos($date1, 'T') ? date('Y-m-d\TH:i:s', strtotime(substr($date1, 0, 10).sprintf('+%d hours', substr($date1, -5, 2)))) : date('Y-m-d\TH:i:s', strtotime(substr($date1, 0, 10))));
$returnDate = strtotime(false !== strpos($date2, 'T') ? date('Y-m-d\TH:i:s', strtotime(substr($date2, 0, 10).sprintf('+%d hours', substr($date2, -5, 2)))) : date('Y-m-d\TH:i:s', strtotime(substr($date2, 0, 10))));
$now = strtotime('today');
if ($pickUpDate < $now || $returnDate <= $pickUpDate) {
$returnDate = $pickUpDate < $now ? date('Y-m-d\TH:i', strtotime('+8 day')) : date('Y-m-d\TH:i', strtotime($date1.'+8 day'));
$pickUpDate = $pickUpDate < $now ? date('Y-m-d\TH:i', strtotime('+1 day')) : date('Y-m-d\TH:i', $pickUpDate);
$url = 'aviatur_car_availability_1';
$data = [
'origin' => $origin,
'destination' => $destination,
'date1' => $pickUpDate,
'date2' => $returnDate,
];
if ($sameOrigin) {
$url = 'aviatur_car_availability_2';
$data = [
'origin' => $origin,
'date1' => $pickUpDate,
'date2' => $returnDate,
];
}
return $this->redirect($errorHandler->errorRedirectNoEmail($this->generateUrl($url, $data), 'Recomendación Automática', 'La consulta que realizaste no era válida, hemos analizado tu búsqueda y esta es nuestra recomendación'));
}
if ($fullRequest->isXmlHttpRequest()) {
$configsCarAgency = $em->getRepository(ConfigCarAgency::class)->findProviderForCarsWithAgency($agency);
$overrideArray = [];
$overrideProviders = [];
if ($configsCarAgency) {
$providers = [];
foreach ($configsCarAgency as $configCarAgency) {
$providers[] = $configCarAgency->getProvider()->getProvideridentifier();
$provider = $configCarAgency->getProvider()->getProvideridentifier();
if (1 == $configCarAgency->getOverride()) {
$overrideProviders[] = $configCarAgency->getProvider()->getProvideridentifier();
if (null == $configCarAgency->getExternalid()) {
$overrideArray[$provider]['externalId'] = $configCarAgency->getOfficeid();
$overrideArray[$provider]['officeId'] = $configCarAgency->getOfficeid();
} else {
$overrideArray[$provider]['externalId'] = $configCarAgency->getExternalid();
$overrideArray[$provider]['officeId'] = $configCarAgency->getOfficeid();
}
}
}
$carModel = new CarModel();
$variable = [
'ProviderId' => implode(';', $providers),
'correlationId' => '',
'pickUpDateTime' => date('Y-m-d\TH:i:s', $pickUpDate),
'returnDateTime' => date('Y-m-d\TH:i:s', $returnDate),
'pickUpLocation' => $origin,
'returnLocation' => $destination,
];
$hasTransaction = true;
$xmlOverrideArray = $carModel->getXmlOverride();
$tempOverride = '';
foreach ($overrideArray as $key => $array) {
$search = [
'{provider}',
'{externalId}',
'{officeId}',
];
$replace = [
$key,
$array['externalId'],
$array['officeId'],
];
$tempOverride .= str_replace($search, $replace, $xmlOverrideArray[1]);
}
$xmlOverride = $xmlOverrideArray[0].$tempOverride.$xmlOverrideArray[2];
$overrideVariables = [
'ProviderId' => implode(';', $overrideProviders),
];
$responseOverride = $webService->callWebServiceAmadeus('SERVICIO_MPT', 'VehOverride', 'dummy|http://www.aviatur.com.co/dummy/', $xmlOverride, $overrideVariables, true);
if (isset($responseOverride->Message->OTA_ScreenTextRS['CorrelationID'])) {
$variable['correlationId'] = (string) $responseOverride->Message->OTA_ScreenTextRS['CorrelationID'];
$hasTransaction = false;
}
$providersCars = $em->getRepository(ProviderCarCode::class)->findBy(['isActive' => 1]);
if (empty($providersCars)) {
$data = [
'error' => 'Error',
'message' => 'No se encontraron disponibilidades para las fechas 1.',
];
return $this->json($data);
}
$codeProviders = [];
foreach ($providersCars as $providerCar) {
$codeProviders[$providerCar->getCodeProviderCar()] = $providerCar->getInfo();
}
$xmlRequest = $carModel->getXmlAvailability($codeProviders);
$responseTemp = $webService->callWebServiceAmadeus('SERVICIO_MPT', 'VehAvailRate', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequest, $variable, $hasTransaction);
if (null != $responseTemp && !empty($responseTemp->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails)) {
$response = \simplexml_load_string(str_replace('4.JPEG', '6.JPEG', $responseTemp->asXml())); // try fetching bigger images
$response->Message->OTA_VehAvailRateRS['TransactionID'] = $response->Message->OTA_VehAvailRateRS['TransactionIdentifier'];
$response = $this->orderResponse($response, $codeProviders);
if (isset($response['error'])) {
$response = new Response(json_encode($response));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
$financialValue = $this->getCurrencyExchange($webService);
/* Se debe inicializar la sesión al momento de generar la disponibilidad */
$session->set('[car][finantial_rate_info]', $financialValue);
$vendorTypeList = [];
$cars = [];
foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $vendor) {
if (isset($vendor->VehAvails)) {
foreach ($vendor->VehAvails as $VehAvails) {
foreach ($VehAvails->VehAvail as $car) {
$car->VehAvailCore->Vehicle['PictureURL'] = str_replace(['9.JPEG', '&'], ['4.JPEG', '&'], (string) $car->VehAvailCore->Vehicle->PictureURL);
$VehicleChargeAmount = (float) $car->VehAvailCore->RentalRate->VehicleCharges->VehicleCharge['Amount'];
if (
isset($car->VehAvailCore->TPA_Extensions->LocalRate['CurrencyCode']) && isset($financialValue)
&& $VehicleChargeAmount > 0
&& !in_array($car->Vendor['Code'] . '-' . $car->VehAvailCore->Vehicle['VendorCarType'] . '-' . $car->Vendor['Provider'], $vendorTypeList)
) {
$cars[] = $car;
$vendorTypeList[] = $car->Vendor['Code'] . '-' . $car->VehAvailCore->Vehicle['VendorCarType'] . '-' . $car->Vendor['Provider'];
}
}
}
}
}
$stringFindReferer = (string) ((empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
$arrayFindReferer = explode('?', $stringFindReferer);
return $this->render($twigFolder->twigExists(sprintf('@AviaturTwig/%s/Car/Default/availability_ajaxResults.html.twig', $twigFolder->twigFlux())), [
'cars' => $cars,
'finantial_rate' => $session->get('[car][finantial_rate_info]'),
'transactionId' => (string) $response->Message->OTA_VehAvailRateRS['TransactionID'],
'correlationId' => (string) $response->Message->OTA_VehAvailRateRS['CorrelationID'],
'findReferer' => $arrayFindReferer[0]
]);
} else {
$data = [
'error' => 'Error',
'message' => 'No se encontraron disponibilidades para las fechas, por favor intente con otras fechas.',
];
return $this->json($data);
}
} else {
$exceptionLog->log(
'Error Fatal',
'No se encontró configuración para la agencia '.$agency->getId(),
null,
false
);
return $this->json([
'error' => 'error',
'message' => 'no se encontró agencias para consultar disponibilidad.',
]);
}
} else {
$from = $em->getRepository(SearchAirports::class)->findOneByIata($origin);
$to = $em->getRepository(SearchAirports::class)->findOneByIata($destination);
if ($from && $to) {
$cookieArray = [
'date1' => date('Y-m-d\TH:i:s', strtotime($date1)),
'date2' => date('Y-m-d\TH:i:s', strtotime($date2)),
'origin' => $origin,
'originLabel' => $from->getName().', '.$from->getCity().', '.$from->getCountry().' ('.$origin.')',
'destination' => $destination,
'destinationLabel' => $to->getName().', '.$to->getCity().', '.$to->getCountry().' ('.$destination.')',
'sameOrigin' => $sameOrigin,
];
if ($agency->getDomainsecure() == $agency->getDomain() && '443' != $agency->getCustomport()) {
$safeUrl = 'https://'.$agency->getDomain();
} else {
$safeUrl = 'https://'.$agency->getDomainsecure();
}
$cookieLastSearch = $carCookie->searchCarCookie(['car' => base64_encode(json_encode($cookieArray))]);
$availableArrayCar = array_merge($cookieArray, [
'originLocation' => $from->getName(),
'destinationLocation' => $to->getName(),
'cityOriginName' => $from->getCity(),
'cityDestinationName' => $to->getCity(),
]);
$pointRedemption = $em->getRepository(PointRedemption::class)->findPointRedemptionWithAgency($agency);
if (null != $pointRedemption) {
$points = 0;
if ($fullRequest->request->has('pointRedemptionValue')) {
$points = $fullRequest->request->get('pointRedemptionValue');
$session->set('point_redemption_value', $points);
} elseif ($fullRequest->query->has('pointRedeem')) {
$points = $fullRequest->query->get('pointRedeem');
$session->set('point_redemption_value', $points);
} elseif ($session->has('point_redemption_value')) {
$points = $session->get('point_redemption_value');
}
$pointRedemption['Config']['Amount']['CurPoint'] = $points;
}
$agencyFolder = $twigFolder->twigFlux();
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), array_merge($fullRequest->attributes->get('_route_params'), []));
$response = $this->render($twigFolder->twigExists(sprintf('@AviaturTwig/%s/Car/Default/availability.html.twig', $agencyFolder)), [
'ajaxUrl' => $requestUrl,
'safeUrl' => $safeUrl,
'availableArrayCar' => $availableArrayCar,
'cookieLastSearch' => $cookieLastSearch,
'urlDescription' => $urlDescription,
'inlineEngine' => true,
'pointRedemption' => $pointRedemption,
]);
$response->headers->setCookie(new Cookie('_availability_array[car]', base64_encode(json_encode($cookieArray)), (time() + 3600 * 24 * 7), '/'));
} else {
return $this->redirect($errorHandler->errorRedirect('/', 'Error búsqueda autos', sprintf('Una de las ciudades no se pudo encontrar en la base de datos, iatas: %s %s', $origin, $destination)));
}
return $response;
}
}
public function detailPostAction(Request $request, ManagerRegistry $managerRegistry, AviaturLogSave $logSave, AviaturEncoder $aviaturEncoder)
{
$transactionId = null;
$fullRequest = $request;
$request = $fullRequest->request;
//$queryString = $fullRequest->query;
if (true === $request->has('carTransactionID')) {
$transactionId = $request->get('carTransactionID');
if (false !== strpos($transactionId, '||')) {
$explodedTransaction = explode('||', $transactionId);
$transactionId = $explodedTransaction[0];
}
}
$logSave->logSave($transactionId, 'tidDetailCar', 'RS');
if ($request->has('carTransactionID')) {
$info = [];
$variables = ['carSelection', 'carPickUpDateTime', 'carReturnDateTime', 'carPickUpLocation', 'carReturnLocation', 'vehicleCategory', 'carProviderID'];
foreach ($variables as $variable) {
if ($request->has($variable)) {
$info['selection'][$variable] = $request->get($variable);
}
}
$em = $managerRegistry->getManager();
$directRouteFlight = $em->getRepository(DirectRoutesCar::class)->findOneByInfo(json_encode($info));
if (null == $directRouteFlight) {
$url = $aviaturEncoder->aviaturRandomKey();
$directRoutesFlights = new DirectRoutesCar();
$directRoutesFlights->setCreationdate(new \DateTime());
$directRoutesFlights->setInfo(json_encode($info));
$directRoutesFlights->setUrl($url);
$em->persist($directRoutesFlights);
$em->flush();
} else {
$url = $directRouteFlight->getUrl();
}
return $this->redirectToRoute('aviatur_car_detail_specific_secure', ['url' => $url], 307);
} else {
return $this->redirectToRoute('aviatur_car_detail_secure', [], 307);
}
}
public function detailSpecificAction(Request $request, ManagerRegistry $managerRegistry, AviaturErrorHandler $errorHandler, AviaturWebService $webService, $url)
{
$server = $request->server;
$requestParams = $request->request;
$em = $managerRegistry->getManager();
if (true === $requestParams->has('carTransactionID')) {
$transactionIdResponse = $requestParams->get('carTransactionID');
} else {
$transactionIdResponse = $webService->loginService('SERVICIO_MPT', 'dummy|http://www.aviatur.com.co/dummy/');
if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
$errorHandler->errorRedirect('', 'Error MPA', 'No se creo Login!');
return new Response('Estamos experimentando dificultades técnicas en este momento.');
}
}
$directRouteFlight = $em->getRepository(DirectRoutesCar::class)->findOneByUrl($url);
if (null == $directRouteFlight) {
return $this->redirect($errorHandler->errorRedirectNoEmail('/', 'URL no encontrada', 'La URL de detalle no es valida por favor verifique e intente nuevamente'));
}
$infos = json_decode($directRouteFlight->getInfo(), true);
$variables = ['carSelection', 'carPickUpDateTime', 'carReturnDateTime', 'carPickUpLocation', 'carReturnLocation', 'vehicleCategory', 'carProviderID'];
$requestParams->set('carTransactionID', $transactionIdResponse);
$requestParams->set('carSessionID', 'Direct');
foreach ($variables as $variable) {
$requestParams->set($variable, $infos['selection'][$variable]);
}
if (!$server->has('HTTP_REFERER')) {
$server->set('HTTP_REFERER', '/');
}
// Using forward instead of calling method directly to send all the services.
return $this->forward('Aviatur\CarBundle\Controller\DefaultController::detailAction');
}
private function orderResponse($response, $codeProviders)
{
$key = 0;
$options = [];
$blockedVendors = [
// 'AC', 'AD', 'EH', 'AT', 'BV',
// 'CR', 'CI', 'ES', 'EY', 'ET',
// 'EX', 'EM', 'EP', 'IM', 'EZ',
// 'FF', 'FC', 'FX', 'GR', 'HH',
// 'EG', 'MO', 'ZA', 'PC', 'RF',
// 'RH', 'SX', 'HT', 'ZT', 'SV',
// 'UN', 'WF', 'MG'
];
foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $vendor) {
if (!in_array((string) $vendor->Vendor['Code'], $blockedVendors) && isset($vendor->Vendor['Code']) && isset($codeProviders)) {
foreach ($vendor->VehAvails as $VehAvails) {
foreach ($VehAvails->VehAvail as $car) {
$car->Vendor['CompanyShortName'] = $vendor->Vendor['CompanyShortName'];
$car->Vendor['TravelSector'] = $vendor->Vendor['TravelSector'];
$car->Vendor['Code'] = $vendor->Vendor['Code'];
$car->Vendor['RPH'] = $vendor->Info->TPA_Extensions->RPH;
$correlationIdArray = explode('CorrelationID=', (string) $vendor->Notes);
$correlationIdArray = explode(';', $correlationIdArray[1]);
$correlationSegment = $correlationIdArray[0];
$car->Vendor['CorrelationId'] = str_replace(['ProviderId=', ';'], '', $correlationSegment);
$providerIdArray = explode('ProviderId=', (string) $vendor->Notes);
$providerIdArray = explode(';', $providerIdArray[1]);
$providerSegment = $providerIdArray[0];
$car->VehAvailCore->Vehicle->PictureURL = str_replace(['&', '6.JPEG'], ['&', '4.JPEG'], $car->VehAvailCore->Vehicle->PictureURL);
$car->Vendor['Provider'] = str_replace(['ProviderId=', ';'], '', $providerSegment);
$options[$key]['amount'] = (float) $car->VehAvailCore->TotalCharge['RateTotalAmount'];
$options[$key]['xml'] = $car->asXml();
$options[$key]['provider'] = $providerSegment;
++$key;
}
}
}
}
usort($options, fn($a, $b) => $a['amount'] - $b['amount']);
$responseXml = explode('<VehAvail>', str_replace('</VehAvail>', '<VehAvail>', $response->asXml()));
$orderedResponse = $responseXml[0];
foreach ($options as $option) {
$orderedResponse .= $option['xml'];
}
$orderedResponse .= $responseXml[sizeof($responseXml) - 1];
libxml_use_internal_errors(true);
$orderResponse = \simplexml_load_string($orderedResponse);
if (false === $orderResponse) {
$data = ['error' => 'Error', 'message' => 'No se encontraron disponibilidades para las fechas, por favor intente con otras fechas.'];
return $data;
} else {
return $orderResponse;
}
}
public function availabilitySeoAction(Request $request, ManagerRegistry $managerRegistry, SessionInterface $session, RouterInterface $router, $url)
{
$em = $managerRegistry->getManager();
$seoUrl = $em->getRepository(SeoUrl::class)->findOneByUrl('autos/'.$url);
if (null != $seoUrl) {
$maskedUrl = $seoUrl->getMaskedurl();
$session->set('maxResults', $request->query->get('maxResults'));
if (false !== strpos($maskedUrl, '?')) {
$parameters = explode('&', substr($maskedUrl, strpos($maskedUrl, '?') + 1));
foreach ($parameters as $parameter) {
$sessionInfo = explode('=', $parameter);
if (2 == sizeof($sessionInfo)) {
$session->set($sessionInfo[0], $sessionInfo[1]);
}
}
$maskedUrl = substr($maskedUrl, 0, strpos($maskedUrl, '?'));
}
if (null != $seoUrl) {
$route = $router->match($maskedUrl);
$route['_route_params'] = [];
foreach ($route as $param => $val) {
// set route params without defaults
if ('_' !== \substr($param, 0, 1)) {
$route['_route_params'][$param] = $val;
}
}
return $this->forward($route['_controller'], $route);
} else {
throw $this->createNotFoundException('La página que solicitaste no existe o se ha movido permanentemente');
}
} else {
throw $this->createNotFoundException('La página que solicitaste no existe o se ha movido permanentemente');
}
}
/**
* @param Request $request
* @param ManagerRegistry $managerRegistry
* @param TokenStorageInterface $tokenStorage
* @param ParameterBagInterface $parameterBag
* @param LoginManagerInterface $loginManager
* @param TwigFolder $twigFolder
* @param AviaturErrorHandler $errorHandler
* @param CustomerMethodPaymentService $methodPaymentService
* @param AviaturWebService $webService
* @param PayoutExtraService $extraService
*
* @return RedirectResponse|Response
*/
public function detailAction(Request $request, ManagerRegistry $managerRegistry, TokenStorageInterface $tokenStorage, ParameterBagInterface $parameterBag, LoginManagerInterface $loginManager, TwigFolder $twigFolder, AviaturErrorHandler $errorHandler, CustomerMethodPaymentService $methodPaymentService, AviaturWebService $webService, PayoutExtraService $extraService)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$correlationIdSessionName = $parameterBag->get('correlation_id_session_name');
$session = $request->getSession();
$em = $managerRegistry->getManager();
$fullRequest = $request;
$availabilityUrl = $fullRequest->server->get("HTTP_REFERER");
$requestParams = $request->request;
$carFindReferer = $requestParams->get("carFindReferer");
$serverParams = $request->server;
$passangerTypes = [];
$customer = null;
$list = [];
$location = null;
$financialValue = [];
$carsInfo = [];
$response = [];
$agency = $em->getRepository(Agency::class)->find($session->get('agencyId'));
$configsCarAgency = $em->getRepository(ConfigCarAgency::class)->findProviderForCarsWithAgency($agency);
$car_homologate_hertz_codes = json_decode($em->getRepository(Parameter::class)->findOneByName('car_homologate_hertz_codes')->getDescription(), true);
if (true === $requestParams->has('whitemarkDataInfo')) {
$session->set('whitemarkDataInfo', json_decode($requestParams->get('whitemarkDataInfo'), true));
}
if (true === $requestParams->has('userLogin') && '' != $requestParams->get('userLogin') && null != $requestParams->get('userLogin')) {
$user = $em->getRepository(Customer::class)->findOneByEmail($requestParams->get('userLogin'));
$this->authenticateUser($user, $loginManager);
}
if ($configsCarAgency) {
$providers = [];
foreach ($configsCarAgency as $configCarAgency) {
$providers[] = $configCarAgency->getProvider()->getProvideridentifier();
}
} else {
$message = 'no se encontró agencias para consultar disponibilidad.';
$returnUrl = $twigFolder->pathWithLocale('aviatur_general_homepage');
if (true === $requestParams->has('referer') && true === $requestParams->has('http_referer')) {
$returnUrl = $requestParams->get('http_referer');
}
return $this->redirect($errorHandler->errorRedirect($returnUrl, '', $message));
}
$transactionId = $requestParams->get('carTransactionID');
$isFront = $session->has('operatorId');
if ($session->has('typeCoin')) {
$session->set($transactionId.'[typeCoin]', $session->get('typeCoin'));
$session->set($transactionId.'[RateChange]', $session->get('RateChange'));
$session->set($transactionId.'[financialValue]', $session->get('financialValue'));
$session->set($transactionId.'[trmValue]', $session->get('trmValue'));
}
if ($session->has($transactionId.'[car][retry]')) {
$response = \simplexml_load_string($session->get($transactionId.'[car][detail]'));
$typeDocument = $em->getRepository(DocumentType::class)->findAll();
$typeGender = $em->getRepository(Gender::class)->findAll();
$repositoryDocumentType = $managerRegistry->getRepository(DocumentType::class);
$queryDocumentType = $repositoryDocumentType
->createQueryBuilder('p')
->where('p.paymentcode != :paymentcode')
->setParameter('paymentcode', '')
->getQuery();
$documentPaymentType = $queryDocumentType->getResult();
$passangerTypes[1] = [
'ADT' => 1,
'CHD' => 0,
'INF' => 0,
];
$postDataJson = $session->get($transactionId.'[car][detail_data]');
$paymentData = json_decode($postDataJson);
$conditions = $em->getRepository(HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'reservation_conditions_for_hotels');
$first_name = $paymentData->PI->first_name_1_1;
$last_name = $paymentData->PI->last_name_1_1;
$nationality = $em->getRepository(Country::class)->findOneByIatacode($paymentData->PI->nationality_1_1)->getDescription();
if (strpos($first_name, '***') > 0) {
$customer = $em->getRepository(Customer::class)->find($paymentData->BD->id);
$first_name = $customer->getFirstname();
$last_name = $customer->getLastname();
}
$passangerInfo = [
'first_name_1_1' => $first_name,
'last_name_1_1' => $last_name,
'doc_type_1_1' => $paymentData->PI->doc_type_1_1,
'doc_num_1_1' => $paymentData->PI->doc_num_1_1,
'born_date_1_1' => $paymentData->PI->birthday_1_1,
'nationality_1_1_validate' => $nationality,
'phone_1_1' => $customer->getPhone(),
'email_1_1' => $customer->getEmail(),
'person_count_1' => $paymentData->PI->person_count_1,
'passanger_type_1_1' => $paymentData->PI->passanger_type_1_1,
'gender_1_1' => $paymentData->PI->gender_1_1,
'birthday_1_1' => $paymentData->PI->birthday_1_1,
'nationality_1_1' => $paymentData->PI->nationality_1_1,
];
$billingData = [
'doc_type' => $paymentData->BD->doc_type,
'doc_num' => $paymentData->BD->doc_num,
'first_name' => $paymentData->BD->first_name,
'last_name' => $paymentData->BD->last_name,
'email' => $paymentData->BD->email,
'address' => $paymentData->BD->address,
'phone' => $paymentData->BD->phone,
];
$contactData = [
'phone' => $paymentData->CD->phone,
];
$locations = [];
foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Info->LocationDetails as $location) {
$locations[] = $location;
}
foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $VehVendorAvail) {
if ((int) $VehVendorAvail->Info->TPA_Extensions->RPH == explode('-', $paymentData->SD->selection)[0]) {
foreach ($VehVendorAvail->VehAvails as $VehAvails) {
foreach ($VehAvails->VehAvail as $VehAvail) {
if ((int) $VehAvail->VehAvailInfo->TPA_Extensions->RPH == explode('-', $paymentData->SD->selection)[1]) {
$carsInfo[] = $VehVendorAvail;
}
}
}
}
}
/* Se deberían comparar si tienen características básicas completamente iguales, para no permitir que se muestren repetidas */
//$this->reorderCarsInfo($carsInfo);
$carSelection = $paymentData->SD->selection;
$selection = json_decode($session->get($transactionId.'[car][selection]'), true);
$ProviderCarInfo = json_decode($session->get($transactionId.'[car][ProviderCarInfo]'), true);
$vehicleCategory = $session->get($transactionId.'[car][vehicleCategory]');
$list = json_decode($session->get($transactionId.'[car][list]'), true);
if (isset($paymentData->cusPOptSelected)) {
$customerLogin = $tokenStorage->getToken()->getUser();
if (is_object($customerLogin)) {
$paymentsSaved = $methodPaymentService->getMethodsByCustomer($customerLogin, false);
}
}
$paymentOptions = [];
$paymentMethodAgency = $em->getRepository(PaymentMethodAgency::class)->findBy(['agency' => $agency, 'isactive' => 1]);
$paymentMethodsPermitted = ['p2p', 'cybersource', 'world'];
foreach ($paymentMethodAgency as $payMethod) {
$paymentCode = $payMethod->getPaymentMethod()->getCode();
if (!in_array($paymentCode, $paymentOptions) && in_array($paymentCode, $paymentMethodsPermitted)) {
$paymentOptions[] = $paymentCode;
}
}
$banks = [];
if (in_array('pse', $paymentOptions)) {
$banks = $em->getRepository(PseBank::class)->findAll();
}
$cybersource = [];
if (in_array('cybersource', $paymentOptions)) {
$cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource', $paymentOptions)]->getSitecode();
$cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource', $paymentOptions)]->getTrankey();
}
$financialValue = json_decode($session->get('[car][finantial_rate_info]'), true);
$agencyFolder = $twigFolder->twigFlux();
/* Aplicando para vuelo, pero teniendo cuidado con los otros productos */
/* Necesitamos crear un arreglo que tenga todos los rangos de IIN asociados a su franquicia y a sus límites de número de tarjeta */
$iinRecordsArray = $this->getIINRanges($em);
return $this->render($twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Car/Default/detail.html.twig'), [
'payment_doc_type' => $documentPaymentType,
'billingData' => $billingData,
'banks' => $banks,
'finantial_rate' => $financialValue,
'carSelection' => $carSelection,
'cybersource' => $cybersource,
'cards' => $em->getRepository(Card::class)->findBy(['isactive' => 1]),
'inactiveCards' => $em->getRepository(Card::class)->findBy(['isactive' => 0]),
'contactData' => $contactData,
'paymentOptions' => $paymentOptions,
'baloto' => in_array('baloto', $paymentOptions) ? true : false,
'pse' => in_array('pse', $paymentOptions) ? true : false,
'safety' => in_array('safety', $paymentOptions) ? true : false,
'passanger_data' => $passangerInfo,
'twig_readonly' => true,
'doc_type' => $typeDocument,
'gender' => $typeGender,
'services' => $passangerTypes,
'conditions' => $conditions,
'transactionId' => base64_encode($transactionId),
'CriteoTags' => null,
'passengers' => $passangerInfo,
'pickUpLocation' => $locations[0],
'vendorPref' => $selection[0],
'vehicleCategory' => $vehicleCategory,
'returnLocation' => end($locations),
'serviceResponse' => $response->Message->OTA_VehAvailRateRS,
'carsInfo' => $carsInfo,
'carsItems' => (null != $ProviderCarInfo) ? $ProviderCarInfo : null,
'carDescription' => $list,
'payment_type_form_name' => $session->get($transactionId . '[car][paymentType]'),
'payment_form' => $session->get($transactionId . '[car][payment_car_form]'),
'referer' => $availabilityUrl,
'total_amount' => $session->get($transactionId . '[car][total_amount]'),
'currency_code' => $session->get($transactionId . '[car][currency]'),
'total_amount_local' => $session->get($transactionId . '[car][total_amount_local]'),
'currency_code_local' => $session->get($transactionId . '[car][currency_code_local]'),
'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
'car_homologate_hertz_codes' => $car_homologate_hertz_codes,
'ccranges' => $iinRecordsArray["ccranges"],
'ccfranchises' => $iinRecordsArray["ccfranchises"],
]);
} else {
if (true === $requestParams->has('referer')) {
$session->set($transactionId.'[availability_url]', $requestParams->get('http_referer'));
$session->set($transactionId.'[referer]', $requestParams->get('referer'));
} elseif (true !== $session->has($transactionId.'[availability_url]')) {
$session->set($transactionId.'[availability_url]', $serverParams->get('HTTP_REFERER'));
}
$autoModel = new CarModel();
$xmlRequestAvail = $autoModel->getXmlDetail();
$pickUpDate = $requestParams->get('carPickUpDateTime');
$returnDate = $requestParams->get('carReturnDateTime');
$pickUpLocation = $requestParams->get('carPickUpLocation');
$returnLocation = $requestParams->get('carReturnLocation');
$selection = explode('-', $requestParams->get('carSelection'));
$vehicleCategory = $requestParams->get('vehicleCategory');
$provider = $em->getRepository(Provider::class)->findOneByProvideridentifier($requestParams->get('carProviderID'));
$ProviderCarInfo = $em->getRepository(ProviderCarCode::class)->findOneBy(['codeProviderCar' => $selection[0], 'isActive' => 1]);
if (!$ProviderCarInfo) {
$message = 'Ha ocurrido un error inesperado del proveedor';
$returnUrl = $twigFolder->pathWithLocale('aviatur_general_homepage');
return $this->redirect($errorHandler->errorRedirect($returnUrl, '', $message));
}
$session->set($transactionId.'[car][selection]', json_encode($selection));
$session->set($transactionId.'[car][vehicleCategory]', $vehicleCategory);
$session->set($transactionId.'[car][ProviderCarInfo]', $ProviderCarInfo->getInfo());
$variable = [
'pickUpDate' => date('Y-m-d\TH:i:s', strtotime($pickUpDate)),
'returnDate' => date('Y-m-d\TH:i:s', strtotime($returnDate)),
'pickUpLocation' => $pickUpLocation,
'returnLocation' => $returnLocation,
'vendorPref' => $selection[0],
'ProviderId' => $provider->getProvideridentifier(),
'transactionId' => $transactionId,
'ProviderXml' => $autoModel->providers($ProviderCarInfo->getInfo(), $selection[0]),
'vehicleCategory' => $vehicleCategory,
];
$responseTemp = $webService->callWebServiceAmadeus('SERVICIO_MPT', 'VehAvailRate', 'dummy|http://www.aviatur.com.co/dummy/', $xmlRequestAvail, $variable, false, $transactionId);
if (!isset($responseTemp['error'])) {
$response = \simplexml_load_string(str_replace('4.JPEG', '9.JPEG', $responseTemp->asXml()));
$session->set($transactionId.'[car][provider]', $provider->getProvideridentifier());
$session->set($transactionId.'[car][detail]', $response->asXML());
$session->set($transactionId.'[car][detail_time]', time());
$session->set($transactionIdSessionName, $transactionId);
$session->set('[referer]', $serverParams->get('HTTP_REFERER'));
if (!isset($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail) || !isset($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Notes)) {
$message = $response['error'] ?? 'Ha ocurrido un error inesperado en el servicio';
$returnUrl = $twigFolder->pathWithLocale('aviatur_general_homepage');
if (true === $requestParams->has('referer') && true === $requestParams->has('http_referer')) {
$returnUrl = $requestParams->get('http_referer');
}
return $this->redirect($errorHandler->errorRedirect($returnUrl, '', $message));
}
$twigVariables = [];
$correlationId = (string) explode('=', explode(';', $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Notes)[0])[1];
$session->set($transactionId.'[car]['.$correlationIdSessionName.']', $correlationId);
$typeDocument = $em->getRepository(DocumentType::class)->findAll();
$typeGender = $em->getRepository(Gender::class)->findAll();
$repositoryDocumentType = $managerRegistry->getRepository(DocumentType::class);
$queryDocumentType = $repositoryDocumentType
->createQueryBuilder('p')
->where('p.paymentcode != :paymentcode')
->setParameter('paymentcode', '')
->getQuery();
$documentPaymentType = $queryDocumentType->getResult();
$paymentMethodAgency = $em->getRepository(PaymentMethodAgency::class)->findBy(['agency' => $agency, 'isactive' => 1]);
$paymentOptions = [];
$paymentMethodsPermitted = ['p2p', 'cybersource', 'world'];
foreach ($paymentMethodAgency as $payMethod) {
$paymentCode = $payMethod->getPaymentMethod()->getCode();
if (!in_array($paymentCode, $paymentOptions) && in_array($paymentCode, $paymentMethodsPermitted)) {
$paymentOptions[] = $paymentCode;
}
}
$banks = [];
if (in_array('pse', $paymentOptions)) {
$banks = $em->getRepository(PseBank::class)->findAll();
}
$cybersource = [];
if (in_array('cybersource', $paymentOptions)) {
$cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource', $paymentOptions)]->getSitecode();
$cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource', $paymentOptions)]->getTrankey();
}
$twigVariables += [
'cards' => $em->getRepository(Card::class)->findAll(),
'paymentOptions' => $paymentOptions,
'banks' => $banks,
'cybersource' => $cybersource,
];
$paymentType = 'paymentForm';
$session->set($transactionId.'[car][paymentType]', $paymentType);
$passangerTypes[1] = [
'ADT' => 1,
'CHD' => 0,
'INF' => 0,
];
$conditions = $em->getRepository(HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'reservation_conditions_for_hotels');
$agencyFolder = $twigFolder->twigFlux();
$list[0] = ['M' => 'Mini', 'N' => 'Mini Élite', 'E' => 'Económico', 'H' => 'Económico Élite', 'C' => 'Compacto', 'D' => 'Compacto Élite', 'I' => 'Intermedio', 'J' => 'Intermedio Élite', 'S' => 'Estándar', 'R' => 'Estándar Élite', 'F' => 'Fullsize', 'G' => 'Fullsize Elite', 'P' => 'Premium', 'U' => 'Premium Élite', 'L' => 'Lujoso', 'W' => 'Lujoso Élite', 'O' => 'Oversize', 'X' => 'Especial'];
$list[1] = ['B' => '2-3 Puertas', 'C' => '2/4 Puertas', 'D' => '4-5 Puertas', 'W' => 'Vagón', 'V' => 'Van de pasajeros', 'L' => 'Limosina', 'S' => 'Deportivo', 'T' => 'Convertible', 'F' => 'SUV', 'J' => 'Todo Terreno', 'X' => 'Especial', 'P' => 'Pick up de Cabina Regular', 'Q' => 'Pick up de Cabina Extendida', 'Z' => 'Auto de Oferta Especial', 'E' => 'Coupe', 'M' => 'Minivan', 'R' => 'Vehículo recreacional', 'H' => 'Casa rodante', 'Y' => 'Vehículo de dos ruedas', 'N' => 'Roasted', 'G' => 'Crossover', 'K' => 'Van comercial / Camión'];
$list[2] = ['M' => 'Transmisión Manual, Tracción sin especificar', 'N' => 'Transmisión Manual, Tracción 4WD', 'C' => 'Transmisión Manual, Tracción AWD', 'A' => 'Transmisión Automática, Tracción sin especificar', 'B' => 'Transmisión Automática, Tracción 4WD', 'D' => 'Transmisión Automática, Tracción AWD'];
$list[3] = ['R' => 'Combustible no especificado, con aire acondicionado', 'N' => 'Combustible no especificado, sin aire acondicionado', 'D' => 'Diesel, con aire acondicionado', 'Q' => 'Diesel, sin aire acondicionado', 'H' => 'Híbrido, con aire acondicionado', 'I' => 'Híbrido, sin aire acondicionado', 'E' => 'Eléctrico, con aire acondicionado', 'C' => 'Eléctrico, sin aire acondicionado', 'L' => 'Gas comprimido, con aire acondicionado', 'S' => 'Gas comprimido, sin aire acondicionado', 'A' => 'Hidrógeno, con aire acondicionado', 'B' => 'Hidrógeno, sin aire acondicionado', 'M' => 'Multi combustible, con aire acondicionado', 'F' => 'Multi combustible, sin aire acondicionado', 'V' => 'Gasolina, con aire acondicionado', 'Z' => 'Gasolina, sin aire acondicionado', 'U' => 'Etanol, con aire acondicionado', 'X' => 'Etanol, sin aire acondicionado'];
$session->set($transactionId.'[car][list]', json_encode($list));
$locations = [];
foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Info->LocationDetails as $location) {
$locations[] = $location;
}
$session->set($transactionId.'[car][locations]', json_encode($locations));
$isNational = true;
if ('CO' != $location->Address->CountryName) {
$isNational = false;
}
$args = (object)[
'passangerTypes' => $passangerTypes,
'isNational' => $isNational,
];
$payoutExtras = null;
if (!$isFront) {
$payoutExtras = $extraService->loadPayoutExtras($agency, $transactionId, 'Car', $args);
}
$pointRedemption = $em->getRepository(PointRedemption::class)->findPointRedemptionWithAgency($agency);
if (null != $pointRedemption) {
$points = 0;
if ($requestParams->has('pointRedemptionValue')) {
$points = $requestParams->get('pointRedemptionValue');
$session->set('point_redemption_value', $points);
} elseif ($requestParams->has('pointRedeem')) {
$points = $requestParams->get('pointRedeem');
$session->set('point_redemption_value', $points);
} elseif ($session->has('point_redemption_value')) {
$points = $session->get('point_redemption_value');
}
$pointRedemption['Config']['Amount']['CurPoint'] = $points;
}
foreach ($response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $key => $VehVendorAvail) {
$carsInfo[] = $VehVendorAvail;
}
/* Se deberían comparar si tienen características básicas completamente iguales, para no permitir que se muestren repetidas */
//$this->reorderCarsInfo($carsInfo);
$financialValue = $this->getCurrencyExchange($webService);
$session->set('[car][finantial_rate_info]', json_encode($financialValue));
$session->set($transactionId.'[car][carsInfo]', json_encode($carsInfo));
$prueba = $session->get($transactionId.'[availability_url]');
$twigVariables += [
'payment_doc_type' => $documentPaymentType,
'twig_readonly' => false,
'finantial_rate' => $financialValue,
'doc_type' => $typeDocument,
'gender' => $typeGender,
'services' => $passangerTypes,
'conditions' => $conditions,
'transactionId' => base64_encode($transactionId),
'CriteoTags' => null,
'passanger_data' => [],
'pickUpLocation' => $locations[0],
'vendorPref' => $selection[0],
'vehicleCategory' => $vehicleCategory,
'returnLocation' => end($locations),
'serviceResponse' => $response->Message->OTA_VehAvailRateRS,
'carsInfo' => $carsInfo,
'carsItems' => json_decode($ProviderCarInfo->getInfo(), true),
'carDescription' => $list,
'payment_type_form_name' => $paymentType,
//'referer' => $serverParams->get('HTTP_REFERER'),
'referer' => $availabilityUrl,
'total_amount' => (string) $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
'currency_code' => (string) $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['CurrencyCode'],
'total_amount_local' => (string) $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TPA_Extensions->LocalRate['RateTotalAmount'],
'currency_code_local' => (string) $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TPA_Extensions->LocalRate['CurrencyCode'],
'car_homologate_hertz_codes' => $car_homologate_hertz_codes,
'payoutExtras' => $payoutExtras,
'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
'pointRedemption' => $pointRedemption,
];
$twigVariables['baloto'] ?? ($twigVariables['baloto'] = false);
$twigVariables['pse'] ?? ($twigVariables['pse'] = true);
$twigVariables['safety'] ?? ($twigVariables['safety'] = true);
/* Aplicando para vuelo, pero teniendo cuidado con los otros productos */
/* Necesitamos crear un arreglo que tenga todos los rangos de IIN asociados a su franquicia y a sus límites de número de tarjeta */
$iinRecordsArray = $this->getIINRanges($em);
$twigVariables["ccranges"] = $iinRecordsArray["ccranges"];
$twigVariables["ccfranchises"] = $iinRecordsArray["ccfranchises"];
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/detail.html.twig'), $twigVariables);
} else {
$message = $response['error'] ?? 'Ha ocurrido un error inesperado';
$returnUrl = $twigFolder->pathWithLocale('aviatur_general_homepage');
if (true === $requestParams->has('referer') && true === $requestParams->has('http_referer')) {
$returnUrl = $requestParams->get('http_referer');
}
return $this->redirect($errorHandler->errorRedirect($returnUrl, '', $message));
}
}
}
public function prePaymentStep1Action(Request $request, ManagerRegistry $managerRegistry, TokenStorageInterface $tokenStorage, ParameterBagInterface $parameterBag, AviaturEncoder $aviaturEncoder, CustomerMethodPaymentService $methodPaymentService, TokenizerService $tokenizerService, AviaturErrorHandler $errorHandler, TwigFolder $twigFolder)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$session = $request->getSession();
if ($request->isXmlHttpRequest()) {
$request = $request->request;
$transactionId = $session->get($transactionIdSessionName);
$billingData = $request->get('BD');
$em = $managerRegistry->getManager();
$postData = $request->all();
$publicKey = $aviaturEncoder->aviaturRandomKey();
if (isset($postData['PD']['card_num'])) {
$postDataInfo = $postData;
if (isset($postDataInfo['PD']['cusPOptSelected'])) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $methodPaymentService->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'] = $tokenizerService->getToken($postData['PD']['card_num']);
}
$postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
}
$encodedInfo = $aviaturEncoder->AviaturEncode(json_encode($postDataInfo ?? $postData), $publicKey);
$formUserInfo = new FormUserInfo();
$formUserInfo->setInfo($encodedInfo);
$formUserInfo->setPublicKey($publicKey);
$em->persist($formUserInfo);
$em->flush();
$session->set($transactionId.'[car][user_info]', $formUserInfo->getId());
if (true !== $session->has($transactionId.'[car][order]')) {
if (true === $session->has($transactionId.'[car][detail]')) {
$session->set($transactionId.'[car][detail_data]', 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(NameWhitelist::class)->findLikeWhitelist($passangerNames);
if (0 == sizeof($nameWhitelist)) {
$nameBlacklist = $em->getRepository(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(Customer::class)->find($billingData['id']);
$ordersProduct = $em->getRepository(OrderProduct::class)->getOrderProductsPending($customer);
}
if (null == $ordersProduct) {
$session->set($transactionId.'[car][retry]', $aviaturPaymentRetryTimes);
$ajaxUrl = $this->generateUrl('aviatur_car_prepayment_step_2_secure');
return $this->json(['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' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo 1')]);
}
} else {
$paymentData = $request->get('PD');
$paymentData = json_decode(json_encode($paymentData));
$json = json_decode($session->get($transactionId.'[car][order]'));
if (!is_null($json)) {
$json->ajax_url = $this->generateUrl('aviatur_car_prepayment_step_2_secure');
// reemplazar datos de pago por los nuevos.
$oldPostData = json_decode($session->get($transactionId.'[car][detail_data]'));
if (isset($paymentData->cusPOptSelected) || isset($paymentData->card_num)) {
if (isset($paymentData->cusPOptSelected)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $methodPaymentService->getMethodsByCustomer($customerLogin, true);
$card_num_token = $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
} else {
$card_num_token = $tokenizerService->getToken($paymentData->card_num);
}
$card_values = ['card_num_token' => $card_num_token, 'card_num' => $paymentData->card_num];
}
unset($oldPostData->PD);
$oldPostData->PD = $paymentData;
if (isset($card_num_token)) {
$oldPostData->PD->card_values = $card_values;
}
$session->set($transactionId.'[car][detail_data]', 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' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos datos de tu orden, por favor inténtalo nuevamente')]);
}
}
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado'));
}
}
public function prePaymentStep2Action(Request $request, ManagerRegistry $managerRegistry, ParameterBagInterface $parameterBag, AviaturErrorHandler $errorHandler, OrderController $orderController, TwigFolder $twigFolder)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$currency_code_local = null;
$total_amount = null;
$total_amount_local = null;
$currency = null;
$pickUpLocationCode = null;
$returnLocationCode = null;
$pickUpDate = null;
$returnDate = null;
$order = [];
$session = $request->getSession();
if ($request->isXmlHttpRequest()) {
$fullRequest = $request;
$request = $request->request;
$em = $managerRegistry->getManager();
$agency = $em->getRepository(Agency::class)->find($session->get('agencyId'));
$billingData = $request->get('BD');
$transactionId = $session->get($transactionIdSessionName);
$session->set($transactionId.'[car][prepayment_check]', true);
$postData = json_decode($session->get($transactionId.'[car][detail_data]'));
$detailInfo = \simplexml_load_string($session->get($transactionId.'[car][detail]'));
$selection = json_decode($session->get($transactionId.'[car][selection]'));
$car_homologate_hertz_codes = json_decode($em->getRepository(Parameter::class)->findOneByName('car_homologate_hertz_codes')->getDescription(), true);
$PaymentForm = 0;
$error = true;
foreach ($detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $VehVendorAvail) {
$pickUpLocationCode = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'];
$returnLocationCode = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'];
$pickUpDate = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['PickUpDateTime'];
$returnDate = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['ReturnDateTime'];
if ((int) $VehVendorAvail->Info->TPA_Extensions->RPH == (int) explode('-', $postData->SD->selection)[0]) {
foreach ($VehVendorAvail->VehAvails as $VehAvails) {
foreach ($VehAvails->VehAvail as $VehAvail) {
if ((int) $VehAvail->VehAvailInfo->TPA_Extensions->RPH == (int) explode('-', $postData->SD->selection)[1]) {
$error = false;
$total_amount = number_format((float) $VehAvail->VehAvailCore->RentalRate->VehicleCharges->VehicleCharge['Amount'], 0, '', '');
$currency = (string) $VehAvail->VehAvailCore->RentalRate->VehicleCharges->VehicleCharge['CurrencyCode'];
$total_amount_local = (float) $VehAvail->VehAvailCore->TPA_Extensions->LocalRate['RateTotalAmount'];
$currency_code_local = (string) $VehAvail->VehAvailCore->TPA_Extensions->LocalRate['CurrencyCode'];
$discountNumbers = $VehAvail->VehAvailCore->TPA_Extensions->discountNumbers;
if (isset($VehAvail->VehAvailCore->TPA_Extensions->LocalRate['ExtraAmount'])) {
$extra_amount = (float) $VehAvail->VehAvailCore->RentalRate->TotalCharge['ExtraAmount'];
$extra_amount_local = (float) $VehAvail->VehAvailCore->TPA_Extensions->LocalRate['ExtraAmount'];
}
}
}
}
}
}
if ($error) {
return $this->json(['error' => 'fatal', 'message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo 3')]);
}
$ProviderCarInfo = $em->getRepository(ProviderCarCode::class)->findOneBy(['codeProviderCar' => $postData->selectionVendor, 'isActive' => 1]);
if (!$ProviderCarInfo) {
$message = 'Ha ocurrido un error inesperado del proveedor';
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), '', $message));
}
$PaymentComission = json_decode($ProviderCarInfo->getPaymentComission(), true)[0]['comision'];
foreach (json_decode($ProviderCarInfo->getInfo(), true) as $providerCar) {
foreach ($discountNumbers->customerReferenceInfo as $discount) {
$referenceNumber = rtrim((string) $discount->referenceNumber);
if (isset($car_homologate_hertz_codes[$referenceNumber]) && 1 == $car_homologate_hertz_codes[$referenceNumber]['status']) {
$referenceNumber = $car_homologate_hertz_codes[$referenceNumber]['homologate'];
}
if ($referenceNumber == rtrim($providerCar['number']) && 1 == $providerCar['isActive']) {
$PaymentForm = (int) $providerCar['payment'];
}
}
}
if (2 == $PaymentForm) {
if (isset($postData->selectionMethod)) {
if (1 == (int) $postData->selectionMethod) {
$PaymentForm = (int) 1;
$comission = $PaymentComission['online'];
$typeRes = 'online';
} else {
$PaymentForm = (int) 0;
$comission = $PaymentComission['offline'];
$typeRes = 'offline';
}
} else {
$PaymentForm = (int) 0;
$comission = $PaymentComission['offline'];
$typeRes = 'offline';
}
} elseif (1 == $PaymentForm) {
$comission = $PaymentComission['online'];
$typeRes = 'online';
} else {
$comission = $PaymentComission['offline'];
$typeRes = 'offline';
}
$rateInfo = json_decode($session->get('[car][finantial_rate_info]'), true);
if (isset($rateInfo[$currency_code_local])) {
$finantial_rate = ('COP' == $currency_code_local || empty($currency_code_local)) ? 1 : $rateInfo[$currency_code_local];
$exchangeValues = [
'MONEDA_ORIGEN' => (string) $currency_code_local,
'TIPO_TASA_CAMBIO' => (string) $rateInfo[$currency_code_local],
];
$session->set('[car][finantial_rate]', $finantial_rate);
$session->set($transactionId.'[car][exchangeValues]', json_encode($exchangeValues));
} elseif ($currency_code_local === 'COP') {
$finantial_rate = 1;
$exchangeValues = [
'MONEDA_ORIGEN' => (string) $currency_code_local,
'TIPO_TASA_CAMBIO' => '1',
];
$session->set('[car][finantial_rate]', $finantial_rate);
$session->set($transactionId.'[car][exchangeValues]', json_encode($exchangeValues));
} else {
return $this->json(['error' => 'fatal', 'message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'Error en la conversión, vuelva a intentarlo')]);
}
// if (isset(json_decode($session->get('[car][finantial_rate_info]'), true)[$currency_code_local])) {
// $finantial_rate = ('COP' == $currency_code_local || empty($currency_code_local)) ? 1 : json_decode($session->get('[car][finantial_rate_info]'), true)[$currency_code_local];
// $exchangeValues = [
// 'MONEDA_ORIGEN' => (string) $currency_code_local,
// 'TIPO_TASA_CAMBIO' => (string) json_decode($session->get('[car][finantial_rate_info]'), true)[$currency_code_local],
// ];
// $session->set('[car][finantial_rate]', $finantial_rate);
// $session->set($transactionId.'[car][exchangeValues]', json_encode($exchangeValues));
// } else {
// return $this->json(['error' => 'fatal', 'message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'Error en la conversi�n, vuelta a intentarlo')]);
// }
if ('COP' == $currency_code_local || empty($currency_code_local)) {
if (0 == $PaymentForm && isset($extra_amount)) {
$total_amount = $total_amount + $extra_amount;
}
$total_amount = ($total_amount * $finantial_rate);
} else {
if (0 == $PaymentForm && isset($extra_amount_local)) {
$total_amount_local = $total_amount_local + $extra_amount_local;
}
$total_amount = ($total_amount_local * $finantial_rate);
}
$session->set($transactionId.'[car][payment_type_res]', $typeRes);
$session->set($transactionId.'[car][payment_car_form]', $PaymentForm);
$session->set($transactionId.'[car][payment_comission]', $comission);
$session->set($transactionId.'[car][total_amount]', $total_amount);
$session->set($transactionId.'[car][currency]', $currency);
$session->set($transactionId.'[car][total_amount_local]', $total_amount_local);
$session->set($transactionId.'[car][currency_code_local]', $currency_code_local);
$session->set($transactionId.'[car][providerCarInfo]', $ProviderCarInfo->getInfo());
$session->set($transactionId.'[car][pickUpLocationCode]', $pickUpLocationCode);
$session->set($transactionId.'[car][returnLocationCode]', $returnLocationCode);
$session->set($transactionId.'[car][pickUpDate]', $pickUpDate);
$session->set($transactionId.'[car][returnDate]', $returnDate);
$pickUpLocationCode = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'];
$returnLocationCode = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'];
$pickUpDate = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['PickUpDateTime'];
$returnDate = (string) $detailInfo->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['ReturnDateTime'];
if (true !== $session->has($transactionId.'[car][order]')) {
if (true === $session->has($transactionId.'[car][detail]')) {
if (isset($agency)) {
$session->set($transactionIdSessionName, $transactionId);
$customerData = $em->getRepository(Customer::class)->find($billingData['id']);
$isFront = $session->has('operatorId');
if ($isFront) {
$customer = $billingData;
$customer['isFront'] = true;
$status = 'B2T';
} else {
$customer = $customerData;
$status = 'waiting';
}
$productType = $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findByCode('CAR');
$orderIdentifier = '{order_product_num}';
$order = $orderController->createAction($agency, $customer, $productType, $orderIdentifier, $status);
$orderId = str_replace('ON', '', $order['order']);
$orderEntity = $em->getRepository(Order::class)->find($orderId);
$formUserInfo = $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[car][user_info]'));
$formUserInfo->setOrder($orderEntity);
$em->persist($formUserInfo);
$em->flush();
if ($isFront) {
$order['url'] = $this->generateUrl('aviatur_car_payment_secure');
} else {
$order['url'] = $this->generateUrl('aviatur_car_payment_secure');
}
return $this->json($order);
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró la agencia con el dominio: '.$fullRequest->getHost()));
}
} else {
return $this->json(['error' => 'fatal', 'message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo 2')]);
}
} else {
$order['url'] = $this->generateUrl('aviatur_car_payment_secure');
return $this->json($order);
}
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado'));
}
}
public function paymentAction(Request $request, ManagerRegistry $managerRegistry, RouterInterface $router, ParameterBagInterface $parameterBag, PayoutExtraService $extraService, AviaturCarService $carService, P2PController $p2PController, WorldPayController $worldPayController, AviaturErrorHandler $errorHandler, TwigFolder $twigFolder, PSEController $PSEController, SafetypayController $safetypayController, \Swift_Mailer $mailer, CashController $cashController, OrderController $orderController, ExceptionLog $logSave,TokenizerService $tokenizerService,CustomerMethodPaymentService $methodPaymentService, AviaturLogSave $aviaturlogSave)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$emailNotification = $parameterBag->get('email_notification');
$orderProduct = [];
$paymentResponse = null;
$return = null;
//$safetyData = null;
$safetyData = new \stdClass();
$array = [];
$emissionData = [];
$em = $managerRegistry->getManager();
$session = $request->getSession();
$transactionId = $session->get($transactionIdSessionName);
$postData = json_decode($session->get($transactionId.'[car][detail_data]'));
$orderInfo = json_decode($session->get($transactionId.'[car][order]'));
$response = $session->get($transactionId.'[car][detail]');
$domain = $request->getHost();
$data = json_decode($session->get($domain.'[parameters]'), true);
$aviaturPaymentIva = (float) $data['aviatur_payment_iva'];
$payoutExtrasValues = null;
$PaymentForm = $session->get($transactionId.'[car][payment_car_form]');
$amount = $session->get($transactionId.'[car][total_amount]');
$currency = $session->get($transactionId.'[car][currency]');
$xml = simplexml_load_string((string) $response)->Message->OTA_VehAvailRateRS;
if (isset($postData->payoutExtrasSelection)) {
$payoutExtrasValues = $extraService->getPayoutExtrasValues($postData->payoutExtrasSelection, $transactionId);
}
if (0 == $PaymentForm || $session->has('operatorId')) {
$orderProductId = str_replace('PN', '', $orderInfo->products);
$orderProduct[] = $em->getRepository(OrderProduct::class)->find($orderProductId);
$carService->carReservation($orderProduct[0], true, true);
return $this->redirect($this->generateUrl('aviatur_car_confirmation_secure'));
} elseif (1 == $PaymentForm) {
$retryCount = (int) $session->get($transactionId.'[car][retry]');
if ($retryCount > 0) {
//$paymentData = json_decode($session->get($transactionId.'[car][detail_data]'));
$pickUpLocationCode = (string) $xml->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'];
$returnLocationCode = (string) $xml->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'];
$pickUpDate = (string) $xml->VehAvailRSCore->VehRentalCore['PickUpDateTime'];
$returnDate = (string) $xml->VehAvailRSCore->VehRentalCore['ReturnDateTime'];
$description = 'Autos - '.$pickUpLocationCode.' ('.date('d/m/Y', strtotime($pickUpDate)).') '.$returnLocationCode.' ('.date('d/m/Y', strtotime($returnDate)).') - ' /* . $idContext */;
$orderProductCode = $session->get($transactionId.'[car][order]');
$orderProduct = null;
if (isset($orderProductCode) && isset(json_decode($orderProductCode)->products)) {
$orderProductId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct[] = $em->getRepository(OrderProduct::class)->find($orderProductId);
$paymentData = $postData->PD;
$customer = $em->getRepository(Customer::class)->find($postData->BD->id);
$carService->carReservation($orderProduct[0], true, false);
if ('p2p' == $paymentData->type || 'world' == $paymentData->type) {
$array = [
'x_currency_code' => (string) $currency,
'x_amount' => round(number_format($amount, 2, '.', '')),
'x_tax' => number_format($amount * $aviaturPaymentIva, 2, '.', ''),
'x_amount_base' => number_format($amount * (1 - $aviaturPaymentIva), 2, '.', ''),
'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
'x_first_name' => $customer->getFirstname(),
'x_last_name' => $customer->getLastname(),
'x_description' => $description,
'x_city' => $customer->getCity()->getIatacode(),
'x_country_id' => $customer->getCountry()->getIatacode(),
'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' => 'car',
'x_cantidad' => $postData->PI->person_count_1,
'administrative_base' => 0,
'administrative_amount_tax' => 0,
'admin_amount' => 0,
'franchise' => $paymentData->franquise,
'worldpay_validate' => true,
];
if (isset($paymentData->card_values)) {
$array['card_values'] = (array) $paymentData->card_values;
}
if ('p2p' == $paymentData->type) {
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;
}
}
}
if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
foreach ($payoutExtrasValues as $payoutExtraValues) {
$array['x_amount'] += round((float) $payoutExtraValues->values->fare->total);
$array['x_tax'] += round((float) $payoutExtraValues->values->fare->tax);
$array['x_amount_base'] += round((float) $payoutExtraValues->values->fare->base);
}
}
$payoutExtrasValues = $extraService->setPayoutExtrasAsProcessed($transactionId);
if ('p2p' == $paymentData->type) {
$paymentResponse = $p2PController->placetopayAction($parameterBag,$tokenizerService,$methodPaymentService,$mailer,$aviaturlogSave, $array);
$return = $this->redirect($this->generateUrl('aviatur_car_payment_p2p_return_url_secure', [], true));
} elseif ('world' == $paymentData->type) {
$array['city'] = $customer->getCity()->getIatacode();
$array['countryCode'] = $customer->getCity()->getCountry()->getIatacode();
$paymentResponse = $worldPayController->worldAction($request, $mailer, $aviaturlogSave, $methodPaymentService, $parameterBag, $array);
$return = $this->redirect($this->generateUrl('aviatur_car_payment_world_return_url_secure', [], true));
}
unset($array['x_client_id']);
if (null != $paymentResponse) {
return $return;
} else {
$orderProduct[0]->setStatus('pending');
$em->persist($orderProduct[0]);
$em->flush();
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), '', 'No hay respuesta por parte del servicio de pago, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción'));
}
} elseif ('pse' == $paymentData->type) {
$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' => $description,
'x_currency' => (string) $currency,
'x_total_amount' => number_format($amount, 2, '.', ''),
'x_tax_amount' => number_format($amount * $aviaturPaymentIva, 2, '.', ''),
'x_devolution_base' => number_format($amount * (1 - $aviaturPaymentIva), 2, '.', ''),
'x_tax' => number_format(round((float) (0)), 2, '.', ''),
'x_tip_amount' => number_format(round((float) (0)), 2, '.', ''),
'x_cantidad' => $postData->PI->person_count_1,
'product_type' => 'car',
];
if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
foreach ($payoutExtrasValues as $payoutExtraValues) {
$array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
$array['x_tax_amount'] += round((float) $payoutExtraValues->values->fare->tax);
$array['x_devolution_base'] += round((float) $payoutExtraValues->values->fare->base);
}
}
$payoutExtrasValues = $extraService->setPayoutExtrasAsProcessed($transactionId);
$paymentResponse = $PSEController->sendPaymentAction($request, $session, $router, $parameterBag, $mailer, $orderController, $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_car_retry_secure'), '');
default:
return $this->redirect($this->generateUrl('aviatur_car_retry_secure'), '');
}
} else {
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), 'Error al procesar el pago', 'Ocurrió un problema al intentar crear tu 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_description' => $description,
'x_currency' => $currency,
'x_total_amount' => number_format($amount, 2, '.', ''),
'x_tax_amount' => number_format($amount * $aviaturPaymentIva, 2, '.', ''),
'x_devolution_base' => number_format($amount * (1 - $aviaturPaymentIva), 2, '.', ''),
'x_tip_amount' => number_format(round(0), 2, '.', ''),
'x_payment_data' => $paymentData->type,
'x_type_description' => 'car',
'x_cantidad' => $postData->PI->person_count_1,
];
if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
foreach ($payoutExtrasValues as $payoutExtraValues) {
$array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
$array['x_tax_amount'] += round((float) $payoutExtraValues->values->fare->tax);
$array['x_devolution_base'] += round((float) $payoutExtraValues->values->fare->base);
}
}
$payoutExtrasValues = $extraService->setPayoutExtrasAsProcessed($transactionId);
$parametMerchant = [
'MerchantSalesID' => $array['x_reference'],
'Amount' => $array['x_total_amount'],
'transactionUrl' => $transactionUrl,
'dataTrans' => $array,
];
$safeTyPay = $safetypayController->safetyAction($router, $parameterBag, $mailer, $parametMerchant, $array);
if ('ok' == $safeTyPay['status']) {
return $this->redirect($safeTyPay['response']);
} else {
$safetyData->x_booking = $array['x_booking'];
$safetyData->x_first_name = $array['x_first_name'];
$safetyData->x_last_name = $array['x_last_name'];
$safetyData->x_doc_num = $array['x_doc_num'];
$safetyData->x_reference = $array['x_reference'];
$safetyData->x_description = $array['x_description'];
$safetyData->x_total_amount = $array['x_total_amount'];
$safetyData->x_email = $array['x_email'];
$safetyData->x_address = $array['x_address'];
$safetyData->x_phone = $array['x_phone'];
$safetyData->x_type_description = $array['x_type_description'];
$safetyData->x_resultSafetyPay = $safeTyPay;
$mailInfo = print_r($safetyData, 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 Car'.$safetyData->x_reference)
->setBody($mailInfo);
$mailer->send($message);
return $this->redirect($this->generateUrl('aviatur_Car_payment_rejected_secure'));
}
} elseif ('cash' == $paymentData->type) {
$agency = $em->getRepository(Agency::class)->find($session->get('agencyId'));
$agencyName = $agency->getOfficeId();
$orderInfo = json_decode($session->get($transactionId.'[car][order]'));
$array['x_officeId'] = $agencyName;
$array['x_doc_num'] = $customer->getDocumentnumber();
$array['x_doc_type'] = $customer->getDocumentType()->getPaymentcode();
$array['x_first_name'] = $this->unaccent($customer->getFirstname());
$array['x_last_name'] = $this->unaccent($customer->getLastname());
$array['x_company'] = 'Aviatur';
$array['x_email'] = $customer->getEmail();
$array['x_address'] = $customer->getAddress();
$array['x_city'] = $customer->getCity()->getDescription();
$array['x_province'] = $customer->getCity()->getDescription();
$array['x_country'] = $customer->getCountry()->getDescription();
$array['x_phone'] = $customer->getPhone();
$array['x_mobile'] = $customer->getCellphone();
$array['x_payment_data'] = $paymentData->type;
$array['x_reference'] = $orderInfo->products;
$array['x_description'] = $description;
$array['x_booking'] = $orderProduct[0]->getBooking();
$array['x_total_amount'] = number_format(round((float) $amount), 0, '.', '');
$array['x_tax_amount'] = number_format(round((float) (0)), 2, '.', '');
$array['x_devolution_base'] = number_format(round((float) (0)), 2, '.', '');
$array['x_tip_amount'] = number_format(round(0), 0, '.', '');
$array['x_currency'] = $currency;
$array['x_type_description'] = $orderProduct[0]->getDescription();
$array['x_cantidad'] = $postData->PI->person_count_1;
if ($payoutExtrasValues && !(bool) $session->get($transactionId.'[PayoutExtras][Processed]')) {
foreach ($payoutExtrasValues as $payoutExtraValues) {
$array['x_total_amount'] += round((float) $payoutExtraValues->values->fare->total);
}
}
$payoutExtrasValues = $extraService->setPayoutExtrasAsProcessed($transactionId);
$fecha = $orderProduct[0]->getCreationDate()->format('Y-m-d H:i:s');
$fechalimite = $orderProduct[0]->getCreationDate()->format('Y-m-d 23:40:00');
$nuevafecha = strtotime('+2 hour', strtotime($fecha));
$fechavigencia = date('Y-m-d H:i:s', $nuevafecha);
if (strcmp($fechavigencia, $fechalimite) > 0) {
$fechavigencia = $fechalimite;
}
$array['x_fechavigencia'] = $fechavigencia;
$cashPay = $cashController->cashAction($aviaturlogSave, $array);
$orderController->updatePaymentAction($orderProduct[0]);
if ('ok' == $cashPay->status) {
$session->set($transactionId.'[car][cash_result]', json_encode($cashPay));
return $this->redirect($this->generateUrl('aviatur_car_payment_success_secure'));
} else {
$toEmails = ['soportepagoelectronico@aviatur.com.co', 'soptepagelectronic@aviatur.com', $emailNotification];
$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_error'] = $cashPay->status;
$mailInfo = print_r($emissionData, true).'<br>'.print_r($cashPay, true);
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($toEmails)
->setBcc('arthur.picerna@aviatur.com')
->setSubject('Error Creación Transacción Baloto'.$emissionData['x_reference'].' - '.$orderProduct[0]->getOrder()->getAgency()->getName())
->setBody($mailInfo);
$mailer->send($message);
$session->set($transactionId.'[car][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl('aviatur_car_payment_rejected_secure'));
}
} else {
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), '', 'El tipo de pago es invalido'));
}
} else {
$logSave->log(
'Error fatal',
'No se encontró un order product en sesión',
null,
false
);
}
} else {
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), '', 'No hay mas intentos permitidos'));
}
}
}
public function p2pCallbackAction(Request $request, ManagerRegistry $managerRegistry, TokenStorageInterface $tokenStorage, ParameterBagInterface $parameterBag, PayoutExtraService $extraService, AviaturMailer $aviaturMailer, CustomerMethodPaymentService $methodPaymentService, AviaturEncoder $aviaturEncoder, AviaturCarService $carService, ValidateSanctions $validateSanctions, AviaturErrorHandler $errorHandler, OrderController $orderController)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$response = [];
$em = $managerRegistry->getManager();
$session = $request->getSession();
$transactionId = $session->get($transactionIdSessionName);
$orderProductCode = $session->get($transactionId.'[car][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(OrderProduct::class)->find($productId);
$agency = $orderProduct->getOrder()->getAgency();
$decodedRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
$jsonSendEmail = $em->getRepository(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) {
$twig = '';
$additionalQS = '';
$retryCount = (int) $session->get($transactionId.'[car][retry]');
switch ($decodedResponse->x_response_code) {
case isset($decodedResponse->x_response_code_cyber) && (2 == $decodedResponse->x_response_code_cyber):
//rechazado cybersource
$parameters = $em->getRepository(Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
if ($parameters) {
if (1 == $parameters->getValue()) {
if (1 == $decodedResponse->x_response_code) {
$postData = json_decode($session->get($transactionId.'[car][detail_data]'));
if (isset($postData->PD->cusPOptSelected)) {
if (isset($postData->PD->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
$postData->PD->cusPOptSelectedStatus = 'ACTIVE';
$customerLogin = $tokenStorage->getToken()->getUser();
$methodPaymentService->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
if (isset($postData->PD->savePaymProc)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$methodPaymentService->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
}
$twig = 'aviatur_car_payment_rejected_secure';
// no break
case 3:// pendiente p2p
$twig = '' != $twig ? $twig : 'aviatur_car_payment_pending_secure';
$updateOrder = $orderController->updatePaymentAction($orderProduct);
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$retryCount = 1;
break;
case 0:// error p2p
$twig = 'aviatur_car_payment_error_secure'; //no existe?
if (isset($email)) {
$from = $session->get('emailNoReply');
$error = $twig;
$subject = $orderProduct->getDescription().':Error en el proceso de pago';
$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_car_payment_rejected_secure';
$orderProduct->setResume('No reservation');
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
$decodedRequest->product_type = 'car';
$decodedResponse->product_type = 'car';
$encodedRequest = $aviaturEncoder->AviaturEncode(json_encode($decodedRequest), $orderProduct->getPublicKey());
$encodedResponse = $aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey());
$orderProduct->setPayrequest($encodedRequest);
$orderProduct->setPayresponse($encodedResponse);
$updateOrder = $orderController->updatePaymentAction($orderProduct);
$postData = json_decode($session->get($transactionId.'[car][detail_data]'));
if (isset($postData->PD->cusPOptSelected)) {
if (isset($postData->PD->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
$postData->PD->cusPOptSelectedStatus = 'ACTIVE';
$customerLogin = $tokenStorage->getToken()->getUser();
$methodPaymentService->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
if (isset($postData->PD->savePaymProc)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$methodPaymentService->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
$twig = 'aviatur_car_payment_success_secure';
//aviatur_car_payment_success_secure
//aviatur_car_confirmation_secure
if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
$additionalQS = '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->x_amount;
}
$carService->carReservation($orderProduct, false, true);
if (isset($response['error'])) {
$orderProduct->setResume('Book_in_basket');
}
$em->persist($orderProduct);
$em->flush();
break;
}
$extraService->payoutExtrasCallback($twig, $transactionId, 'car', $agency);
$session->set($transactionId.'[car][retry]', $retryCount - 1);
$urlResume = $this->generateUrl($twig);
$urlResume .= $additionalQS;
//////// se envia el correo del modulo anti fraude en caso de ser necesario//////////
if ($session->has('Marked_name') && $session->has('Marked_document')) {
$product = 'Autos';
$validateSanctions->sendMarkedEmail($orderProductCode, $session, $agency, $orderProduct, $transactionId, $product);
}
////////////////////////////////////////////////////////////////////////////////////
return $this->redirect($urlResume);
} else {
$orderProduct->setStatus('pending');
$em->persist($orderProduct);
$em->flush();
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), '', 'No hay respuesta por parte del servicio de pago'));
}
}
public function pseCallbackAction(Request $request, ManagerRegistry $managerRegistry, ParameterBagInterface $parameterBag, PayoutExtraService $extraService, AviaturEncoder $aviaturEncoder, AviaturCarService $carService, AviaturErrorHandler $errorHandler, TwigFolder $twigFolder, PSEController $PSEController, OrderController $orderController, $transaction)
{
$status = null;
$twig = null;
$em = $managerRegistry->getManager();
$session = $request->getSession();
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$transactionId = $session->get($transactionIdSessionName);
$orderProductCode = $session->get($transactionId.'[car][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->getPayresponse(), $orderProduct->getPublicKey()));
if ($session->has('agencyId')) {
$agency = $em->getRepository(Agency::class)->find($session->get('agencyId'));
} else {
$agency = $em->getRepository(Agency::class)->find(1);
}
$paymentMethod = $em->getRepository(PaymentMethod::class)->findOneByCode('pse');
$paymentMethodAgency = $em->getRepository(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['car'])) {
$carOrders = explode('+', $orders['car']);
$orderProductCode = $carOrders[0];
$productId = $carOrders[0];
$retryCount = 1;
} else {
return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontro identificador de la transacción'));
}
//$orderProduct = $em->getRepository(OrderProduct::class)->find($productId);
if (empty($orderProduct)) {
return $this->redirect($errorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró orden asociada a este pago'));
} else {
if ('approved' == $orderProduct->getStatus()) {
return $this->redirect($errorHandler->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)) {
$additionalQS = '';
$pseTransactionId = $decodedResponse->createTransactionResult->transactionID;
$paymentResponse = $PSEController->pseCallbackAction($pseTransactionId);
if (!isset($paymentResponse->error)) {
if (!$session->has($transactionId.'[car][detail_data]')) {
$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($errorHandler->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_car_payment_success_secure';
//aviatur_car_confirmation_secure
$status = 'approved';
if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
$additionalQS = '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->totalAmount;
}
break;
case 'PENDING':
$twig = 'aviatur_car_payment_pending_secure';
$status = 'pending';
break;
case 'NOT_AUTHORIZED':
$twig = 'aviatur_car_payment_error_secure';
$status = 'rejected';
break;
case 'FAILED':
$twig = 'aviatur_car_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();
$extraService->payoutExtrasCallback($twig, $transactionId, 'car', $agency);
if ('approved' == $status) {
$orderController->updatePaymentAction($orderProduct, false, null);
$carService->carReservation($orderProduct, false, true);
}
} elseif ('FAIL_INVALIDTRAZABILITYCODE' == (string) $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_ACCESSDENIED' == $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_TIMEOUT' == $paymentResponse->getTransactionInformationResult->returnCode) {
echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
transacción <#CUS> .';
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$twig = 'aviatur_car_payment_error_secure';
}
if ($session->has($transactionId.'[car][retry]')) {
$session->set($transactionId.'[car][retry]', $retryCount - 1);
}
$urlResume = $this->generateUrl($twig);
$urlResume .= $additionalQS;
return $this->redirect($urlResume);
} 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($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Ocurrió un error al consultar el estado de la transacción'));
}
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró información de la transacción'));
}
}
}
}
public function safetyCallbackOkAction(Request $request, ManagerRegistry $managerRegistry, ParameterBagInterface $parameterBag, PayoutExtraService $extraService, AviaturEncoder $aviaturEncoder, AviaturCarService $carService, TwigFolder $twigFolder, AviaturErrorHandler $errorHandler, OrderController $orderController)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$em = $managerRegistry->getManager();
$session = $request->getSession();
$agency = $em->getRepository(Agency::class)->find($session->get('agencyId'));
if (true === $session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
if (true === $session->has($transactionId.'[car][order]')) {
$orderProductCode = $session->get($transactionId.'[car][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(OrderProduct::class)->find($productId);
$postData = json_decode($session->get($transactionId.'[car][detail_data]'));
$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)) {
$additionalQS = '';
if (0 === $payError) {
$retryCount = (int) $session->get($transactionId.'[car][retry]');
if (0 == $notifyError) {
$twig = 'aviatur_car_payment_success_secure';
$status = 'approved';
if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
$additionalQS = '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->x_amount;
}
$orderProduct->setStatus($status);
$orderProduct->getOrder()->setStatus($status);
$orderProduct->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$orderController->updatePaymentAction($orderProduct);
$extraService->payoutExtrasCallback($twig, $transactionId, 'car', $agency);
if ('approved' == $status) {
$carService->carReservation($orderProduct, false, true);
}
} else {
echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
transacción <#CUS> .';
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$twig = 'aviatur_car_payment_error_secure';
}
$session->set($transactionId.'[car][retry]', $retryCount - 1);
$urlResume = $this->generateUrl($twig);
$urlResume .= $additionalQS;
return $this->redirect($urlResume);
} 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($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Ocurrió un error al consultar el estado de la transacción'));
}
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró información de la transacción, por favor comuniquese con nosotros'));
}
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró orden asociada a este pago'));
}
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró identificador de la transacción'));
}
}
public function safetyCallbackErrorAction(Request $request, ManagerRegistry $managerRegistry, ParameterBagInterface $parameterBag, AviaturEncoder $aviaturEncoder, AviaturErrorHandler $errorHandler, TwigFolder $twigFolder)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$status = null;
$fullRequest = $request;
$em = $managerRegistry->getManager();
$session = $fullRequest->getSession();
$transactionId = $session->get($transactionIdSessionName);
$retryCount = (int) $session->get($transactionId.'[car][retry]');
$orderProductCode = json_decode($session->get($transactionId.'[car][order]'));
$productId = str_replace('PN', '', $orderProductCode->products);
$orderProduct = $em->getRepository(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(Order::class)->find($orderProduct->getOrder()->getId());
$order->setStatus($status);
$em->persist($order);
$em->persist($orderProduct);
$em->flush();
if (!$session->has($transactionId.'[car][order]')) {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró orden asociada a este pago'));
}
$session->set($transactionId.'[car][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl('aviatur_car_payment_rejected_secure'));
}
public function worldCallbackAction(Request $request, ManagerRegistry $managerRegistry, ParameterBagInterface $parameterBag, AviaturEncoder $aviaturEncoder, AviaturCarService $carService, OrderController $orderController, AviaturErrorHandler $errorHandler)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$response = [];
$em = $managerRegistry->getManager();
$session = $request->getSession();
$transactionId = $session->get($transactionIdSessionName);
$orderProductCode = $session->get($transactionId.'[car][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(OrderProduct::class)->find($productId);
$decodedRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
if (null != $decodedResponse) {
$twig = 'aviatur_car_payment_rejected_secure';
$retryCount = (int) $session->get($transactionId.'[car][retry]');
if (isset($decodedResponse->x_response_code_cyber) && (2 == $decodedResponse->x_response_code_cyber)) {
$decodedResponse->x_response_code_case = 99;
} else {
if (isset($decodedResponse->resultado->reply->orderStatus->payment->lastEvent)) {
$decodedResponse->x_response_code_case = (string) $decodedResponse->resultado->reply->orderStatus->payment->lastEvent;
} elseif (isset($decodedResponse->resultado->reply->orderStatusEvent->payment->lastEvent)) {
$decodedResponse->x_response_code_case = 'REFUSED';
} elseif (isset($decodedResponse->resultado->reply->error)) {
$decodedResponse->x_response_code_case = 'REFUSED';
}
}
switch ($decodedResponse->x_response_code_case) {
case 'ERROR':
$twig = 'aviatur_car_payment_error_secure';
break;
case 'AUTHORISED':
$decodedRequest->product_type = 'car';
$decodedResponse->product_type = 'car';
$encodedRequest = $aviaturEncoder->AviaturEncode(json_encode($decodedRequest), $orderProduct->getPublicKey());
$encodedResponse = $aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey());
$orderProduct->setPayrequest($encodedRequest);
$orderProduct->setPayresponse($encodedResponse);
$twig = 'aviatur_car_payment_success_secure';
if (isset($response['error'])) {
$orderProduct->setResume('Book_in_basket');
}
$em->persist($orderProduct);
$em->flush();
$carService->carReservation($orderProduct, false, true);
break;
case 'REFUSED':
$twig = '' != $twig ? $twig : 'aviatur_car_payment_rejected_secure';
$orderProduct->setResume('No reservation');
break;
default:
$twig = '' != $twig ? $twig : 'aviatur_car_payment_pending_secure';
$updateOrder = $orderController->updatePaymentAction($orderProduct);
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$retryCount = 1;
break;
}
$session->set($transactionId.'[car][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl($twig));
} else {
$orderProduct->setStatus('pending');
$em->persist($orderProduct);
$em->flush();
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_car_retry_secure'), '', 'No hay respuesta por parte del servicio de pago'));
}
}
/**
* @param Request $request
* @param ManagerRegistry $managerRegistry
* @param ParameterBagInterface $parameterBag
* @param TwigFolder $twigFolder
* @param AviaturEncoder $aviaturEncoder
* @param \Swift_Mailer $mailer
* @param Pdf $pdf
* @param ExceptionLog $exceptionLog
* @return Response
*/
public function paymentOutputAction(Request $request, ManagerRegistry $managerRegistry, ParameterBagInterface $parameterBag, TwigFolder $twigFolder, AviaturEncoder $aviaturEncoder, \Swift_Mailer $mailer, Pdf $pdf, ExceptionLog $exceptionLog)
{
$projectDir = $parameterBag->get('kernel.project_dir');
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$list = [];
$clientFranquice = [];
$renderResumeView = [];
$session = $request->getSession();
$em = $managerRegistry->getManager();
$agency = $em->getRepository(Agency::class)->find($session->get('agencyId'));
$transactionId = $session->get($transactionIdSessionName);
$agencyFolder = $twigFolder->twigFlux();
$postDataJson = $session->get($transactionId.'[car][detail_data]');
$PaymentForm = $session->get($transactionId.'[car][payment_car_form]');
$detail = \simplexml_load_string($session->get($transactionId.'[car][detail]'));
$total_amount_local = $session->get($transactionId.'[car][total_amount_local]');
$currency_code_local = $session->get($transactionId.'[car][currency_code_local]');
$total_amount = $session->get($transactionId.'[car][total_amount]');
$currency = $session->get($transactionId.'[car][currency]');
$orderProductCode = $session->get($transactionId.'[car][order]');
$providerCarInfo = $session->get($transactionId.'[car][providerCarInfo]');
$car_homologate_hertz_codes = json_decode($em->getRepository(Parameter::class)->findOneByName('car_homologate_hertz_codes')->getDescription(), true);
$prepayment = null;
$paymentData = json_decode($postDataJson);
if ($session->has($transactionId.'[car][vehReservation]')) {
$prepayment = \simplexml_load_string($session->get($transactionId.'[car][vehReservation]'));
}
$customer = $em->getRepository(Customer::class)->find($paymentData->BD->id);
if (false !== strpos($paymentData->BD->first_name, '***')) {
$facturationResume = [
'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
'customer_address' => $customer->getAddress(),
'customer_doc_num' => $customer->getDocumentnumber(),
'customer_phone' => $customer->getPhone(),
'customer_email' => $customer->getEmail(),
];
} else {
$facturationResume = [
'customer_names' => $paymentData->BD->first_name.' '.$paymentData->BD->last_name,
'customer_address' => $paymentData->BD->address ?? null,
'customer_doc_num' => $paymentData->BD->doc_num,
'customer_phone' => $paymentData->BD->phone,
'customer_email' => $paymentData->BD->email ?? null,
];
}
$orderProductId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(OrderProduct::class)->find($orderProductId);
$productResponse = $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
$opResponse = json_decode($productResponse);
$productRequest = $aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey());
$opRequest = json_decode($productRequest);
$isFront = $session->has('operatorId');
if ($isFront) {
$userFront = simplexml_load_string($session->get('front_user'));
$customerEmail = (string) $userFront->CORREO_ELECTRONICO;
} else {
$customer = $em->getRepository(Customer::class)->find($paymentData->BD->id);
$customerEmail = $customer->getEmail();
}
$list[0] = ['M' => 'Mini', 'N' => 'Mini Élite', 'E' => 'Económico', 'H' => 'Económico Élite', 'C' => 'Compacto', 'D' => 'Compacto Élite', 'I' => 'Intermedio', 'J' => 'Intermedio Élite', 'S' => 'Estándar', 'R' => 'Estándar Élite', 'F' => 'Fullsize', 'G' => 'Fullsize Elite', 'P' => 'Premium', 'U' => 'Premium Élite', 'L' => 'Lujoso', 'W' => 'Lujoso Élite', 'O' => 'Oversize', 'X' => 'Especial'];
$list[1] = ['B' => '2-3 Puertas', 'C' => '2/4 Puertas', 'D' => '4-5 Puertas', 'W' => 'Vagón', 'V' => 'Van de pasajeros', 'L' => 'Limosina', 'S' => 'Deportivo', 'T' => 'Convertible', 'F' => 'SUV', 'J' => 'Todo Terreno', 'X' => 'Especial', 'P' => 'Pick up de Cabina Regular', 'Q' => 'Pick up de Cabina Extendida', 'Z' => 'Auto de Oferta Especial', 'E' => 'Coupe', 'M' => 'Minivan', 'R' => 'Vehículo recreacional', 'H' => 'Casa rodante', 'Y' => 'Vehículo de dos ruedas', 'N' => 'Roasted', 'G' => 'Crossover', 'K' => 'Van comercial / Camión'];
$list[2] = ['M' => 'Transmisión Manual, Tracción sin especificar', 'N' => 'Transmisión Manual, Tracción 4WD', 'C' => 'Transmisión Manual, Tracción AWD', 'A' => 'Transmisión Automática, Tracción sin especificar', 'B' => 'Transmisión Automática, Tracción 4WD', 'D' => 'Transmisión Automática, Tracción AWD'];
$list[3] = ['R' => 'Combustible no especificado, con aire acondicionado', 'N' => 'Combustible no especificado, sin aire acondicionado', 'D' => 'Diesel, con aire acondicionado', 'Q' => 'Diesel, sin aire acondicionado', 'H' => 'Híbrido, con aire acondicionado', 'I' => 'Híbrido, sin aire acondicionado', 'E' => 'Eléctrico, con aire acondicionado', 'C' => 'Eléctrico, sin aire acondicionado', 'L' => 'Gas comprimido, con aire acondicionado', 'S' => 'Gas comprimido, sin aire acondicionado', 'A' => 'Hidrógeno, con aire acondicionado', 'B' => 'Hidrógeno, sin aire acondicionado', 'M' => 'Multi combustible, con aire acondicionado', 'F' => 'Multi combustible, sin aire acondicionado', 'V' => 'Gasolina, con aire acondicionado', 'Z' => 'Gasolina, sin aire acondicionado', 'U' => 'Etanol, con aire acondicionado', 'X' => 'Etanol, sin aire acondicionado'];
$carsInfo = [];
$selection = json_decode($session->get($transactionId.'[car][selection]'));
foreach ($detail->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail as $VehVendorAvail) {
if ((int) $VehVendorAvail->Info->TPA_Extensions->RPH == explode('-', $paymentData->SD->selection)[0]) {
foreach ($VehVendorAvail->VehAvails as $VehAvails) {
foreach ($VehAvails->VehAvail as $VehAvail) {
if ((int) $VehAvail->VehAvailInfo->TPA_Extensions->RPH == explode('-', $paymentData->SD->selection)[1]) {
$carsInfo[] = $VehAvail;
}
}
}
}
}
$locations = [];
foreach ($detail->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Info->LocationDetails as $location) {
$locations[] = $location;
}
$carImg = (string) $detail->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->Vehicle->PictureURL;
$agencyData = [
'agency_name' => $agency->getName(),
'agency_nit' => $agency->getNit(),
'agency_phone' => $agency->getPhone(),
'agency_email' => $agency->getMailContact(),
];
$journeySummary = [
'serviceResponse' => $detail->Message->OTA_VehAvailRateRS,
'carsInfo' => $carsInfo,
'reservationInfo' => $prepayment->Message->OTA_VehResRS ?? null,
'carDescription' => $list,
'pickUpLocation' => $locations[0],
'returnLocation' => end($locations),
'carsItems' => (null != $providerCarInfo) ? json_decode($providerCarInfo, true) : null,
'carImg' => str_replace('9.JPEG', '4.JPEG', $carImg),
'total_amount' => $total_amount,
'currency_code' => $currency,
'total_amount_local' => $total_amount_local,
'currency_code_local' => $currency_code_local,
'order' => json_decode($orderProductCode)->products,
];
if ($session->has($transactionId.'[car][voucher_num]')) {
$journeySummary['voucher_num'] = $session->get($transactionId.'[car][voucher_num]');
}
$emailData = [
'agencyData' => $agencyData,
'journeySummary' => $journeySummary,
'car_homologate_hertz_codes' => $car_homologate_hertz_codes,
'paymentForm' => $session->get($transactionId.'[car][payment_car_form]'),
];
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' => ''],
'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,
'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
'customer_address' => $customer->getAddress(),
'customer_doc_num' => $customer->getDocumentnumber(),
'customer_phone' => $customer->getPhone(),
'customer_email' => $customer->getEmail(),
'agency_name' => $agency->getName(),
'agency_nit' => $agency->getNit(),
'client_names' => $opResponse->x_first_name.' '.$opResponse->x_last_name,
'client_email' => $opResponse->x_email,
];
$paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
} 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';
}
$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 ?? null,
'x_payment_data' => $opRequest->dataTransf->x_payment_data,
'client_franquice' => ['description' => 'SafetyPay'],
'customer_names' => $customer->getFirstname() . ' ' . $customer->getLastname(),
'customer_address' => $customer->getAddress(),
'customer_doc_num' => $customer->getDocumentnumber(),
'customer_phone' => $customer->getPhone(),
'customer_email' => $customer->getEmail(),
'agency_name' => $agency->getName(),
'agency_nit' => $agency->getNit(),
'client_names' => $opResponse->x_first_name . ' ' . $opResponse->x_last_name,
'client_email' => $opResponse->x_email,
];
} 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,
'customer_names' => $customer->getFirstname() . ' ' . $customer->getLastname(),
'customer_address' => $customer->getAddress(),
'customer_doc_num' => $customer->getDocumentnumber(),
'customer_phone' => $customer->getPhone(),
'customer_email' => $customer->getEmail(),
'agency_name' => $agency->getName(),
'agency_nit' => $agency->getNit(),
'client_names' => $opResponse->x_first_name . ' ' . $opResponse->x_last_name,
'client_email' => $opResponse->x_email,
];
}
if ('baloto' == $opRequest->dataTransf->x_payment_data) {
$paymentResume['transaction_state'] = 3;
}
$paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
} elseif (isset($opRequest->infoCash)) {
$paymentResume = [
'id' => $orderProduct->getBooking(),
'id_context' => $opRequest->infoCash->x_reference,
'currency' => $opRequest->infoCash->x_currency,
'total_amount' => $opRequest->infoCash->x_total_amount,
'client_franquice' => ['description' => 'Efectivo'],
'amount' => null,
'iva' => null,
'ip_address' => $opRequest->infoCash->dirIp,
'airport_tax' => null,
'reference' => $opRequest->infoCash->x_reference,
'auth' => null,
'transaction_date' => $opRequest->infoCash->x_fechavigencia,
'description' => $opRequest->infoCash->x_description,
'reason_code' => 101,
'reason_description' => 'Transacción creada',
'client_email' => $opRequest->infoCash->x_email,
'fecha_vigencia' => $opRequest->infoCash->x_fechavigencia,
'customer_names' => $customer->getFirstname() . ' ' . $customer->getLastname(),
'customer_address' => $customer->getAddress(),
'customer_doc_num' => $customer->getDocumentnumber(),
'customer_phone' => $customer->getPhone(),
'customer_email' => $customer->getEmail(),
'agency_name' => $agency->getName(),
'agency_nit' => $agency->getNit(),
'client_names' => $opRequest->infoCash->x_first_name . ' ' . $opRequest->infoCash->x_last_name,
];
$cash_result = json_decode($session->get($transactionId . '[car][cash_result]'));
$paymentResume['transaction_state'] = 3;
if ('' == $cash_result) {
$paymentResume['transaction_state'] = 2;
}
$paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
} else {
if ((empty($opResponse) && empty($opRequest) && 0 == $session->get($transactionId.'[car][payment_car_form]')) || $isFront) {
$paymentResume = [];
} else {
$bank_info = $em->getRepository(PseBank::class)->findOneByCode($opRequest->bankCode);
$bank_name = $bank_info->getName();
$clientFranquice['description'] = 'PSE';
$paymentResume = [
'transaction_state' => $opResponse->getTransactionInformationResult->responseCode,
'id' => $orderProduct->getBooking(),
'id_context' => $opRequest->reference,
'currency' => $opRequest->currency,
'total_amount' => $opRequest->totalAmount,
'amount' => $opRequest->devolutionBase,
'iva' => $opRequest->taxAmount,
'ip_address' => $opRequest->ipAddress,
'bank_name' => $bank_name,
'client_franquice' => $clientFranquice,
'reference' => $opResponse->createTransactionResult->transactionID,
'auth' => $opResponse->getTransactionInformationResult->trazabilityCode,
'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate,
'description' => $opRequest->description,
'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode,
'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText,
'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
'customer_address' => $customer->getAddress(),
'customer_doc_num' => $customer->getDocumentnumber(),
'customer_phone' => $customer->getPhone(),
'customer_email' => $customer->getEmail(),
'agency_name' => $agency->getName(),
'agency_nit' => $agency->getNit(),
'client_names' => $opRequest->payer->firstName.' '.$opRequest->payer->lastName,
'client_email' => $opRequest->payer->emailAddress,
];
}
}
if ($session->has($transactionId.'[car][vehReservation]') && !$session->has($transactionId.'[car][emission_email]')) {
$emailData['paymentResume'] = $paymentResume;
//return $this->render($twigFolder->twigExists('@AviaturTwig/' . $agencyFolder . '/Car/Default/email.html.twig'), $emailData);
if (!file_exists($projectDir.'/app/serviceLogs/carReservation')) {
mkdir($projectDir.'/app/serviceLogs/carReservation');
}
$urlResume = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/email.html.twig');
$carFile = $projectDir.'/app/serviceLogs/carReservation/'.$orderProduct->getBooking().'.pdf';
if (!file_exists($carFile)) {
try {
$pdf->generateFromHtml($this->renderView($urlResume, $emailData), $carFile, ['encoding' => 'utf-8']);
} catch (\Exception $e) {
}
}
$setBcc = ['sergio.amaya@aviatur.com', 'sara.calderon@aviatur.com'];
$setTo = $customerEmail;
if ($isFront && 1 == $PaymentForm) {
$setBcc = ['sergio.amaya@aviatur.com'];
$setTo = 'sara.calderon@aviatur.com';
}
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
->setBcc($setBcc)
->attach(\Swift_Attachment::fromPath($carFile))
->setSubject($session->get('agencyShortName') . (($isFront) ? ' B2T ' : '') . ' - [Autos] Gracias por su compra')
->setBody(
$this->renderView($urlResume, $emailData)
);
if ($session->has($transactionId.'[car][vehReservation]')) {
try {
$mailer->send($message);
$session->set($transactionId.'[car][emission_email]', 'emailed');
} catch (\Exception $ex) {
$exceptionLog->log(
$message,
$ex
);
}
}
}
if ($session->has($transactionId.'[car][cash_result]')) {
$renderResumeView['infos'][0]['agencyData']['agency_nit'] = $agency->getNit();
$renderResumeView['infos'][0]['agencyData']['agency_name'] = $agency->getName();
$renderResumeView['infos'][0]['agencyData']['agency_phone'] = $agency->getPhone();
$renderResumeView['infos'][0]['agencyData']['agency_email'] = $agency->getMailContact();
$renderResumeView['infos'][0]['paymentResume'] = $paymentResume;
$voucherFile = $projectDir.'/app/serviceLogs/CashTransaction/ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
if (file_exists($voucherFile)) {
$renderResumeView['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
}
$emailData['cash_result'] = json_decode($session->get($transactionId.'[car][cash_result]'), true);
$renderResumeView['cash_result'] = json_decode($session->get($transactionId.'[car][cash_result]'), true);
$renderResumeView['exportPDF'] = true;
$ruta = '@AviaturTwig/'.$agencyFolder.'/General/Templates/email_cash.html.twig';
if (!file_exists($voucherFile)) {
$pdf->generateFromHtml($this->renderView($twigFolder->twigExists($ruta), $renderResumeView), $voucherFile);
$renderResumeView['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
}
$paymentResume['NameArchive'] = $renderResumeView['NameArchive'];
$paymentResume['exportPDF'] = false;
if (!$session->has($transactionId.'[car][emission_baloto_email]')) {
$setTo = $paymentResume['client_email'];
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
//->setBcc(array('soptepagelectronic@aviatur.com', 'soportepagoelectronico@aviatur.com.co', 'gustavo.hincapie@aviatur.com'))
->setSubject($session->get('agencyShortName').' - Transacción Efectivo Creada '.$paymentResume['id_context'])
->attach(\Swift_Attachment::fromPath($voucherFile))
->setBody(
$this->renderView($twigFolder->twigExists($ruta), $renderResumeView)
);
try {
$mailer->send($message);
$session->set($transactionId.'[car][emission_baloto_email]', 'emailed');
} catch (\Exception $ex) {
$exceptionLog->log($message, $ex);
}
}
}
$paymentResume['finantial_rate'] = json_decode($session->get('[car][finantial_rate_info]'), true);
$paymentResume['facturationResume'] = $facturationResume;
$paymentResume['serviceResponse'] = $detail->Message->OTA_VehAvailRateRS;
$paymentResume['carsInfo'] = $carsInfo;
$paymentResume['car_homologate_hertz_codes'] = $car_homologate_hertz_codes;
$paymentResume['reservationInfo'] = $prepayment->Message->OTA_VehResRS ?? null;
$paymentResume['order'] = 'PN'.$orderProduct->getId();
$paymentResume['carDescription'] = $list;
$paymentResume['pickUpLocation'] = $locations[0];
$paymentResume['returnLocation'] = end($locations);
$paymentResume['transactionID'] = $transactionId;
$paymentResume['carsItems'] = (null != $providerCarInfo) ? json_decode($providerCarInfo, true) : null;
$paymentResume['emailData'] = $emailData;
$paymentResume['backDetail'] = $this->generateUrl('aviatur_car_retry_secure');
$paymentResume['passengerData'] = ($session->has($transactionId.'[car][passengerData]')) ? json_decode($session->get($transactionId.'[car][passengerData]'), true) : false;
if (!isset($paymentResume['total_amount'])) {
$paymentResume['total_amount'] = $total_amount;
$paymentResume['currency_code'] = $currency;
}
if (!isset($paymentResume['retry_count'])) {
$paymentResume['retry_count'] = $session->get($transactionId.'[car][retry]');
}
$resumeOrderProduct = $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/confirmation.html.twig'), $paymentResume);
if (null == $orderProduct->getResume()) {
$orderProduct->setEmail(json_encode($emailData));
$orderProduct->setResume($resumeOrderProduct);
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
}
return $resumeOrderProduct;
}
private function unaccent($string)
{
return preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8'));
}
public function indexAction(Request $request, ManagerRegistry $managerRegistry, AuthorizationCheckerInterface $authorizationChecker, TwigFolder $twigFolder, AviaturErrorHandler $errorHandler, PaginatorInterface $paginator, $page, $active, $search = null)
{
$em = $managerRegistry->getManager();
$fullRequest = $request;
$routeParams = $fullRequest->attributes->get('_route_params');
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), $routeParams);
$session = $request->getSession();
$agencyId = $session->get('agencyId');
$agency = $em->getRepository(Agency::class)->find($agencyId);
$agencyFolder = $twigFolder->twigFlux();
if ($request->isXmlHttpRequest()) {
//BUSCADOR
$query = $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.id = :id AND a.isactive = 1 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
$query = $query->setParameter('agency', $agency);
$query = $query->setParameter('id', $search);
$queryIn = $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.id = :id AND a.isactive = 0 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
$queryIn = $queryIn->setParameter('agency', $agency);
$queryIn = $queryIn->setParameter('id', $search);
$path = '/Car/Default/Ajaxindex_car.html.twig';
$urlReturn = '@AviaturTwig/'.$agencyFolder.$path;
if ('activo' == $active) {
$articulos = $query->getResult();
} elseif ('inactivo' == $active) {
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_CREATE_'.$agencyId) || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_EDIT_'.$agencyId) || $authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
$articulos = $queryIn->getResult();
} else {
return $twigFolder->pathWithLocale('aviatur_general_homepage');
}
}
$actualArticles = [];
foreach ($articulos as $articulo) {
$description = json_decode($articulo->getDescription(), true);
if ($description && is_array($description)) {
$actualArticles[] = $articulo;
}
}
if (empty($actualArticles)) {
return $this->redirect($errorHandler->errorRedirectNoEmail('/', '', 'No existen contenidos para esta agencia.'));
}
$cantdatos = count($actualArticles);
$cantRegis = 10;
$totalRegi = ceil($cantdatos / $cantRegis);
$pagination = $paginator->paginate($actualArticles, $fullRequest->query->get('page', $page), $cantRegis);
return $this->render($twigFolder->twigExists($urlReturn), ['agencyId' => $agencyId, 'articulo' => $pagination, 'page' => $page, 'active' => $active, 'totalRegi' => $totalRegi, 'ajaxUrl' => $requestUrl]);
} else {
//INDEX
$query = $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.isactive = 1 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
$query = $query->setParameter('agency', $agency);
$queryIn = $em->createQuery('SELECT a FROM AviaturContentBundle:Content a WHERE a.isactive = 0 AND (a.agency = :agency OR a.agency IS NULL) ORDER BY a.creationdate DESC');
$queryIn = $queryIn->setParameter('agency', $agency);
$path = '/Car/Default/index_car.html.twig';
$urlReturn = '@AviaturTwig/'.$agencyFolder.$path;
}
if ('activo' == $active) {
$articulos = $query->getResult();
} elseif ('inactivo' == $active) {
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_CREATE_'.$agencyId) || $authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_PROMO_PRODUCT_EDIT_'.$agencyId) || $authorizationChecker->isGranted('ROLE_SUPER_ADMIN')) {
$articulos = $queryIn->getResult();
} else {
return $this->redirect($twigFolder->pathWithLocale('aviatur_general_homepage'));
}
}
$actualArticles = [];
foreach ($articulos as $articulo) {
$description = json_decode($articulo->getDescription(), true);
if ($description && is_array($description)) {
if ('autos' == $description['type']) {
$actualArticles[] = $articulo;
}
}
}
if (empty($actualArticles)) {
return $this->redirect($errorHandler->errorRedirectNoEmail('/', '', 'No existen contenidos para esta agencia.'));
}
$cantdatos = count($actualArticles);
$cantRegis = 9;
$totalRegi = ceil($cantdatos / $cantRegis);
$pagination = $paginator->paginate($actualArticles, $fullRequest->query->get('page', $page), $cantRegis);
return $this->render($twigFolder->twigExists($urlReturn), ['agencyId' => $agencyId, 'articulo' => $pagination, 'page' => $page, 'active' => $active, 'totalRegi' => $totalRegi, 'ajaxUrl' => $requestUrl]);
}
public function viewAction(SessionInterface $session, TwigFolder $twigFolder, $id)
{
$em = $this->getDoctrine()->getManager();
$agencyId = $session->get('agencyId');
$agency = $em->getRepository(Agency::class)->find($agencyId);
$articulo = $em->getRepository(\Aviatur\ContentBundle\Entity\Content::class)->findByAgencyNull($session->get('agencyId'), $id);
$promoType = '';
if (isset($articulo[0]) && (null != $articulo[0])) {
$agencyFolder = $twigFolder->twigFlux();
$description = json_decode($articulo[0]->getDescription(), true);
// determine content type based on eventual json encoded description
$carPromoList = $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromoList::class)->findOneBy(['type' => '__rent-autos'.$promoType, 'agency' => $agency]);
if (null != $carPromoList) {
$carPromos = $em->getRepository(\Aviatur\EditionBundle\Entity\HomePromo::class)->findByHomePromoList($carPromoList, ['date' => 'DESC']);
} else {
$carPromos = [];
}
if ($description && is_array($description)) {
$cookieArray = [];
foreach ($description as $key => $value) {
$cookieArray[$key] = $value;
}
if (isset($cookieArray['origin1']) && preg_match('/^[A-Z]{3}$/', $cookieArray['origin1'])) {
$ori = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['origin1']]);
$cookieArray['originLabel1'] = $ori->getCity().', '.$ori->getCountry().' ('.$ori->getIata().')';
} else {
$cookieArray['originLabel1'] = '';
}
if (isset($cookieArray['destination1']) && preg_match('/^[A-Z]{3}$/', $cookieArray['destination1'])) {
$dest = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneBy(['iata' => $cookieArray['destination1']]);
$cookieArray['destinationLabel1'] = $dest->getCity().', '.$dest->getCountry().' ('.$dest->getIata().')';
} else {
$cookieArray['destinationLabel1'] = '';
}
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/view_car.html.twig'), ['articulo' => $articulo[0], 'cookieLastSearchC' => $cookieArray, 'carPromos' => $carPromos, 'promoType' => '__rent-autos']);
}
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/view_car.html.twig'), ['articulo' => $articulo[0], 'carPromos' => $carPromos, 'promoType' => '__rent-autos']);
} else {
throw $this->createNotFoundException('Contenido no encontrado');
}
}
public function searchRentalsAction(Request $request, ManagerRegistry $managerRegistry)
{
$em = $managerRegistry->getManager();
$session = $request->getSession();
if ($request->isXmlHttpRequest()) {
$agencyId = $session->get('agencyId');
$agency = $em->getRepository(Agency::class)->find($agencyId);
$term = $request->query->get('term');
$url = $request->query->get('url');
$queryIn = $em->createQuery('SELECT a.id, a.title, a.url, a.description, a.isactive FROM AviaturContentBundle:Content a WHERE a.title LIKE :title AND a.description LIKE :description AND (a.agency = :agency OR a.agency IS NULL)');
$queryIn = $queryIn->setParameter('title', '%'.$term.'%');
$queryIn = $queryIn->setParameter('description', '%\"autos\"%');
$queryIn = $queryIn->setParameter('agency', $agency);
$articulos = $queryIn->getResult();
$type = '';
$json_template = '<value>:<label>*';
$json = '';
if ($articulos) {
foreach ($articulos as $contenidos) {
$description = json_decode($contenidos['description'], true);
if (null == $description || is_array($description)) {
if (isset($description['type'])) {
$type = $description['type'];
}
}
$json .= str_replace(['<value>', '<label>'], [$contenidos['id'].'|'.$type.'|'.$contenidos['url'], $contenidos['title']], $json_template);
}
$json = \rtrim($json, '-');
} else {
$json = 'NN:No hay Resultados';
}
$response = \rtrim($json, '*');
return new Response($response);
} else {
return new Response('Acceso Restringido');
}
}
public function quotationAction(Request $request, ManagerRegistry $managerRegistry, ParameterBagInterface $parameterBag, AviaturWebService $webService, AviaturLogSave $logSave, TwigFolder $twigFolder, \Swift_Mailer $mailer, AbstractGenerator $pdf)
{
$projectDir = $parameterBag->get('kernel.project_dir');
$list = [];
$codImg = null;
$fullRequest = $request;
$session = $fullRequest->getSession();
$isFront = $session->has('operatorId');
$em = $managerRegistry->getManager();
$agency = $em->getRepository(Agency::class)->find($session->get('agencyId'));
$agencyFolder = $twigFolder->twigFlux();
$transactionId = $session->get('transactionId');
$additionalUserFront = simplexml_load_string($session->get('front_user_additionals'));
$response = \simplexml_load_string($session->get($transactionId.'[car][detail]'));
$detailCarRaw = $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails;
$locationCar = $response->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore;
$dateIn = strtotime((string) $locationCar['PickUpDateTime']);
$dateOut = strtotime((string) $locationCar['ReturnDateTime']);
$postDataJson = $session->get($transactionId.'[car][carsInfo]');
if ($session->has($transactionId.'[crossed]'.'[url-car]')) {
$urlAvailability = $session->get($transactionId.'[crossed]'.'[url-car]');
} elseif ($session->has($transactionId.'[car][availability_url]')) {
$urlAvailability = $session->get($transactionId.'[car][availability_url]');
} else {
$urlAvailability = $session->get($transactionId.'[availability_url]');
}
$list[0] = ['M' => 'Mini', 'N' => 'Mini Élite', 'E' => 'Económico', 'H' => 'Económico Élite', 'C' => 'Compacto', 'D' => 'Compacto Élite', 'I' => 'Intermedio', 'J' => 'Intermedio Élite', 'S' => 'Estándar', 'R' => 'Estándar Élite', 'F' => 'Fullsize', 'G' => 'Fullsize Elite', 'P' => 'Premium', 'U' => 'Premium Élite', 'L' => 'Lujoso', 'W' => 'Lujoso Élite', 'O' => 'Oversize', 'X' => 'Especial'];
$list[1] = ['B' => '2-3 Puertas', 'C' => '2/4 Puertas', 'D' => '4-5 Puertas', 'W' => 'Vagón', 'V' => 'Van de pasajeros', 'L' => 'Limosina', 'S' => 'Deportivo', 'T' => 'Convertible', 'F' => 'SUV', 'J' => 'Todo Terreno', 'X' => 'Especial', 'P' => 'Pick up de Cabina Regular', 'Q' => 'Pick up de Cabina Extendida', 'Z' => 'Auto de Oferta Especial', 'E' => 'Coupe', 'M' => 'Minivan', 'R' => 'Vehículo recreacional', 'H' => 'Casa rodante', 'Y' => 'Vehículo de dos ruedas', 'N' => 'Roasted', 'G' => 'Crossover', 'K' => 'Van comercial / Camión'];
$list[2] = ['M' => 'Transmisión Manual, Tracción sin especificar', 'N' => 'Transmisión Manual, Tracción 4WD', 'C' => 'Transmisión Manual, Tracción AWD', 'A' => 'Transmisión Automática, Tracción sin especificar', 'B' => 'Transmisión Automática, Tracción 4WD', 'D' => 'Transmisión Automática, Tracción AWD'];
$list[3] = ['R' => 'Combustible no especificado, con aire acondicionado', 'N' => 'Combustible no especificado, sin aire acondicionado', 'D' => 'Diesel, con aire acondicionado', 'Q' => 'Diesel, sin aire acondicionado', 'H' => 'Híbrido, con aire acondicionado', 'I' => 'Híbrido, sin aire acondicionado', 'E' => 'Eléctrico, con aire acondicionado', 'C' => 'Eléctrico, sin aire acondicionado', 'L' => 'Gas comprimido, con aire acondicionado', 'S' => 'Gas comprimido, sin aire acondicionado', 'A' => 'Hidrógeno, con aire acondicionado', 'B' => 'Hidrógeno, sin aire acondicionado', 'M' => 'Multi combustible, con aire acondicionado', 'F' => 'Multi combustible, sin aire acondicionado', 'V' => 'Gasolina, con aire acondicionado', 'Z' => 'Gasolina, sin aire acondicionado', 'U' => 'Etanol, con aire acondicionado', 'X' => 'Etanol, sin aire acondicionado'];
$session->set($transactionId.'[car][list]', json_encode($list));
$html = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Car/Default/quotation.html.twig');
$namefilepdf = 'Aviatur_cotizacion_auto_'.$transactionId.'.pdf';
$voucherCruiseFile = $projectDir.'/app/quotationLogs/carQuotation/'.$namefilepdf.'.pdf';
if ('N' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
$codImg = $additionalUserFront->EMPRESA;
} elseif ('S' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
$codImg = $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
}
$imgAgency = 'assets/common_assets/img/offices/'.$codImg.'.png';
if (!file_exists($imgAgency)) {
$codImg = 10;
}
if (!file_exists($voucherCruiseFile)) {
$pdf->setOption('page-size', 'Legal');
$pdf->setOption('margin-top', 0);
$pdf->setOption('margin-right', 0);
$pdf->setOption('margin-bottom', 0);
$pdf->setOption('margin-left', 0);
$pdf->setOption('orientation', 'portrait');
$pdf->setOption('enable-javascript', true);
$pdf->setOption('no-stop-slow-scripts', true);
$pdf->setOption('no-background', false);
$pdf->setOption('lowquality', false);
$pdf->setOption('encoding', 'utf-8');
$pdf->setOption('images', true);
$pdf->setOption('dpi', 300);
$pdf->setOption('enable-external-links', true);
$pdf->setOption('enable-internal-links', true);
$pdf->generateFromHtml($this->renderView($html, [
'dateIn' => $dateIn,
'dateOut' => $dateOut,
'dateInStr' => (string) $locationCar['PickUpDateTime'],
'dateOutStr' => (string) $locationCar['ReturnDateTime'],
'nights' => floor(($dateOut - $dateIn) / (24 * 60 * 60)),
'total' => $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
'priceCurrency' => (string) $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->TotalCharge['CurrencyCode'],
'category' => (string) $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->Vehicle->VehMakeModel['Name'],
'TransmissionType' => $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->Vehicle['TransmissionType'],
'AirConditionInd' => $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->Vehicle['AirConditionInd'],
'PassengerQuantity' => $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->Vehicle['PassengerQuantity'],
'description' => '',
'vendor' => (string) $detailCarRaw->VehVendorAvail->Vendor,
'email' => '',
'services' => '',
'photo' => (string) $detailCarRaw->VehVendorAvail->VehAvails[0]->VehAvail->VehAvailCore->Vehicle->PictureURL,
'agentName' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
'agentMail' => $additionalUserFront->CORREO_ELECTRONICO,
'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL,
'prepaymentsInfo' => '',
'namesClient' => $fullRequest->request->get('quotationName'),
'lastnamesClient' => $fullRequest->request->get('quotationLastname'),
'emailClient' => $fullRequest->request->get('quotationEmail'),
'priceTotalQuotation' => $fullRequest->request->get('quotationPriceTotal'),
'infoTerms' => $fullRequest->request->get('quotationTerms'),
'infoComments' => $fullRequest->request->get('quotationComments'),
'codImg' => $codImg,
]), $voucherCruiseFile);
}
$subject = 'Cotización de Auto';
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom('noreply@aviatur.com')
->setTo($additionalUserFront->CORREO_ELECTRONICO)
->setSubject($session->get('agencyShortName').' - '.$subject)
->attach(\Swift_Attachment::fromPath($voucherCruiseFile))
->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Bus/Default/quotation_email_body.html.twig'), [
'nameAgent' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
'codImg' => $codImg,
]), 'text/html');
$mailer->send($messageEmail);
chmod($projectDir.'/app/quotationLogs/carQuotation/', 777);
$this->saveInformationCGS($request, $webService, $errorhandler, $logSave, $response, $additionalUserFront, $fullRequest->request);
unlink($voucherCruiseFile);
return $this->redirect($this->generateUrl('aviatur_car_search'));
}
public function saveInformationCGS(Request $request, ManagerRegistry $managerRegistry, AviaturWebService $webService, AviaturErrorHandler $errorHandler, AviaturLogSave $logSave, $data, $customer, $agency)
{
$em = $managerRegistry->getManager();
$parametersLogin =$em->getRepository(Parameter::class)->findParameters($agency, 'aviatur_service_login_cgs');
$urlLoginCGS = $parametersLogin[0]['value'];
$parametersProduct = $em->getRepository(Parameter::class)->findParameters($agency, 'aviatur_service_car_cgs');
$urlAddProductCar = $parametersProduct[0]['value'];
/*
* get token api autentication
* PENDIENTE: Validar si se puede obtener el token, si no entonces no hacer este proceso
*/
$userLoginCGS = $webService->encryptUser(trim(strtolower($customer->CODIGO_USUARIO)), 'AviaturCGSMTK');
$jsonReq = json_encode(['username' => $userLoginCGS]); //j_acosta (encriptado)
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $urlLoginCGS,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $jsonReq,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
],
]);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if (200 != $httpcode) {
$logSave->logSave('HTTPCODE: '.$httpcode.' Error usuario: '.strtolower($customer->CODIGO_USUARIO), 'CGS', 'CGSCAR_ERRORLOGIN');
$logSave->logSave(print_r($response, true), 'CGS', 'responseCarCGS');
return $this->redirect($errorHandler->errorRedirectNoEmail('/buscar/autos', 'Error Login', 'Error Login'));
} else {
$tokenInfoApiQuotation = json_decode($response);
$tokenApiQuotation = $tokenInfoApiQuotation->TOKEN;
}
if ($data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'] == $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode']) {
$dataCity = $em->getRepository(City::class)->findOneByIatacode($data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode']);
$sameCity = true;
} else {
$dataCity1 = $em->getRepository(City::class)->findOneByIatacode($data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode']);
$dataCity2 = $em->getRepository(City::class)->findOneByIatacode($data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode']);
$sameCity = false;
}
$emails_arr = [
'active' => true,
'dateCreated' => '0001-01-01T00:00:00',
'emailAddress' => (string) $request->get('quotationEmail'),
'id' => 0,
'lastUpdated' => '0001-01-01T00:00:00',
'version' => 0,
];
$phones_arr = [
'active' => false,
'dateCreated' => '0001-01-01T00:00:00',
'id' => 0,
'lastUpdated' => '0001-01-01T00:00:00',
'number' => null,
'type' => null,
'version' => 0,
];
$data_send = [
'customer' => [
'firstName' => (string) $request->get('quotationName'),
'lastName' => (string) $request->get('quotationLastname'),
'mothersName' => null,
'fullName' => trim($request->get('quotationName')).' '.trim($request->get('quotationLastname')),
'birthDate' => 'true',
'billingInformations' => null,
'emails' => [$emails_arr],
'phones' => [$phones_arr],
'city' => null,
],
'selectedProduct' => [
'airExists' => false,
'associatedProductIndex' => null,
'complementPackageList' => null,
'deleteInfo' => null,
'description' => null,
'discount' => null,
'duration' => 10,
'emit' => false,
'fareData' => [
'aditionalFee' => 0.0,
'airpotService' => null,
'baseFare' => (int) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
'cO' => 0.0,
'commission' => 0.0, //Consultar esto
'commissionPercentage' => 0.0, //Consultar esto
'complements' => null,
'currency' => [
'type' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['CurrencyCode'],
],
'equivFare' => 0.0,
'iva' => 0.0,
'otherDebit' => null,
'otherTax' => null,
'price' => (int) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
'providerPrice' => 0.0,
'qSe' => 0.0, //Consultar esto
'qSeIva' => 0.0,
'qse' => null,
'revenue' => 0.0,
'serviceCharge' => 0.0,
'sureCancel' => null,
'tA' => 0.0,
'taIva' => 0.0,
'tax' => 0.0,
'total' => (int) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
'yQ' => 0.0,
'yQiva' => 0.0,
'originalNationalCurrencyTotal' => (int) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->VehAvails->VehAvail->VehAvailCore->TotalCharge['RateTotalAmount'],
],
'passengerDataList' => [
[
'age' => 0,
'birthday' => '0001-01-01T00:00:00',
'fareData' => null,
'gender' => '',
'id' => '',
'lastName' => (string) $request->get('quotationLastname'),
'mail' => (string) $request->get('quotationEmail'),
'mothersName' => '',
'name' => (string) $request->get('quotationName'),
'passengerCode' => [
'accountCode' => '',
'promo' => false,
'realType' => 'ADT',
'type' => 'ADT',
],
'passengerContact' => null,
'passengerInsuranceInfo' => null,
'phone' => null,
'document' => null,
'typeDocument' => null,
],
],
'passengerNumber' => null,
'priceForPassenger' => false,
'priceType' => null,
'priority' => '',
'productType' => [
'description' => 'Vehiculo Renta de Automovil',
'typeProduct' => 'Vehicle',
],
'provider' => [
'category' => null,
'claveProveedor' => null,
'commissionPercentage' => 0,
'descripcionProveedor' => null,
'idProviders' => 0,
'name' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Vendor['CompanyShortName'],
'nuevoProveedor' => false,
'providerRef' => null,
'utilityMax' => 0,
'utilityMin' => 0,
],
'route' => [
'arrivalDate' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['ReturnDateTime'],
'arrivalDateString' => null,
'arrivalDescription' => ($sameCity) ? $dataCity->getDescription() : $dataCity2->getDescription(),
'arrivalIATA' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'],
'departureDate' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore['PickUpDateTime'],
'departureDateString' => null,
'departureDescription' => ($sameCity) ? (string) $dataCity->getDescription() : (string) $dataCity1->getDescription(),
'departureIATA' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'],
'destination' => null,
'flightTime' => null,
'origin' => null,
'providerCode' => null,
'subRoutes' => null,
],
'savedPassenger' => false,
'searchHost' => null,
'selected' => false,
'serviceProvider' => null,
'specialRequirements' => null,
'subcategory' => null,
'taxExists' => false,
'travelInsuranceExists' => false,
'vehicleData' => [
'departureAddress' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->PickUpLocation['LocationCode'],
'arrivalAddress' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehRentalCore->ReturnLocation['LocationCode'],
],
'visaInformationQuestion' => false,
'visaValidityQuestion' => false,
'productName' => 'Renta de Automovil',
'itinerary' => [
'accountCode' => null,
'bookingClass' => null,
'currency' => null,
'europeanFlight' => false,
'fareType' => null,
'gdsType' => null,
'insuranceCancelationExits' => false,
'insuranceCancelationValue' => 0,
'internationalFlight' => false,
'price' => null,
'promo' => false,
'requieredVisa' => false,
'seatsRemaining' => 0,
'segments' => null,
'ticketTimeLimit' => null,
'validatingCarrier' => null,
'txPrice' => null,
'txZone' => '',
'txDestination' => '',
'txDescription' => '',
],
'packageName' => (string) $data->Message->OTA_VehAvailRateRS->VehAvailRSCore->VehVendorAvails->VehVendorAvail->Vendor['CompanyShortName'],
],
'quote' => [
'channel' => 'B2C WEB',
],
];
$authorization = 'Authorization: Bearer '.$tokenApiQuotation;
//API URL
$url = $urlAddProductCar;
//create a new cURL resource
$ch = curl_init($url);
//setup request to send json via POST
$payload = json_encode($data_send);
$logSave->logSave(print_r($payload, true), 'CGS', 'RQCarCGS');
// print_r($payload);die;
//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'accept: application/json',
'authorization: Bearer '.$tokenApiQuotation,
'content-type: application/json',
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute the POST request
$result = curl_exec($ch);
$logSave->logSave(print_r($result, true), 'CGS', 'RSCarCGS');
//print_r($result);
//die;
//close CURL resource
curl_close($ch);
/*
* End API data send
*/
}
protected function authenticateUser(UserInterface $user, LoginManagerInterface $loginManager)
{
try {
$loginManager->loginUser(
'main',
$user
);
} catch (AccountStatusException $ex) {
// We simply do not authenticate users which do not pass the user
// checker (not enabled, expired, etc.).
}
}
protected function getCurrencyExchange(AviaturWebService $webService) {
$financialValue = [];
$productInfo = new PackageModel();
$hoy = date('Y-m-d');
$xmlTemplate = $productInfo->getTasaCambio($hoy);
$financial = $webService->callWebService('GENERALLAVE', 'dummy|http://www.aviatur.com.co/dummy/', $xmlTemplate);
$validate = false;
foreach ($financial->MENSAJE->TASAS_CAMBIO->ELEMENTO_TASA_CAMBIO as $tasa) {
if ('COP' == mb_strtoupper($tasa->MONEDA_DESTINO) && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
$financialValue[mb_strtoupper($tasa->MONEDA_ORIGEN)] = number_format((float) (($tasa->VALOR)), 2, '.', '');
$validate = true;
}
}
if (!$validate) {
$hoy = date('Y-m-d', strtotime('-1 day', strtotime(date('Y-m-d'))));
$xmlTemplate = $productInfo->getTasaCambio($hoy);
$financial = $webService->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) && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
$financialValue[mb_strtoupper($tasa->MONEDA_ORIGEN)] = number_format((float) (($tasa->VALOR)), 2, '.', '');
}
}
}
return $financialValue;
}
private function reorderCarsInfo($carsInfo){
foreach ($carsInfo as $key1 => $carInfo) {
$sizeCarInfo = sizeof($carInfo->VehAvails->VehAvail);
if($sizeCarInfo > 1){
for ($ii = $sizeCarInfo - 1; $ii > 0; $ii--) {
for ($jj = $ii - 1; $jj >= 0; $jj--) {
/* Para ir aplicando que no estén vacíos y que estén definidos */
if(isset($carsInfo[$key1]->VehAvails->VehAvail[$ii]) && isset($carsInfo[$key1]->VehAvails->VehAvail[$jj])){
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->Vehicle) != json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->Vehicle)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->RentalRate->VehicleCharges) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->RentalRate->VehicleCharges)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->RentalRate->RateQualifier->RateComments) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->RentalRate->RateQualifier->RateComments)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->RentalRate->RateQualifier['RateCategory']) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->RentalRate->RateQualifier['RateCategory'])){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->RentalRate->RateQualifier['RateQualifier']) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->RentalRate->RateQualifier['RateQualifier'])){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->RentalRate->RateQualifier->RateRestrictions) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->RentalRate->RateQualifier->RateRestrictions)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TotalCharge) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TotalCharge)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->Fees) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->Fees)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->Reference['Type']) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->Reference['Type'])){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->Reference['ID_Context']) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->Reference['ID_Context'])){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->Reference['DateTime']) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->Reference['DateTime'])){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->VendorLocation) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->VendorLocation)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->DropOffLocation) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->DropOffLocation)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->LocalRate) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->LocalRate)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->RateText) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->RateText)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->VendorLocation) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->VendorLocation)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->DropOffLocation) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->DropOffLocation)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->rateType) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->rateType)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->terms) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->terms)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailCore->TPA_Extensions->freeText) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailCore->TPA_Extensions->freeText)){
continue;
}
if(json_encode($carsInfo[$key1]->VehAvails->VehAvail[$ii]->VehAvailInfo->PricedCoverages) !== json_encode($carsInfo[$key1]->VehAvails->VehAvail[$jj]->VehAvailInfo->PricedCoverages)){
continue;
}
/* Al no cumplir con ninguno de los if, se determina que es igual y se elimina el objeto del índice ii */
unset($carsInfo[$key1]->VehAvails->VehAvail[$ii]);
break;
}
}
}
}
}
}
/**
* getIINRanges()
* Para obtener todos los rangos asociados a IIN de las franquicias activas, y estas se manejarán en variables globales con arrays de javascript
* Author: Ing. David Rincon
* Email: david.rincon@aviatur.com
* Date: 2025/03/06
* @param $em (Object of DB manager).
* @return array
*/
public function getIINRanges($em){
$iinRecords = $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findByActiveFranchises();
$iinRecordsArray = [];
$ccranges = [];
$ccfranchises = [];
foreach ($iinRecords as $key => $iinRecord) {
$paymentGatewayCode = $iinRecord["paymentgatewaycode"];
$description = $iinRecord["description"];
$description = strtoupper(str_replace(' ', '', trim($description)));
$stringRanges = $iinRecord["ranges"];
$ranges = json_decode($stringRanges, true);
$stringLengths = $iinRecord["lengths"];
$lengths = json_decode($stringLengths, true);
$luhn = $iinRecord["luhn"];
$cvvDigits = $iinRecord["cvvdigits"];
$tempLengths = [];
foreach ($lengths["lengths"] as $length) {
$tempLengths[] = array(0 => $length[0], 1 => (isset($length[1]) ? $length[1] : $length[0]));
}
$tempRecordArrayFranchises = [];
$tempRecordArrayFranchises["code"] = $paymentGatewayCode;
$tempRecordArrayFranchises["codename"] = $description;
$tempRecordArrayFranchises["luhn"] = $luhn;
$tempRecordArrayFranchises["length"] = $tempLengths;
$tempRecordArrayFranchises["cvvd"] = $cvvDigits;
$ccfranchises[$paymentGatewayCode] = $tempRecordArrayFranchises;
foreach ($ranges["ranges"] as $range) {
$tempRecordArrayRanges = [];
$tempRecordArrayRanges["range"][0] = $range[0];
$tempRecordArrayRanges["range"][1] = (isset($range[1]) ? $range[1] : $range[0]);
$tempRecordArrayRanges["minimum"] = strlen($range[0]);
$tempRecordArrayRanges["code"] = $paymentGatewayCode;
$ccranges[] = $tempRecordArrayRanges;
}
}
$iinRecordsArray = array("ccranges" => $ccranges, "ccfranchises" => $ccfranchises);
return $iinRecordsArray;
}
}