<?php
namespace Aviatur\ExperienceBundle\Controller;
use Aviatur\CustomerBundle\Services\ValidateSanctions;
use Aviatur\ExperienceBundle\Services\SearchExperienceCookie;
use Aviatur\GeneralBundle\Controller\OrderController;
use Aviatur\GeneralBundle\Entity\FormUserInfo;
use Aviatur\GeneralBundle\Models\GeneralModel;
use Aviatur\GeneralBundle\Services\AviaturEncoder;
use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
use Aviatur\GeneralBundle\Services\AviaturExperienceService;
use Aviatur\GeneralBundle\Services\AviaturMailer;
use Aviatur\GeneralBundle\Services\AviaturWebService;
use Aviatur\GeneralBundle\Services\ExceptionLog;
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\Services\CustomerMethodPaymentService;
use Aviatur\PaymentBundle\Services\TokenizerService;
use Aviatur\TwigBundle\Services\TwigFolder;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Security\LoginManagerInterface;
use Knp\Snappy\Pdf;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Cookie;
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\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Aviatur\GeneralBundle\Services\AviaturLogSave;
class ExperienceController extends AbstractController
{
/**
* @var \Doctrine\Persistence\ObjectManager
*/
protected $managerRegistry;
/**
* @var SessionInterface
*/
protected $session;
protected $agency;
public function __construct(ManagerRegistry $registry, SessionInterface $session)
{
$this->managerRegistry = $registry->getManager();
$this->session = $session;
$this->agency = $this->managerRegistry->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
}
public function searchAction()
{
return $this->redirect($this->generateUrl('aviatur_search_experiences', []));
}
public function availabilityAction(Request $request, TwigFolder $twigFolder, AviaturErrorHandler $errorHandler, AviaturWebService $webService, ExceptionLog $exceptionLog, SearchExperienceCookie $experienceCookie, $destination1, $date1 = null, $date2 = null, $trips)
{
$channel = [];
$providers = [];
$urlDescription = [];
$em = $this->managerRegistry;
$session = $this->session;
$server = $request->server;
$referer = $server->get('REQUEST_URI');
$fullRequest = $request;
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
$agency = $this->agency;
$configExperienceAgency = $em->getRepository(\Aviatur\ExperienceBundle\Entity\ConfigExperienceAgency::class)->findProviderForExperiencesWithAgency($agency);
$agencyFolder = $twigFolder->twigFlux();
if (!$configExperienceAgency || !isset($configExperienceAgency[0])) {
return $this->redirect($errorHandler->errorRedirectNoEmail('/buscar/experiencias', 'Busqueda de resultados', 'No podemos realizar la consulta ya que no existe un proveedor configurado para este servicio'));
} else {
$provider = $configExperienceAgency[0]->getProvider()->getProvideridentifier();
}
$info = [];
$channel['channel'] = $configExperienceAgency[0]->getChannel();
$OfficeId = explode('-', $configExperienceAgency[0]->getOfficeid());
$channel['officeId'] = $OfficeId[1];
$keyword='';
if (strlen($destination1) > 3) {
$keyword = $destination1;
} else {
$destinationObject = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchCities::class)->findOneByIata($destination1);
if ('' == $destinationObject) {
$destinationLabel=NULL;
$destinationObject = $em->getRepository(\Aviatur\SearchBundle\Entity\SearchAirports::class)->findOneByIata($destination1);
if ($destinationObject) {
$destination1 = $destinationObject->getSearchCities()->getIata();
$destinationLabel = $destinationObject->getCity().', '.$destinationObject->getCountry().' ('.$destinationObject->getIata().')';
}
} else {
$destinationLabel = $destinationObject->getCity().', '.$destinationObject->getCountry().' ('.$destinationObject->getIata().')';
}
}
if ($fullRequest->isXmlHttpRequest()) {
$tempDate1 = (null == $date1) ? date('Y-m-d') : $date1;
$info = [
'Start' => $tempDate1,
'End' => (null == $date2) ? $tempDate1 : $date2,
'Code' => $destination1,
'IdChannel' => $channel['channel'],
'OfficeId' => '',
'keywords' => (isset($keyword) && null != $keyword) ? str_replace('-', ' ', $keyword) : null,
'ProviderId' => $provider,
'referer' => $referer,
'destinationLabel' => $destinationLabel ?? null,
];
// var_dump($session->get('whitemark'));
// die;
if ('aviaseguros' == $session->get('whitemark')) {
if ('seguros' == $keyword) {
$info['IdChannel'] = 4;
$info['TypesOfService'] = 48;
}
}
$generalModel = new GeneralModel();
$xmlTemplateExperiences = $generalModel->getXmlExperiencesAvail($info);
$variableExperiences = [
'ProviderId' => $provider,
];
$responseExperiences = $webService->callWebServiceAmadeus('SERVICIO_MPT', 'SvcAvail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlTemplateExperiences, $variableExperiences, true);
//$responseExperiences = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\serviciosQ\experience\SvcAvailRS.xml')));
if (isset($responseExperiences['error'])) {
if (false === strpos($responseExperiences['error'], 'No se encontro información para la busqueda seleccionada')) {
$errorHandler->errorRedirect($requestUrl, 'Error disponibilidad buscador', $responseExperiences['error']);
}
return new Response($responseExperiences['error']);
}
$info['transactionId'] = (string) $responseExperiences->Message->OTAServiceAvailRS['TransactionIdentifier'];
$ExperiencesInfo = null;
foreach ($responseExperiences->Message->OTAServiceAvailRS->Service as $experience) {
$experience->TPA_Extensions->ProductInfo->Description = htmlspecialchars_decode($experience->TPA_Extensions->ProductInfo->Description);
$selectDate = strtotime($info['Start']);
$endDate = isset($experience) ? strtotime($experience->TPA_Extensions->ProductInfo->VigenciaFinal) : null;
$startDate = isset($experience) ? strtotime($experience->TPA_Extensions->ProductInfo->VigenciaInicial) : null;
if (($selectDate < $endDate /* && $selectDate > $startDate */)) {
$ExperiencesInfo[] = $experience;
}
}
$urlAvailability = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Experience/Default/AjaxAvailability.html.twig');
return $this->render($urlAvailability, [
'ExperiencesInfo' => $ExperiencesInfo,
'info' => $info,
]);
} else {
if ($configExperienceAgency) {
$providers[] = $configExperienceAgency[0]->getProvider()->getProvideridentifier();
} else {
$domain = $request->getHost();
$exceptionLog->log('Error Fatal', 'No se encontró la agencia segun el dominio: '.$domain, null, false);
return new Response('No se encontró agencias para consultar disponibilidad.');
}
$provider = implode(';', $providers);
$availabilityArray = [
'ProviderId' => $provider,
'destination' => (strlen($destination1) > 3) ? null : $destination1,
'searchInfoExperience' => (strlen($destination1) > 3) ? $destination1 : null,
'destinationLabel' => $destinationLabel ?? null,
];
if (null != $date1) {
$availabilityArray['date1'] = $date1;
}
if (null != $date2) {
$availabilityArray['date2'] = $date2;
}
$urlAvailability = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Experience/Default/availability.html.twig');
$safeUrl = 'https://'.$agency->getDomainsecure();
$cookieLastSearch = $experienceCookie->searchExperienceCookie(['experience' => base64_encode(json_encode($availabilityArray))]);
$pointRedemption = $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
if (null != $pointRedemption) {
$points = 0;
if ($fullRequest->request->has('pointRedemptionValue')) {
$points = $fullRequest->request->get('pointRedemptionValue');
$session->set('point_redemption_value', $points);
} elseif ($fullRequest->query->has('pointRedeem')) {
$points = $fullRequest->query->get('pointRedeem');
$session->set('point_redemption_value', $points);
} elseif ($session->has('point_redemption_value')) {
$points = $session->get('point_redemption_value');
}
$pointRedemption['Config']['Amount']['CurPoint'] = $points;
}
$seoUrl = $em->getRepository(\Aviatur\GeneralBundle\Entity\SeoUrl::class)->findByUrlorMaskedUrl($requestUrl);
$urlDescription['url'] = null != $seoUrl ? '/'.$seoUrl[0]->getUrl() : $requestUrl;
$response = $this->render($urlAvailability, [
'ajaxUrl' => $requestUrl,
'inlineEngine' => true,
'safeUrl' => $safeUrl,
'availabilityArray' => $availabilityArray,
'cookieLastSearch' => $cookieLastSearch,
'pointRedemption' => $pointRedemption,
'urlDescription' => $urlDescription,
]);
$response->headers->setCookie(new Cookie('_availability_array[experience]', base64_encode(json_encode($availabilityArray)), (time() + 3600 * 24 * 7), '/'));
return $response;
}
}
public function ajaxDetailAction(AviaturWebService $webService, $id, $startDate = null, $transactionId = false)
{
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$ProviderId = $em->getRepository(\Aviatur\ExperienceBundle\Entity\ConfigExperienceAgency::class)->findProviderForExperiencesWithAgency($agency)[0]->getProvider()->getProviderIdentifier();
$variableExperiences = ['ProviderId' => $ProviderId];
if (!$transactionId) {
$transactionId = $webService->loginService('SERVICIO_MPT', 'dummy|http://www.aviatur.com.co/dummy/', []);
}
$generalModel = new GeneralModel();
if (!$startDate) {
$startDate = date('Y-m-d');
}
$info = ['ID' => $id, 'Start' => $startDate, 'End' => ''];
$xmlTemplateExperiences = $generalModel->getXmlExperiencesDetail($info);
$responseExperiences = $webService->callWebServiceAmadeus('SERVICIO_MPT', 'SvcDetail', 'dummy|http://www.aviatur.com.co/dummy/', $xmlTemplateExperiences, $variableExperiences, false, $transactionId, false);
// $this->get("aviatur_log_save")->logSave(var_dump($responseExperiences), 'decksterr', 'xperience');
// die;
$infodetail = [
'UnitCostName' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->UnitCostName,
'CurrencyCode' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->CurrencyCode,
'CurrencyName' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->CurrencyName,
'ValorTotal' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Valor,
'Description' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Description,
'Email' => (string) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Email,
];
$images = [];
foreach ($responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Multimedia->ImageItems->ImageItem as $image) {
$images[] = ['URL' => (string) $image->Url, 'Name' => (string) $image->Name];
}
$dates = [];
$datesArray = [];
$daysBeforeReservation = (int) $responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->DiasAntesReserva + 1;
if ($startDate < date('Y-m-d', strtotime('+ '.$daysBeforeReservation.' days'))) {
$startDate = date('Y-m-d', strtotime('+ '.$daysBeforeReservation.' days'));
}
foreach ($responseExperiences->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Salidas->Salida as $date) {
if ('' != (string) $date['DepartureArrivalDate']) {
if ((string) $date['DepartureArrivalDate'] >= $startDate) {
$datesArray[] = (string) $date['DepartureArrivalDate'];
}
} else {
if ((string) $date['BeginDate'] > $startDate) {
$begin = new \DateTime((string) $date['BeginDate']);
} else {
$begin = new \DateTime($startDate);
}
$end = new \DateTime((string) $date['EndDate']);
$interval = \DateInterval::createFromDateString('1 day');
$period = new \DatePeriod($begin, $interval, $end);
foreach ($period as $dt) {
$datesArray[] = $dt->format('Y-m-d');
}
if (empty($dates)) {
$datesArray[0] = $period->start->format('Y-m-d');
}
}
}
asort($datesArray);
foreach ($datesArray as $key => $val) {
$dates[] = $val;
}
$cautions = [];
foreach ($responseExperiences->Message->OTAServiceAvailRS->Service->Cautions->Caution as $caution) {
$cautions[] = ['Type' => (string) $caution['ID'], 'Info' => (string) $caution];
}
$infoFares = ['ID' => $id, 'Start' => $dates[0], 'End' => $dates[4] ?? $dates[sizeof($dates) - 1] ?? $dates[0]];
$xmlTemplateExperiencesFares = $generalModel->getXmlExperiencesFares($infoFares);
$responseExperiencesFares = $webService->callWebServiceAmadeus('SERVICIO_MPT', 'SvcFares', 'dummy|http://www.aviatur.com.co/dummy/', $xmlTemplateExperiencesFares, $variableExperiences, false, $transactionId, false);
$fares = [];
foreach ($responseExperiencesFares->Message->OTAServiceAvailRS->Service->Items->Item->Provider->PropertyProfiles->PropertyProfile as $fare) {
if ($startDate >= (string) $fare['EffectiveDate'] && $startDate <= (string) $fare['ExpireDate']) {
$fare['PropertyCategory'] ??= 'General';
$fares[(string) $fare['PropertyCategory']][(string) $fare['PropertyType']] = [
'Count' => (string) $fare->Prices->Price['Count'],
'CurrencyCode' => (string) $fare->Prices->Price['CurrencyCode'],
'PriceBasis' => (string) $fare->Prices->Price['PriceBasis'],
'DecimalPlaces' => (string) $fare->Prices->Price['DecimalPlaces'],
'PriceQualifier' => (string) $fare->Prices->Price['PriceQualifier'],
'Amount' => (string) $fare->Prices->Price['Amount'],
'AmountSpecified' => (string) $fare->Prices->Price['AmountSpecified'],
'RangeMaximum' => (string) $fare->Prices->Price['RangeMaximum'],
'RangeMinimum' => (string) $fare->Prices->Price['RangeMinimum'],
'Description' => (string) $fare['Description'],
];
$fares[(string) $fare['PropertyCategory']]['StartDate'] = (string) $fare['EffectiveDate'];
$fares[(string) $fare['PropertyCategory']]['EndDate'] = (string) $fare['ExpireDate'];
}
}
$dateFares = [];
for ($i = 0; $i <= (isset($dates[4]) ? 4 : sizeof($dates) - 1); ++$i) {
foreach ($fares as $fareKey => $fare) {
if (/* $fare["StartDate"] <= $dates[$i] && */$fare['EndDate'] >= $dates[$i]) {
$dateFares[$dates[$i]][$fareKey] = $fare;
unset($dateFares[$dates[$i]][$fareKey]['StartDate']);
unset($dateFares[$dates[$i]][$fareKey]['EndDate']);
}
}
}
$attributes = [];
$sessionAttributes = ['operatorId', 'whitemark', 'special_campaing', 'typeCoin', 'typeCountry', 'CoinValue', 'financialValue', 'trmValue', 'RateChange', 'RateDiff'];
foreach ($sessionAttributes as $attribute) {
if ($session->has($attribute)) {
$attributes['session'][$attribute] = $session->get($attribute);
}
}
//agrupar por propertyCategory como inicial
return $this->json(['infodetail' => base64_encode(json_encode($infodetail)), 'images' => base64_encode(json_encode($images)), 'dates' => $dates, 'cautions' => base64_encode(json_encode($cautions)), 'fares' => $fares, 'dateFares' => $dateFares, 'attributes' => $attributes]);
}
public function detailAction(Request $request, TwigFolder $twigFolder, LoginManagerInterface $loginManager, ParameterBagInterface $parameterBag, AviaturErrorHandler $errorHandler, AviaturWebService $webService, TokenStorageInterface $tokenStorage, CustomerMethodPaymentService $methodPaymentService, $id = null, $date = null, $adults = null, $children = null)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$exchangeValues = null;
$postData = null;
$responseExperiences = [];
$fullRequest = $request;
$request = $fullRequest->request;
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$agencyFolder = $twigFolder->twigFlux();
$passengerTypes = [];
$productInfo = new PackageModel();
$generalModel = new GeneralModel();
if (true === $request->has('whitemarkDataInfo')) {
$session->set('whitemarkDataInfo', json_decode($request->get('whitemarkDataInfo'), true));
}
if (true === $request->has('userLogin') && '' != $request->get('userLogin') && null != $request->get('userLogin')) {
$user = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneByEmail($request->get('userLogin'));
$this->authenticateUser($user, $loginManager);
}
if ($request->has('transactionID')) {
$transactionId = $request->get('transactionID');
$session->set($transactionIdSessionName, $transactionId);
$session->set($transactionId.'[experience][availability_url]', $fullRequest->server->get('HTTP_REFERER'));
} elseif ($session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
if ('POST' == $fullRequest->getMethod()) {
$session->set('redirectedRetry', false);
} else {
$loadInfo = json_decode($this->ajaxDetailAction($webService, $id, $date, $transactionId)->getContent(), true);
$images = json_decode(base64_decode($loadInfo['images']));
$cautions = json_decode(base64_decode($loadInfo['cautions']));
$infodetail = json_decode(base64_decode($loadInfo['infodetail']));
}
} else {
if (empty($id) || empty($date)) {
return new Response('error');
} else {
$transactionId = $webService->loginService('SERVICIO_MPT', 'dummy|http://www.aviatur.com.co/dummy/', []);
$session->set($transactionIdSessionName, $transactionId);
$loadInfo = json_decode($this->ajaxDetailAction($webService, $id, $date, $transactionId)->getContent(), true);
$images = json_decode(base64_decode($loadInfo['images']));
$cautions = json_decode(base64_decode($loadInfo['cautions']));
$infodetail = json_decode(base64_decode($loadInfo['infodetail']));
}
}
if ('' != $request->get('ProviderId')) {
$session->set($transactionId.'[experience][ProviderId]', $request->get('ProviderId'));
$ProviderId = $request->get('ProviderId');
} else {
if (isset($transactionId) && $session->has($transactionId.'[experience][ProviderId]')) {
$ProviderId = $session->get($transactionId.'[experience][ProviderId]');
} else {
$ProviderId = $em->getRepository(\Aviatur\ExperienceBundle\Entity\ConfigExperienceAgency::class)->findProviderForExperiencesWithAgency($agency)[0]->getProvider()->getProviderIdentifier();
}
}
$provider = $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findOneByProvideridentifier($ProviderId);
$paymentType = $provider->getPaymentType()->getTwig();
$repositoryDocumentType = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
$queryDocumentType = $repositoryDocumentType
->createQueryBuilder('p')
->where('p.paymentcode != :paymentcode')
->setParameter('paymentcode', '')
->getQuery();
$documentPaymentType = $queryDocumentType->getResult();
$paymentMethodAgency = $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency, 'isactive' => 1]);
$paymentOptions = [];
foreach ($paymentMethodAgency as $payMethod) {
$paymentCode = $payMethod->getPaymentMethod()->getCode();
if (!in_array($paymentCode, $paymentOptions) && 'davivienda' != $paymentCode) {
$paymentOptions[] = $paymentCode;
}
}
$banks = [];
if (in_array('pse', $paymentOptions)) {
$banks = $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
}
$cybersource = [];
if (in_array('cybersource', $paymentOptions)) {
$cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource', $paymentOptions)]->getSitecode();
$cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource', $paymentOptions)]->getTrankey();
}
foreach ($paymentOptions as $key => $paymentOption) {
if ('cybersource' == $paymentOption) {
unset($paymentOptions[$key]); // strip from other renderizable payment methods
}
}
if ($session->has($transactionId.'[experience][retry]')) {
$twigVariables = json_decode($session->get($transactionId.'[experience][detailVariables]'), true);
$postData = json_decode($session->get($transactionId.'[experience][detail_data]'));
$conditions = $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'reservation_conditions_for_hotels');
$twig_readonly = true;
$twigVariables['twig_readonly'] = $twig_readonly;
$twigVariables['passengers'] = $postData->PI;
$twigVariables['billingData'] = $postData->BD;
$twigVariables['contactData'] = $postData->CD;
if (isset($postData->OD)) {
$twigVariables['observations'] = $postData->OD->notes;
}
$twigVariables['cards'] = $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]);
$twigVariables['inactiveCards'] = $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]);
$twigVariables['banks'] = $banks;
$twigVariables['cybersource'] = $cybersource;
$twigVariables['paymentOptions'] = $paymentOptions;
$twigVariables['payment_doc_type'] = $documentPaymentType;
$twigVariables['cybersource'] = $cybersource;
$twigVariables['doc_type'] = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$twigVariables['gender'] = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
$twigVariables['gconditionsender'] = $conditions;
$twigVariables['payment_type_form_name'] = $paymentType;
} else {
$twig_readonly = false;
$passengerTypes = [
1 => [
'ADT' => ('' != $request->get('adults')) ? (int) $request->get('adults') : ($adults ?? 1),
'CHD' => ('' != $request->get('children')) ? (int) $request->get('children') : ($children ?? 0),
'INF' => 0,
],
];
$info = [
'ID' => ('' == $request->get('packageCode')) ? $id : $request->get('packageCode'),
'Start' => ('' == $request->get('date1')) ? $date : $request->get('date1'),
'End' => ('' == $request->get('date2')) ? (('' == $request->get('date1')) ? $date : $request->get('date1')) : $request->get('date2'),
'date1' => ('' == $request->get('date1')) ? $date : $request->get('date1'),
'date2' => ('' == $request->get('date2')) ? (('' == $request->get('date1')) ? $date : $request->get('date1')) : $request->get('date2'),
'Code' => $request->get('destination'),
'passangerTypes' => $passengerTypes,
];
$variableExperiences = ['ProviderId' => $ProviderId];
$session->set($transactionId.'[experiences][args]', json_encode($info));
$validateChild = 0;
$count = 0;
$validateRph = 0;
$dias = (strtotime($info['Start']) - strtotime(date('Y-m-d'))) / 86400;
$xmlTemplateExperiencesFares = $generalModel->getXmlExperiencesFares($info);
$itemcount = ('' != $request->get('itemcount')) ? explode(',', $request->get('itemcount')) : '';
$parameters = json_decode($session->get($session->get('domain').'[parameters]'));
$webService->setUrls($parameters);
$responseExperiencesFares = $webService->callWebServiceAmadeus('SERVICIO_MPT', 'SvcFares', 'dummy|http://www.aviatur.com.co/dummy/', $xmlTemplateExperiencesFares, $variableExperiences, false, $transactionId, false);
//$responseExperiencesFares = simplexml_load_string(str_replace(['mpa:', 'soap:'], '', file_get_contents('C:\serviciosQ\experience\SvcFaresRS.xml')));
if (!isset($responseExperiencesFares['error'])) {
$infodetail = !isset($infodetail) ? json_decode(base64_decode($request->get('infodetail'))) : $infodetail;
$cautions = !isset($cautions) ? json_decode(base64_decode($request->get('cautions'))) : $cautions;
$images = !isset($images) ? json_decode(base64_decode($request->get('images'))) : $images;
$session->set($transactionId.'[experience][detailInfo]', $cautions);
$typeDocument = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$typeGender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
$conditions = $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'reservation_conditions_for_hotels');
$totalPassengers = $passengerTypes[1]['ADT'] + $passengerTypes[1]['CHD'];
$profilesServices = [];
if ($responseExperiencesFares) {
foreach ($responseExperiencesFares->Message->OTAServiceAvailRS->Service as $serviceFare) {
//$DiasAntesReserva = (int) $serviceDetail->TPA_Extensions->ProductInfo->DiasAntesReserva;
// if ($DiasAntesReserva >= $dias) {
// return $this->redirect($this->get("aviatur_error_handler")->errorRedirect(($fullRequest->server->get('HTTP_REFERER') != '') ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar', 'Este producto debe reservarse con minimo ' . $DiasAntesReserva . ' dĆas antes de la entrada.'));
// }
$responseExperiencesFares->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->Description = $infodetail->Description;
$totalAmount[0] = (int) $infodetail->ValorTotal;
$baseAmount[0] = (int) 0;
$tax[0] = (int) 0;
$percentage[0] = (int) 0;
$legend[0] = (string) $serviceFare->TPA_Extensions->ProductInfo->Description;
$PassengerExperienceDetail[0]['ImageItem'] = $images;
$PassengerExperienceDetail[0]['ID'] = (int) $serviceFare['ID'];
$PassengerExperienceDetail[0]['ProductName'] = (string) $serviceFare->TPA_Extensions->ProductInfo->ProductName;
$PassengerExperienceDetail[0]['UnitCostName'] = (string) $infodetail->UnitCostName;
$PassengerExperienceDetail[0]['CurrencyCode'] = (string) $infodetail->CurrencyCode;
$PassengerExperienceDetail[0]['CurrencyName'] = (string) $infodetail->CurrencyName;
$PassengerExperienceDetail[0]['FormaVenta'] = (string) $serviceFare->TPA_Extensions->ProductInfo->FormaVenta;
$PassengerExperienceDetail[0]['Description'] = (string) $serviceFare->TPA_Extensions->ProductInfo->Description;
$PassengerExperienceDetail[0]['ClaseServicio'] = (string) $serviceFare->TPA_Extensions->ProductInfo->ClaseServicio;
$PassengerExperienceDetail[0]['ValorTotal'] = (int) $infodetail->ValorTotal;
$PassengerExperienceDetail[0]['Email'] = (string) $infodetail->Email;
$PassengerExperienceDetail[0]['cautions'] = $cautions;
if (isset($serviceFare->Items->Item->Provider->PropertyProfiles)) {
$PassengerExperienceDetail[0]['BrandCode'] = (string) $serviceFare->Items->Item->Provider->Identity['BrandCode'];
$PassengerExperienceDetail[0]['HotelCode'] = (string) $serviceFare->Items->Item->Provider->Identity['HotelCode'];
$PassengerExperienceDetail[0]['HotelName'] = (string) $serviceFare->Items->Item->Provider->Identity['HotelName'];
$PassengerExperienceDetail[0]['ResortCode'] = (string) $serviceFare->Items->Item->Provider['ResortCode'];
$PassengerExperienceDetail[0]['ResortName'] = (string) $serviceFare->Items->Item->Provider['ResortName'];
$PassengerExperienceDetail[0]['DestinationCode'] = (string) $serviceFare->Items->Item->Provider['DestinationCode'];
$PassengerExperienceDetail[0]['DestinationName'] = (string) $serviceFare->Items->Item->Provider['DestinationName'];
foreach ($serviceFare->Items->Item->Provider->PropertyProfiles->PropertyProfile as $PropertyProfiles) {
$rph = (int) $PropertyProfiles['RPH'];
$rphInfo[] = $rph;
$PropertyTypeCode = (int) $PropertyProfiles['PropertyTypeCode'];
$Quantity = (string) $PropertyProfiles['CotQuantity'];
$PropertyViewCode = (string) $PropertyProfiles['PropertyViewCode'];
$PassengerExperienceDetail[0]['PropertyViewCode'] = $PropertyViewCode;
if ('True' == (string) $PropertyProfiles['FreeChildFlag']) {
++$validateChild;
}
if ('' != $request->get('itemcount')) {
if (in_array($PropertyProfiles['PropertyTypeCode'], $itemcount)) {
foreach ($PropertyProfiles->Prices as $prices) {
if ((string) $PropertyProfiles['EffectiveDate'] <= $date && (string) $PropertyProfiles['ExpireDate'] >= $date) {
if (isset($passengerTypes[1][(string) $prices->Price['PriceQualifier']])) {
$quantity = $passengerTypes[1][(string) $prices->Price['PriceQualifier']];
} else {
$quantity = $totalPassengers;
}
if ((int) $prices->Price['RangeMaximum'] >= $quantity && (int) $prices->Price['RangeMinimum'] <= $quantity) {
if ($totalPassengers > $rph && 'true' == (string) $responseExperiencesFares->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->FormaVenta) {
++$validateRph;
continue;
}
if (false === strpos((string) $prices->Price['WeekDay'], date('N', strtotime($info['date1'])))) {
$dias_ES = ['Lunes', 'Martes', 'MiƩrcoles', 'Jueves', 'Viernes', 'SƔbado', 'Domingo'];
$dias_EN = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
$nombredia = str_replace($dias_EN, $dias_ES, date('l', strtotime($info['date1'])));
return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar', 'Los dias '.$nombredia.' no hay servicio'));
}
$profilesServices[] = $PropertyProfiles;
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Count'.$PropertyTypeCode] = (int) $prices->Price['Count'];
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Amount'.$PropertyTypeCode] = (int) $prices->Price['Amount'];
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Quantity'.$PropertyTypeCode] = $Quantity;
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['CurrencyCode'.$PropertyTypeCode] = (string) $prices->Price['CurrencyCode'];
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['RPH'.$PropertyTypeCode] = $rph;
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Age'.$PropertyTypeCode] = (int) $prices->Price['RangeMinimum'];
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['AgeEnd'.$PropertyTypeCode] = (int) $prices->Price['RangeMaximum'];
if (isset($info['passangerTypes'][1][(string) $prices->Price['PriceQualifier']]) && $info['passangerTypes'][1][(string) $prices->Price['PriceQualifier']] > 0) {
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Unity'.$PropertyTypeCode] = (string) $prices->Price['PriceQualifier'];
} elseif (!isset($prices->Price['PriceQualifier']) && isset($prices->Price['PriceBasis'])) {
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Unity'.$PropertyTypeCode] = (string) $prices->Price['PriceBasis'];
} else {
continue;
}
}
}
}
}
} else {
foreach ($PropertyProfiles->Prices as $prices) {
if ((string) $PropertyProfiles['EffectiveDate'] <= $date && (string) $PropertyProfiles['ExpireDate'] >= $date) {
if (isset($passengerTypes[1][(string) $prices->Price['PriceQualifier']])) {
$quantity = $passengerTypes[1][(string) $prices->Price['PriceQualifier']];
} else {
$quantity = $totalPassengers;
}
if ((int) $prices->Price['RangeMaximum'] >= $quantity && (int) $prices->Price['RangeMinimum'] <= $quantity) {
if ($totalPassengers > $rph && 'true' == (string) $responseExperiencesFares->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->FormaVenta) {
++$validateRph;
continue;
}
if (false === strpos((string) $prices->Price['WeekDay'], date('N', strtotime($info['date1'])))) {
$dias_ES = ['Lunes', 'Martes', 'MiƩrcoles', 'Jueves', 'Viernes', 'SƔbado', 'Domingo'];
$dias_EN = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
$nombredia = str_replace($dias_EN, $dias_ES, date('l', strtotime($info['date1'])));
return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar', 'Los dias '.$nombredia.' no hay servicio'));
}
$profilesServices[] = $PropertyProfiles;
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Count'.$PropertyTypeCode] = (int) $prices->Price['Count'];
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Amount'.$PropertyTypeCode] = (int) $prices->Price['Amount'];
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Quantity'.$PropertyTypeCode] = $Quantity;
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['CurrencyCode'.$PropertyTypeCode] = (string) $prices->Price['CurrencyCode'];
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['RPH'.$PropertyTypeCode] = $rph;
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Age'.$PropertyTypeCode] = (int) $prices->Price['RangeMinimum'];
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['AgeEnd'.$PropertyTypeCode] = (int) $prices->Price['RangeMaximum'];
if (isset($info['passangerTypes'][1][(string) $prices->Price['PriceQualifier']]) && $info['passangerTypes'][1][(string) $prices->Price['PriceQualifier']] > 0) {
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Unity'.$PropertyTypeCode] = (string) $prices->Price['PriceQualifier'];
} elseif (!isset($prices->Price['PriceQualifier']) && isset($prices->Price['PriceBasis'])) {
$PassengerExperienceDetail[0]['Prices'][$PropertyTypeCode]['Unity'.$PropertyTypeCode] = (string) $prices->Price['PriceBasis'];
} else {
continue;
}
}
}
}
}
++$count;
}
if ($validateRph >= $count) {
return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar', 'Este producto posee '.max($rphInfo).' cupo(s) disponibles'));
}
$infoExperience[0] = $this->generateReturn([$totalAmount[0], $baseAmount[0], $tax[0], $percentage[0], $totalAmount[0]], $legend[0], ['ExperienceDetail' => $PassengerExperienceDetail[0]]);
$infoExperience[0]['values'] = $infoExperience[0];
} else {
return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar', 'Hubo un problema al realizar el cƔlculo de tu producto'));
}
}
}
if (empty($profilesServices)) {
return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar', 'No hay tarifas disponibles para la fecha seleccionada o para la cantidad de pasajeros'));
}
//elseif($validateChild == 0 && $passengerTypes[1]['CHD'] > 0){
//return $this->redirect($this->get("aviatur_error_handler")->errorRedirect(($fullRequest->server->get('HTTP_REFERER') != '') ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar', 'No se permiten niƱos para este producto'));
//}
$passengerTypes[1]['countDate'] = is_countable($date) ? count($date) : 0;
$rateExperiences = $this->rateExperience($profilesServices, $passengerTypes[1]);
if (isset($rateExperiences['error'])) {
return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_search_experiences'), 'Error al tarificar', $rateExperiences['error']));
}
$rpm = 1;
if (isset($rateExperiences['Amount']) && 'COP' != mb_strtoupper((string) $infodetail->CurrencyCode) && 'true' == (string) $responseExperiencesFares->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->FormaVenta) {
$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) && mb_strtoupper((string) $infodetail->CurrencyCode) == $tasa->MONEDA_ORIGEN && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
$financialValue = (int) $tasa->VALOR;
$exchangeValues = [
'MONEDA_ORIGEN' => (string) $tasa->MONEDA_ORIGEN,
'TIPO_TASA_CAMBIO' => (string) $tasa->TIPO_TASA_CAMBIO,
];
$validate = true;
}
}
if (!$validate) {
$hoy = date('Y-m-d', strtotime('-1 day', strtotime(date('Y-m-d'))));
$xmlTemplate = $productInfo->getTasaCambio($hoy);
$financial = $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) && mb_strtoupper((string) $infodetail->CurrencyCode) == $tasa->MONEDA_ORIGEN && 'FIN' == mb_strtoupper($tasa->TIPO_TASA_CAMBIO)) {
$financialValue = (int) $tasa->VALOR;
$exchangeValues = [
'MONEDA_ORIGEN' => (string) $tasa->MONEDA_ORIGEN,
'TIPO_TASA_CAMBIO' => (string) $tasa->TIPO_TASA_CAMBIO,
];
}
}
}
if (!isset($financialValue) || !is_numeric($financialValue)) {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_experience_search'), 'Error en la conversión de moneda', ''));
} else {
$rpm = $financialValue;
$AmountTotal = min(array_filter($rateExperiences['Amount'])) * $financialValue;
$session->set('[mpt][finantial_rate]', $financialValue);
$session->set($transactionId.'[mpt][exchangeValues]', json_encode($exchangeValues));
}
} else {
$AmountTotal = min(array_filter($rateExperiences['Amount']));
}
$pointRedemption = $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
if (null != $pointRedemption) {
$points = 0;
if ($fullRequest->request->has('pointRedemptionValue')) {
$points = $fullRequest->request->get('pointRedemptionValue');
$session->set('point_redemption_value', $points);
} elseif ($fullRequest->query->has('pointRedeem')) {
$points = $fullRequest->query->get('pointRedeem');
$session->set('point_redemption_value', $points);
} elseif ($session->has('point_redemption_value')) {
$points = $session->get('point_redemption_value');
}
$pointRedemption['Config']['Amount']['CurPoint'] = $points;
}
if (isset($postData->cusPOptSelected)) {
//$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData->id);
//$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData->id);
$customerLogin = $tokenStorage->getToken()->getUser();
if (is_object($customerLogin)) {
$paymentsSaved = $methodPaymentService->getMethodsByCustomer($customerLogin, false);
}
}
$twigVariables = [
'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]),
'inactiveCards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]),
'banks' => $banks,
'cybersource' => $cybersource,
'paymentOptions' => $paymentOptions,
'payment_doc_type' => $documentPaymentType,
'twig_readonly' => $twig_readonly,
'doc_type' => $typeDocument,
'gender' => $typeGender,
'services' => $passengerTypes,
'profilesServices' => $profilesServices,
'rateExperiences' => $rateExperiences['optionsList'],
'transactionId' => base64_encode($transactionId),
'CriteoTags' => null,
'conditions' => $conditions,
'serviceResponse' => $responseExperiencesFares->Message->OTAServiceAvailRS->Service,
'payment_type_form_name' => $paymentType,
'referer' => ('' != $request->get('referer')) ? $request->get('referer') : $fullRequest->server->get('REQUEST_URI'),
'amount' => min(array_filter($rateExperiences['Amount'])),
'AmountTotal' => $AmountTotal,
'currency' => (string) $infodetail->CurrencyCode,
'info' => $info,
'rpm' => $rpm,
'infoExperience' => $infoExperience,
'FormaVenta' => (string) $responseExperiencesFares->Message->OTAServiceAvailRS->Service->TPA_Extensions->ProductInfo->FormaVenta,
'pointRedemption' => $pointRedemption,
'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
'Email' => $infodetail->Email,
];
$twigVariables['pse'] = true;
$twigVariables['safety'] = true;
$session->set($transactionId.'[experience][detailVariables]', json_encode($twigVariables));
$agencyFolder = $twigFolder->twigFlux();
} else {
$message = $responseExperiences['error'] ?? 'Ha ocurrido un error inesperado';
return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_general_homepage'), 'PƔgina no accesible', $message));
}
}
if (empty($twigVariables['rateExperiences'])) {
$message = 'Por favor cambia los filtros de busqueda para este producto';
return $this->redirect($errorHandler->errorRedirect(('' != $fullRequest->server->get('HTTP_REFERER')) ? $fullRequest->server->get('HTTP_REFERER') : $this->generateUrl('aviatur_general_homepage'), 'Error en las tarifas', $message));
}
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Experience/Default/detail.html.twig'), $twigVariables);
}
public function prePaymentStep1Action(Request $request, ParameterBagInterface $parameterBag, TwigFolder $twigFolder, AviaturErrorHandler $errorHandler, AviaturEncoder $aviaturEncoder, TokenizerService $tokenizerService, AviaturWebService $webService, ExceptionLog $exceptionLog, SearchExperienceCookie $experienceCookie, TokenStorageInterface $tokenStorage, CustomerMethodPaymentService $methodPaymentService)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
if ($request->isXmlHttpRequest()) {
$session = $this->session;
$transactionId = $session->get($transactionIdSessionName);
$billingData = $request->get('BD');
$em = $this->managerRegistry;
$postData = $request->request->all();
$publicKey = $aviaturEncoder->aviaturRandomKey();
/* if (isset($postData['PD']['card_num'])) {
$postDataInfo = $postData;
$postDataInfo['PD']['card_num'] = $this->get('aviatur_tokenizer')->getToken($postData['PD']['card_num']);
$postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
} */
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']];
$postDataInfo['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.'[experience][user_info]', $formUserInfo->getId());
if ((true !== $session->has($transactionId.'[experience][retry]')) || (true !== $session->has($transactionId.'[experience][prepayment_check]'))) {
if ($session->has($transactionId.'[experience][detailVariables]')) {
//$postData = $request->all(); |
$passangersData = $request->get('PI');
$passangerNames = [];
for ($i = 1; $i <= $passangersData['person_count_1']; ++$i) {
$passangerNames[] = mb_strtolower($passangersData['first_name_1_'.$i]);
$passangerNames[] = mb_strtolower($passangersData['last_name_1_'.$i]);
}
$nameWhitelist = $em->getRepository(\Aviatur\GeneralBundle\Entity\NameWhitelist::class)->findLikeWhitelist($passangerNames);
if (0 == sizeof($nameWhitelist)) {
$nameBlacklist = $em->getRepository(\Aviatur\GeneralBundle\Entity\NameBlacklist::class)->findLikeBlacklist($passangerNames);
if ((sizeof(preg_grep("/^[a-z- *\.]+$/", $passangerNames)) != (sizeof($passangerNames))) ||
(sizeof($nameBlacklist)) ||
(sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/', $passangerNames)))) {
return $this->json(['error' => 'error', 'message' => 'nombre invƔlido']);
}
}
$isFront = $session->has('operatorId');
if ($isFront) {
$customer = null;
$ordersProduct = null;
} else {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
$ordersProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPending($customer);
}
if (null == $ordersProduct) {
$documentTypes = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$arrayDocumentTypes = [];
foreach ($documentTypes as $documentType) {
$arrayDocumentTypes[$documentType->getExternalCode()] = $documentType->getId();
}
$genders = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
$arrayGenders = [];
foreach ($genders as $gender) {
$arrayGenders[$gender->getCode()] = $gender->getExternalCode();
}
$session->set($transactionId.'[experience][retry]', $parameterBag->get('aviatur_payment_retry_times'));
$detail = $session->get($transactionId.'[experience][detailVariables]');
$session->set($transactionId.'[experience][prepayment]', $detail);
$cancelPenalties = (string) '';
$ajaxUrl = $this->generateUrl('aviatur_experience_prepayment_step_2_secure');
return $this->json(['cancelPenalties' => $cancelPenalties, 'ajax_url' => $ajaxUrl]);
} else {
$booking = [];
$cus = [];
foreach ($ordersProduct as $orderProduct) {
$productResponse = $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
$paymentResponse = json_decode($productResponse);
array_push($booking, 'ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId());
if (isset($paymentResponse->x_approval_code)) {
array_push($cus, $paymentResponse->x_approval_code);
} elseif (isset($paymentResponse->createTransactionResult->trazabilityCode)) {
array_push($cus, $paymentResponse->createTransactionResult->trazabilityCode);
}
}
return $this->json([
'error' => 'pending payments',
'message' => 'pending_payments',
'booking' => $booking,
'cus' => $cus,
]);
}
} else {
return $this->json(['error' => 'fatal', 'message' => $errorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos información del detalle de tu búsqueda, por favor vuelve a intentarlo')]);
}
} else {
$paymentData = $request->get('PD');
$paymentData = json_decode(json_encode($paymentData));
$detailVariables = json_decode($session->get($transactionId.'[experience][detailVariables]'));
$json = json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
if (!is_null($json)) {
$json->ajax_url = $this->generateUrl('aviatur_experience_prepayment_step_2_secure');
// reemplazar datos de pago por los nuevos.
$oldPostData = json_decode($session->get($transactionId.'[experience][detail_data]'));
//$card_num_token = $tokenizerService->getToken($paymentData->card_num);
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.'[experience][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 vuelve a intentarlo')]);
}
}
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado'));
}
}
public function prePaymentStep2Action(Request $request, ParameterBagInterface $parameterBag, TwigFolder $twigFolder, AviaturErrorHandler $errorHandler, AviaturExperienceService $experienceService)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$order = [];
$infoDates = [];
if ($request->isXmlHttpRequest()) {
$em = $this->managerRegistry;
$session = $this->session;
$agency = $this->agency;
$billingData = $request->get('BD');
$transactionId = $session->get($transactionIdSessionName);
$session->set($transactionId.'[experience][prepayment_check]', true);
$detailVariables = json_decode($session->get($transactionId.'[experience][detailVariables]'));
if (true !== $session->has($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']')) {
if ($session->has($transactionId.'[experience][detailVariables]')) {
$isFront = $session->has('operatorId');
if ($isFront) {
$customer = $billingData;
$customer['isFront'] = true;
$status = 'B2T';
} else {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
$status = 'waiting';
}
if (isset($agency)) {
$experienceService->createExtraExperience($detailVariables->infoExperience, $request, $transactionId);
$infoDates = json_decode($session->get($transactionId.'[experience][infoDates]['.$detailVariables->infoExperience[0]->id.']'), true);
$postData = json_decode($session->get($transactionId.'[experience][detail_data]'));
$order = json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'), true);
$orderId = str_replace('ON', '', $order['order']);
$orderEntity = $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
$formUserInfo = $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[experience][user_info]'));
$formUserInfo->setOrder($orderEntity);
$em->persist($formUserInfo);
$em->flush();
if ($isFront) {
$order['url'] = $this->makeReservation($transactionId);
} else {
if ('true' == (string) $detailVariables->infoExperience[0]->info->ExperienceDetail->FormaVenta) {
$order['url'] = $this->generateUrl('aviatur_experience_payment_secure');
} else {
$orderProductCode = json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
$productId = str_replace('PN', '', $orderProductCode->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$ratePlan = explode('@||', $postData->EI->ratePlan);
foreach ($detailVariables->rateExperiences as $rateExperiences) {
$code = explode('@||', $rateExperiences->Code);
if ($code[0] === $ratePlan[0] && $code[1] === $ratePlan[1]) {
$x_total_amount = $rateExperiences->Amount;
}
}
if (empty($x_total_amount)) {
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '', 'Ocurrio un error al tarificar, por favor intenta nuevamente o comunĆcate con nosotros para finalizar tu transacción'));
} else {
$infoDates['AmountTotal'] = $x_total_amount;
$session->set($transactionId.'[experience][infoDates]['.$detailVariables->infoExperience[0]->id.']', json_encode($infoDates));
}
$experienceService->xmlExperienceExtra($transactionId, $detailVariables->infoExperience[0]->id, $orderProduct->getStatus(), false, false);
$EmitirSolicitud = $experienceService->EmitirSolicitud($orderProduct, $detailVariables->infoExperience[0]->id, true);
// Obtener el valor almacenado en la sesión
$storedVariables = $session->get($transactionId . '[experience][detailVariables]');
// Decodificar el JSON si es necesario
$detailVariables = json_decode($storedVariables, true);
$FormaVenta = $detailVariables['FormaVenta'] ?? null;
// dd($transactionId, $detailVariables->infoExperience[0]->id, $orderProduct->getStatus());
if ('Ok' == $EmitirSolicitud) {
$twig = 'aviatur_experience_reservation_success_secure';
} elseif('false' == $FormaVenta and isset($FormaVenta)){
$twig = 'aviatur_experience_reservation_success_secure';
} else {
$twig = 'aviatur_experience_payment_error_secure'; //no existe?
}
$order['url'] = $this->generateUrl($twig);
}
}
return $this->json($order);
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró la agencia con el dominio: '.$request->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')]);
}
} else {
$postData = json_decode($session->get($transactionId.'[experience][detail_data]'));
if ('true' == (string) $detailVariables->infoExperience[0]->info->ExperienceDetail->FormaVenta) {
$order['url'] = $this->generateUrl('aviatur_experience_payment_secure');
} else {
$orderProductCode = json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
$productId = str_replace('PN', '', $orderProductCode->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$ratePlan = explode('@||', $postData->EI->ratePlan);
foreach ($detailVariables->rateExperiences as $rateExperiences) {
$code = explode('@||', $rateExperiences->Code);
if ($code[0] === $ratePlan[0] && $code[1] === $ratePlan[1]) {
$x_total_amount = $rateExperiences->Amount;
}
}
if (empty($x_total_amount)) {
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '', 'Ocurrio un error al tarificar, por favor intenta nuevamente o comunĆcate con nosotros para finalizar tu transacción'));
} else {
$infoDates['AmountTotal'] = $x_total_amount;
}
$EmitirSolicitud = $experienceService->EmitirSolicitud($orderProduct, $detailVariables->infoExperience[0]->id, true);
if ('Ok' == $EmitirSolicitud) {
$twig = 'aviatur_experience_reservation_success_secure';
} else {
$twig = 'aviatur_experience_payment_error_secure'; //no existe?
}
$order['url'] = $this->generateUrl($twig);
}
return $this->json($order);
}
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'Acceso no autorizado'));
}
}
public function paymentAction(Request $request, RouterInterface $router, ParameterBagInterface $parameterBag, TwigFolder $twigFolder, AviaturErrorHandler $errorHandler, AviaturExperienceService $experienceService, P2PController $p2PController, PSEController $PSEController, SafetypayController $safetypayController, CashController $cashController, TokenStorageInterface $tokenStorage, CustomerMethodPaymentService $methodPaymentService, \Swift_Mailer $mailer, TokenizerService $tokenizerService, AviaturLogSave $aviaturLogSave, OrderController $orderController)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$emailNotification = $parameterBag->get('email_notification');
$orderProduct = [];
$emissionData = [];
$response = null;
$array = [];
$em = $this->managerRegistry;
$session = $this->session;
$transactionId = $session->get($transactionIdSessionName);
$detailVariables = json_decode($session->get($transactionId.'[experience][detailVariables]'));
$postData = json_decode($session->get($transactionId.'[experience][detail_data]'));
$orderInfo = json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
$infoDates = json_decode($session->get($transactionId.'[experience][infoDates]['.$detailVariables->infoExperience[0]->id.']'), true);
$productId = str_replace('PN', '', $orderInfo->products);
$orderProduct[] = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$paymentData = $postData->PD;
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$parameters = json_decode($session->get($request->getHost().'[parameters]'));
$ratePlan = explode('@||', $postData->EI->ratePlan);
foreach ($detailVariables->rateExperiences as $rateExperiences) {
$code = explode('@||', $rateExperiences->Code);
if ($code[0] === $ratePlan[0] && $code[1] === $ratePlan[1]) {
$x_total_amount = $rateExperiences->Amount;
}
}
if (empty($x_total_amount)) {
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '', 'Ocurrio un error al tarificar, por favor intenta nuevamente o comunĆcate con nosotros para finalizar tu transacción'));
} else {
$infoDates['AmountTotal'] = $x_total_amount;
$trm = 1;
if ($session->has($transactionId.'[mpt][exchangeValues]')) {
$trm = $session->get('[mpt][finantial_rate]');
if (!empty($x_total_amount)) {
$infoDates['amount'] = $x_total_amount;
$x_total_amount = $x_total_amount * $trm;
$infoDates['AmountTotal'] = $x_total_amount;
}
}
$session->set($transactionId.'[experience][infoDates]['.$detailVariables->infoExperience[0]->id.']', json_encode($infoDates));
}
$aviaturPaymentIva = (float) $parameters->aviatur_payment_iva;
$x_amount_base = $x_total_amount / (1 + $aviaturPaymentIva);
$x_amount_iva = $x_amount_base * $aviaturPaymentIva;
$session->set($transactionId.'[experience][payment][only]', true);
if ('p2p' == $paymentData->type) {
if (isset($paymentData->cusPOptSelected)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $methodPaymentService->getMethodsByCustomer($customerLogin, true);
$cardToken = $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
$paymentData->card_num = $cardToken;
$paymentData->card_values->card_num_token = $cardToken;
}
$array = [
'x_currency_code' => (string) 'COP',
'x_amount' => number_format(round((float) ($x_total_amount)), 0, '.', ''),
'x_tax' => number_format(round((float) ($x_amount_iva)), 2, '.', ''),
'x_amount_base' => number_format(round((float) ($x_amount_base)), 2, '.', ''),
'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
'x_first_name' => $customer->getFirstname(),
'x_last_name' => $customer->getLastname(),
'x_description' => 'Paquete - '.$infoDates['datesTransaction']['ProductName'],
'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' => 'experience',
];
if (isset($paymentData->card_values)) {
$array['card_values'] = (array) $paymentData->card_values;
}
if (isset($paymentData->cusPOptSelected)) {
$array['isToken'] = (string) $paymentData->card_values->card_num_token;
}
if (isset($paymentData->savePaymProc)) {
$array['x_provider_id'] = 1;
} elseif (isset($paymentData->cusPOptSelected)) {
if (isset($paymentData->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $paymentData->cusPOptSelectedStatus) {
$array['x_provider_id'] = 1;
} else {
$array['x_provider_id'] = 2;
}
} else {
$array['x_provider_id'] = 2;
}
}
// $paymentResponse = $p2PController->placetopayAction($array, true, $detailVariables->infoExperience[0]->id);
$paymentResponse = $p2PController->placetopayAction($parameterBag, $tokenizerService, $methodPaymentService, $mailer, $aviaturLogSave, $array, true, $detailVariables->infoExperience[0]->id);
$experienceService->xmlExperienceExtra($transactionId, $detailVariables->infoExperience[0]->id, $orderProduct[0]->getStatus());
unset($array['x_client_id']);
if (null != $paymentResponse) {
return $this->redirect($this->generateUrl('aviatur_experience_payment_p2p_return_url_secure', [], true));
} else {
$orderProduct[0]->setStatus('pending');
$em->persist($orderProduct[0]);
$em->flush();
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '', 'No hay respuesta por parte del servicio de pago, por favor intenta nuevamente o comunĆcate con nosotros para finalizar tu transacción22'));
}
} elseif ('pse' == $paymentData->type) {
$array = ['x_doc_num' => $customer->getDocumentnumber(),
'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
'x_first_name' => $customer->getFirstname(),
'x_last_name' => $customer->getLastname(),
'x_company' => 'Aviatur',
'x_email' => $customer->getEmail(),
'x_address' => $customer->getAddress(),
'x_city' => $customer->getCity()->getDescription(),
'x_province' => $customer->getCity()->getDescription(),
'x_country' => $customer->getCountry()->getDescription(),
'x_phone' => $customer->getPhone(),
'x_mobile' => $customer->getCellphone(),
'x_bank' => $paymentData->pse_bank,
'x_type' => $paymentData->pse_type,
'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
'x_description' => 'Paquete - '.$infoDates['datesTransaction']['ProductName'],
'x_currency' => (string) 'COP',
'x_total_amount' => number_format(round((float) ($x_total_amount)), 0, '.', ''),
'x_tax_amount' => number_format(round((float) ($x_amount_iva)), 2, '.', ''),
'x_devolution_base' => number_format(round((float) ($x_amount_base)), 2, '.', ''),
'x_tax' => number_format(round((float) (0)), 2, '.', ''),
'x_tip_amount' => number_format(round((float) (0)), 2, '.', ''),
'product_type' => 'experience',
'x_transactionId' => $transactionId,
];
$paymentResponse = $PSEController->sendPaymentAction($request, $session, $router, $parameterBag, $mailer, $orderController, $array, $orderProduct);
$experienceService->xmlExperienceExtra($transactionId, $detailVariables->infoExperience[0]->id, $orderProduct[0]->getStatus());
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_experience_retry_secure'), '');
default:
return $this->redirect($this->generateUrl('aviatur_experience_retry_secure'), '');
}
} else {
return $this->redirect($errorHandler->errorRedirect($this->generateUrl('aviatur_experience_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_booking' => $request->get('PlanID'),
'x_description' => 'Paquete - '.$infoDates['datesTransaction']['ProductName'],
'x_currency' => 'COP',
'x_total_amount' => number_format(round((float) ($x_total_amount)), 2, '.', ''),
'x_tax_amount' => number_format(round((float) (0)), 2, '.', ''),
'x_devolution_base' => number_format(round((float) (0)), 2, '.', ''),
'x_tip_amount' => number_format(round(0), 2, '.', ''),
'x_payment_data' => $paymentData->type,
'x_type_description' => 'experience',
];
$parametMerchant = [
'MerchantSalesID' => $array['x_reference'],
'Amount' => $array['x_total_amount'],
'transactionUrl' => $transactionUrl,
'dataTrans' => $array,
];
$safeTyPay = $safetypayController->safetyAction($router, $parameterBag, $mailer, $parametMerchant, $array);
$experienceService->xmlExperienceExtra($transactionId, $detailVariables->infoExperience[0]->id, $orderProduct[0]->getStatus());
if ('ok' == $safeTyPay['status']) {
if ('baloto' == $paymentData->type) {
$cash = '&CountryId=COL&ChannelId=CASH';
$session->set($transactionId.'[experience][retry]', 0);
return $this->redirect($safeTyPay['response'].$cash);
} else {
return $this->redirect($safeTyPay['response']);
}
} else {
$emissionData->x_booking = $array['x_booking'];
$emissionData->x_first_name = $array['x_first_name'];
$emissionData->x_last_name = $array['x_last_name'];
$emissionData->x_doc_num = $array['x_doc_num'];
$emissionData->x_reference = $array['x_reference'];
$emissionData->x_description = $array['x_description'];
$emissionData->x_total_amount = $array['x_total_amount'];
$emissionData->x_email = $array['x_email'];
$emissionData->x_address = $array['x_address'];
$emissionData->x_phone = $array['x_phone'];
$emissionData->x_type_description = $array['x_type_description'];
$emissionData->x_resultSafetyPay = $safeTyPay;
$mailInfo = print_r($emissionData, true).'<br>'.print_r($response, true);
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($emailNotification)
->setSubject('Error Creación Token SafetyPay AssistCard'.$emissionData->x_reference)
->setBody($mailInfo);
$mailer->send($message);
return $this->redirect($this->generateUrl('aviatur_experience_payment_rejected_secure'));
}
} elseif ('cash' == $paymentData->type) {
$agency = $this->agency;
$agencyName = $agency->getOfficeId();
$array['x_officeId'] = $agencyName;
$array['x_doc_num'] = $customer->getDocumentnumber();
$array['x_doc_type'] = $customer->getDocumentType()->getPaymentcode();
$array['x_first_name'] = $customer->getFirstname();
$array['x_last_name'] = $customer->getLastname();
$array['x_company'] = 'Aviatur';
$array['x_email'] = $customer->getEmail();
$array['x_address'] = $customer->getAddress();
$array['x_city'] = $customer->getCity()->getDescription();
$array['x_province'] = $customer->getCity()->getDescription();
$array['x_country'] = $customer->getCountry()->getDescription();
$array['x_phone'] = $customer->getPhone();
$array['x_mobile'] = $customer->getCellphone();
$array['x_payment_data'] = $paymentData->type;
$array['x_reference'] = $orderInfo->products;
$array['x_description'] = $infoDates['datesTransaction']['ProductName'];
$array['x_booking'] = $orderProduct[0]->getBooking();
$array['x_total_amount'] = number_format(round((float) $x_total_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'] = 'COP';
$array['x_type_description'] = $orderProduct[0]->getDescription();
$array['x_cantidad'] = $postData->PI->person_count_1;
$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($array);
$experienceService->xmlExperienceExtra($transactionId, $detailVariables->infoExperience[0]->id, $orderProduct[0]->getStatus());
if ('ok' == $cashPay->status) {
$session->set($transactionId.'[experience][cash_result]', json_encode($cashPay));
return $this->redirect($this->generateUrl('aviatur_experience_payment_success_secure'));
} else {
$retryCount = (int) $session->get($transactionId.'[experience][retry]');
//$toEmails = array('soportepagoelectronico@aviatur.com.co', 'soptepagelectronic@aviatur.com', 'gustavo.hincapie@aviatur.com');
$toEmails = ['sergio.amaya@aviatur.com'];
$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.'[experience][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl('aviatur_experience_payment_rejected_secure'));
}
} else {
return $errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '', 'El tipo de pago es invalido');
}
}
public function p2pCallbackAction(Request $request, ParameterBagInterface $parameterBag, AviaturErrorHandler $errorHandler, OrderController $orderController, AviaturMailer $aviaturMailer, AviaturEncoder $aviaturEncoder, AviaturExperienceService $experienceService, ValidateSanctions $validateSanctions, TokenStorageInterface $tokenStorage, CustomerMethodPaymentService $methodPaymentService)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$correlationIdSessionName = $parameterBag->get('correlation_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$agency = null;
$em = $this->managerRegistry;
$session = $this->session;
$fullRequest = $request;
$request = $fullRequest->request;
$transactionId = $session->get($transactionIdSessionName);
if (true === $request->has('correlationID')) {
$correlationId = $request->get('correlationID');
} else {
$correlationId = $session->get($correlationIdSessionName);
}
$detailVariables = json_decode($session->get($transactionId.'[experience][detailVariables]'));
$orderProductCode = json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
$productId = str_replace('PN', '', $orderProductCode->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$decodedRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
$jsonSendEmail = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('send_email');
if (isset(json_decode($jsonSendEmail->getDescription())->email)) {
$email = json_decode($jsonSendEmail->getDescription())->email->CallBack;
}
$references = $orderProductCode->order.'-'.$orderProductCode->products;
$bookings = $orderProduct->getBooking();
if (null != $decodedResponse) {
$twig = '';
$retryCount = (int) $session->get($transactionId.'[experience][retry]');
switch ($decodedResponse->x_response_code) {
case isset($decodedResponse->x_response_code_cyber) && (2 == $decodedResponse->x_response_code_cyber):
//rechazado cybersource
$parameters = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
if ($parameters) {
if (1 == $parameters->getValue()) {
if (1 == $decodedResponse->x_response_code) {
$postData = json_decode($session->get($transactionId.'[experience][detail_data]'));
$postData->PD->card_num = $decodedRequest->x_card_num;
$postData->PD->card_values->card_num_token = $decodedRequest->x_card_num;
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)) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$customerLogin = $tokenStorage->getToken()->getUser();
$methodPaymentService->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
}
$twig = 'aviatur_experience_payment_rejected_secure';
// no break
case 3:// pendiente p2p
$twig = '' != $twig ? $twig : 'aviatur_experience_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_experience_payment_error_secure'; //no existe?
if (isset($email)) {
$from = 'noreply@aviatur.com';
$error = $twig;
$subject = $orderProduct->getDescription().':Error en el proceso de pago de Aviatur';
$body = '</br>El proceso de pago a retornado un error </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
$aviaturMailer->sendEmailGeneral($from, $email, $subject, $body);
}
// no break
case 2:// rechazada p2p
$twig = '' != $twig ? $twig : 'aviatur_experience_payment_rejected_secure';
$orderProduct->setResume('No reservation');
if (isset($email)) {
$from = 'noreply@aviatur.com';
$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 = 'experience';
$decodedResponse->product_type = 'experience';
$encodedRequest = $aviaturEncoder->AviaturEncode(json_encode($decodedRequest), $orderProduct->getPublicKey());
$encodedResponse = $aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey());
$orderProduct->setPayrequest($encodedRequest);
$orderProduct->setPayresponse($encodedResponse);
$twig = 'aviatur_experience_payment_success_secure';
$postData = json_decode($session->get($transactionId.'[experience][detail_data]'));
$postData->PD->card_num = $decodedRequest->x_card_num;
$postData->PD->card_values->card_num_token = $decodedRequest->x_card_num;
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)) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$customerLogin = $tokenStorage->getToken()->getUser();
$methodPaymentService->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
$experienceService->EmitirSolicitud($orderProduct, $detailVariables->infoExperience[0]->id, true);
$updateOrder = $orderController->updatePaymentAction($orderProduct);
$session->set($transactionId.'[experience][retry]', $aviaturPaymentRetryTimes);
$em->persist($orderProduct);
$em->flush();
break;
}
$session->set($transactionId.'[experience][retry]', $retryCount - 1);
//////// se envia el correo del modulo anti fraude en caso de ser necesario//////////
if ($session->has('Marked_name') && $session->has('Marked_document')) {
$product = 'Experiencias';
$validateSanctions->sendMarkedEmail($orderProductCode, $session, $agency, $orderProduct, $transactionId, $product);
}
////////////////////////////////////////////////////////////////////////////////////
return $this->redirect($this->generateUrl($twig));
} else {
$orderProduct->setStatus('pending');
$em->persist($orderProduct);
$em->flush();
return $errorHandler->errorRedirect($this->generateUrl('aviatur_experience_retry_secure'), '', 'No hay respuesta por parte del servicio de pago');
}
}
public function pseCallbackAction(ParameterBagInterface $parameterBag, TwigFolder $twigFolder, AviaturErrorHandler $errorHandler, OrderController $orderController, AviaturMailer $aviaturMailer, AviaturEncoder $aviaturEncoder, AviaturExperienceService $experienceService, PSEController $PSEController, $transaction)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$status = null;
$detailVariables = null;
$twig = null;
$em = $this->managerRegistry;
$session = $this->session;
if ($session->has('agencyId')) {
$agency = $this->agency;
} else {
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find(1);
}
$paymentMethod = $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethod::class)->findOneByCode('pse');
$paymentMethodAgency = $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findOneBy(['agency' => $agency, 'paymentMethod' => $paymentMethod]);
$tranKey = $paymentMethodAgency->getTrankey();
$decodedUrl = json_decode($aviaturEncoder->AviaturDecode(base64_decode($transaction), $tranKey), true);
$transactionId = ($session->has($transactionIdSessionName)) ? $session->get($transactionIdSessionName) : null;
$orders = $decodedUrl['x_orders'];
if (isset($orders['experience'])) {
$experiencesOrders = explode('+', $orders['experience']);
$orderProductCode = $experiencesOrders[0];
$productId = $experiencesOrders[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(\Aviatur\GeneralBundle\Entity\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($this->get("aviatur_error_handler")->errorRedirectNoEmail($this->get("aviatur_agency_twig_folder")->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró información de la transacción'));
}
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
if (isset($decodedResponse->createTransactionResult)) {
$pseTransactionId = $decodedResponse->createTransactionResult->transactionID;
$paymentResponse = $PSEController->pseCallbackAction($orderController, $pseTransactionId);
if (!isset($paymentResponse->error)) {
if (!$session->has($transactionId.'[experience][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_experience_payment_success_secure';
$status = 'approved';
break;
case 'PENDING':
$twig = 'aviatur_experience_payment_pending_secure';
$status = 'pending';
break;
case 'NOT_AUTHORIZED':
$twig = 'aviatur_experience_payment_error_secure';
$status = 'rejected';
break;
case 'FAILED':
$twig = 'aviatur_experience_payment_error_secure';
$status = 'failed';
break;
}
$orderProduct->setStatus($status);
$orderProduct->getOrder()->setStatus($status);
$orderProduct->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
if ('approved' == $status) {
$orderController->updatePaymentAction($orderProduct, false, null);
$segment = $detailVariables->infoExperience[0]->id ?? null;
$experienceService->EmitirSolicitud($orderProduct, $segment, true);
$session->set($transactionId.'[experience][retry]', $aviaturPaymentRetryTimes);
$em->persist($orderProduct);
$em->flush();
}
} elseif ('FAIL_INVALIDTRAZABILITYCODE' == (string) $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_ACCESSDENIED' == $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_TIMEOUT' == $paymentResponse->getTransactionInformationResult->returnCode) {
echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
unos minutos y vuelva a consultar mas tarde para verificar sĆ su pago fue confirmado de
forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
comunicarse a nuestras lĆneas de atención al cliente al telĆ©fono XXXXXX o enviar
inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
transacción <#CUS> .';
$orderProduct->setEmissiondata('error');
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$twig = 'aviatur_experience_payment_error_secure';
}
if ($session->has($transactionId.'[experience][retry]')) {
$session->set($transactionId.'[experience][retry]', $retryCount - 1);
}
return $this->redirect($this->generateUrl($twig));
} else {
$decodedResponse->getTransactionInformationResult = $paymentResponse;
$orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
return $this->redirect($errorHandler->errorRedirectNoEmail($errorHandler->pathWithLocale('aviatur_general_homepage'), '', 'Ocurrió un error al consultar el estado de la transacción'));
}
} else {
return $this->redirect($errorHandler->errorRedirectNoEmail($errorHandler->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró información de la transacción'));
}
}
}
public function safetyCallbackOkAction(ParameterBagInterface $parameterBag, SafetypayController $safetypayController, AviaturEncoder $aviaturEncoder, OrderController $orderController, AviaturExperienceService $experienceService, TwigFolder $twigFolder, AviaturErrorHandler $errorHandler)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$status = null;
$twig = null;
$em = $this->managerRegistry;
$session = $this->session;
$safeTyPay = $safetypayController->safetyok();
if (true === $session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
$detailVariables = json_decode($session->get($transactionId.'[experience][detailVariables]'));
if (true === $session->has($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']')) {
$orderProductCode = json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
$productId = str_replace('PN', '', $orderProductCode->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$decodedRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
$payError = $decodedResponse->payResponse->OperationResponse->ErrorManager->ErrorNumber->{'@content'};
$notifyError = $decodedResponse->notificationResponse->OperationActivityNotifiedResponse->ErrorManager->ErrorNumber->{'@content'};
if (isset($decodedResponse->payResponse->OperationResponse)) {
if (0 === $payError) {
$retryCount = (int) $session->get($transactionId.'[experience][retry]');
if (0 == $notifyError) {
switch ($payError) {
case 0:
$twig = 'aviatur_experience_payment_success_secure';
$status = 'approved';
break;
case 2:
$twig = 'aviatur_experience_payment_error_secure';
$status = 'failed';
break;
}
$orderProduct->setStatus($status);
$orderProduct->getOrder()->setStatus($status);
$orderProduct->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$orderController->updatePaymentAction($orderProduct);
if ('approved' == $status) {
$experienceService->EmitirSolicitud($orderProduct, $detailVariables->infoExperience[0]->id, true);
$session->set($transactionId.'[experience][retry]', $aviaturPaymentRetryTimes);
$em->persist($orderProduct);
$em->flush();
}
} 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_experience_payment_error_secure';
}
$session->set($transactionId.'[experience][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl($twig));
} else {
$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, ParameterBagInterface $parameterBag, AviaturEncoder $aviaturEncoder, TwigFolder $twigFolder, AviaturErrorHandler $errorHandler)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$status = null;
$fullRequest = $request;
$em = $this->managerRegistry;
$session = $this->session;
$transactionId = $session->get($transactionIdSessionName);
$retryCount = (int) $session->get($transactionId.'[experience][retry]');
$detailVariables = json_decode($session->get($transactionId.'[experience][detailVariables]'));
$orderInfo = json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
$productId = str_replace('PN', '', $orderInfo->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$payResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
$payRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey()));
$orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($payResponse), $orderProduct->getPublicKey()));
if ('baloto' == $payRequest->dataTransf->x_payment_data) {
$status = 'pending';
$payResponse->dataTransf->x_response_code = 100;
$payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Pending';
} elseif ('safety' == $payRequest->dataTransf->x_payment_data) {
$status = 'rejected';
$payResponse->dataTransf->x_response_code = 100;
$payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Expired';
}
$orderProduct->setStatus($status);
$orderProduct->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setUpdatingdate(new \DateTime());
$order = $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderProduct->getOrder()->getId());
$order->setStatus($status);
$em->persist($order);
$em->persist($orderProduct);
$em->flush();
if (true === $session->has($transactionId.'[experience][order]')) {
$orderProductCode = $session->get($transactionId.'[experience][order]');
} else {
return $this->redirect($errorHandler->errorRedirect($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró orden asociada a este pago'));
}
$session->set($transactionId.'[experience][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl('aviatur_experience_payment_rejected_secure'));
}
public function createOrderPackage(Request $request, SessionInterface $session)
{
$em = $this->managerRegistry;
$server = $request->server;
$fullRequest = $request;
if ($fullRequest->isXmlHttpRequest()) {
}
}
public function paymentOutputAction(ParameterBagInterface $parameterBag, TwigFolder $twigFolder, AviaturEncoder $aviaturEncoder, ExceptionLog $exceptionLog, \Swift_Mailer $mailer, Pdf $pdf)
{
$projectDir = $parameterBag->get('kernel.project_dir');
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$clientFranquice = [];
$orderProductCode = null;
$paymentResume = [];
$customer = null;
$em = $this->managerRegistry;
$session = $this->session;
$transactionId = $session->get($transactionIdSessionName);
$detailVariables = json_decode($session->get($transactionId.'[experience][detailVariables]'));
$detail_data = json_decode($session->get($transactionId.'[experience][detail_data]'));
$infoDates = json_decode($session->get($transactionId.'[experience][infoDates]['.$detailVariables->infoExperience[0]->id.']'), true);
$orderInfo = json_decode($session->get($transactionId.'[experience][order'.$detailVariables->infoExperience[0]->id.']'));
$detailInfo = $session->get($transactionId.'[experience][detailInfo]');
$productId = str_replace('PN', '', $orderInfo->products);
$paymentData = $detail_data->BD;
$isFront = $session->has('officeId');
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$agency = $orderProduct->getOrder()->getAgency();
if (!$isFront) {
$opRequestInitial = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$opRequest = $opRequestInitial->multi_transaction_hotel ?? $opRequestInitial;
$opResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
if (isset($opResponse->x_franchise) && ('' != $opResponse->x_franchise)) {
$franquiceCode = str_replace(['CR_', 'RM_', 'CDNSA'], ['', '', 'CS'], $opResponse->x_franchise);
$clientFranquice = $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findOneByPaymentgatewaycode($franquiceCode);
$franquiceDescription = $clientFranquice->getDescription();
} else {
$clientFranquice['description'] = 'error';
$franquiceDescription = $clientFranquice['description'];
}
if ((null != $opRequest) && (null != $opResponse)) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->id);
if (isset($opResponse->x_description)) {
$paymentResume = [
'transaction_state' => $opResponse->x_response_code,
'ta_transaction_state' => $opResponse->x_ta_response_code,
'id' => $orderProduct->getBooking(),
'id_context' => $opRequest->x_invoice_num,
'total_amount' => $opResponse->x_amount,
'currency' => $opResponse->x_bank_currency,
'amount' => 0 != $opRequest->x_amount_base ? $opRequest->x_amount_base : $opResponse->x_amount,
'iva' => $opRequest->x_tax,
'ip_address' => $opRequest->x_customer_ip,
'bank_name' => $opResponse->x_bank_name,
'client_franquice' => ['description' => $franquiceDescription],
'cuotas' => $opRequest->x_differed,
'card_num' => '************'.substr($opRequest->x_card_num, strlen($opRequest->x_card_num) - 4),
'reference' => $opResponse->x_transaction_id,
'auth' => $opResponse->x_approval_code,
'transaction_date' => $opResponse->x_transaction_date,
'description' => $opResponse->x_description,
'reason_code' => $opResponse->x_response_reason_code,
'reason_description' => $opResponse->x_response_reason_text,
'client_names' => $opResponse->x_first_name.' '.$opResponse->x_last_name,
'client_email' => $opResponse->x_email,
'serviceResponse' => $detailInfo,
'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
];
if (isset($opRequest->administrative_base)) {
$paymentResume['fee_base'] = $opRequest->administrative_base;
$paymentResume['ta_reference'] = $paymentResume['reference'];
$paymentResume['ta_auth'] = $paymentResume['auth'];
$paymentResume['ta_reason_code'] = $paymentResume['reason_code'];
}
if (isset($opRequest->administrative_amount_tax)) {
$paymentResume['fee_tax'] = $opRequest->administrative_amount_tax;
}
if (isset($opRequest->admin_amount)) {
$paymentResume['x_service_fee'] = $opRequest->admin_amount;
$paymentResume['total_amount'] = $paymentResume['total_amount'] + $opRequest->admin_amount;
}
} elseif (isset($opRequest->dataTransf)) {
if (isset($opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'})):
$state = $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'};
if (102 == $state):
$state = 1;
$reason_description = 'SafetyPay recibe la confirmación del pago de un Banco Asociado'; elseif (101 == $state):
$state = 2;
$reason_description = 'Transacción creada';
endif;
$paymentResume = [
'transaction_state' => $state,
'id' => $orderProduct->getBooking(),
'currency' => $opRequest->dataTransf->x_currency,
'total_amount' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:Amount'},
'amount' => null,
'iva' => null,
'ip_address' => $opRequest->dataTransf->dirIp,
'airport_tax' => null,
'reference' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:MerchantSalesID'},
'auth' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationID'},
'transaction_date' => $opResponse->payResponse->OperationResponse->ResponseDateTime,
'description' => $opRequest->dataTransf->x_description,
'reason_code' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'},
'reason_description' => $reason_description,
'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
'client_email' => $opRequest->dataTransf->x_email,
'x_payment_data' => $opRequest->dataTransf->x_payment_data,
'client_franquice' => ['description' => 'SafetyPay'],
'id_context' => $orderProductCode->order.'-'.$orderProductCode->products,
'serviceResponse' => $detailInfo,
'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
]; else:
$paymentResume = [
'transaction_state' => 2,
'id' => $orderProduct->getBooking(),
'currency' => $opRequest->dataTransf->x_currency,
'total_amount' => $opRequest->dataTransf->x_total_amount,
'amount' => null,
'iva' => null,
'ip_address' => $opRequest->dataTransf->dirIp,
'airport_tax' => null,
'reference' => $opRequest->dataTransf->x_reference,
'auth' => null,
'transaction_date' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:RequestDateTime'},
'description' => $opRequest->dataTransf->x_description,
'reason_code' => 101,
'reason_description' => 'Transacción creada',
'x_payment_data' => $opRequest->dataTransf->x_payment_data,
'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
'client_email' => $opRequest->dataTransf->x_email,
'serviceResponse' => $detailInfo,
'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
];
endif;
if ('baloto' == $opRequest->dataTransf->x_payment_data) {
$paymentResume['transaction_state'] = 3;
}
} elseif (isset($opRequest->infoCash)) {
$paymentResume = [
'transaction_state' => 2,
'id' => $orderProduct->getBooking(),
'id_booking' => $opRequest->infoCash->x_booking,
'id_context' => $opRequest->infoCash->x_reference,
'currency' => $opRequest->infoCash->x_currency,
'total_amount' => $opRequest->infoCash->x_total_amount,
'client_franquice' => ['description' => 'Efectivo'],
'amount' => null,
'iva' => null,
'ip_address' => $opRequest->infoCash->dirIp,
'airport_tax' => null,
'reference' => $opRequest->infoCash->x_reference,
'auth' => null,
'transaction_date' => $opRequest->infoCash->x_fechavigencia,
'description' => $opRequest->infoCash->x_description,
'reason_code' => 101,
'reason_description' => 'Transacción creada',
'client_names' => $opRequest->infoCash->x_first_name.' '.$opRequest->infoCash->x_last_name,
'client_email' => $opRequest->infoCash->x_email,
'fecha_vigencia' => $opRequest->infoCash->x_fechavigencia,
'serviceResponse' => $detailInfo,
'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
];
$cash_result = json_decode($session->get($transactionId.'[experience][cash_result]'));
$paymentResume['transaction_state'] = 3;
if ('' == $cash_result) {
$paymentResume['transaction_state'] = 2;
}
} else {
$bank_info = $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findOneByCode($opRequest->bankCode);
$bank_name = $bank_info->getName();
$clientFranquice['description'] = 'PSE';
$paymentResume = [
'transaction_state' => $opResponse->getTransactionInformationResult->responseCode,
'id' => $orderProduct->getBooking(),
'id_context' => $opRequest->reference,
'currency' => $opRequest->currency,
'total_amount' => $opRequest->totalAmount,
'amount' => $opRequest->devolutionBase,
'iva' => $opRequest->taxAmount,
'ip_address' => $opRequest->ipAddress,
'bank_name' => $bank_name,
'client_franquice' => $clientFranquice,
'reference' => $opResponse->createTransactionResult->transactionID,
'auth' => $opResponse->getTransactionInformationResult->trazabilityCode,
'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate,
'description' => $opRequest->description,
'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode,
'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText,
'client_names' => $opRequest->payer->firstName.' '.$opRequest->payer->lastName,
'client_email' => $opRequest->payer->emailAddress,
'serviceResponse' => $detailInfo,
'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
];
}
} else {
$customer = null;
if ('false' == $infoDates['datesTransaction']['FormaVenta']) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->id);
$EmisionInfo = json_decode($session->get($transactionId.'[experience][EmisionInfo'.$detailVariables->infoExperience[0]->id.']'), true);
$emissionData = json_decode($orderProduct->getEmissionData(), true);
$emissionXml = simplexml_load_string($emissionData['xml'])->Request;
$paymentResume = [
'transaction_state' => isset($emissionData['emission']) ? 3 : 0,
'transaction_state_reservation' => isset($emissionData['emission']) ? 1 : 0,
'id' => $orderProduct->getBooking(),
'id_context' => $emissionData['emission'] ?? $EmisionInfo['message'] ?? '',
'currency' => $detailVariables->currency,
'total_amount' => $detailVariables->AmountTotal,
'amount' => null,
'iva' => null,
'ip_address' => null,
'bank_name' => 'Reserva Off Line',
//'client_franquice' => 'Off Line',
'reference' => $emissionData['emission'] ?? $EmisionInfo['message'] ?? '',
'auth' => null,
'transaction_date' => $orderProduct->getCreationDate(),
'description' => (string) $emissionXml->Producto->ProductName,
'reason_code' => 101,
'reason_description' => $EmisionInfo['Description'] ?? '',
'client_names' => $emissionXml->Cliente->Name.' '.$emissionXml->Cliente->Last_name,
'client_email' => (string) $emissionXml->Cliente->email,
'FormaVenta' => $infoDates['datesTransaction']['FormaVenta'],
'serviceResponse' => $detailInfo,
];
}
}
$paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
} else {
$paymentResume = [
'id' => $orderProduct->getBooking(),
];
}
if (false !== strpos($paymentData->first_name, '***')) {
$facturationResume = [
'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
'customer_address' => $customer->getAddress(),
'customer_doc_num' => $customer->getDocumentnumber(),
'customer_phone' => $customer->getPhone(),
'customer_email' => $customer->getEmail(),
];
} else {
$facturationResume = [
'customer_names' => $paymentData->first_name.' '.$paymentData->last_name,
'customer_address' => $paymentData->address ?? null,
'customer_doc_num' => $paymentData->doc_num,
'customer_phone' => $paymentData->phone,
'customer_email' => $paymentData->email ?? null,
];
}
if (false !== strpos($detail_data->PI->first_name_1_1, '***')) {
$detail_data->PI->first_name_1_1 = $customer->getFirstname();
$detail_data->PI->last_name_1_1 = $customer->getLastname();
$detail_data->PI->email_1_1 = $customer->getEmail();
$detail_data->PI->address_1_1 = $customer->getAddress();
$detail_data->CD->phone = $customer->getPhone();
}
$clientFranquice = '';
$retryCount = (int) $session->get($transactionId.'[experience][retry]');
$agencyFolder = $twigFolder->twigFlux();
$number = 1;
$detailVariables->infoExperience[0]->info->ExperienceDetail->FechaInicio = $detailVariables->info->date1;
if (isset($detailVariables->info->date1) && '' != $detailVariables->info->date2) {
$detailVariables->infoExperience[0]->info->ExperienceDetail->FechaFin = $detailVariables->info->date2;
}
$emailData = [
'retry_count' => $retryCount,
'order' => $orderInfo->order,
'products' => $orderInfo->products,
'description' => $infoDates['datesTransaction']['ProductName'],
'info_travelers' => (array) $detail_data->PI,
'contact_phone' => $detail_data->CD->phone,
'transactionID' => $transactionId,
'facturationResume' => $facturationResume,
'passenger_data' => ($detailVariables->info->passangerTypes->$number->ADT + $detailVariables->info->passangerTypes->$number->CHD),
'detailInfo' => $detailVariables->infoExperience[0]->info->ExperienceDetail,
];
$urlResume = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Experience/Default/resume.html.twig');
$renderResumeView = $emailData;
if (isset($paymentResume)) {
$renderResumeView['infos'][0] = ['paymentResume' => $paymentResume];
}
$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]['retry_count'] = $retryCount;
$renderResumeView['infos'][0]['transactionID'] = $transactionId;
// $mailAgency = $session->get('agencyDataInfo');
// dd($session->get('agencyDataInfo'));
$session->set($transactionId.'[experience][quote_result]', $renderResumeView);
if ($session->has($transactionId.'[experience][quote_result]')) {
$ruta = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Experience/Default/resume_content.html.twig');
$namefilepdf = 'Aviatur_cotizacion_experiencias_'.$transactionId.'.pdf';
$quoteFile = $projectDir.'/app/quotationLogs/experienceQuotation/'.$namefilepdf;
if (!file_exists($quoteFile)) {
$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($ruta, $renderResumeView), $quoteFile);
$renderResumeView['NameArchive'] = 'QN'.$paymentResume['id'].'_'.$transactionId.'.pdf';
}
$paymentResume['exportPDF'] = false;
if (!$session->has($transactionId.'[emission_quote_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', $agency->getMailContact()))
->setSubject($session->get('agencyShortName').' - Cotización Experiencias '.$paymentResume['id'])
->attach(\Swift_Attachment::fromPath($quoteFile))
->setBody(
$this->renderView($twigFolder->twigExists($ruta), $renderResumeView)
);
try {
$mailer->send($message);
$session->set($transactionId.'[emission_quote_email]', 'emailed');
} catch (Exception $ex) {
$exceptionLog->log(var_dump($message), $ex);
}
}
}
$orderProductResume = $this->render($urlResume, $renderResumeView);
if (empty($orderProduct->getResume())) {
try {
$orderProduct->setResume($orderProductResume);
$em->persist($orderProduct);
$em->flush();
} catch(\Exception $e) {
// Implement try/catch to control exception when persist entity.
// the alternatyve flow is not defined yet.
}
}
chmod($projectDir.'/app/quotationLogs/experienceQuotation/', 777);
$carpeta = $parameterBag->get('kernel.project_dir') .'/app/quotationLogs/experienceQuotation/';
if (!chmod($carpeta, 0755)) {
// Manejo de errores si chmod falla
var_dump('No se pudieron establecer los permisos correctamente.', 500);
}
return $orderProductResume;
}
public function rateExperience($profilesServices, $passengerTypes)
{
$totalPassengers = $passengerTypes['ADT'] + $passengerTypes['CHD'];
$pricesResult = [];
$pricesCombinedResult = [];
$PricesQualifier = [];
$count = 0;
$rateCHD = false;
foreach ($profilesServices as $prices) {
foreach ($prices->Prices as $price) {
if (isset($price->Price['PriceQualifier']) && isset($price->Price['PriceBasis']) && isset($passengerTypes[(string) $price->Price['PriceQualifier']]) && in_array((string) $price->Price['PriceQualifier'], $passengerTypes)) {
if ('CHD' == (string) $price->Price['PriceQualifier']) {
$rateCHD = true;
}
$pricesCombinedResult[strtolower((string) $prices['PropertyCategory'])][$count]['Count'] = (string) $price->Price['Count'];
$pricesCombinedResult[strtolower((string) $prices['PropertyCategory'])][$count]['Description'] = (string) $prices['Description'];
$pricesCombinedResult[strtolower((string) $prices['PropertyCategory'])][$count]['Amount'] = (int) $price->Price['Amount'] * $passengerTypes[(string) $price->Price['PriceQualifier']];
$pricesCombinedResult[strtolower((string) $prices['PropertyCategory'])][$count]['Code'] = (string) $price->Price['Count'];
} elseif (isset($price->Price['PriceQualifier'])) {
if ('CHD' == (string) $price->Price['PriceQualifier']) {
$rateCHD = true;
}
if ('ADT' == (string) $price->Price['PriceQualifier'] && $passengerTypes['ADT'] > 0 || 'CHD' == (string) $price->Price['PriceQualifier'] && $passengerTypes['CHD'] > 0) {
$PricesQualifier[$count][(string) $price->Price['PriceQualifier']]['Count'] = (string) $price->Price['Count'];
$PricesQualifier[$count][(string) $price->Price['PriceQualifier']]['Description'] = (string) $prices['Description'];
$PricesQualifier[$count][(string) $price->Price['PriceQualifier']]['Amount'] = (int) $price->Price['Amount'] * $passengerTypes[(string) $price->Price['PriceQualifier']];
}
} else {
$rateCHD = true;
$pricesResult['optionsList'][$count]['Count'] = (string) $price->Price['Count'];
$pricesResult['optionsList'][$count]['Description'] = (string) $prices['Description'];
$pricesResult['optionsList'][$count]['Amount'] = (int) $price->Price['Amount'] * $totalPassengers;
$pricesResult['optionsList'][$count]['Code'] = (string) $price->Price['Count'].'@||'.(int) $price->Price['Amount'] * $totalPassengers;
}
}
++$count;
}
if (!empty($PricesQualifier)) {
$pricesResult = [];
$Count = null;
$Description = null;
$Amount = null;
foreach ($PricesQualifier as $key => $PriceQualifier) {
foreach ($PriceQualifier as $keyQualifier => $Qualifier) {
foreach ($Qualifier as $index => $valueQualifier) {
if ('Count' == $index) {
$Count = $Count.'+'.$valueQualifier;
}
if ('Description' == $index) {
$Description = $Description.'+'.$valueQualifier;
}
if ('Amount' == $index) {
$Amount = $valueQualifier + $Amount;
}
}
}
}
$pricesResult['optionsList'][0]['Count'] = substr($Count, 1);
$pricesResult['optionsList'][0]['Description'] = substr($Description, 1);
$pricesResult['optionsList'][0]['Amount'] = $Amount;
$pricesResult['optionsList'][0]['Code'] = substr($Count, 1).'@||'.$Amount;
}
if (!empty($pricesCombinedResult)) {
$count = 0;
foreach ($pricesCombinedResult as $key => $priceCombined) {
$Count = null;
$Description = null;
$Amount = 0;
foreach ($priceCombined as $keyPrice => $price) {
$Count = $Count.'+'.$price['Count'];
$Description = $Description.'+'.$price['Description'];
$Amount += $price['Amount'];
}
$pricesResult['optionsList'][$count]['Count'] = substr($Count, 1);
$pricesResult['optionsList'][$count]['Description'] = substr($Description, 1);
$pricesResult['optionsList'][$count]['Amount'] = $Amount;
$pricesResult['optionsList'][$count]['Code'] = substr($Count, 1).'@||'.$Amount;
++$count;
}
}
if (!isset($pricesResult['optionsList'])) {
$pricesResult['error'] = 'Ocurrio un problema al tarificar, por favor intente de nuevo.';
} else {
foreach ($pricesResult['optionsList'] as $key => $list) {
$pricesResult['Amount'][] = $list['Amount'];
}
if ($passengerTypes['CHD'] > 0 && false === $rateCHD) {
$pricesResult['error'] = 'El Producto no permite niƱos o la cantidad es inferior a la permitida';
}
}
return $pricesResult;
}
public function generateReturn($fare, $legend = null, $info = null)
{
return [
'fare' => [
'total' => $fare[0], //total amount of Extra
'base' => $fare[1], //base amount less tax
'tax' => $fare[2], // tax amount applied to total
'percentage' => $fare[3], //percentage rate for tax calculation
'amount_insurance' => $fare[4] ?? null,
],
'info' => $info, // mixed object returned to twig to be used at will
'legend' => $legend, // Is the text rendered under price tag in each Extra row
'name' => 'EXPERIENCE',
'id' => $info['ExperienceDetail']['ID'],
];
}
public function normaliza($text)
{
$text = htmlentities($text, ENT_QUOTES, 'UTF-8');
$text = mb_strtolower($text);
$patron = [
// Espacios, puntos y comas por guion
//'/[\., ]+/' => ' ',
// Vocales
'/\+/' => '',
'/à/' => 'a',
'/è/' => 'e',
'/ì/' => 'i',
'/ò/' => 'o',
'/ù/' => 'u',
'/á/' => 'a',
'/é/' => 'e',
'/í/' => 'i',
'/ó/' => 'o',
'/ú/' => 'u',
'/â/' => 'a',
'/ê/' => 'e',
'/î/' => 'i',
'/ô/' => 'o',
'/û/' => 'u',
'/ã/' => 'a',
'/&etilde;/' => 'e',
'/ĩ/' => 'i',
'/õ/' => 'o',
'/ũ/' => 'u',
'/ä/' => 'a',
'/ë/' => 'e',
'/ï/' => 'i',
'/ö/' => 'o',
'/ü/' => 'u',
'/ä/' => 'a',
'/ë/' => 'e',
'/ï/' => 'i',
'/ö/' => 'o',
'/ü/' => 'u',
// Otras letras y caracteres especiales
'/å/' => 'a',
'/ñ/' => 'n',
// Agregar aqui mas caracteres si es necesario
];
$text = preg_replace(array_keys($patron), array_values($patron), $text);
return $text;
}
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.).
}
}
}