<?php
namespace Aviatur\InsuranceBundle\Controller;
use Aviatur\AgentBundle\Entity\AgentTransaction;
use Aviatur\GeneralBundle\Entity\FormUserInfo;
use Aviatur\InsuranceBundle\Models\InsuranceModel;
use FOS\UserBundle\Model\UserInterface;
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 Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Routing\RouterInterface;
use Aviatur\TwigBundle\Services\TwigFolder;
use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
use Aviatur\GeneralBundle\Services\ExceptionLog;
use Aviatur\GeneralBundle\Services\AviaturWebService;
use Aviatur\GeneralBundle\Services\AviaturEncoder;
use Aviatur\GeneralBundle\Controller\OrderController;
use Aviatur\PaymentBundle\Controller\P2PController;
use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
use Aviatur\PaymentBundle\Services\TokenizerService;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Aviatur\GeneralBundle\Services\AviaturPixeles;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Knp\Snappy\Pdf;
use Aviatur\GeneralBundle\Services\AviaturLogSave;
use Aviatur\InsuranceBundle\Services\InsuranceService;
use Aviatur\InsuranceBundle\Services\SearchInsuranceCookie;
use Aviatur\PaymentBundle\Controller\WorldPayController;
use Aviatur\PaymentBundle\Controller\PSEController;
use Aviatur\GeneralBundle\Services\AviaturMailer;
use Aviatur\CustomerBundle\Services\ValidateSanctions;
use Aviatur\PaymentBundle\Controller\SafetypayController;
use Aviatur\PaymentBundle\Controller\CashController;
use FOS\UserBundle\Security\LoginManagerInterface;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
class DefaultController extends AbstractController
{
public function searchAction()
{
return $this->redirect(
$this->generateUrl(
'aviatur_search_insurance',
[]
)
);
}
public function availabilityAction(Request $fullRequest, SearchInsuranceCookie $searchInsuranceCookie, InsuranceService $insuranceService, AviaturPixeles $aviaturPixeles, ExceptionLog $exceptionLog, AuthorizationCheckerInterface $authorizationChecker, TwigFolder $twigFolder, AviaturWebService $aviaturWebService, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag, $destiny, $dateEntry, $dateEnd, $birth1 = null, $birth2 = null, $birth3 = null, $birth4 = null, $birth5 = null, $birth6 = null, $birth7 = null, $birth8 = null, $birth9 = null, $passenger)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$variable = [];
$dateBirth = [];
$calculoEdades = [];
$passanger_type = [];
$pixel = [];
$isAgent = false;
$em = $registry->getManager();
$requestUrl = $this->generateUrl($fullRequest->attributes->get('_route'), $fullRequest->attributes->get('_route_params'));
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$parameters = json_decode($session->get($fullRequest->getHost().'[parameters]'));
if ($session->has('whitemark')) {
$domain = $agency->getDomain();
} else {
$domain = str_replace('www.', '', $fullRequest->getHost());
}
$productType = $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findOneByCode('ASSIST');
$validation = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_crossed_insurance_flight');
$configsInsuranceAgency = $em->createQuery('SELECT cia FROM AviaturInsuranceBundle:ConfigInsuranceAgency cia WHERE cia.agency = :agency ORDER BY cia.id ASC')->setParameters(['agency' => $agency]);
try {
$configsInsuranceAgency = $configsInsuranceAgency->getResult();
} catch (\Exception $e) {
return $configsInsuranceAgency = null;
}
$isFront = $session->has('operatorId');
$pixelInfo = []; //THIS IS INTENDED FOR STORING ALL DATA CLASIFIED BY PIXEL.'
if (!isset($configsInsuranceAgency) || null == $configsInsuranceAgency) {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_search_insurance'), '', 'Error al Configurar la agencia'));
}
$OfficeId = explode('-', $configsInsuranceAgency[0]->getOfficeId());
$routeName = $fullRequest->get('_route');
$findme = 'secure';
$compare = strpos($routeName, $findme);
$agencyFolder = $twigFolder->twigFlux();
if (false === $compare) {
$domain_file = $session->get('domain');
$method = 'assist';
$login = true;
} else {
$domain_file = $session->get('domainsecure');
$method = 'flight';
$login = false;
}
$infoBirth = null;
if ('flight' == $method) {
$transactionId = $session->get($transactionIdSessionName);
$infoBirth = json_decode($session->get($transactionId.'[crossed][infoBirth]'), true);
$variable['transactionId'] = $transactionId;
}
$diffDays = ((strtotime($dateEnd) - strtotime($dateEntry)) / 86400) + 1;
$providers = [];
if ($configsInsuranceAgency) {
foreach ($configsInsuranceAgency as $configInsuranceAgency) {
$provider = $configInsuranceAgency->getProvider()->getProvideridentifier();
if (!(in_array($provider, $providers))) {
$providers[] = $provider;
}
}
} else {
$exceptionLog->log('Error Fatal', 'No se encontró la agencia segun el dominio: '.$domain, null, false);
return new Response('no se encontró agencias para consultar disponibilidad.');
}
$providersAgency = implode(';', $providers);
$variable['ProviderId'] = $providersAgency;
$variable['MaximumTripLength'] = 'P'.$diffDays.'D';
$variable['AreaID'] = $destiny;
$variable['OfficeId'] = $OfficeId[1];
$variable['AgencyId'] = substr($OfficeId[0], 1);
$variable['diffDays'] = $diffDays;
$variable['CoveredTraveler'] = $this->calcInfoPassenger($insuranceService, $passenger, $method, $infoBirth, $fullRequest);
$variable['EffectiveDate'] = $dateEntry;
$variable['ExpireDate'] = $dateEnd;
if ($isFront) {
$userFront = simplexml_load_string($session->get('front_user'));
$additionalUserFront = simplexml_load_string($session->get('front_user_additionals'));
$variable['OperatorId'] = (string) $userFront->ID_AGENTE;
$variable['OfficeId'] = (string) $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
$variable['AgencyId'] = substr((string) $userFront->CODIGO_OFICINA_PERTENECE, 0, 2);
}
$InsuranceModel = new InsuranceModel();
$xmlTemplate = $InsuranceModel->getXmlAvailability($variable);
$echoToken = null;
$ProductInfo = null;
if ($fullRequest->isXmlHttpRequest() || 'aviatur_flight_payment_success_secure' == $routeName) {
$response = $aviaturWebService->callWebServiceAmadeus('Execute', 'InsuranceQuote', 'dummy|http://www.aviatur.com.co/dummy/', $xmlTemplate, $variable, $login);
if ($isAgent) {
$commissionPay = 0;
}
if (isset($response['error'])) {
if ('aviatur_flight_payment_success_secure' != $routeName) {
return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/General/Templates/dispoError.html.twig'), [
'message' => $response['error'],
'errorCode' => '', ]);
} else {
$response = new Response($response['error']);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
} else {
$echoToken = (string) $response->Message->OTA_InsuranceQuoteRS->PlanForQuoteRS[0]->PlanCost->BasePremium['Amount'];
$ID = [];
foreach ($response->Message->OTA_InsuranceQuoteRS->PlanForQuoteRS as $AssistInfo) {
$ID['Amount'][(string) $AssistInfo['PlanID']][] = (int) $AssistInfo->PlanCost['Amount'];
$planCharges = isset($AssistInfo->PlanCost->Charges->Charge['Amount']) ? round((float) $AssistInfo->PlanCost->Charges->Charge['Amount']) : 0;
$ID['Charges'][(string) $AssistInfo['PlanID']][] = $planCharges;
if (in_array($AssistInfo['PlanID'], array_keys($ID))) {
//$ID[(string) $AssistInfo['PlanID']] = $ID[(string) $AssistInfo['PlanID']] + (int) $AssistInfo->PlanCost['Amount'];
$ID[(string) $AssistInfo['PlanID']]['Amount'] += (int) $AssistInfo->PlanCost['Amount'];
$ID[(string) $AssistInfo['PlanID']]['Charges'] += $planCharges;
} else {
//$ID[(string) $AssistInfo['PlanID']] = (int) $AssistInfo->PlanCost['Amount'];
$ID[(string) $AssistInfo['PlanID']] = [
'Amount' => (int) $AssistInfo->PlanCost['Amount'],
'Charges' => $planCharges,
'ChargesSingle' => $planCharges,
];
}
}
$transactionId = (string) $response->Message->OTA_InsuranceQuoteRS['TransactionIdentifier'];
// dd($response->Message->OTA_InsuranceQuoteRS);
$nameProduct = 'insurance';
$productCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentQseProductCommission::class)->findOneByProductname($nameProduct);
$productCommission2 = (array)$productCommission;
$session->set($transactionId.'_isActiveQse', ((is_countable($productCommission2) ? count($productCommission2) : 0) > 0) ? true : false);
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
$agencyId = $session->get('agencyId');
if ((1 == $agency->getId() || 217 == $agency->getId() || 216 == $agency->getId() || 56 == $agency->getId())) { //agentes octopus
$user = $this->getUser();
$emailuser = $user->getemail();
$agent = $user->getAgent();
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($agencyId);
if (!empty($agent)) {
$idagent = $agent[0]->getid();
$nombreagente = $user->getFirstname().' '.$user->getLastname();
$agencyFolder = $twigFolder->twigFlux();
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($idagent);
$infoQse = json_decode($agentCommission->getQseproduct());
$infoQseNameProduct = empty($infoQse->$nameProduct) ? false : $infoQse->$nameProduct;
$infoQse = empty($infoQse) ? false : $infoQseNameProduct;
$agentQseAmount = ($infoQse) ? (int) $infoQse->commission_money : 0;
$agentQseAmountMax = $productCommission->getQsecommissionmax();
$productpercentage = ($infoQse) ? (float) $infoQse->commission_percentage : 0;
$productpercentagemax = $productCommission->getPercentageCommissionMax();
$productActive = ($infoQse) ? (int) $infoQse->active : 0;
$qseCommissionPercentage = $productCommission->getQsecommissionpercentage();
$tarifaCommissionPercentage = $productCommission->getTacommissionpercentage();
$activeDetail = $agentCommission->getActiveDetail();
$isAgent = true;
} else {
$session->set($transactionId.'_isActiveQse', false);
}
}
}
$uniqueID = [];
$count = 0;
$ProductInfoUnsort = [];
$productPrices = [];
$imgBlob = $parameters->blob_azure_assets;
$uriAssistCard = $imgBlob.'assets/common_assets/img/insurance/logo-assit-card.png';
$uriUniversalAssistance = $imgBlob.'assets/common_assets/img/insurance/logo-ua.svg';
$uriAxaAssistance = $imgBlob.'assets/common_assets/img/insurance/logo-axa.svg';
// stores the plan restriction of the universal assistance.
$arrPlanRestrictions = [];
$arrDataExtra = [];
$arrAttributesPlanRestrictions = [];
foreach ($response->Message->OTA_InsuranceQuoteRS->PlanForQuoteRS as $Info) {
switch ((string) $Info['Name']) {
case 'AC CORP 60 D': // este producto no debe mostrarse
break;
default:
if (!in_array($Info['PlanID'], $uniqueID)) {
$uniqueID[] = (string) $Info['PlanID'];
if (empty($Info->QuoteDetail->ProviderCompany['Division'])) {
$name = explode(' ', $Info['Name']);
$Info->QuoteDetail->ProviderCompany['Division'] = ucwords(mb_strtolower($name[0].'.pdf'));
}
$company = (string) $Info->QuoteDetail->ProviderCompany['CompanyShortName'];
$InsuranceInfo = $em->getRepository(\Aviatur\InsuranceBundle\Entity\InsuranceInformation::class)->findBy(['name' => $Info->QuoteDetail->ProviderCompany['Division']]);
$ProductInfoUnsort[$count]['Description'] = isset($InsuranceInfo[0]) ? $InsuranceInfo[0]->getDescription() : null;
$ProductInfoUnsort[$count]['isFront'] = $isFront;
if ('Assist Card' == $company) {
$PlanRestrictions = [];
$PlanRestrictionString = [];
$ProductInfoUnsort[$count]['uriLogo'] = $uriAssistCard;
if ((1 == $agency->getId() || 5 == $agency->getId() || 152 == $agency->getId()) && !$isFront) { // cambios solo para .com
$InsuranceInfo = $em->getRepository(\Aviatur\InsuranceBundle\Entity\InsuranceInformation::class)->findBy(['name' => $Info->QuoteDetail->ProviderCompany['Division'], 'title' => null]);
if (null != $InsuranceInfo) {
$InsuranceInfo = json_decode($InsuranceInfo[0]->getDescription(), true);
$PlanRestrictions[] = $InsuranceInfo['amount'];
foreach ($InsuranceInfo['PlanRestrictions'] as $PlanRestriction) {
$PlanRestrictions[] = $PlanRestriction;
$PlanRestrictionString[] = $PlanRestriction[2].'--'.$PlanRestriction[0].'--'.$PlanRestriction[1].'--';
}
$ProductInfoUnsort[$count]['PlanRestrictions'] = $PlanRestrictions;
$ProductInfoUnsort[$count]['PlanRestrictionString'] = $PlanRestrictionString;
}
} else {
if ('NACIONAL.pdf' == $Info->QuoteDetail->ProviderCompany['Division'] || 'Nacional.pdf' == $Info->QuoteDetail->ProviderCompany['Division']) {
$ProductInfoUnsort[$count]['Description'] = null;
}
}
} elseif ('Universal Assistance' == $company) {
$ProductInfoUnsort[$count]['uriLogo'] = $uriUniversalAssistance;
foreach ($Info->QuoteDetail->PlanRestrictions as $PlanInfo) {
$length = $PlanInfo->PlanRestriction->count(); // count for each card the details of the plan restriction
for ($i = 0; $i < $length; ++$i) {
$attributes = $PlanInfo->PlanRestriction[$i]->attributes();
if ($attributes->count() > 0) {
$ProductInfoUnsort[$count]['attributtes'] = $attributes['Name'].'--'.$attributes['Code'].'--'.$attributes['CodeContext'].'--';
$arrAttributesPlanRestrictions[] = $ProductInfoUnsort[$count]['attributtes'];
$arrPlanRestrictions[] = $attributes;
} else {
// elementos sin atributos.
$data = $PlanInfo->PlanRestriction[$i];
$key = substr($data, 0, strrpos($data, ':'));
$value = substr($data, strrpos($data, ':') + 1);
$arrDataExtra[$key] = $value;
}
}
// generate dynamically key - value -> elementos sin atributos
if (sizeof($arrDataExtra) > 0) {
foreach ($arrDataExtra as $key => $value) {
$ProductInfoUnsort[$count][$key] = $value;
}
}
$ProductInfoUnsort[$count]['PlanRestrictions'] = $arrPlanRestrictions;
$ProductInfoUnsort[$count]['CountPlanRestrictions'] = sizeof($arrPlanRestrictions);
$arrPlanRestrictions = [];
$arrDataExtra = [];
}
}elseif ('Axa Assistance' == $company) {
$ProductInfoUnsort[$count]['uriLogo'] = $uriAxaAssistance;
$ProductInfoUnsort[$count]['PlanRestrictions'] = [];
$ProductInfoUnsort[$count]['PlanRestrictionString'] = [];
}
$ProductInfoUnsort[$count]['PlanID'] = (string) $Info['PlanID'];
$ProductInfoUnsort[$count]['Name'] = (string) $Info['Name'];
$ProductInfoUnsort[$count]['TypeID'] = (string) $Info['TypeID'];
$ProductInfoUnsort[$count]['TypeProduct'] = (string) $Info['Type'];
$ProductInfoUnsort[$count]['agencyId'] = (string) $agency->getId();
$ProductInfoUnsort[$count]['correlationId'] = '';
if ('Universal Assistance' == $company) {
$ProductInfoUnsort[$count]['Name'] = (string) $ProductInfoUnsort[$count]['headline'];
/*
Nota:
Es necesario el correlationId para la emision en universal assitance.
Normalmente deberia llegar en el atributo CorrelationId del rq en InsuranceQuote,
como no llega, se opto por mandarlo en el atributo TypeID ya que no se estaba usando en UniversalAssitance.
Se mantiene la misma estrutura del XML por estandar OTA.
*/
$ProductInfoUnsort[$count]['TypeID'] = '';
$ProductInfoUnsort[$count]['correlationId'] = (string) $Info['TypeID'];
}
for ($i = 0; $i < sizeof($providers); ++$i) {
if ((130 == $providers[$i] || 90 == $providers[$i]) && ('Universal Assistance' == $company)) {
$ProductInfoUnsort[$count]['providerId'] = $providers[$i];
} elseif ((69 == $providers[$i] || 44 == $providers[$i]) && ('Assist Card' == $company)) {
$ProductInfoUnsort[$count]['providerId'] = $providers[$i];
} elseif ((162 == $providers[$i] || 122 == $providers[$i]) && ('Axa Assistance' == $company)) {
$ProductInfoUnsort[$count]['providerId'] = $providers[$i];
}
}
$ProductInfoUnsort[$count]['RPH'] = (string) $Info['RPH'];
$ProductInfoUnsort[$count]['CompanyShortName'] = (string) $Info->QuoteDetail->ProviderCompany['CompanyShortName'];
$ProductInfoUnsort[$count]['Division'] = (string) $Info->QuoteDetail->ProviderCompany['Division'];
if ('$' == (string) $Info->PlanCost['CurrencyCode']) {
$ProductInfoUnsort[$count]['CurrencyCode'] = 'COP';
} else {
$ProductInfoUnsort[$count]['CurrencyCode'] = 'USD';
}
$baseAmount = $ID[(string) $Info['PlanID']]['Amount'];
$chargesAmount = $ID[(string) $Info['PlanID']]['Charges'];
$totalAmount = $baseAmount + $chargesAmount;
$ProductInfoUnsort[$count]['baseAmount'] = $baseAmount;
$ProductInfoUnsort[$count]['chargesAmount'] = $chargesAmount;
$ProductInfoUnsort[$count]['totalAmount'] = $totalAmount;
/* * ************************ Commission Agent QSE or Percentage **************** */
if ($isAgent) {
$commissionFare = number_format((float) $Info->PlanCost->Charges->Charge['Percent'] * (float) $tarifaCommissionPercentage, 2, '.', ''); //round((float) $Info->PlanCost->Charges->Charge['Percent'] * $tarifaCommissionPercentage);
$commissionFareAll = round($baseAmount * ((float) $Info->PlanCost->Charges->Charge['Percent'] / 100));
$commissionFare = round($baseAmount * ($commissionFare / 100));
$ProductInfoUnsort[$count]['AmountTaAgent'] = $commissionFareAll;
$ProductInfoUnsort[$count]['CommissionTaAgent'] = $commissionFare;
$ProductInfoUnsort[$count]['CommissionActive'] = $productActive;
$ProductInfoUnsort[$count]['PercentageTarifa'] = (float) $Info->PlanCost->Charges->Charge['Percent'];
if ('0' == $productActive) {
$ProductInfoUnsort[$count]['CommissionAgent'] = $agentQseAmount;
$commissionPay = round(($agentQseAmount / 1.19) * $qseCommissionPercentage);
$ProductInfoUnsort[$count]['CommissionPay'] = $commissionPay;
$ProductInfoUnsort[$count]['AmountPay'] = $commissionPay + $commissionFare;
} elseif ('1' == $productActive) {
$totalValue = $ProductInfoUnsort[$count]['totalAmount'];
$valueCommissionPercentage = round($totalValue * $productpercentage);
$ProductInfoUnsort[$count]['CommissionAgent'] = $valueCommissionPercentage;
$commissionPay = round(($valueCommissionPercentage / 1.19) * $qseCommissionPercentage);
$ProductInfoUnsort[$count]['CommissionPay'] = $commissionPay;
$ProductInfoUnsort[$count]['AmountPay'] = $commissionPay + $commissionFare;
}
$ProductInfoUnsort[$count]['totalAmount'] += round($ProductInfoUnsort[$count]['CommissionAgent']);
$ProductInfoUnsort[$count]['activeDetail'] = $activeDetail;
}
$ProductInfoUnsort[$count]['Amount'] = $ID['Amount'][(string) $Info['PlanID']];
//$ProductInfoUnsort[$count]['Information'] = base64_encode($ProductInfoUnsort[$count]['TypeID'] . '*' . $ProductInfoUnsort[$count]['Name'] . '*' . $ProductInfoUnsort[$count]['CurrencyCode'] . '*' . $ProductInfoUnsort[$count]['totalAmount'] . '*' . json_encode($ProductInfoUnsort[$count]['Amount']) . '*' . $ID[(string) $Info['PlanID']]["ChargesSingle"] . '*' . (string) $Info->PlanCost->Charges->Charge["Percent"]);
$ProductInfoUnsort[$count]['Information'] = $ProductInfoUnsort[$count]['TypeID'].'*'.$ProductInfoUnsort[$count]['Name'].'*'.$ProductInfoUnsort[$count]['CurrencyCode'].'*'.$ProductInfoUnsort[$count]['totalAmount'].'*'.json_encode($ProductInfoUnsort[$count]['Amount']).'*'.$ID[(string) $Info['PlanID']]['ChargesSingle'].'*'.(string) $Info->PlanCost->Charges->Charge['Percent'];
if ($isAgent) {
$ProductInfoUnsort[$count]['Information'] .= '*'.$ProductInfoUnsort[$count]['CommissionAgent'].'*'.$ProductInfoUnsort[$count]['CommissionActive'].'*'.$ProductInfoUnsort[$count]['CommissionPay'].'*'.$ProductInfoUnsort[$count]['activeDetail'].'*'.$ProductInfoUnsort[$count]['AmountTaAgent'].'*'.$ProductInfoUnsort[$count]['CommissionTaAgent'].'*'.$ProductInfoUnsort[$count]['AmountPay'].'*'.$ProductInfoUnsort[$count]['PercentageTarifa'];
}
if ('Universal Assistance' == $company || 'Assist Card' == $company || 'Axa Assistance' == $company) {
$ProductInfoUnsort[$count]['InformationCard'] = $ProductInfoUnsort[$count]['uriLogo'].'*'.$ProductInfoUnsort[$count]['CompanyShortName'].'*'.$ProductInfoUnsort[$count]['Division'].'*'.$diffDays;
if ('Universal Assistance' == $company) {
$result = implode($arrAttributesPlanRestrictions);
$ProductInfoUnsort[$count]['InformationCard'] .= '*'.$result.'*'.$ProductInfoUnsort[$count]['bodyCopy'].'*'.$ProductInfoUnsort[$count]['CountPlanRestrictions'];
} elseif ('Assist Card' == $company) {
if (isset($ProductInfoUnsort[$count]['PlanRestrictionString'])) {
$result = implode($ProductInfoUnsort[$count]['PlanRestrictionString']);
$ProductInfoUnsort[$count]['InformationCard'] .= '*'.$result.'*'.(string) $agency->getId().'*'.(string) $isFront;
} elseif (isset($InsuranceInfo[0])) {
$ProductInfoUnsort[$count]['InformationCard'] .= '*'.$ProductInfoUnsort[$count]['Description'].'*'.(string) $agency->getId().'*'.(string) $isFront;
} else {
$ProductInfoUnsort[$count]['InformationCard'] .= '*'.''.'*'.(string) $agency->getId().'*'.(string) $isFront;
}
}elseif ('Axa Assistance' == $company) {
$ProductInfoUnsort[$count]['InformationCard'] .= '*'.''.'*'.(string) $agency->getId().'*'.(string) $isFront;
}
$arrAttributesPlanRestrictions = [];
}
$ProductInfoUnsort[$count]['Information'] = base64_encode($ProductInfoUnsort[$count]['Information']);
$ProductInfoUnsort[$count]['InformationCard'] = base64_encode($ProductInfoUnsort[$count]['InformationCard']);
$productPrices[$count] = $ProductInfoUnsort[$count]['Amount'];
++$count;
}
}
}
}
$ProductInfo = [];
if ($productPrices) {
asort($productPrices);
foreach ($productPrices as $count => $price) {
$ProductInfo[] = $ProductInfoUnsort[$count];
}
} else {
$ProductInfo = $ProductInfoUnsort;
}
unset($ProductInfoUnsort);
$infoInsurance = $response->Message->asXml();
if ('flight' == $method) {
$session->set($transactionId.'[assist]'.'[infoInsurance]', $infoInsurance);
$session->set($transactionId.'[assist]'.'[infoInsuranceFlight]', json_encode($variable));
$session->set($transactionId.'[assist]'.'[infoInsuranceAvaibility]', $infoInsurance);
$session->set($transactionId.'[availability_url_insurance]', $requestUrl);
$variable['transactionId'] = $transactionId;
} else {
$transactionId = (string) $response->Message->OTA_InsuranceQuoteRS['TransactionIdentifier'];
$session->set($transactionId.'[assist]'.'[infoInsurance]', $infoInsurance);
$variable['transactionId'] = $transactionId;
}
$variable['passenger'] = $passenger;
$variable['domain_file'] = $domain_file;
$variable['method'] = $method;
$variable['OfficeId'] = $OfficeId[1];
$variable['AgencyId'] = substr($OfficeId[0], 1);
$variable['echoToken'] = $echoToken;
if ($session->has('operatorId')) {
$userFront = simplexml_load_string($session->get('front_user'));
$additionalUserFront = simplexml_load_string($session->get('front_user_additionals'));
$variable['OfficeId'] = (string) $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
$variable['AgencyId'] = substr((string) $userFront->CODIGO_OFICINA_PERTENECE, 0, 2);
}
$urlAvailability = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/AjaxAvailability.html.twig');
if (false == $compare) {
return $this->render($urlAvailability, ['ProductsInfo' => $ProductInfo, 'variable' => $variable]);
} else {
$dispo_ajax = $fullRequest->get('dispo_ajax');
if ($response['error'] || 0 == $validation->getValue()) {
if (isset($dispo_ajax)) {
$avaibility = 0;
$response = new Response($avaibility);
$response->headers->set('Content-Type', 'application/json');
return $response;
} else {
if (0 == $validation->getValue()) {
$avaibility = 0;
$response = new Response($avaibility);
$response->headers->set('Content-Type', 'application/json');
return $response;
} else {
return $this->render($urlAvailability, ['ProductsInfo' => $ProductInfo, 'variable' => $variable]);
}
}
} else {
return $this->render($urlAvailability, ['ProductsInfo' => $ProductInfo, 'variable' => $variable]);
}
}
} else {
$cookieArray = [
'destination' => $destiny,
'date1' => $dateEntry,
'date2' => $dateEnd,
'passenger' => $passenger,
'providerId' => $providersAgency,
'echoToken' => $echoToken,
];
$Birthdate = '';
for ($i = 1; $i <= $passenger; ++$i) {
if ('flight' == $method) {
if (1 == $passenger) {
$dateBirth[] = $infoBirth[0]['BirthDate'];
$Birthdate = $infoBirth[0]['BirthDate'];
$cookieArray['birthDate'] = $Birthdate;
} else {
$dateBirth[] = $infoBirth[($i - 1)]['BirthDate'];
$Birthdate .= $infoBirth[($i - 1)]['BirthDate'].'*';
$cookieArray['birthDate'] = substr($Birthdate, 0, -1);
}
} else {
if (1 == $passenger) {
$dateBirth[] = $fullRequest->attributes->get('birth1');
$Birthdate = $fullRequest->attributes->get('birth1');
$cookieArray['birthDate'] = $Birthdate;
} else {
$dateBirth[] = $fullRequest->attributes->get('birth'.$i);
$Birthdate .= $fullRequest->attributes->get('birth'.$i).'*';
$cookieArray['birthDate'] = substr($Birthdate, 0, -1);
}
}
$calculoEdades[] = $insuranceService->calcular_edad($dateBirth[($i - 1)]);
if ($calculoEdades[($i - 1)] >= 0 && $calculoEdades[($i - 1)] < 2) {
$passanger_type[] = 1; //INF
} elseif ($calculoEdades[($i - 1)] >= 2 && $calculoEdades[($i - 1)] < 12) {
$passanger_type[] = 2; //CHD
} else {
$passanger_type[] = 3; //ADT
}
}
$cookieArray['Age'] = $calculoEdades;
$cookieArray['passanger_type'] = $passanger_type;
$cookieArray['birth'] = $dateBirth;
$cookieArray['domain_file'] = $domain_file;
$cookieArray['method'] = $method;
$urlAvailability = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/availability.html.twig');
if ($agency->getDomainsecure() == $agency->getDomain() && '443' !== $agency->getCustomport()) {
$safeUrl = 'https://'.$agency->getDomain();
} else {
$safeUrl = 'https://'.$agency->getDomainsecure();
}
$cookieLastSearch = $searchInsuranceCookie->searchInsuranceCookie(['insurance' => base64_encode(json_encode($cookieArray))]);
$regionMap = [
'1' => 'Norte America',
'2' => 'Europa - Medio Oriente',
'3' => 'Centro America & Caribe',
'4' => 'Sur America',
'5' => 'Africa',
'6' => 'Asia',
'7' => 'Oceania',
'8' => 'Colombia',
];
$availableArray = array_merge($cookieArray, ['destinationLabel' => $regionMap[$destiny]]);
if (!$isFront) {
// PIXELES INFORMATION
$pixel['partner_datalayer'] = [
'enabled' => true,
'event' => 'seguros_search',
'dimension1' => $destiny,
'dimension3' => $dateEntry,
'dimension4' => $dateEnd,
'dimension5' => 'Seguro de Viaje',
'dimension10' => $passenger,
'dimension12' => 'busqueda-seguro',
'ecommerce' => [
'currencyCode' => 'COP',
],
];
// $pixel['dataxpand'] = true;
$pixelInfo = $aviaturPixeles->verifyPixeles($pixel, 'insurance', 'availability', $agency->getAssetsFolder(), false);
}
$pointRedemption = $em->getRepository(\Aviatur\GeneralBundle\Entity\PointRedemption::class)->findPointRedemptionWithAgency($agency);
if (null != $pointRedemption) {
$points = 0;
if ($fullRequest->request->has('pointRedemptionValue')) {
$points = $fullRequest->request->get('pointRedemptionValue');
$session->set('point_redemption_value', $points);
} elseif ($fullRequest->query->has('pointRedeem')) {
$points = $fullRequest->query->get('pointRedeem');
$session->set('point_redemption_value', $points);
} elseif ($session->has('point_redemption_value')) {
$points = $session->get('point_redemption_value');
}
$pointRedemption['Config']['Amount']['CurPoint'] = $points;
}
$response = $this->render($urlAvailability, [
'ajaxUrl' => $requestUrl,
'availableArrayInsurance' => $availableArray,
'inlineEngine' => true,
'safeUrl' => $safeUrl,
'cookieLastSearch' => $cookieLastSearch,
'pixel_info' => $pixelInfo,
'pointRedemption' => $pointRedemption,
]);
$response->headers->setCookie(new Cookie('_availability_array[insurance]', base64_encode(json_encode($cookieArray)), (time() + 3600 * 24 * 7), '/'));
return $response;
}
return $this->render($urlAvailability, ['ProductsInfo' => $ProductInfo, 'variable' => $variable]);
}
public function formularioAction(Request $fullRequest, AviaturPixeles $aviaturPixeles, AuthorizationCheckerInterface $authorizationChecker, TwigFolder $twigFolder, AviaturEncoder $aviaturEncoder, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag, LoginManagerInterface $loginManager)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$transactionId = null;
$typePerson = [];
$pixel = [];
$server = $fullRequest->server;
$isAgent = false;
$em = $registry->getManager();
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$request = $fullRequest->request;
$agencyFolder = $twigFolder->twigFlux();
$paymentMethodAgency = $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency, 'isactive' => 1]);
$paymentOptions = [];
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);
}
foreach ($paymentMethodAgency as $payMethod) {
$paymentCode = $payMethod->getPaymentMethod()->getCode();
if (!in_array($paymentCode, $paymentOptions) && 'davivienda' != $paymentCode) {
$paymentOptions[] = $paymentCode;
}
}
$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
}
}
$banks = [];
if (in_array('pse', $paymentOptions)) {
$banks = $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
}
$conditions = $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'reservation_conditions_for_insurance');
$typeGender = $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
$typeDocument = $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
$publicKey = $aviaturEncoder->aviaturRandomKey();
$encodedInfo = $aviaturEncoder->AviaturEncode(json_encode($request), $publicKey);
$formUserInfo = new FormUserInfo();
$formUserInfo->setInfo($encodedInfo);
$formUserInfo->setPublicKey($publicKey);
$em->persist($formUserInfo);
$em->flush();
$routeName = $fullRequest->get('_route');
$fromCurrency = $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('USD');
$toCurrency = $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('COP');
$TRM = $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->findOneBy(['fromCurrency' => $fromCurrency, 'toCurrency' => $toCurrency], ['id' => 'DESC']);
$adt = 0;
$chd = 0;
$inf = 0;
if (true === $request->has('transactionId')) {
$transactionId = $request->get('transactionId');
$session->set($transactionIdSessionName, $transactionId);
} elseif (true === $session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
}
$session->set($transactionId.'[assist][request]', $request);
//$session->set($transactionId.'[assist][fullrequest]', $fullRequest);
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
$user = $this->getUser();
$emailuser = $user->getemail();
$agent = $user->getAgent();
if (!empty($agent[0])) {
$idagent = $agent[0]->getid();
$nombreagente = $user->getFirstname().' '.$user->getLastname();
$agencyFolder = $twigFolder->twigFlux();
$isAgent = true;
}
}
if ('aviatur_insurance_form_secure' == $routeName) {
$twig_readonly = false;
$session->set($transactionId.'[assist][user_info]', $formUserInfo->getId());
$session->set($transactionId.'[assist][provider]', $request->get('providerId'));
$session->set($transactionId.'[assist][detail]', $request);
$TypeID = explode('*', base64_decode($request->get('TypeID')));
$x_total_amount = $TypeID[3];
// $x_base_amount = str_replace(array('[',']'),'',$TypeID[4]);
$x_base_amount = $x_total_amount;
if ($isAgent) {
$x_base_amount -= (float) $TypeID[7];
$commissionAgent = $TypeID[7];
$commissionActive = $TypeID[8];
$commissionPay = $TypeID[9];
$activeDetail = $TypeID[10];
$amountTa = $TypeID[11];
$commissionTa = $TypeID[12];
$amountPay = $TypeID[13];
$percentageTarifa = $TypeID[14];
}
$method = $request->get('method');
if ('flight' == $method) {
$passanger = json_decode($session->get($transactionId.'[assist]'.'[infoInsuranceFlight]'), true);
$infoDataFlight = json_decode($session->get($transactionId.'[crossed]'.'[infoDataFlight]'), true);
$postData = json_decode($session->get($transactionId.'[flight][detail_data_flight]'));
// $passangerInfo = $postData->PI;
// $billingData = $postData->BD;
// $contactData = $postData->CD;
$passanger_type = $passanger['CoveredTraveler'];
for ($i = 0; $i < (is_countable($passanger_type) ? count($passanger_type) : 0); ++$i) {
if (1 == $passanger_type[$i]['passanger_type']) {
++$inf;
} elseif (2 == $passanger_type[$i]['passanger_type']) {
++$chd;
} else {
++$adt;
}
}
} else {
$passanger_type = json_decode($request->get('passanger_type'));
for ($i = 0; $i < (is_countable($passanger_type) ? count($passanger_type) : 0); ++$i) {
if (1 == $passanger_type[$i]) {
++$inf;
} elseif (2 == $passanger_type[$i]) {
++$chd;
} else {
++$adt;
}
}
}
$variables = [
'transactionId' => base64_encode($transactionId),
'destiny' => $request->get('destiny'),
'dateEntry' => $request->get('dateEntry'),
'dateEnd' => $request->get('dateEnd'),
'passenger' => $request->get('passenger'),
'birth' => $request->get('birth'),
'id' => $request->get('id'),
'TypeID' => base64_decode($request->get('TypeID')),
'informationCard' => base64_decode($request->get('informationCard')),
'providerId' => $request->get('providerId'),
'method' => $request->get('method'),
'passanger_type' => $passanger_type,
'Age' => json_decode($request->get('Age')),
'x_total_amount' => $x_total_amount,
'x_base_amount' => $x_base_amount,
'reintento' => false,
'payment_type_form_name' => 'paymentForm',
'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
'echoToken' => $request->get('echoToken'),
];
if ($isAgent) {
$variables['commissionAgent'] = $commissionAgent;
$variables['commissionActive'] = $commissionActive;
$variables['commissionPay'] = $commissionPay;
$variables['commissionTa'] = $commissionTa;
$variables['amountTa'] = $amountTa;
$variables['activeDetail'] = $activeDetail;
$variables['amountPay'] = $amountPay;
$info_product = ['amountQse' => (float) $commissionAgent,
'commissionQse' => (float) $commissionPay,
'amountTa' => (float) $amountTa,
'commissionTa' => (float) $commissionTa,
'amountPay' => (float) $amountPay,
'amountProduct' => $x_base_amount,
'percentageTarifa' => isset($percentageTarifa) ? (float) $percentageTarifa : 0, ];
$session->set($transactionId.'_agentInfoTransaction', $info_product);
}
} else {
$twig_readonly = true;
$detail = $session->get($transactionId.'[assist]'.'[detail]');
$detail_data_insurance = json_decode($session->get($transactionId.'[assist]'.'[detail_data_assist]'));
$infoclient = $session->get($transactionId.'[assist]'.'[infoclient]');
$TypeID = explode('*', base64_decode($detail->get('TypeID')));
$x_total_amount = $TypeID[3];
$method = $detail->get('method');
if ('flight' == $method) {
$passanger = json_decode($session->get($transactionId.'[assist]'.'[infoInsuranceFlight]'), true);
$passanger_type = $passanger['CoveredTraveler'];
for ($i = 0; $i < (is_countable($passanger_type) ? count($passanger_type) : 0); ++$i) {
if (1 == $passanger_type[$i]['passanger_type']) {
++$inf;
} elseif (2 == $passanger_type[$i]['passanger_type']) {
++$chd;
} else {
++$adt;
}
}
} else {
$passanger_type = json_decode($detail->get('passanger_type'));
for ($i = 0; $i < (is_countable($passanger_type) ? count($passanger_type) : 0); ++$i) {
if (1 == $passanger_type[$i]) {
++$inf;
} elseif (2 == $passanger_type[$i]) {
++$chd;
} else {
++$adt;
}
}
}
$billingData = $detail_data_insurance->BD;
$variables = [
'transactionId' => base64_encode($transactionId),
'destiny' => $detail->get('destiny'),
'dateEntry' => $detail->get('dateEntry'),
'dateEnd' => $detail->get('dateEnd'),
'passenger' => $detail->get('passenger'),
'birth' => $detail->get('birth'),
'id' => $detail->get('id'),
'TypeID' => base64_decode($detail->get('TypeID')),
'informationCard' => base64_decode($detail->get('informationCard')),
'providerId' => $detail->get('providerId'),
'method' => $detail->get('method'),
'passanger_type' => json_decode($detail->get('passanger_type')),
'Age' => json_decode($detail->get('Age')),
'x_total_amount' => $x_total_amount,
'reintento' => true,
'infoPassengers' => $detail_data_insurance->PI,
'infoclient' => $detail_data_insurance->BD,
'payment_type_form_name' => 'paymentForm',
'paymentsSaved' => isset($paymentsSaved) ? $paymentsSaved['info'] : null,
'echoToken' => $request->get('echoToken'),
];
}
$typePerson[1] = [
'ADT' => $adt,
'CHD' => $chd,
'INF' => $inf,
];
if ('flight' == $method) {
$information = $session->get($transactionId.'[crossed]'.'[infoDataFlight]');
$objectInfo = json_decode($information);
$variables['travelers'] = (array) $objectInfo->travelers;
$variables['facturation'] = $objectInfo->facturationResume;
if ('' == $variables['birth']) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('aviatur_insurance_prueba_secure'), '', 'No hay información'));
}
}
$session->set($transactionId.'[availability_url]', $server->get('HTTP_REFERER'));
$infoInsurance = simplexml_load_string($session->get($transactionId.'[assist]'.'[infoInsurance]'));
$urlAvailability = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/detail_form.html.twig');
$pixelInfo = [];
if (!$session->has('operatorId')) {
$pixel['partner_datalayer'] = [
'event' => 'seguros_checkout',
'dimension1' => $variables['destiny'],
'dimension3' => $variables['dateEntry'],
'dimension4' => $variables['dateEnd'],
'dimension5' => 'Seguro de Viaje',
'dimension10' => $variables['passenger'],
'dimension12' => 'checkout-seguro',
'ecommerce' => [
'checkout' => [
'products' => [
'actionField' => "{'step': 1}",
'name' => $TypeID[1],
'price' => $x_total_amount,
'brand' => 'assist card',
'category' => 'Seguros',
'variant' => $TypeID[1],
'quantity' => $variables['passenger'],
],
],
],
];
// $pixel['dataxpand'] = true;
$pixelInfo = $aviaturPixeles->verifyPixeles($pixel, 'insurance', 'detail', $agency->getAssetsFolder(), $transactionId);
$variables['pixel_info'] = $pixelInfo;
}
$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;
}
// dd($infoTravel);
/* Aplicando para vuelo, pero teniendo cuidado con los otros productos */
/* Necesitamos crear un arreglo que tenga todos los rangos de IIN asociados a su franquicia y a sus límites de número de tarjeta */
$iinRecordsArray = $this->getIINRanges($em);
$returnInfo = [
'billingData' => $billingData ?? null,
'services' => $typePerson,
'gender' => $typeGender,
'banks' => $banks,
'cybersource' => $cybersource,
'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 1]),
'inactiveCards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findBy(['isactive' => 0]),
'twig_readonly' => $twig_readonly,
'doc_type' => $typeDocument,
'variables' => $variables,
'conditions' => $conditions,
'paymentOptions' => $paymentOptions,
'pointRedemption' => $pointRedemption,
'pse' => in_array('pse', $paymentOptions) ? true : false,
'safety' => in_array('safety', $paymentOptions) ? true : false,
'ccranges' => $iinRecordsArray["ccranges"],
'ccfranchises' => $iinRecordsArray["ccfranchises"],
];
return $this->render($urlAvailability, $returnInfo);
}
public function prePaymentStep1Action(Request $request, TokenizerService $tokenizerService, CustomerMethodPaymentService $customerMethodPayment, TokenStorageInterface $tokenStorage, AviaturEncoder $aviaturEncoder, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag)
{
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
if ($request->isXmlHttpRequest()) {
$request = $request->request;
$selectionData = $request->get('SD');
$transactionId = base64_decode($selectionData['selection']);
$billingData = $request->get('BD');
$em = $registry->getManager();
$postData = $request->all();
$publicKey = $aviaturEncoder->aviaturRandomKey();
if (isset($postData['PD']['card_num'])) {
$postDataInfo = $postData;
if (isset($postDataInfo['PD']['cusPOptSelected'])) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $customerMethodPayment->getMethodsByCustomer($customerLogin, true);
$cardToken = $infoMethodPaymentByClient['info'][$postDataInfo['PD']['cusPOptSelected']]['token'];
$postDataInfo['PD']['card_num'] = $cardToken;
$postData['PD']['card_num'] = $cardToken;
} else {
$postDataInfo['PD']['card_num'] = $tokenizerService->getToken($postData['PD']['card_num']);
}
$postData['PD']['card_values'] = ['card_num_token' => $postDataInfo['PD']['card_num'], 'card_num' => $postData['PD']['card_num']];
}
$encodedInfo = $aviaturEncoder->AviaturEncode(json_encode($postDataInfo ?? $postData), $publicKey);
$formUserInfo = new FormUserInfo();
$formUserInfo->setInfo($encodedInfo);
$formUserInfo->setPublicKey($publicKey);
$em->persist($formUserInfo);
$em->flush();
$session->set($transactionId.'[assist][user_info]', $formUserInfo->getId());
if ((true !== $session->has($transactionId.'[assist][retry]')) || (true !== $session->has($transactionId.'[assist][prepayment_check]'))) {
if (true === $session->has($transactionId.'[assist][detail]')) {
//$postData = $request->all();
$session->set($transactionId.'[assist][detail_data_assist]', json_encode($postData));
$passangersData = $request->get('PI');
$passangerNames = [];
for ($i = 1; $i <= $passangersData['person_count_1']; ++$i) {
$passangerNames[] = mb_strtolower($passangersData['first_name_1_'.$i]);
$passangerNames[] = mb_strtolower($passangersData['last_name_1_'.$i]);
}
$nameWhitelist = $em->getRepository(\Aviatur\GeneralBundle\Entity\NameWhitelist::class)->findLikeWhitelist($passangerNames);
if (0 == sizeof($nameWhitelist)) {
$nameBlacklist = $em->getRepository(\Aviatur\GeneralBundle\Entity\NameBlacklist::class)->findLikeBlacklist($passangerNames);
if ((sizeof(preg_grep("/^[a-z- *\.]+$/", $passangerNames)) != (sizeof($passangerNames))) ||
(sizeof($nameBlacklist)) ||
(sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/', $passangerNames)))) {
return $this->json(['error' => 'error', 'message' => 'nombre inválido']);
}
}
$isFront = $session->has('operatorId');
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
if (false !== strpos($postData['PI']['first_name_1_1'], '***')) {
$postData['PI']['first_name_1_1'] = $customer->getFirstname();
$postData['PI']['last_name_1_1'] = $customer->getLastname();
$postData['PI']['phone_1_1'] = $customer->getPhone();
$postData['PI']['email_1_1'] = $customer->getEmail();
$postData['PI']['address_1_1'] = $customer->getAddress();
$postData['PI']['doc_num_1_1'] = $customer->getDocumentnumber();
}
if ($isFront) {
$session->set($transactionId.'[assist][customer_email]', $postData['PI']['email_1_1']);
$customer = null;
$ordersProduct = null;
} else {
$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.'[assist][retry]', $aviaturPaymentRetryTimes);
$detail = $session->get($transactionId.'[assist][detail]');
$cancelPenalties = (string) '';
$ajaxUrl = $this->generateUrl('aviatur_insurance_prepayment_step_2_secure');
return $this->json(['cancelPenalties' => $cancelPenalties, 'ajax_url' => $ajaxUrl]);
} else {
$booking = [];
$cus = [];
foreach ($ordersProduct as $orderProduct) {
$productResponse = $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
$paymentResponse = json_decode($productResponse);
array_push($booking, 'ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId());
if (isset($paymentResponse->x_approval_code)) {
array_push($cus, $paymentResponse->x_approval_code);
} elseif (isset($paymentResponse->createTransactionResult->trazabilityCode)) {
array_push($cus, $paymentResponse->createTransactionResult->trazabilityCode);
}
}
return $this->json([
'error' => 'pending payments',
'message' => 'pending_payments',
'booking' => $booking,
'cus' => $cus,
]);
}
} else {
return $this->json(['error' => 'fatal', 'message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos información del detalle de tu búsqueda, por favor inténtalo nuevamente')]);
}
} else {
$paymentData = $request->get('PD');
$paymentData = json_decode(json_encode($paymentData));
$json = json_decode($session->get($transactionId.'[assist][order]'));
if (!is_null($json)) {
$json->ajax_url = $this->generateUrl('aviatur_insurance_prepayment_step_2_secure');
// reemplazar datos de pago por los nuevos.
$oldPostData = json_decode($session->get($transactionId.'[assist][detail_data_assist]'));
if (isset($paymentData->cusPOptSelected) || isset($paymentData->card_num)) {
if (isset($paymentData->cusPOptSelected)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $customerMethodPayment->getMethodsByCustomer($customerLogin, true);
$card_num_token = $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
} else {
$card_num_token = $tokenizerService->getToken($paymentData->card_num);
}
$card_values = ['card_num_token' => $card_num_token, 'card_num' => $paymentData->card_num];
}
unset($oldPostData->PD);
$oldPostData->PD = $paymentData;
if (isset($card_num_token)) {
$oldPostData->PD->card_values = $card_values;
}
$session->set($transactionId.'[assist][detail_data_assist]', json_encode($oldPostData));
$response = new Response(json_encode($json));
$response->headers->set('Content-Type', 'application/json');
return $response;
} else {
return $this->json(['error' => 'fatal', 'message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos datos de tu orden, por favor inténtalo nuevamente')]);
}
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '', 'Acceso no autorizado'));
}
}
public function prePaymentStep2Action(
Request $request,
OrderController $orderController,
AuthorizationCheckerInterface $authorizationChecker,
AviaturErrorHandler $aviaturErrorHandler,
SessionInterface $session,
ManagerRegistry $registry,
InsuranceService $insuranceService,
AviaturWebService $aviaturWebService,
ParameterBagInterface $parameterBag,
\Swift_Mailer $mailer
)
{
$order = [];
if ($request->isXmlHttpRequest()) {
$em = $registry->getManager();
// $request = $request->request;
$selectionData = $request->get('SD');
$transactionId = base64_decode($selectionData['selection']);
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$billingData = $request->get('BD');
if (empty($billingData)) {
$detail_data_assist = json_decode($session->get($transactionId.'[assist]'.'[detail_data_assist]'));
$billingData = (array) $detail_data_assist->BD;
}
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
if (false !== strpos($billingData['first_name'], '***')) {
$billingData['first_name'] = $customer->getFirstname();
$billingData['last_name'] = $customer->getLastname();
$billingData['phone'] = $customer->getPhone();
$billingData['email'] = $customer->getEmail();
$billingData['address'] = $customer->getAddress();
$billingData['doc_num'] = $customer->getDocumentnumber();
$billingData['id'] = $customer->getAviaturclientid();
}
$session->set($transactionId.'[assist][prepayment_check]', true);
if (true !== $session->has($transactionId.'[assist][order]')) {
if (true === $session->has($transactionId.'[assist][detail]')) {
$isFront = $session->has('operatorId');
if ($isFront) {
$customer = $billingData;
$customer['isFront'] = true;
$status = 'B2T';
} else {
$status = 'waiting';
}
if (isset($agency)) {
$productType = $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findByCode('ASSIST');
if ($isFront) {
$orderIdentifier = '{order_product_reservation}';
} else {
$orderIdentifier = '{order_product_num}';
}
$order = $orderController->createAction($agency, $customer, $productType, $orderIdentifier, $status);
$orderId = str_replace('ON', '', $order['order']);
$orderEntity = $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
$formUserInfo = $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[assist][user_info]'));
$formUserInfo->setOrder($orderEntity);
$em->persist($formUserInfo);
$em->flush();
// Agent Transaction, Save commission QSE or Percentage
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
$orderInfo = json_decode($session->get($transactionId.'[assist][order]'));
$productId = str_replace('PN', '', $orderInfo->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$agentId = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
$agentCommission = $em->getRepository(\Aviatur\AgentBundle\Entity\AgentCommission::class)->findOneByAgent($agentId);
$arrayInfo = $session->get($transactionId.'_agentInfoTransaction');
// $commissionPay = $selectionData['commissionPay'];
$agentTransaction = new AgentTransaction();
$agentTransaction->setAgent($agentId);
$agentTransaction->setAgentCommission($agentCommission);
$agentTransaction->setOrderProduct($orderProduct);
$agentTransaction->setCommissionvalue($arrayInfo['amountPay']);
$agentTransaction->setAmountQse($arrayInfo['amountQse']);
$agentTransaction->setCommissionQse($arrayInfo['commissionQse']);
$agentTransaction->setPercentageTarifa($arrayInfo['percentageTarifa']);
$agentTransaction->setAmountTarifa($arrayInfo['amountTa']);
$agentTransaction->setCommissionTarifa($arrayInfo['commissionTa']);
$agentTransaction->setAmountProduct($arrayInfo['amountProduct']);
$em->persist($agentTransaction);
$em->flush();
}
if ($isFront) {
$order['Transaction'] = $this->createOrderAction($request,$insuranceService,$aviaturWebService,$session,$registry,$parameterBag,$mailer,$transactionId);
$order['Transaction']['resumeView']['Estado'] = 'OK';
if ('Error' == $order['Transaction']['resumeView']['Estado']) {
$order['url'] = $this->generateUrl('aviatur_insurance_payment_error_front_secure');
} else {
$order['url'] = $this->generateUrl('aviatur_insurance_payment_front_secure');
}
} else {
$order['url'] = $this->generateUrl('aviatur_insurance_payment_secure');
}
return $this->json($order);
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '', 'No se encontró la agencia con el dominio: '.$request->getHost()));
}
} else {
return $this->json(['error' => 'fatal', 'message' => $aviaturErrorHandler->errorRedirect($session->get($transactionId.'[availability_url]'), '', 'No encontramos información del detalle de tu búsqueda, por favor inténtalo nuevamente')]);
}
} else {
$order['url'] = $this->generateUrl('aviatur_insurance_payment_secure');
return $this->json($order);
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '', 'Acceso no autorizado'));
}
}
public function paymentAction(Request $request, CashController $cashPaymentController, SafetypayController $safetyPayController, PSEController $aviaturPsePaymentController, RouterInterface $router, WorldPayController $worldPaymentController, P2PController $p2pPaymentController, InsuranceService $insuranceService, AviaturLogSave $aviaturLogSave, CustomerMethodPaymentService $customerMethodPayment, TokenStorageInterface $tokenStorage, AuthorizationCheckerInterface $authorizationChecker, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag, \Swift_Mailer $mailer,TokenizerService $tokenizerService, OrderController $orderController)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$emailNotification = $parameterBag->get('email_notification');
$orderProduct = [];
$dateBirth = [];
$GivenName = [];
$Surname = [];
$Email = [];
$StateCode = [];
$Telephone = [];
$Document = [];
$CityName = [];
$GivenName_contact = [];
$Surname_contact = [];
$Telephone_contact = [];
$calculoEdades = [];
$paymentResponse = null;
$return = null;
$response = null;
$array = [];
$isAgent = false;
$em = $registry->getManager();
$transactionId = $session->get($transactionIdSessionName);
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
$isAgent = true;
}
$postData = json_decode($session->get($transactionId.'[assist][detail_data_assist]'));
$infoInsurance = $session->get($transactionId.'[assist][infoInsurance]');
$detail = $session->get($transactionId.'[assist][detail]');
$aviaturLogSave->logSave(print_r($detail, true), 'InsuranceOrder', 'RS');
$orderInfo = json_decode($session->get($transactionId.'[assist][order]'));
@$productId = str_replace('PN', '', $orderInfo->products);
$orderProduct[] = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$startDate = $detail->get('dateEntry');
$endDate = $detail->get('dateEnd');
$passenger = $detail->get('passenger');
$method = $detail->get('method');
$destiny = $detail->get('destiny');
$echoToken = $detail->get('echoToken');
$parameters = json_decode($session->get($request->getHost().'[parameters]'));
$aviaturPaymentIva = (float) $parameters->aviatur_payment_iva;
$TypeID = explode('*', base64_decode($detail->get('TypeID')));
$paymentData = $postData->PD;
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$configInsuranceAgency = $em->getRepository(\Aviatur\InsuranceBundle\Entity\ConfigInsuranceAgency::class)->findOneByAgency($agency);
$OfficeId = explode('-', $configInsuranceAgency->getOfficeId());
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$fromCurrency = $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('USD');
$toCurrency = $em->getRepository(\Aviatur\TrmBundle\Entity\Currency::class)->findOneByIata('COP');
$TRM = $em->getRepository(\Aviatur\TrmBundle\Entity\Trm::class)->findOneBy(['fromCurrency' => $fromCurrency, 'toCurrency' => $toCurrency], ['id' => 'DESC']);
$x_total_amount = (int) $TypeID[3];
if ('COP' != $TypeID[2]) {
$x_total_amount = (int) $TypeID[3] * $TRM->getRate()->getFinantialrate();
}
$x_amount_base = $x_total_amount / (1 + $aviaturPaymentIva);
$x_amount_iva = $x_amount_base * $aviaturPaymentIva;
$description = 'Tarjeta Asistencia - '.$TypeID[1].' - ('.$startDate.' - '.$endDate.')';
$diffDays = ((strtotime($endDate) - strtotime($startDate)) / 86400) + 1;
$PI = (array) $postData->PI;
if (false !== strpos($PI['first_name_1_1'], '***')) {
$PI['first_name_1_1'] = $customer->getFirstname();
$PI['last_name_1_1'] = $customer->getLastname();
$PI['phone_1_1'] = $customer->getPhone();
$PI['email_1_1'] = $customer->getEmail();
$PI['address_1_1'] = $customer->getAddress();
$PI['doc_num_1_1'] = $customer->getDocumentnumber();
}
$variable = [
'echoToken' => $echoToken,
'PlanID' => $detail->get('id'),
'TypeID' => $TypeID[0],
'OfficeId' => $OfficeId[1],
'AgencyId' => substr($OfficeId[0], 1),
'transactionId' => $transactionId,
'correlationId' => $detail->get('correlationId'),
'EffectiveDate' => $startDate,
'ExpireDate' => $endDate,
'MaximumTripLength' => 'P'.$diffDays.'D',
'AreaID' => $destiny,
'ProviderId' => $detail->get('providerId'),
'method' => $method,
];
$emailUser = $PI['email_1_1'];
$isFront = false;
if ($session->has('operatorId')) {
$isFront = true;
$userFront = simplexml_load_string($session->get('front_user'));
$additionalUserFront = simplexml_load_string($session->get('front_user_additionals'));
$variable['OperatorId'] = (string) $userFront->ID_AGENTE;
$variable['OfficeId'] = (string) $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
$variable['AgencyId'] = substr((string) $userFront->CODIGO_OFICINA_PERTENECE, 0, 2);
$emailUser = (string) $userFront->CORREO_ELECTRONICO;
}
for ($i = 1; $i <= $passenger; ++$i) {
if (1 == $passenger) {
$dateBirth[] = $PI['birthday_1_1'];
$GivenName[] = $PI['first_name_1_1'];
$Surname[] = $PI['last_name_1_1'];
$Email[] = $emailUser;
$StateCode[] = $PI['origin_1_1'];
$Telephone[] = $PI['phone_contact_1_1'];
$Document[] = $PI['doc_num_1_1'];
$originValidate = explode(',', $PI['origin_1_1Validate']);
$CityName[] = $originValidate[0];
$GivenName_contact[] = $PI['first_name_contact_1_1'];
$Surname_contact[] = $PI['last_name_contact_1_1'];
$Telephone_contact[] = $PI['phone_contact_1_1'];
} else {
$dateBirth[] = $PI['birthday_1_'.$i];
$GivenName[] = $PI['first_name_1_'.$i];
$Surname[] = $PI['last_name_1_'.$i];
$Email[] = $emailUser;
$StateCode[] = $PI['origin_1_'.$i];
$Telephone[] = $PI['phone_contact_1_'.$i];
$Document[] = $PI['doc_num_1_'.$i];
$originValidate = explode(',', $PI['origin_1_'.$i.'Validate']);
$CityName[] = $originValidate[0];
$GivenName_contact[] = $PI['first_name_contact_1_'.$i];
$Surname_contact[] = $PI['last_name_contact_1_'.$i];
$Telephone_contact[] = $PI['phone_contact_1_'.$i];
}
$calculoEdades[] = $insuranceService->calcular_edad($dateBirth[($i - 1)]);
$variable['CoveredTraveler'][] = [
'BirthDate' => $dateBirth[($i - 1)],
'Age' => $calculoEdades[($i - 1)],
'GivenName' => $GivenName[($i - 1)],
'Surname' => $Surname[($i - 1)],
'Email' => $Email[($i - 1)],
'StateCode' => $StateCode[($i - 1)],
'CityName' => $CityName[($i - 1)],
'Telephone' => $Telephone[($i - 1)],
'Document' => $Document[($i - 1)],
'GivenName_contact' => $GivenName_contact[($i - 1)],
'Surname_contact' => $Surname_contact[($i - 1)],
'Telephone_contact' => $Telephone_contact[($i - 1)],
];
}
$InsuranceModel = new InsuranceModel();
$searchInsurance = ['{EchoToken}', '{PlanID}', '{TypeID}', '{OfficeId}', '{AgencyId}', '{transactionId}', '{correlationId}', '{EffectiveDate}', '{ExpireDate}', '{MaximumTripLength}', '{AreaID}'];
$xmlTemplate = $InsuranceModel->getXmlCreateOrder($variable, $isFront);
$xmlCreateOrder = str_replace($searchInsurance, $variable, $xmlTemplate);
if ('p2p' == $paymentData->type || 'world' == $paymentData->type) {
if (isset($paymentData->cusPOptSelected)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$infoMethodPaymentByClient = $customerMethodPayment->getMethodsByCustomer($customerLogin, true);
$cardToken = $infoMethodPaymentByClient['info'][$paymentData->cusPOptSelected]['token'];
$paymentData->card_num = $cardToken;
$paymentData->card_values->card_num_token = $cardToken;
}
if (!empty($paymentData)) {
if (false !== strpos($paymentData->address, '***')) {
$paymentData->address = $customer->getAddress();
}
if (false !== strpos($paymentData->phone, '***')) {
$paymentData->phone = $customer->getPhone();
}
if (false !== strpos($paymentData->email, '***')) {
$paymentData->email = $customer->getEmail();
}
}
$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' => $paymentData->first_name,
'x_last_name' => $paymentData->last_name,
'x_description' => $description,
'x_city' => $customer->getCity()->getIatacode(),
'x_country_id' => $customer->getCountry()->getIatacode(),
'x_cust_id' => $paymentData->doc_type.' '.$paymentData->doc_num,
'x_address' => $paymentData->address,
'x_phone' => $paymentData->phone,
'x_email' => $paymentData->email,
'x_card_num' => $paymentData->card_num,
'x_exp_date' => $paymentData->exp_month.$paymentData->exp_year,
'x_card_code' => $paymentData->card_code,
'x_differed' => $paymentData->differed,
'x_client_id' => $postData->BD->id,
'product_type' => 'assist',
'x_cant_passenger' => $passenger,
'franchise' => $paymentData->franquise,
'worldpay_validate' => true,
];
if (isset($paymentData->card_values)) {
$array['card_values'] = (array) $paymentData->card_values;
}
if ('p2p' == $paymentData->type) {
if (isset($paymentData->cusPOptSelected)) {
$array['isToken'] = (string) $paymentData->card_values->card_num_token;
}
if (isset($postData->PD->savePaymProc)) {
$array['x_provider_id'] = 1;
} elseif (isset($paymentData->cusPOptSelected)) {
if (isset($paymentData->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $paymentData->cusPOptSelectedStatus) {
$array['x_provider_id'] = 1;
} else {
$array['x_provider_id'] = 2;
}
} else {
$array['x_provider_id'] = 2;
}
}
}
if ('p2p' == $paymentData->type) {
$paymentResponse = $p2pPaymentController->placetopayAction($parameterBag,$tokenizerService,$customerMethodPayment,$mailer,$aviaturLogSave,$array);
$return = 'aviatur_insurance_payment_p2p_return_url_secure';
} elseif ('world' == $paymentData->type) {
$array['city'] = $customer->getCity()->getIatacode();
$array['countryCode'] = $customer->getCity()->getCountry()->getIatacode();
$paymentResponse = $worldPaymentController->worldAction($array);
$return = 'aviatur_insurance_payment_world_return_url_secure';
}
$emissionData = $insuranceService->xmlInsuranceExtra($transactionId, false);
unset($array['x_client_id']);
if (null != $paymentResponse) {
return $this->redirect($this->generateUrl($return, [], true));
} else {
$orderProduct[0]->setStatus('pending');
$em->persist($orderProduct[0]);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_insurance_retry_secure'), '', 'No hay respuesta por parte del servicio de pago, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción'));
}
} elseif ('pse' == $paymentData->type) {
$array = ['x_doc_num' => $customer->getDocumentnumber(),
'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
'x_first_name' => $customer->getFirstname(),
'x_last_name' => $customer->getLastname(),
'x_company' => 'Aviatur',
'x_email' => $customer->getEmail(),
'x_address' => $customer->getAddress(),
'x_city' => $customer->getCity()->getDescription(),
'x_province' => $customer->getCity()->getDescription(),
'x_country' => $customer->getCountry()->getDescription(),
'x_phone' => $customer->getPhone(),
'x_mobile' => $customer->getCellphone(),
'x_bank' => $paymentData->pse_bank,
'x_type' => $paymentData->pse_type,
'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
'x_description' => $TypeID[1],
'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, '.', ''),
'x_cant_passenger' => $passenger,
'product_type' => 'assist',
];
$route = $router->match(str_replace($request->getSchemeAndHttpHost(), '', $request->getUri()));
$isMulti = false !== strpos($route['_route'], 'multi') ? true : false;
if ($isMulti) {
return $this->json($array);
}
$paymentResponse = $aviaturPsePaymentController->sendPaymentAction($request,$session,$router,$parameterBag,$mailer,$orderController,$array, $orderProduct);
$emissionData = $insuranceService->xmlInsuranceExtra($transactionId, false);
if (!isset($paymentResponse->error)) {
switch ($paymentResponse->createTransactionResult->returnCode) {
case 'SUCCESS':
return $this->redirect($paymentResponse->createTransactionResult->bankURL);
case 'FAIL_EXCEEDEDLIMIT':
return $this->redirect($this->generateUrl('homepage'), '');
case 'FAIL_BANKUNREACHEABLE':
return $this->redirect($this->generateUrl('aviatur_insurance_retry_secure'), '');
default:
return $this->redirect($this->generateUrl('aviatur_insurance_retry_secure'), '');
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_insurance_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' => $TypeID[1],
'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' => 'assist',
'x_cant_passenger' => $passenger,
'product_type' => 'assist',
'xmlCreateOrder' => $xmlCreateOrder,
];
$parametMerchant = [
'MerchantSalesID' => $array['x_reference'],
'Amount' => $array['x_total_amount'],
'transactionUrl' => $transactionUrl,
'dataTrans' => $array,
];
$safeTyPay = $safetyPayController->safetyAction($router, $parameterBag, $mailer, $parametMerchant, $array);
$emissionData = $insuranceService->xmlInsuranceExtra($transactionId, false);
if ('ok' == $safeTyPay['status']) {
if ('baloto' == $paymentData->type) {
$cash = '&CountryId=COL&ChannelId=CASH';
$session->set($transactionId.'[assist][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_insurance_payment_rejected_secure'));
}
} elseif ('cash' == $paymentData->type) {
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$agencyName = $agency->getOfficeId();
$array['x_officeId'] = $agencyName;
$array['x_doc_num'] = $customer->getDocumentnumber();
$array['x_doc_type'] = $customer->getDocumentType()->getPaymentcode();
$array['x_first_name'] = $customer->getFirstname();
$array['x_last_name'] = $customer->getLastname();
$array['x_company'] = 'Aviatur';
$array['x_email'] = $customer->getEmail();
$array['x_address'] = $customer->getAddress();
$array['x_city'] = $customer->getCity()->getDescription();
$array['x_province'] = $customer->getCity()->getDescription();
$array['x_country'] = $customer->getCountry()->getDescription();
$array['x_phone'] = $customer->getPhone();
$array['x_mobile'] = $customer->getCellphone();
$array['x_payment_data'] = $paymentData->type;
$array['x_type_description'] = $orderProduct[0]->getDescription();
$array['x_reference'] = $orderInfo->products;
$array['x_total_amount'] = number_format(round((float) ($x_total_amount)), 0, '.', '');
$array['x_currency'] = 'COP';
$array['x_description'] = $description;
$array['x_cant_passenger'] = $passenger;
$array['x_booking'] = $orderProduct[0]->getBooking();
$array['product_type'] = 'assist';
$fecha = $orderProduct[0]->getCreationDate()->format('Y-m-d H:i:s');
$fechalimite = $orderProduct[0]->getCreationDate()->format('Y-m-d 23:40:00');
$nuevafecha = strtotime('+2 hour', strtotime($fecha));
$fechavigencia = date('Y-m-d H:i:s', $nuevafecha);
if (strcmp($fechavigencia, $fechalimite) > 0) {
$fechavigencia = $fechalimite;
}
$array['x_fechavigencia'] = $fechavigencia;
$array['x_transactionId'] = $transactionId;
$retryCount = (int) $session->get($transactionId.'[assist][retry]');
if ($session->has($transactionId.'[assist][detail_cash]')) {
$detail_cash = json_decode($session->get($transactionId.'[assist][detail_cash]'));
if ('error' == $detail_cash->status) {
$cashPay = $cashPaymentController->cashAction($array);
} else {
$cashPay = json_decode($session->get($transactionId.'[assist][detail_cash]'));
}
} else {
$cashPay = $cashPaymentController->cashAction($aviaturLogSave, $array);
$session->set($transactionId.'[assist][detail_cash]', json_encode($cashPay));
}
$emissionData = $insuranceService->xmlInsuranceExtra($transactionId, false);
if ('ok' == $cashPay->status) {
$session->set($transactionId.'[assist][cash_result]', json_encode($cashPay));
return $this->redirect($this->generateUrl('aviatur_insurance_confirmation_success_secure'));
} else {
$emissionData['x_first_name'] = $array['x_first_name'];
$emissionData['x_last_name'] = $array['x_last_name'];
$emissionData['x_doc_num'] = $array['x_doc_num'];
$emissionData['x_reference'] = $array['x_reference'];
$emissionData['x_description'] = $array['x_description'];
$emissionData['x_total_amount'] = $array['x_total_amount'];
$emissionData['x_email'] = $array['x_email'];
$emissionData['x_address'] = $array['x_address'];
$emissionData['x_phone'] = $array['x_phone'];
$emissionData['x_type_description'] = $array['x_type_description'];
$emissionData['x_error'] = $cashPay->status;
$mailInfo = print_r($emissionData, true).'<br>'.print_r($cashPay, true);
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
// ->setTo('soportepagoelectronico@aviatur.com.co', 'soptepagelectronic@aviatur.com', $emailNotification)
->setSubject('Error Creación Transacción Efectivo'.$emissionData['x_reference'])
->setBody($mailInfo);
$mailer->send($message);
$session->set($transactionId.'[assist][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl('aviatur_insurance_payment_rejected_secure'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_insurance_retry_secure'), '', 'El tipo de pago es inválido'));
}
}
public function p2pCallbackAction(
Request $request,
InsuranceService $insuranceService,
AviaturWebService $aviaturWebService,
SessionInterface $session,
ValidateSanctions $validateSanctions,
AviaturMailer $aviaturMailer,
OrderController $orderController,
CustomerMethodPaymentService $customerMethodPayment,
TokenStorageInterface $tokenStorage,
AviaturEncoder $aviaturEncoder,
AviaturErrorHandler $aviaturErrorHandler,
ManagerRegistry $registry,
ParameterBagInterface $parameterBag,
\Swift_Mailer $mailer
)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$agency = null;
$session = $session;
$em = $registry->getManager();
$transactionId = $session->get($transactionIdSessionName);
$orderProductCode = $session->get($transactionId.'[assist][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$decodedRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
$jsonSendEmail = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('send_email');
if (isset(json_decode($jsonSendEmail->getDescription())->email)) {
$email = json_decode($jsonSendEmail->getDescription())->email->CallBack;
}
$reference = str_replace('{"order":"', '', $orderProductCode);
$reference = str_replace('","products":"', '-', $reference);
$reference = str_replace('"}', '', $reference);
$references = $reference;
$bookings = $orderProduct->getBooking();
if (null != $decodedResponse) {
//$prepaymentInfo = \simplexml_load_string($session->get($transactionId . '[hotel][prepayment]'));
$twig = '';
$additionalQS = '';
if (!isset($decodedResponse->x_response_code)) {
$twig = '' != $twig ? $twig : 'aviatur_insurance_payment_rejected_secure';
$retryCount = 1;
} else {
$retryCount = (int) $session->get($transactionId.'[assist][retry]');
if (isset($decodedResponse->x_response_code_cyber) && (2 == $decodedResponse->x_response_code_cyber)) {
$decodedResponse->x_response_code_case = 99;
} else {
$decodedResponse->x_response_code_case = $decodedResponse->x_response_code;
}
switch ($decodedResponse->x_response_code_case) {
case 99:
//rechazado cybersource
$parameters = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
if ($parameters) {
if (1 == $parameters->getValue()) {
if (1 == $decodedResponse->x_response_code) {
$postData = json_decode($session->get($transactionId.'[assist][detail_data_assist]'));
if (isset($postData->PD->cusPOptSelected)) {
if (isset($postData->PD->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
$postData->PD->cusPOptSelectedStatus = 'ACTIVE';
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPayment->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
if (isset($postData->PD->savePaymProc)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPayment->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
}
$twig = 'aviatur_insurance_payment_rejected_secure';
// no break
case 3:// pendiente p2p
$twig = '' != $twig ? $twig : 'aviatur_insurance_payment_pending_secure';
$retryCount = 1;
break;
case 0:// error p2p
$twig = 'aviatur_insurance_payment_error_secure';
if (isset($email)) {
$from = $session->get('emailNoReply');
$error = $twig;
$subject = $orderProduct->getDescription().':Error en el proceso de pago de Aviatur';
$body = '</br>El proceso de pago a retornado un error </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
$aviaturMailer->sendEmailGeneral($from, $email, $subject, $body);
}
// no break
case 2:// rechazada p2p
$twig = '' != $twig ? $twig : 'aviatur_insurance_payment_rejected_secure';
if (isset($email)) {
$from = $session->get('emailNoReply');
$error = $twig;
$subject = $orderProduct->getDescription().':Transacción rechazada';
$body = '</br>El pago fue rechazado </br>Referencia: '.$references.'</br>Reserva:'.$bookings;
$aviaturMailer->sendEmailGeneral($from, $email, $subject, $body);
}
break;
case 1:// aprobado p2p
$postData = json_decode($session->get($transactionId.'[assist][detail_data_assist]'));
if (isset($postData->PD->cusPOptSelected)) {
if (isset($postData->PD->cusPOptSelectedStatus)) {
if ('NOTVERIFIED' == $postData->PD->cusPOptSelectedStatus) {
$postData->PD->cusPOptSelectedStatus = 'ACTIVE';
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPayment->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
}
}
if (isset($postData->PD->savePaymProc)) {
$customerLogin = $tokenStorage->getToken()->getUser();
$customerMethodPayment->setMethodsByCustomer($customerLogin, json_decode(json_encode($postData), true));
}
$twig = 'aviatur_insurance_payment_success_secure';
if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
$additionalQS = '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->x_amount;
}
//Reemplazar por consumo de reserva!!!!
$updateOrder = $orderController->updatePaymentAction($orderProduct, false, null);
$session->set($transactionId.'[assist][retry]', $aviaturPaymentRetryTimes);
$response = $this->createOrderAction($request,$insuranceService,$aviaturWebService,$session,$registry,$parameterBag,$mailer,$transactionId);
if ('Error' == $response['resumeView']['Estado']) {
$session->set($transactionId.'[emission][error]', true);
return $this->redirect($this->generateUrl('aviatur_insurance_payment_success_secure'));
}
break;
}
$session->set($transactionId.'[assist][retry]', $retryCount - 1);
}
$urlResume = $this->generateUrl($twig);
$urlResume .= $additionalQS;
//////// se envia el correo del modulo anti fraude en caso de ser necesario//////////
if ($session->has('Marked_name') && $session->has('Marked_document')) {
$product = 'Vuelo';
$validateSanctions->sendMarkedEmail($orderProductCode, $session, $agency, $orderProduct, $transactionId, $product);
}
////////////////////////////////////////////////////////////////////////////////////
return $this->redirect($urlResume);
} else {
$orderProduct->setStatus('pending');
$em->persist($orderProduct);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_insurance_retry_secure'), '', 'No hay respuesta por parte del servicio de pago'));
}
}
public function pseCallbackAction(Request $request, SessionInterface $session, PSEController $aviaturPsePaymentController, OrderController $orderController, TwigFolder $twigFolder, AviaturEncoder $aviaturEncoder, AviaturErrorHandler $aviaturErrorHandler, ManagerRegistry $registry, InsuranceService $insuranceService, AviaturWebService $aviaturWebService, ParameterBagInterface $parameterBag, $transaction, \Swift_Mailer $mailer)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$decodedRequest = null;
$status = null;
$twig = null;
$session = $session;
$em = $registry->getManager();
if ($session->has('agencyId')) {
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
} 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['assist'])) {
$assistOrders = explode('+', $orders['assist']);
$orderProductCode = $assistOrders[0];
$productId = $assistOrders[0];
$retryCount = 1;
} else {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontro identificador de la transacción'));
}
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
if (empty($orderProduct)) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró orden asociada a este pago'));
} else {
if ('approved' == $orderProduct->getStatus()) {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), '', 'No se encontró información de la transacción'));
}
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
if (isset($decodedResponse->createTransactionResult)) {
$additionalQS = '';
$pseTransactionId = $decodedResponse->createTransactionResult->transactionID;
$paymentResponse = $aviaturPsePaymentController->pseCallbackAction($orderController,$pseTransactionId);
if (!isset($paymentResponse->error)) {
if (!$session->has($transactionId.'[assist][detail_data_assist]')) {
$message = 'Una vez el pago sea confirmado recibirá su confirmación de reserva, de no ser así comuníquese con nuestra central de reservas.';
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($twigFolder->pathWithLocale('aviatur_general_homepage'), 'Gracias por su compra', $message));
}
$decodedResponse->getTransactionInformationResult = $paymentResponse->getTransactionInformationResult;
$orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
if ('SUCCESS' == (string) $paymentResponse->getTransactionInformationResult->returnCode) {
switch ((string) $paymentResponse->getTransactionInformationResult->transactionState) {
case 'OK':
$twig = 'aviatur_insurance_payment_success_secure';
$status = 'approved';
if ('rappi' == $orderProduct->getOrder()->getAgency()->getAssetsFolder()) {
$additionalQS = '?bookingid='.$orderProduct->getBooking().'&total='.$decodedRequest->totalAmount;
}
break;
case 'PENDING':
$twig = 'aviatur_insurance_payment_pending_secure';
$status = 'pending';
break;
case 'NOT_AUTHORIZED':
$twig = 'aviatur_insurance_payment_error_secure';
$status = 'rejected';
break;
case 'FAILED':
$twig = 'aviatur_insurance_payment_error_secure';
$status = 'failed';
break;
}
$orderProduct->setStatus($status);
$orderProduct->getOrder()->setStatus($status);
$orderProduct->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
if ('approved' == $status) {
// //Reemplazar por consumo de reserva!!!!
$orderController->updatePaymentAction($orderProduct, false, null);
$response = $this->createOrderAction($request,$insuranceService,$aviaturWebService,$session,$registry,$parameterBag,$mailer,$transactionId);
$session->set($transactionId.'[assist][retry]', $aviaturPaymentRetryTimes);
if ('Error' == $response['resumeView']['Estado']) {
$session->set($transactionId.'[emission][error]', true);
}
}
} elseif ('FAIL_INVALIDTRAZABILITYCODE' == (string) $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_ACCESSDENIED' == $paymentResponse->getTransactionInformationResult->returnCode || 'FAIL_TIMEOUT' == $paymentResponse->getTransactionInformationResult->returnCode) {
echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
transacción <#CUS> .';
$orderProduct->setEmissiondata('error');
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$twig = 'aviatur_insurance_payment_error_secure';
}
if ($session->has($transactionId.'[assist][retry]')) {
$session->set($transactionId.'[assist][retry]', $retryCount - 1);
}
$urlResume = $this->generateUrl($twig);
$urlResume .= $additionalQS;
return $this->redirect($urlResume);
} else {
$decodedResponse->getTransactionInformationResult = $paymentResponse;
$orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('homepage'), '', 'Ocurrió un error al consultar el estado de la transacción'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl('homepage'), '', 'No se encontró información de la transacción'));
}
}
}
public function safetyCallbackOkAction(
Request $request,
SessionInterface $session,
SafetypayController $safetyPayController,
OrderController $orderController,
AviaturEncoder $aviaturEncoder,
AviaturErrorHandler $aviaturErrorHandler,
ManagerRegistry $registry,
ParameterBagInterface $parameterBag,
InsuranceService $insuranceService,
AviaturWebService $aviaturWebService,
\Swift_Mailer $mailer)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$status = null;
$twig = null;
$em = $registry->getManager();
$safeTyPay = $safetyPayController->safetyok();
if (true === $session->has($transactionIdSessionName)) {
$transactionId = $session->get($transactionIdSessionName);
if (true === $session->has($transactionId.'[assist][order]')) {
$orderProductCode = $session->get($transactionId.'[assist][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$decodedRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
$payError = $decodedResponse->payResponse->OperationResponse->ErrorManager->ErrorNumber->{'@content'};
$notifyError = $decodedResponse->notificationResponse->OperationActivityNotifiedResponse->ErrorManager->ErrorNumber->{'@content'};
if (isset($decodedResponse->payResponse->OperationResponse)) {
if (0 == $payError) {
$retryCount = (int) $session->get($transactionId.'[assist][retry]');
if (0 == $notifyError) {
switch ($payError) {
case 0:
$twig = 'aviatur_insurance_payment_success_secure';
$status = 'approved';
break;
case 2:
$twig = 'aviatur_insurance_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 (0 == $payError) {
if ('approved' == $status) {
//Reemplazar por consumo de reserva!!!!
$response = $this->createOrderAction($request,$insuranceService,$aviaturWebService,$session,$registry,$parameterBag,$mailer,$transactionId);
$session->set($transactionId.'[assist][retry]', $aviaturPaymentRetryTimes);
if ('Error' == $response['resumeView']['Estado']) {
$session->set($transactionId.'[emission][error]', true);
}
return $this->redirect($this->generateUrl('aviatur_insurance_payment_success_secure'));
}
}
} else {
echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
transacción <#CUS> .';
$orderProduct->setEmissiondata('error');
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
$twig = 'aviatur_insurance_payment_error_secure';
}
$session->set($transactionId.'[assist][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl($twig));
} else {
$decodedResponse->payResponse->OperationResponse->ListOfOperations = $paymentResponse;
$orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '', 'Ocurrió un error al consultar el estado de la transacción'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '', 'No se encontró información de la transacción, por favor comuniquese con nosotros'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '', 'No se encontró orden asociada a este pago'));
}
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '', 'No se encontró identificador de la transacción'));
}
}
public function safetyCallbackErrorAction(Request $request, AviaturEncoder $aviaturEncoder, AviaturErrorHandler $aviaturErrorHandler, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$status = null;
$fullRequest = $request;
$em = $registry->getManager();
$transactionId = $session->get($transactionIdSessionName);
$retryCount = (int) $session->get($transactionId.'[assist][retry]');
$orderProductCode = json_decode($session->get($transactionId.'[assist][order]'));
$productId = str_replace('PN', '', $orderProductCode->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$payResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
$payRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayRequest(), $orderProduct->getPublicKey()));
$orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($payResponse), $orderProduct->getPublicKey()));
if ('baloto' == $payRequest->dataTransf->x_payment_data) {
$status = 'pending';
$payResponse->dataTransf->x_response_code = 100;
$payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Pending';
} elseif ('safety' == $payRequest->dataTransf->x_payment_data) {
$status = 'rejected';
$payResponse->dataTransf->x_response_code = 100;
$payResponse->dataTransf->x_response_reason_text = (string) 'Transaction Expired';
}
$orderProduct->setStatus($status);
$orderProduct->setUpdatingdate(new \DateTime());
$orderProduct->getOrder()->setUpdatingdate(new \DateTime());
$order = $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderProduct->getOrder()->getId());
$order->setStatus($status);
$em->persist($order);
$em->persist($orderProduct);
$em->flush();
if (true === $session->has($transactionId.'[assist][order]')) {
$orderProductCode = $session->get($transactionId.'[assist][order]');
} else {
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('homepage'), '', 'No se encontró orden asociada a este pago'));
}
$session->set($transactionId.'[assist][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl('aviatur_insurance_payment_rejected_secure'));
}
public function worldCallbackAction(
Request $request,
SessionInterface $session,
OrderController $orderController,
AviaturEncoder $aviaturEncoder,
AviaturErrorHandler $aviaturErrorHandler,
ManagerRegistry $registry,
InsuranceService $insuranceService,
AviaturWebService $aviaturWebService,
ParameterBagInterface $parameterBag,
\Swift_Mailer $mailer)
{
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$aviaturPaymentRetryTimes = $parameterBag->get('aviatur_payment_retry_times');
$em = $registry->getManager();
$transactionId = $session->get($transactionIdSessionName);
$orderProductCode = $session->get($transactionId.'[assist][order]');
$productId = str_replace('PN', '', json_decode($orderProductCode)->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$decodedRequest = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$decodedResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
if (null != $decodedResponse) {
$twig = 'aviatur_insurance_payment_rejected_secure';
$retryCount = (int) $session->get($transactionId.'[assist][retry]');
$orderController->updatePaymentAction($orderProduct, false, null);
if (isset($decodedResponse->x_response_code_cyber) && (2 == $decodedResponse->x_response_code_cyber)) {
$decodedResponse->x_response_code_case = 99;
} else {
if (isset($decodedResponse->resultado->reply->orderStatus->payment->lastEvent)) {
$decodedResponse->x_response_code_case = (string) $decodedResponse->resultado->reply->orderStatus->payment->lastEvent;
} elseif (isset($decodedResponse->resultado->reply->orderStatusEvent->payment->lastEvent)) {
$decodedResponse->x_response_code_case = 'REFUSED';
} elseif (isset($decodedResponse->resultado->reply->error)) {
$decodedResponse->x_response_code_case = 'REFUSED';
}
}
switch ($decodedResponse->x_response_code_case) {
case 99:
$twig = 'aviatur_insurance_payment_rejected_secure';
break;
case 'ERROR':
$twig = 'aviatur_insurance_payment_error_secure';
break;
case 'AUTHORISED':
$twig = 'aviatur_insurance_payment_success_secure';
$session->set($transactionId.'[assist][retry]', $aviaturPaymentRetryTimes);
$response = $this->createOrderAction($request,$insuranceService,$aviaturWebService,$session,$registry,$parameterBag,$mailer,$transactionId);
if ('Error' == $response['resumeView']['Estado']) {
$session->set($transactionId.'[emission][error]', true);
return $this->redirect($this->generateUrl('aviatur_insurance_payment_error_secure'));
}
break;
case 'REFUSED':
$twig = 'aviatur_insurance_payment_rejected_secure';
break;
default:
$twig = 'aviatur_insurance_payment_pending_secure';
break;
}
$session->set($transactionId.'[assist][retry]', $retryCount - 1);
return $this->redirect($this->generateUrl($twig));
} else {
$orderProduct->setStatus('pending');
$em->persist($orderProduct);
$em->flush();
return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_insurance_retry_secure'), '', 'No hay respuesta por parte del servicio de pago'));
}
}
public function createOrderAction(Request $request, InsuranceService $insuranceService, AviaturWebService $aviaturWebService, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag, \Swift_Mailer $mailer, $transactionId)
{
$emailNotification = $parameterBag->get('email_notification');
$postData = [];
$GivenName = [];
$Surname = [];
$Email = [];
$StateCode = [];
$Telephone = [];
$Document = [];
$CityName = [];
$GivenName_contact = [];
$Surname_contact = [];
$Telephone_contact = [];
$searchPayment = [];
$replace = [];
$em = $registry->getManager();
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$configInsuranceAgency = $em->getRepository(\Aviatur\InsuranceBundle\Entity\ConfigInsuranceAgency::class)->findOneByAgency($agency);
$OfficeId = explode('-', $configInsuranceAgency->getOfficeId());
$detail_data = json_decode($session->get($transactionId.'[assist][detail_data_assist]'));
$orderInfo = json_decode($session->get($transactionId.'[assist][order]'));
$productId = str_replace('PN', '', $orderInfo->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$detail = $session->get($transactionId.'[assist][detail]');
$provider = $session->get($transactionId.'[assist][provider]');
$domain = str_replace('www.', '', $request->getHost());
$productType = $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findOneByCode('ASSIST');
$dateBirth = [];
$calculoEdades = [];
$InsuranceModel = new InsuranceModel();
$dateEnd = $detail->get('dateEnd');
$dateEntry = $detail->get('dateEntry');
$destiny = $detail->get('destiny');
$passenger = $detail->get('passenger');
$method = $detail->get('method');
$echoToken = $detail->get('echoToken');
$diffDays = ((strtotime($dateEnd) - strtotime($dateEntry)) / 86400) + 1;
$PI = (array) $detail_data->PI;
$passengerCLI = (array) $detail_data->BD;
$TypeID = explode('*', base64_decode($detail->get('TypeID')));
$informationCard = explode('*', base64_decode($detail->get('informationCard')));
if (!$session->has('operatorId')) {
$postData['PD'] = $detail_data->PD;
$PD = (array) $detail_data->PD;
}
$CD = (array) $detail_data->CD;
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($detail_data->BD->id);
if (false !== strpos($PI['first_name_1_1'], '***')) {
$PI['first_name_1_1'] = $customer->getFirstname();
$PI['last_name_1_1'] = $customer->getLastname();
$PI['phone_1_1'] = $customer->getPhone();
$PI['email_1_1'] = $customer->getEmail();
$PI['address_1_1'] = $customer->getAddress();
$PI['doc_num_1_1'] = $customer->getDocumentnumber();
}
$variable = [
'EchoToken' => $echoToken,
'MaximumTripLength' => 'P'.$diffDays.'D',
'AreaID' => $destiny,
'transactionId' => $transactionId,
'TypeID' => $TypeID[0],
'PlanID' => $detail->get('id'),
'ProviderId' => $provider,
'correlationId' => $detail->get('correlationId'),
'EffectiveDate' => $dateEntry,
'ExpireDate' => $dateEnd,
'method' => $method,
'OfficeId' => $OfficeId[1],
'AgencyId' => substr($OfficeId[0], 1),
];
$isFront = false;
$emailUser = $PI['email_1_1'];
if ($session->has('operatorId')) {
$isFront = true;
$userFront = simplexml_load_string($session->get('front_user'));
$additionalUserFront = simplexml_load_string($session->get('front_user_additionals'));
$variable['OperatorId'] = (string) $userFront->ID_AGENTE.'-'.$userFront->NOMBRE_AGENTE;
$variable['OfficeId'] = (string) $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
$variable['AgencyId'] = substr((string) $userFront->CODIGO_OFICINA_PERTENECE, 0, 2);
$emailUser = (string) $userFront->CORREO_ELECTRONICO;
}
for ($i = 1; $i <= $passenger; ++$i) {
if (1 == $passenger) {
$dateBirth[] = $PI['birthday_1_1'];
$GivenName[] = $PI['first_name_1_1'];
$Surname[] = $PI['last_name_1_1'];
$Email[] = $emailUser;
$StateCode[] = $PI['origin_1_1'];
$Telephone[] = $PI['phone_contact_1_1'];
$Document[] = $PI['doc_num_1_1'];
$originValidate = explode(',', $PI['origin_1_1Validate']);
$CityName[] = $originValidate[0];
$GivenName_contact[] = $PI['first_name_contact_1_1'];
$Surname_contact[] = $PI['last_name_contact_1_1'];
$Telephone_contact[] = $PI['phone_contact_1_1'];
} else {
$dateBirth[] = $PI['birthday_1_'.$i];
$GivenName[] = $PI['first_name_1_'.$i];
$Surname[] = $PI['last_name_1_'.$i];
$Email[] = $emailUser;
$StateCode[] = $PI['origin_1_'.$i];
$Telephone[] = $PI['phone_contact_1_'.$i];
$Document[] = $PI['doc_num_1_'.$i];
$originValidate = explode(',', $PI['origin_1_'.$i.'Validate']);
$CityName[] = $originValidate[0];
$GivenName_contact[] = $PI['first_name_contact_1_'.$i];
$Surname_contact[] = $PI['last_name_contact_1_'.$i];
$Telephone_contact[] = $PI['phone_contact_1_'.$i];
}
$calculoEdades[] = $insuranceService->calcular_edad($dateBirth[($i - 1)]);
$variable['CoveredTraveler'][] = [
'BirthDate' => $dateBirth[($i - 1)],
'Age' => $calculoEdades[($i - 1)],
'GivenName' => $GivenName[($i - 1)],
'Surname' => $Surname[($i - 1)],
'Email' => $Email[($i - 1)],
'StateCode' => $StateCode[($i - 1)],
'CityName' => $CityName[($i - 1)],
'Telephone' => $Telephone[($i - 1)],
'Document' => $Document[($i - 1)],
'GivenName_contact' => $GivenName_contact[($i - 1)],
'Surname_contact' => $Surname_contact[($i - 1)],
'Telephone_contact' => $Telephone_contact[($i - 1)],
];
}
$cliente = null;
$data = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->findOneBydocumentnumber($passengerCLI['doc_num']);
if (null == $data) {
if ($isFront) {
$passengerCLI['address'] = '';
$passengerCLI['email'] = '';
}
$cliente = [
'doc_num' => $passengerCLI['doc_num'],
'Name' => $passengerCLI['first_name'],
'Last_name' => $passengerCLI['last_name'],
'address' => $passengerCLI['address'],
'phone' => $passengerCLI['phone'],
'email' => $passengerCLI['email'],
];
} else {
$cliente = [
'doc_num' => $data->getDocumentNumber(),
'Name' => $data->getFirstname(),
'Last_name' => $data->getLastname(),
'address' => $data->getAddress(),
'phone' => $data->getPhone(),
'email' => $data->getEmail(),
];
}
$xmlTemplate = $InsuranceModel->getXmlCreateOrder($variable, $isFront);
if ($session->has($transactionId.'[assist][cash_result]')) {
$infoDetail = [
'xmlTemplate' => $xmlTemplate,
'variable' => $variable,
];
return $infoDetail;
} else {
$response = $aviaturWebService->callWebServiceAmadeus('Execute', 'InsuranceBook', 'dummy|http://www.aviatur.com.co/dummy/', $xmlTemplate, $variable, false);
if (isset($response['error']) || !isset($response->Message->OTA_InsuranceBookRS)) {
$setTo = 'soportepagoelectronico@aviatur.com.co';
if (true == $isFront) {
$setTo = $emailUser;
}
$bodyMail = $response['error'];
$estado = 'Error';
$variable['error'] = $response['error'];
$mailInfo = print_r($variable, true);
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
->setBcc([$emailNotification, 'sebastian.huertas@aviatur.com', 'f_villate@aviatur.com'])
->setSubject('Error Creación Reserva '.$informationCard[1].' '.$orderInfo->products)
->setBody($mailInfo);
$mailer->send($messageEmail);
$resumeView = [
'Estado' => $estado,
'message' => $bodyMail,
'body' => $response['error'],
];
$arraydecode = json_encode($resumeView);
$result = [
'resumeView' => $resumeView,
];
$session->set($transactionId.'[assist]'.'[resumeTransaction]', json_encode($response));
$session->set($transactionId.'[assist]'.'[infoclient]', json_encode($cliente));
$session->set($transactionId.'[assist]'.'[resumeOrderCreate]', json_encode($arraydecode));
$emissionData = $insuranceService->xmlInsuranceExtra($transactionId, false);
$orderProduct->setEmissiondata($emissionData);
$orderProduct->setUpdatingdate(new \DateTime());
$em->persist($orderProduct);
$em->flush();
} else {
$PolicyDetail = null;
$UpdatePaymentData = $orderProduct->getUpdatePaymentData();
$conteo = 1;
$reservationId = 'PN'.$orderProduct->getId();
$reservationId2 = (string) $response->Message->OTA_InsuranceBookRS->PlanForBookRS['PlanID'];
$reservationId3 = (string) $response->Message->OTA_InsuranceBookRS->PlanForBookRS['TypeID'];
foreach ($response->Message->OTA_InsuranceBookRS->PlanForBookRS as $PlanForBookRS) {
$searchPayment[] = '{policy-booking-'.$conteo.'}';
$searchPayment[] = '{policy-number-'.$conteo.'}';
$replace[] = $reservationId.'-'.$conteo;
$replace[] = (string) rtrim($PlanForBookRS->PolicyDetail->PolicyNumber['ID']);
$PolicyDetail .= rtrim($PlanForBookRS->PolicyDetail->PolicyNumber['ID']).'+';
++$conteo;
}
$xmlUpdatePaymentData = str_replace($searchPayment, $replace, $UpdatePaymentData);
$bodyMail = [
'PlanID' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS['PlanID'],
'Name' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS['Name'],
'PolicyDetail' => substr($PolicyDetail, 0, -1),
'Type' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS['Type'],
'TypeID' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS['TypeID'],
'PolicyDetail' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->PolicyDetail->PolicyNumber['ID'],
'CoveredTravelerAge' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->CoveredTravelers->CoveredTraveler->CoveredPerson['Age'],
'CoveredTravelerGivenName' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->CoveredTravelers->CoveredTraveler->CoveredPerson->GivenName,
'CoveredTravelerSurname' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->CoveredTravelers->CoveredTraveler->CoveredPerson->Surname,
'CoveredTravelerAddress' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->CoveredTravelers->CoveredTraveler->Address->CityName,
'InsCoverageDetailEffectiveDate' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->InsCoverageDetail['EffectiveDate'],
'InsCoverageDetailExpireDate' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->InsCoverageDetail['ExpireDate'],
'InsCoverageDetailType' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->InsCoverageDetail['Type'],
'PlanCostAmount' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->PlanCost['Amount'],
'PlanCostCurrencyCode' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->PlanCost['CurrencyCode'],
'ContactGivenName' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->Contact->PersonName->GivenName,
'ContactTelephone' => $response->Message->OTA_InsuranceBookRS->PlanForBookRS->Contact->PersonName->Telephone,
];
//$orderProduct->setEmissiondata($reservationId);
$orderProduct->setUpdatingdate(new \DateTime());
$session->set($transactionId.'[assist][reservation]', $response->asXml());
$searchData = ['{order_product_reservation}', '{order_product_reservation_2}', '{property_name_2}'];
$replaceData = [$reservationId, $reservationId2, $reservationId3];
$orderXml = str_replace($searchData, $replaceData, $orderProduct->getAddProductData());
$count = 1;
$PolicyNumber = explode('+', substr($PolicyDetail, 0, -1));
foreach ($PolicyNumber as $TypeID) {
$orderXml = str_replace($reservationId.'-'.$count, $TypeID, $orderXml);
++$count;
}
$orderProduct->setAddProductData($orderXml);
$orderProduct->setUpdatePaymentData($xmlUpdatePaymentData);
$orderProduct->setBooking($reservationId);
$em->persist($orderProduct);
$em->flush();
if ($isFront) {
try {
$responseOrder = $aviaturWebService->busWebServiceAmadeus(null, null, $orderXml);
} catch (\Exception $e) {
}
}
$estado = 'Ok';
$resumeView = [
'Estado' => $estado,
'message' => $bodyMail,
];
$session->set($transactionId.'[assist]'.'[resumeTransaction]', json_encode($response));
$session->set($transactionId.'[assist]'.'[infoclient]', json_encode($cliente));
$arraydecode = json_encode($resumeView);
$session->set($transactionId.'[assist]'.'[resumeOrderCreate]', json_encode($arraydecode));
$result = [
'resumeView' => $resumeView,
];
}
return $result;
}
}
public function paymentOutputAction(Request $request, \Swift_Mailer $mailer, Pdf $pdf, AviaturPixeles $aviaturPixeles, AuthorizationCheckerInterface $authorizationChecker, TwigFolder $twigFolder, AviaturEncoder $aviaturEncoder, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag, ExceptionLog $exceptionLog)
{
$projectDir = $parameterBag->get('kernel.project_dir');
$transactionIdSessionName = $parameterBag->get('transaction_id_session_name');
$emailNotification = $parameterBag->get('email_notification');
$clientFranquice = [];
$paymentResume = [];
$voucherFile = null;
$em = $registry->getManager();
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$transactionId = $session->get($transactionIdSessionName);
$infoClient = json_decode($session->get($transactionId.'[assist]'.'[infoclient]'));
$infoInsuranceFlight = json_decode($session->get($transactionId.'[assist]'.'[infoInsuranceFlight]'), true);
$detail = $session->get($transactionId.'[assist]'.'[detail]');
$detail_data_insurance = json_decode($session->get($transactionId.'[assist]'.'[detail_data_assist]'));
$orderProductCode = json_decode($session->get($transactionId.'[assist]'.'[order]'));
$productId = str_replace('PN', '', $orderProductCode->products);
$orderProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
$resumeTransaction = json_decode($session->get($transactionId.'[assist]'.'[resumeTransaction]'), true);
$cliente = json_decode($session->get($transactionId.'[assist]'.'[infoclient]'), true);
$arraydecode = json_decode($session->get($transactionId.'[assist]'.'[resumeOrderCreate]'), true);
$opRequestInitial = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
$opRequest = $opRequestInitial->multi_transaction_hotel ?? $opRequestInitial;
$opResponse = json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
if (isset($opResponse->x_franchise) && ('' != $opResponse->x_franchise)) {
$franquiceCode = str_replace(['CR_', 'RM_', 'CDNSA'], ['', '', 'CS'], $opResponse->x_franchise);
$clientFranquice = $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findOneByPaymentgatewaycode($franquiceCode);
} else {
$clientFranquice['description'] = 'error';
if (isset($opRequest->paymentMethod) && 'world' == $opRequest->paymentMethod) {
$clientFranquice['description'] = '----';
}
}
$paymentData = $detail_data_insurance->BD;
$emailDataJson = json_decode($orderProduct->getEmail(), true);
$customer = $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($paymentData->id);
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,
];
}
$info_travelers = $detail_data_insurance->PI;
if (false !== strpos($detail_data_insurance->PI->first_name_1_1, '***')) {
$info_travelers->first_name_1_1 = $customer->getFirstname();
$info_travelers->last_name_1_1 = $customer->getLastname();
$info_travelers->email_1_1 = $customer->getEmail();
$info_travelers->address_1_1 = $customer->getAddress();
$detail_data_insurance->CD->phone = $customer->getPhone();
}
if ((null != $opRequest) && (null != $opResponse)) {
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' => (is_object($clientFranquice) ? $clientFranquice->getDescription() : $clientFranquice['description'])],
'cuotas' => $opRequest->x_differed,
'card_num' => '************'.substr($opRequest->x_card_num, strlen($opRequest->x_card_num) - 4),
'reference' => $opResponse->x_transaction_id,
'auth' => $opResponse->x_approval_code,
'transaction_date' => $opResponse->x_transaction_date,
'description' => $opResponse->x_description,
'reason_code' => $opResponse->x_response_reason_code,
'reason_description' => $opResponse->x_response_reason_text,
'client_names' => $opResponse->x_first_name.' '.$opResponse->x_last_name,
'client_email' => $opResponse->x_email,
];
} elseif (isset($opRequest->dataTransf)) {
if (isset($opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'})):
$state = $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'};
if (102 == $state):
$state = 1;
$reason_description = 'SafetyPay recibe la confirmación del pago de un Banco Asociado'; elseif (101 == $state):
$state = 2;
$reason_description = 'Transacción creada';
endif;
$paymentResume = [
'transaction_state' => $state,
'id' => $orderProduct->getBooking(),
'currency' => $opRequest->dataTransf->x_currency,
'total_amount' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:Amount'},
'amount' => null,
'iva' => null,
'ip_address' => $opRequest->dataTransf->dirIp,
'airport_tax' => null,
'reference' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:MerchantSalesID'},
'auth' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationID'},
'transaction_date' => $opResponse->payResponse->OperationResponse->ResponseDateTime,
'description' => $opRequest->dataTransf->x_description,
'reason_code' => $opRequest->notificationRequest->{'urn:OperationActivityNotifiedRequest'}->{'urn:ListOfOperationsActivityNotified'}->{'urn1:ConfirmOperation'}->{'urn1:OperationStatus'},
'reason_description' => $reason_description,
'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
'client_email' => $opRequest->dataTransf->x_email,
'x_payment_data' => $opRequest->dataTransf->x_payment_data,
'client_franquice' => ['description' => 'SafetyPay'],
'id_context' => $orderProductCode->order.'-'.$orderProductCode->products,
]; else:
$paymentResume = [
'transaction_state' => 2,
'id' => $orderProduct->getBooking(),
'currency' => $opRequest->dataTransf->x_currency,
'total_amount' => $opRequest->dataTransf->x_total_amount,
'amount' => null,
'iva' => null,
'ip_address' => $opRequest->dataTransf->dirIp,
'airport_tax' => null,
'reference' => $opRequest->dataTransf->x_reference,
'auth' => null,
'transaction_date' => $opRequest->tokenRequest->{'urn:ExpressTokenRequest'}->{'urn:RequestDateTime'},
'description' => $opRequest->dataTransf->x_description,
'reason_code' => 101,
'reason_description' => 'Transacción creada',
'x_payment_data' => $opRequest->dataTransf->x_payment_data,
'client_names' => $opRequest->dataTransf->x_first_name.' '.$opRequest->dataTransf->x_last_name,
'client_email' => $opRequest->dataTransf->x_email,
];
endif;
if ('baloto' == $opRequest->dataTransf->x_payment_data) {
$paymentResume['transaction_state'] = 3;
}
} elseif (isset($opRequest->infoCash)) {
$paymentResume = [
'transaction_state' => 2,
'id' => $orderProduct->getBooking(),
'id_context' => $opRequest->infoCash->x_reference,
'currency' => $opRequest->infoCash->x_currency,
'total_amount' => $opRequest->infoCash->x_total_amount,
'client_franquice' => ['description' => 'Efectivo'],
'amount' => null,
'iva' => null,
'ip_address' => $opRequest->infoCash->dirIp,
'airport_tax' => null,
'reference' => $opRequest->infoCash->x_reference,
'auth' => null,
'transaction_date' => $opRequest->infoCash->x_fechavigencia,
'description' => $opRequest->infoCash->x_description,
'reason_code' => 101,
'reason_description' => 'Transacción creada',
'client_names' => $opRequest->infoCash->x_first_name.' '.$opRequest->infoCash->x_last_name,
'client_email' => $opRequest->infoCash->x_email,
'fecha_vigencia' => $opRequest->infoCash->x_fechavigencia,
];
$cash_result = json_decode($session->get($transactionId.'[assist][cash_result]'));
$paymentResume['transaction_state'] = 3;
if ('' == $cash_result) {
$paymentResume['transaction_state'] = 2;
}
} else {
$bank_info = $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findOneByCode($opRequest->bankCode);
$bank_name = $bank_info->getName();
$clientFranquice['description'] = 'PSE';
$paymentResume = [
'transaction_state' => $opResponse->getTransactionInformationResult->responseCode,
'id' => $orderProduct->getBooking(),
'id_context' => $opRequest->reference,
'currency' => $opRequest->currency,
'total_amount' => $opRequest->totalAmount,
'amount' => $opRequest->devolutionBase,
'iva' => $opRequest->taxAmount,
'ip_address' => $opRequest->ipAddress,
'bank_name' => $bank_name,
'client_franquice' => $clientFranquice,
'reference' => $opResponse->createTransactionResult->transactionID,
'auth' => $opResponse->getTransactionInformationResult->trazabilityCode,
'transaction_date' => $opResponse->getTransactionInformationResult->bankProcessDate,
'description' => $opRequest->description,
'reason_code' => $opResponse->getTransactionInformationResult->responseReasonCode,
'reason_description' => $opResponse->getTransactionInformationResult->responseReasonText,
'client_names' => $opRequest->payer->firstName.' '.$opRequest->payer->lastName,
'client_email' => $opRequest->payer->emailAddress,
];
}
} else {
$paymentResume['id'] = $orderProduct->getBooking();
$infoDetail = explode('*', base64_decode($detail->get('TypeID')));
$paymentResume['transaction_state'] = 1;
if (isset($resumeTransaction['error'])) {
$paymentResume['transaction_state'] = 2;
}
$paymentResume['currency'] = $infoDetail[2];
$paymentResume['total_amount'] = $infoDetail[3];
if ($session->has('operatorId')) {
$paymentResume['client_names'] = $paymentData->first_name.' '.$paymentData->last_name;
$paymentResume['client_email'] = $paymentData->first_name.' '.$paymentData->last_name;
$paymentResume['customer_address'] = $paymentData->first_name.' '.$paymentData->last_name;
} else {
$paymentResume['client_names'] = $customer->getFirstname().' '.$customer->getLastname();
}
$customer = null;
}
$paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
if ($session->has('operatorId')) {
$paymentResume['transaction_state_cyber'] = 1;
}
$clientFranquice = '';
$retryCount = (int) $session->get($transactionId.'[assist][retry]');
$agencyFolder = $twigFolder->twigFlux();
$routeName = $request->get('_route');
$detail = $session->get($transactionId.'[assist]'.'[detail]');
$detail_data_insurance = json_decode($session->get($transactionId.'[assist]'.'[detail_data_assist]'));
$TypeID = explode('*', base64_decode($detail->get('TypeID')));
$informationCard = explode('*', base64_decode($detail->get('informationCard')));
$agencyData = [
'agency_name' => $agency->getName(),
'agency_nit' => $agency->getNit(),
'agency_phone' => $agency->getPhone(),
'agency_email' => $agency->getMailContact(),
];
$emailData = [
'retry_count' => $retryCount,
'paymentResume' => $paymentResume,
'order' => $orderProductCode->order,
'products' => $orderProductCode->products,
'method' => $detail->get('method'),
'Estado' => 'error',
'Name' => $TypeID[1],
'TypeID' => $TypeID[0],
'companyName' => $informationCard[1],
'agencyData' => $agencyData,
'info_travelers' => (array) $info_travelers,
'transactionID' => $transactionId,
'infoClient' => $facturationResume,
'dateEntry' => $detail->get('dateEntry'),
'dateEnd' => $detail->get('dateEnd'),
'dateEntry' => $detail->get('dateEntry'),
'total_amount' => $paymentResume['total_amount'],
];
$infoDataFlight = json_decode($session->get($transactionId.'[crossed]'.'[infoDataFlight]'), true);
$resumeTransaction = json_decode($session->get($transactionId.'[assist]'.'[resumeTransaction]'), true);
$emailData['infoDataFlight'] = $infoDataFlight;
$emailData['infoDataInsurance'] = $resumeTransaction;
if (('aviatur_insurance_payment_rejected_secure' == $routeName)) {
$urlResume = '@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resume_insurance.html.twig';
} else {
$resumeOrderCreate = $session->get($transactionId.'[assist]'.'[detail]');
if ('assist' == $resumeOrderCreate->get('method')) {
$urlResume = '@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resume_insurance.html.twig';
$info_travelers = (array) $detail_data_insurance->PI;
} else {
$urlResume = '@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resume_insurance_flight.html.twig';
$info_travelers = $infoDataFlight['travelers'];
}
}
/* * *
* Agente Octopus
* Cambiar logo Correo Gracias por tu compra.
*/
$isAgent = false;
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
$user = $this->getUser();
$agent = $user->getAgent();
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
if (!empty($agent[0]) && $agent[0]->getAgency()->getId() === $agency->getId()) {
$isAgent = true;
$agent = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
$idAgentLogo = $agent->getId();
$folderImg = 'assets/octopus_assets/img/custom/logoAgent/'.$idAgentLogo.'.png';
$domain = 'https://'.$agency->getDomain();
$folderLogoAgent = $domain.'/'.$folderImg;
if (file_exists($folderImg)) {
$emailData['imgLogoAgent'] = $folderLogoAgent;
}
}
}
$renderResumeView = $emailData;
$renderResumeView['infos'][0] = $emailData;
$setTo = null == $customer ? null : $customer->getEmail();
if ($session->has('operatorId')) {
$userFront = simplexml_load_string($session->get('front_user'));
$setTo = (string) $userFront->CORREO_ELECTRONICO;
}
if (!isset($resumeTransaction['error']) && isset($resumeTransaction['Message']['OTA_InsuranceBookRS'])) {
if (null != $emailData['infoDataInsurance']) {
$voucherFile = $projectDir.'/app/serviceLogs/InsuranceVoucher/ON'.$orderProduct->getOrder()->getId().'-PN'.$orderProduct->getId().'_'.$transactionId.'.pdf';
if (!$session->has($transactionId.'[emission_assist_email]')) {
$pdf->generateFromHtml(
$this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resumePdf.html.twig'), $renderResumeView),
$voucherFile
);
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
->setBcc([$emailNotification, 'soptepagelectronic@aviatur.com', 'soportepagoelectronico@aviatur.com.co'])
->setSubject($session->get('agencyShortName').' - '.'Reserva '.$informationCard[1].' Creada')
->attach(\Swift_Attachment::fromPath($voucherFile))
->setBody(
$this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resumePdf.html.twig'), $renderResumeView)
);
try {
$mailer->send($message);
$session->set($transactionId.'[emission_assist_email]', 'emailed');
/*
* Email de la reserva del agente hijo enviado al agente Padre Octopus.
*/
//Fin entrega de tarjeta One-timeUnited
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR')) {
$bccMails = [$agency->getMailBooking()];
$agencyName = '';
if ($session->has('whitemark')) {
if ('' != $session->get('whitemarkMail')) {
$bccMails[] = $session->get('whitemarkMail');
}
$agencyName = $session->get('whitemarkName');
} else {
$bccMails[] = $agency->getMailcontact();
$agencyName = $session->get('agencyShortName');
}
$user = $this->getUser();
$agent = $user->getAgent();
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
if (!empty($agent[0]) && $agent[0]->getAgency()->getId() === $agency->getId()) {
$agent = $em->getRepository(\Aviatur\AgentBundle\Entity\Agent::class)->findOneByCustomer($this->getUser());
$request = $request;
$parent = $agent->getparentAgent();
if (0 != $parent) {
$myParent = $em->createQuery('SELECT a,b FROM AviaturAgentBundle:Agent a JOIN a.customer b WHERE a.id= :idAgent');
$myParent = $myParent->setParameter('idAgent', $parent);
$parentInfo = $myParent->getResult();
$emailParent = $parentInfo[0]->getCustomer()->getEmail();
$emailData['infoSubAgent'] = ['nameSubAgent' => strtoupper($agent->getCustomer()->__toString()), 'emailSubAgent' => strtoupper($agent->getCustomer()->getEmail())];
$renderResumeView = $emailData;
$renderResumeView['infos'][0] = $emailData;
$messageAgent = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo([$agent->getCustomer()->getEmail(), $emailParent])
->setBcc($bccMails)
->setSubject($agencyName.' - Reserva '.$informationCard[1].' Creada - '.$customer->getFirstname().' '.$customer->getLastname().' Vendedor - '.$agent->getCustomer()->getFirstName().' '.$agent->getCustomer()->getLastName())
->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resumePdf.html.twig'), $renderResumeView));
$mailer->send($messageAgent);
} else {
$messageAgent = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($agent->getCustomer()->getEmail())
->setBcc($bccMails)
->setSubject($session->get('agencyShortName').' - '.'Reserva '.$informationCard[1].' Creada'.' - '.$customer->getFirstname().' '.$customer->getLastname().' Vendedor - '.$agent->getCustomer()->getFirstName().' '.$agent->getCustomer()->getLastName())
->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/resumePdf.html.twig'), $renderResumeView));
$mailer->send($messageAgent);
}
}
}
} catch (\Exception $ex) {
$exceptionLog->log(
var_dump($message),
$ex
);
}
}
}
}
$orderProduct->setEmail(json_encode($renderResumeView));
if ($session->has($transactionId.'[emission][error]')) {
$renderResumeView['emission_error'] = true;
}
if (isset($renderResumeView['paymentResume']['description'])) {
$renderResumeView['descriptionInsurance'] = $renderResumeView['paymentResume']['description'];
}
if (isset($paymentResume['id_context'])) {
$voucherFile = $projectDir.'/app/serviceLogs/CashTransaction/ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
if (file_exists($voucherFile)) {
$renderResumeView['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
}
}
if ($session->has($transactionId.'[assist][cash_result]') && !$session->has($transactionId.'[emission_baloto_email]')) {
$renderResumeView['cash_result'] = json_decode($session->get($transactionId.'[assist][cash_result]'));
$renderResumeView['exportPDF'] = true;
$ruta = '@AviaturTwig/'.$agencyFolder.'/General/Templates/email_cash.html.twig';
if (!file_exists($voucherFile)) {
$pdf->generateFromHtml($this->renderView($twigFolder->twigExists($ruta), $renderResumeView), $voucherFile);
$renderResumeView['NameArchive'] = 'ON'.$paymentResume['id_context'].'_'.$transactionId.'.pdf';
}
$setTo = $paymentResume['client_email'];
$paymentResume['exportPDF'] = false;
$message = (new \Swift_Message())
->setContentType('text/html')
->setFrom($session->get('emailNoReply'))
->setTo($setTo)
// ->setBcc(array('soptepagelectronic@aviatur.com', 'soportepagoelectronico@aviatur.com.co', $emailNotification))
->setSubject($session->get('agencyShortName').' - Transacción Efectivo Creada '.$paymentResume['id_context'])
->attach(\Swift_Attachment::fromPath($voucherFile))
->setBody(
$this->renderView($twigFolder->twigExists($ruta), $renderResumeView)
);
try {
$mailer->send($message);
$session->set($transactionId.'[emission_email]', 'emailed');
} catch (\Exception $ex) {
$exceptionLog->log(var_dump($message), $ex);
}
}
$pixelInfo = [];
if (!$session->has('operatorId') && 1 == $renderResumeView['paymentResume']['transaction_state']) {
$pixel = json_decode($session->get($transactionId.'[pixeles_info]'), true);
$pixel['partner_datalayer']['event'] = 'seguros_purchase';
$pixel['partner_datalayer']['dimension12'] = 'compra-seguro';
$products = [
'actionField' => "{'id': '".$renderResumeView['paymentResume']['id_context']."', 'affiliation': 'Portal Web', 'revenue': '".$renderResumeView['paymentResume']['total_amount']."', 'tax':'".$renderResumeView['paymentResume']['iva']."', 'coupon': ''}",
'name' => $renderResumeView['Name'],
'price' => $renderResumeView['paymentResume']['total_amount'],
'brand' => 'assist card',
'category' => 'Seguros',
'variant' => $renderResumeView['descriptionInsurance'],
'quantity' => $detail->get('passenger'),
];
if (isset($pixel['partner_datalayer']['ecommerce']['checkout'])) {
unset($pixel['partner_datalayer']['ecommerce']['checkout']);
}
$pixel['partner_datalayer']['ecommerce']['purchase']['products'] = $products;
//$pixel['dataxpand'] = true;
//$pixel['pickback'] = true;
$pixelInfo = $aviaturPixeles->verifyPixeles($pixel, 'insurance', 'resume', $agency->getAssetsFolder(), false);
$renderResumeView['pixel_info'] = $pixelInfo;
}
$setResume = $this->render($twigFolder->twigExists($urlResume), $renderResumeView);
$orderProduct->setResume($setResume);
$em->persist($orderProduct);
$em->flush();
return $setResume;
}
public function calcInfoPassenger(InsuranceService $insuranceService, $passenger, $method, $infoBirth, $fullRequest)
{
$dateBirth = [];
$calculoEdades = [];
$passanger_type = [];
$variable = [];
for ($i = 1; $i <= $passenger; ++$i) {
if ('flight' == $method) {
if (1 == $passenger) {
$dateBirth[] = $infoBirth[0]['BirthDate'];
} else {
$dateBirth[] = $infoBirth[($i - 1)]['BirthDate'];
}
} else {
if (1 == $passenger) {
$dateBirth[] = $fullRequest->attributes->get('birth1');
} else {
$dateBirth[] = $fullRequest->attributes->get('birth'.$i);
}
}
$calculoEdades[] = $insuranceService->calcular_edad($dateBirth[($i - 1)]);
if ($calculoEdades[($i - 1)] >= 0 && $calculoEdades[($i - 1)] < 2) {
$passanger_type[] = 1;
} elseif ($calculoEdades[($i - 1)] >= 2 && $calculoEdades[($i - 1)] < 12) {
$passanger_type[] = 2;
} else {
$passanger_type[] = 3;
}
$variable[] = [
'BirthDate' => $dateBirth[($i - 1)],
'Age' => $calculoEdades[($i - 1)],
'passanger_type' => $passanger_type[($i - 1)],
];
}
return $variable;
}
public function quotationAction(Request $fullRequest, Pdf $pdf, AuthorizationCheckerInterface $authorizationChecker, TwigFolder $twigFolder, SessionInterface $session, ManagerRegistry $registry, ParameterBagInterface $parameterBag, \Swift_Mailer $mailer)
{
$projectDir = $parameterBag->get('kernel.project_dir');
$typePerson = [];
$codImg = null;
$quotationName = $fullRequest->request->get('quotationName');
$quotationLastname = $fullRequest->request->get('quotationLastname');
$quotationEmail = $fullRequest->request->get('quotationEmail');
$request = $fullRequest->request;
$transactionId = $session->get('transactionId');
$fullRequest = $session->get($transactionId.'[assist][fullrequest]');
$request = $session->get($transactionId.'[assist][request]');
$server = $fullRequest->server;
$isAgent = false;
$queryString = $fullRequest->query;
$isFront = $session->has('operatorId');
$em = $registry->getManager();
$agency = $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
$agencyFolder = $twigFolder->twigFlux();
$additionalUserFront = simplexml_load_string($session->get('front_user_additionals'));
$detailIns = simplexml_load_string($session->get($transactionId.'[assist][infoInsurance]'));
if ($authorizationChecker->isGranted('ROLE_AVIATUR_ADMIN_ADMIN_AGENT_OPERATOR') && $session->get($transactionId.'_isActiveQse')) {
$user = $this->getUser();
$emailuser = $user->getemail();
$agent = $user->getAgent();
if (!empty($agent[0])) {
$idagent = $agent[0]->getid();
$nombreagente = $user->getFirstname().' '.$user->getLastname();
$agencyFolder = $twigFolder->twigFlux();
$isAgent = true;
}
}
$conditions = $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency, 'reservation_conditions_for_insurance');
$twig_readonly = false;
$passanger_type = json_decode($request->get('passanger_type'));
$inf = $chd = $adt = 0;
for ($i = 0; $i < (is_countable($passanger_type) ? count($passanger_type) : 0); ++$i) {
if (1 == $passanger_type[$i]) {
++$inf;
} elseif (2 == $passanger_type[$i]) {
++$chd;
} else {
++$adt;
}
}
$typePerson[1] = [
'ADT' => $adt,
'CHD' => $chd,
'INF' => $inf,
];
$TypeID = explode('*', base64_decode($request->get('TypeID')));
$x_total_amount = $TypeID[3];
// $x_base_amount = str_replace(array('[',']'),'',$TypeID[4]);
$x_base_amount = $x_total_amount;
if ($isAgent) {
$x_base_amount -= (float) $TypeID[7];
$commissionAgent = $TypeID[7];
$commissionActive = $TypeID[8];
$commissionPay = $TypeID[9];
$activeDetail = $TypeID[10];
$amountTa = $TypeID[11];
$commissionTa = $TypeID[12];
$amountPay = $TypeID[13];
$percentageTarifa = $TypeID[14];
}
$dataRestric = [];
$countPlanRestrictions = 0;
$ProductInfoUnsort = [];
$productPrices = [];
$uriAssistCard = '/assets/common_assets/img/insurance/logo-assit-card.png';
$uriUniversalAssistance = '/assets/common_assets/img/insurance/logo-universal-assistance.png';
// stores the plan restriction of the universal assistance.
$arrPlanRestrictions = [];
$arrDataExtra = [];
$arrAttributesPlanRestrictions = [];
foreach ($detailIns->OTA_InsuranceQuoteRS->PlanForQuoteRS as $Info) {
if ($Info['PlanID'] == $request->get('id')) {
$company = (string) $Info->QuoteDetail->ProviderCompany['CompanyShortName'];
if (0 === strcmp($company, 'Universal Assistance')) {
$countRestric = 0;
foreach ($Info->QuoteDetail->PlanRestrictions->PlanRestriction as $restric) {
$dataRestric[$countRestric]['Name'] = $restric['Name'];
$dataRestric[$countRestric]['Code'] = $restric['Code'];
$dataRestric[$countRestric]['CodeContext'] = $restric['CodeContext'];
++$countRestric;
if ($countRestric > 2) {
break;
}
}
}
}
++$countPlanRestrictions;
}
$variables = [
'transactionId' => base64_encode($transactionId),
'destiny' => $request->get('destiny'),
'dateEntry' => $request->get('dateEntry'),
'dateEnd' => $request->get('dateEnd'),
'passenger' => $request->get('passenger'),
'birth' => $request->get('birth'),
'id' => $request->get('id'),
'TypeID' => base64_decode($request->get('TypeID')),
'informationCard' => base64_decode($request->get('informationCard')),
'dataRestric' => $dataRestric ?? null,
'providerId' => $request->get('providerId'),
'method' => $request->get('method'),
'passanger_type' => $passanger_type,
'Age' => json_decode($request->get('Age')),
'x_total_amount' => $x_total_amount,
'x_base_amount' => $x_base_amount,
'reintento' => false,
'echoToken' => $request->get('echoToken'),
];
if ($isAgent) {
$variables['commissionAgent'] = $commissionAgent;
$variables['commissionActive'] = $commissionActive;
$variables['commissionPay'] = $commissionPay;
$variables['commissionTa'] = $commissionTa;
$variables['amountTa'] = $amountTa;
$variables['activeDetail'] = $activeDetail;
$variables['amountPay'] = $amountPay;
/*$info_product = array('amountQse' => (float) $commissionAgent,
'commissionQse' => (float) $commissionPay,
'amountTa' => (float) $amountTa,
'commissionTa' => (float) $commissionTa,
'amountPay' => (float) $amountPay,
'amountProduct' => $x_base_amount,
'percentageTarifa' => isset($percentageTarifa) ? (float) $percentageTarifa : 0);
$session->set($transactionId . '_agentInfoTransaction', $info_product);*/
}
if ('N' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
$codImg = $additionalUserFront->EMPRESA;
} elseif ('S' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
$codImg = $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
}
$imgAgency = 'assets/common_assets/img/offices/'.$codImg.'.png';
if (!file_exists($imgAgency)) {
$codImg = 10;
}
$urlAvailability = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/quotation.html.twig');
//var_dump($variables);die;
$returnInfo = [
'quotationName' => $quotationName,
'quotationLastname' => $quotationLastname,
'quotationEmail' => $quotationEmail,
'services' => $typePerson,
'codImg' => $codImg,
'variables' => $variables,
'conditions' => $conditions,
'agentName' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
'agentMail' => $additionalUserFront->CORREO_ELECTRONICO,
'agentPhone' => $additionalUserFront->TELEFONO_SUCURSAL,
'agentAddress' => $additionalUserFront->DIRECCION_SUCURSAL,
];
//var_dump($returnInfo['variables']);die;
$html = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Insurance/Default/quotation.html.twig');
$namefilepdf = 'Aviatur_cotizacion_tarjeta_asistencia_'.$transactionId;
$voucherInsuranceFile = $projectDir.'/app/quotationLogs/insuranceQuotation/'.$namefilepdf.'.pdf';
if ('N' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
$codImg = $additionalUserFront->EMPRESA;
} elseif ('S' == $additionalUserFront->INDICA_SUCURSAL_ADMINISTRADA) {
$codImg = $additionalUserFront->CODIGO_SUCURSAL_SEVEN;
}
$imgAgency = 'assets/common_assets/img/offices/'.$codImg.'.png';
if (!file_exists($imgAgency)) {
$codImg = 10;
}
if (!file_exists($voucherInsuranceFile)) {
$pdf->setOption('page-size', 'LETTER');
$pdf->setOption('margin-top', 0);
$pdf->setOption('margin-right', 0);
$pdf->setOption('margin-bottom', 0);
$pdf->setOption('margin-left', 0);
$pdf->setOption('orientation', 'portrait');
$pdf->setOption('enable-javascript', true);
$pdf->setOption('no-stop-slow-scripts', true);
$pdf->setOption('no-background', false);
$pdf->setOption('lowquality', false);
$pdf->setOption('encoding', 'utf-8');
$pdf->setOption('images', true);
$pdf->setOption('dpi', 300);
$pdf->setOption('enable-external-links', true);
$pdf->setOption('enable-internal-links', true);
$pdf->generateFromHtml($this->renderView($html, $returnInfo), $voucherInsuranceFile);
}
$subject = 'Cotización de Auto';
$messageEmail = (new \Swift_Message())
->setContentType('text/html')
->setFrom('noreply@aviatur.com')
->setTo($additionalUserFront->CORREO_ELECTRONICO)
->setSubject($session->get('agencyShortName').' - '.$subject)
->attach(\Swift_Attachment::fromPath($voucherInsuranceFile))
->setBody($this->renderView($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/Bus/Default/quotation_email_body.html.twig'), [
'nameAgent' => $additionalUserFront->NOMBRE_USUARIO.' '.$additionalUserFront->APELLIDOS_USUARIO,
'codImg' => $codImg,
]), 'text/html');
$mailer->send($messageEmail);
chmod($projectDir.'/app/quotationLogs/insuranceQuotation/', 777);
$this->saveInformationCGS($returnInfo, $additionalUserFront, $request, $agency);
unlink($voucherInsuranceFile);
//return $this->render($urlAvailability, $returnInfo);
return $this->redirect($this->generateUrl('aviatur_search_insurance'));
}
public function saveInformationCGS(ManagerRegistry $registry, AviaturLogSave $aviaturLogSave, AviaturWebService $aviaturWebService, AviaturErrorHandler $aviaturErrorHandler, $data, $customer, $request, $agency)
{
$em = $registry->getManager();
$parametersLogin = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findParameters($agency, 'aviatur_service_login_cgs');
$urlLoginCGS = $parametersLogin[0]['value'];
$parametersProduct = $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findParameters($agency, 'aviatur_service_insurance_cgs');
$urlAddProductInsurance = $parametersProduct[0]['value'];
/*
* get token api autentication
* PENDIENTE: Validar si se puede obtener el token, si no entonces no hacer este proceso
*/
$userLoginCGS = $aviaturWebService->encryptUser(trim(strtolower($customer->CODIGO_USUARIO)), 'AviaturCGSMTK');
$jsonReq = json_encode(['username' => $userLoginCGS]); //j_acosta (encriptado)
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $urlLoginCGS,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $jsonReq,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
],
]);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if (200 != $httpcode) {
$aviaturLogSave->logSave('HTTPCODE: '.$httpcode.' Error usuario: '.strtolower($customer->CODIGO_USUARIO), 'CGS_LOGIN', 'CGS_ERRORLOGIN');
$aviaturLogSave->logSave(print_r($response, true), 'CGS_LOGIN', 'RSLoginCGS');
return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail('/buscar/seguros-de-viaje/', 'Error Login', 'Error Login'));
} else {
$tokenInfoApiQuotation = json_decode($response);
$tokenApiQuotation = $tokenInfoApiQuotation->TOKEN;
}
ini_set('xdebug.var_display_max_depth', '-1');
ini_set('xdebug.var_display_max_children', '-1');
ini_set('xdebug.var_display_max_data', '-1');
$informationCard = explode('*', base64_decode($request->get('informationCard')));
$TypeID = explode('*', base64_decode($request->get('TypeID')));
$destiny = '';
switch ($request->get('destiny')) {
case '1':
$destiny = 'Norteamérica';
break;
case '2':
$destiny = 'Europa - Medio Oriente';
break;
case '3':
$destiny = 'Centroamérica y Caribe';
break;
case '4':
$destiny = 'Suramérica (sin cobertura en Colombia)';
break;
case '5':
$destiny = 'África';
break;
case '6':
$destiny = 'Asia';
break;
case '7':
$destiny = 'Oceanía';
break;
case '8':
$destiny = 'Colombia (sin cobertura para extranjeros)';
break;
default:
$destiny = 'Sin destino';
break;
}
$emails_arr = [
'active' => true,
'dateCreated' => '0001-01-01T00:00:00',
'emailAddress' => (string) $data['quotationEmail'],
'id' => 0,
'lastUpdated' => '0001-01-01T00:00:00',
'version' => 0,
];
$phones_arr = [
'active' => false,
'dateCreated' => '0001-01-01T00:00:00',
'id' => 0,
'lastUpdated' => '0001-01-01T00:00:00',
'number' => null,
'type' => null,
'version' => 0,
];
$data_send = [
'customer' => [
'firstName' => (string) $data['quotationName'],
'lastName' => (string) $data['quotationLastname'],
'mothersName' => null,
'fullName' => trim($data['quotationName']).' '.trim($data['quotationLastname']),
'birthDate' => 'true',
'billingInformations' => null,
'emails' => [$emails_arr],
'phones' => [$phones_arr],
'city' => null,
],
'selectedProduct' => [
'description' => (string) $TypeID[1],
'packageName' => (string) $TypeID[1],
'emit' => false,
'fareData' => [
'aditionalFee' => 0.0,
'airpotService' => null,
'baseFare' => (int) $data['variables']['x_total_amount'],
'cO' => 0.0,
'commission' => 0.0, //Consultar esto
'commissionPercentage' => 0.0, //Consultar esto
'complements' => null,
'currency' => [
'type' => (string) $TypeID[2],
],
'equivFare' => 0.0,
'iva' => 0.0,
'otherDebit' => null,
'otherTax' => null,
'price' => (int) $data['variables']['x_total_amount'],
'providerPrice' => 0.0,
'qSe' => 0.0, //Consultar esto
'qSeIva' => 0.0,
'qse' => null,
'revenue' => 0.0,
'serviceCharge' => 0.0,
'sureCancel' => null,
'tA' => 0.0,
'taIva' => 0.0,
'tax' => 0.0,
'total' => (int) $data['variables']['x_total_amount'],
'yQ' => 0.0,
'yQiva' => 0.0,
'originalNationalCurrencyTotal' => (int) $data['variables']['x_total_amount'],
],
'passengerDataList' => [
[
'fareData' => null,
'gender' => '',
'id' => '',
'lastName' => (string) $request->get('quotationLastname'),
'mail' => (string) $request->get('quotationEmail'),
'mothersName' => '',
'name' => (string) $request->get('quotationName'),
'passengerCode' => [
'accountCode' => '',
'promo' => false,
'realType' => 'ADT',
'type' => 'ADT',
],
'passengerContact' => null,
'passengerInsuranceInfo' => null,
'phone' => null,
'document' => null,
'typeDocument' => null,
],
],
'productType' => [
'description' => 'Tarjeta de Asistencia',
'typeProduct' => 'Insurance',
],
'provider' => [
'category' => null,
'claveProveedor' => null,
'commissionPercentage' => 0,
'descripcionProveedor' => null,
'idProviders' => 0,
'name' => (string) $informationCard[1],
'nuevoProveedor' => false,
'providerRef' => null,
'utilityMax' => 0,
'utilityMin' => 0,
],
'route' => [
'arrivalDate' => (string) $request->get('dateEnd').'T00:00:00',
'arrivalDateString' => null,
'arrivalDescription' => (string) $destiny,
'arrivalIATA' => null,
'departureDate' => (string) $request->get('dateEntry').'T00:00:00',
'departureDateString' => null,
'departureDescription' => (string) $destiny,
'departureIATA' => null,
'destination' => null,
'flightTime' => null,
'origin' => null,
'providerCode' => null,
'subRoutes' => null,
],
],
'quote' => [
'channel' => 'B2C WEB',
],
];
$authorization = 'Authorization: Bearer '.$tokenApiQuotation;
//API URL
$url = $urlAddProductInsurance;
//create a new cURL resource
$ch = curl_init($url);
//setup request to send json via POST
$payload = json_encode($data_send);
$aviaturLogSave->logSave(print_r($payload, true), 'CGS_INSURANCE', 'RQInsuranceCGS');
// print_r($payload);die;
//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'accept: application/json',
'authorization: Bearer '.$tokenApiQuotation,
'content-type: application/json',
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//execute the POST request
$result = curl_exec($ch);
$aviaturLogSave->logSave(print_r($result, true), 'CGS_INSURANCE', 'RSInsuranceCGS');
//print_r($result);
//die;
//close CURL resource
curl_close($ch);
/*
* End API data send
*/
}
protected function authenticateUser(UserInterface $user, LoginManagerInterface $loginManager)
{
try {
$loginManager->loginUser(
'main',
$user
);
} catch (AccountStatusException $ex) {
// We simply do not authenticate users which do not pass the user
// checker (not enabled, expired, etc.).
}
}
/**
* getIINRanges()
* Para obtener todos los rangos asociados a IIN de las franquicias activas, y estas se manejarán en variables globales con arrays de javascript
* Author: Ing. David Rincon
* Email: david.rincon@aviatur.com
* Date: 2025/03/06
* @param $em (Object of DB manager).
* @return array
*/
public function getIINRanges($em){
$iinRecords = $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findByActiveFranchises();
$iinRecordsArray = [];
$ccranges = [];
$ccfranchises = [];
foreach ($iinRecords as $key => $iinRecord) {
$paymentGatewayCode = $iinRecord["paymentgatewaycode"];
$description = $iinRecord["description"];
$description = strtoupper(str_replace(' ', '', trim($description)));
$stringRanges = $iinRecord["ranges"];
$ranges = json_decode($stringRanges, true);
$stringLengths = $iinRecord["lengths"];
$lengths = json_decode($stringLengths, true);
$luhn = $iinRecord["luhn"];
$cvvDigits = $iinRecord["cvvdigits"];
$tempLengths = [];
foreach ($lengths["lengths"] as $length) {
$tempLengths[] = array(0 => $length[0], 1 => (isset($length[1]) ? $length[1] : $length[0]));
}
$tempRecordArrayFranchises = [];
$tempRecordArrayFranchises["code"] = $paymentGatewayCode;
$tempRecordArrayFranchises["codename"] = $description;
$tempRecordArrayFranchises["luhn"] = $luhn;
$tempRecordArrayFranchises["length"] = $tempLengths;
$tempRecordArrayFranchises["cvvd"] = $cvvDigits;
$ccfranchises[$paymentGatewayCode] = $tempRecordArrayFranchises;
foreach ($ranges["ranges"] as $range) {
$tempRecordArrayRanges = [];
$tempRecordArrayRanges["range"][0] = $range[0];
$tempRecordArrayRanges["range"][1] = (isset($range[1]) ? $range[1] : $range[0]);
$tempRecordArrayRanges["minimum"] = strlen($range[0]);
$tempRecordArrayRanges["code"] = $paymentGatewayCode;
$ccranges[] = $tempRecordArrayRanges;
}
}
$iinRecordsArray = array("ccranges" => $ccranges, "ccfranchises" => $ccfranchises);
return $iinRecordsArray;
}
}