src/Aviatur/GiftVoucherBundle/Controller/GiftVoucherController.php line 115

Open in your IDE?
  1. <?php
  2. namespace Aviatur\GiftVoucherBundle\Controller;
  3. use Doctrine\Persistence\ManagerRegistry;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\Routing\RouterInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  11. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  12. use Aviatur\GeneralBundle\Services\AviaturErrorHandler;
  13. use Aviatur\TwigBundle\Services\TwigFolder;
  14. use Aviatur\GeneralBundle\Services\AviaturWebService;
  15. use Aviatur\GeneralBundle\Controller\OrderController;
  16. use Aviatur\GeneralBundle\Entity\FormUserInfo;
  17. use Aviatur\CustomerBundle\Services\ValidateSanctionsRenewal;
  18. use Aviatur\CustomerBundle\Services\PhoneNumberService;
  19. use Aviatur\GeneralBundle\Services\AviaturChangeCoin;
  20. use Aviatur\GeneralBundle\Services\AviaturEncoder;
  21. use Aviatur\GeneralBundle\Services\AviaturLogSave;
  22. use Aviatur\GeneralBundle\Services\AviaturMailer;
  23. use Aviatur\GeneralBundle\Services\AviaturRestService;
  24. use Aviatur\GeneralBundle\Services\ExceptionLog;
  25. use Aviatur\GiftVoucherBundle\Services\EmissionWebservice;
  26. use Aviatur\PaymentBundle\Controller\P2PController;
  27. use Aviatur\PaymentBundle\Controller\WorldPayController;
  28. use Aviatur\PaymentBundle\Controller\CashController;
  29. use Aviatur\PaymentBundle\Controller\PSEController;
  30. use Aviatur\PaymentBundle\Controller\PSERestController;
  31. use Aviatur\PaymentBundle\Services\CustomerMethodPaymentService;
  32. use Aviatur\PaymentBundle\Services\TokenizerService;
  33. use Knp\Snappy\Pdf;
  34. class GiftVoucherController extends AbstractController
  35. {
  36.     /**
  37.     * @var ManagerRegistry
  38.     */
  39.     protected ManagerRegistry $managerRegistry;
  40.     private \Swift_Mailer $mailer;
  41.     /**
  42.     * @var SessionInterface
  43.     */
  44.     protected $session;
  45.     protected $paymentMethod;
  46.     public function __construct(ManagerRegistry $managerRegistry, \Swift_Mailer $mailerSessionInterface $session)
  47.     {
  48.         $em $managerRegistry->getManager();
  49.         $this->mailer $mailer;
  50.         $paymentMethods $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethod::class)->findByCode(['pse''pseRest']);
  51.         $agencyId $session->has('agencyId') ? $session->get('agencyId') : 1;
  52.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($agencyId);
  53.         $activePayments array_filter($paymentMethods, function($payment) use ($agency$em) {
  54.             $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)
  55.                 ->findOneBy(['agency' => $agency->getId(), 'paymentMethod' => $payment->getId()]);
  56.             return $payment->getIsactive() && $paymentMethodAgency && $paymentMethodAgency->getIsactive();
  57.         });
  58.         switch (count($activePayments)) {
  59.             case 0:
  60.                 $this->paymentMethod null;
  61.                 break;
  62.             case 1:
  63.                 $this->paymentMethod reset($activePayments);
  64.                 break;
  65.             default:
  66.                 $paymentMethod $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethod::class)->findOneByCode('pseRest');
  67.                 $this->paymentMethod $paymentMethod;
  68.                 break;
  69.         }
  70.     }
  71.     public function searchAction()
  72.     {
  73.         return $this->redirect(
  74.             $this->generateUrl(
  75.                 'aviatur_gift_voucher_home',
  76.                 []
  77.             )
  78.         );
  79.     }
  80.     // Vista Home
  81.     public function indexAction(Request $requestTwigFolder $twigFolderAviaturErrorHandler $aviaturErrorHandler,ManagerRegistry $registrySessionInterface $session)
  82.     {
  83.         $em $registry->getManager();
  84.         // $agencyFolder = $twigFolder->twigFlux();
  85.         // $template = '@AviaturTwig/'.$agencyFolder.'/GiftVoucher/Default/Landing/detail.html.twig';
  86.         $template '@AviaturTwig/default/Flux/GiftVoucher/Default/Landing/detail.html.twig';
  87.         // Valida la existencia y configuración de tarjeta regalo en la agencia
  88.         $validateAgencyRequest $this->validateAgencyRequest($session->get('agencyId'), $request$em$aviaturErrorHandlerfalse);
  89.         if(!isset($validateAgencyRequest["agency"])){
  90.             return $this->redirect($validateAgencyRequest);
  91.         }
  92.         if ($twigFolder->twigExists($template)) {
  93.             return $this->render($template, []);
  94.         }
  95.         // optional: handle case where template doesn't exist
  96.         throw $this->createNotFoundException("Template not found: $template");
  97.     }
  98.     // Vista de personalización
  99.     public function personalizeAction(Request $requestTwigFolder $twigFolderAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registrySessionInterface $session)
  100.     {
  101.         // Información de agencia
  102.         $em $registry->getManager();
  103.         // Valida la existencia y configuración de tarjeta regalo en la agencia
  104.         $validateAgencyRequest $this->validateAgencyRequest($session->get('agencyId'), $request$em$aviaturErrorHandlerfalse);
  105.         if(!isset($validateAgencyRequest["agency"])){
  106.             return $this->redirect($validateAgencyRequest);
  107.         }
  108.         $agency =$validateAgencyRequest["agency"];
  109.         // Array configuración bono de regalo
  110.         $giftVoucherConfigObject $validateAgencyRequest["giftVoucherConfigObject"];
  111.         $giftVoucherConfigArray json_decode($giftVoucherConfigObject[0]['params'], true);
  112.         try {
  113.             // Organizar de menor a mayor precio
  114.             usort($giftVoucherConfigArray['fares'], function($a$b) {
  115.                 return intval($a['value']) <=> intval($b['value']);
  116.             });
  117.             // Crear transactionId
  118.             $transactionIdResponse $aviaturWebService->loginService('SERVICIO_MPT''dummy|http://www.aviatur.com.co/dummy/', []);
  119.             if ('error' == $transactionIdResponse || is_array($transactionIdResponse)) {
  120.                 return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_home'), '''Lo sentimos, estamos experimentando dificultades técnicas en este momento.'));
  121.             }
  122.             $transactionId = (string) $transactionIdResponse;
  123.             // Información a enviar
  124.             $detailData = [
  125.                 'currency' => 'COP',
  126.                 'giftValue' => $giftVoucherConfigArray['minValue'],
  127.                 'arrayImage' => $giftVoucherConfigArray["images"],
  128.                 'giftVoucherFares' => $giftVoucherConfigArray['fares'],
  129.                 'giftVoucherParams' => [
  130.                     'minValue' => $giftVoucherConfigArray['minValue'],
  131.                     'maxValue' => $giftVoucherConfigArray['maxValue'],
  132.                 ],
  133.                 'transactionId' => $transactionId,
  134.                 'safeUrl' => 'https://' $agency->getDomain(),
  135.             ];
  136.         } catch (\Exception $e) {
  137.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_home'), '''Lo sentimos, estamos experimentando dificultades técnicas en este momento. Error en la configuración.'));
  138.         }
  139.         $agencyFolder $twigFolder->twigFlux();
  140.         return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/GiftVoucher/Default/personalize.html.twig'), $detailData);
  141.     }
  142.     // Vista de checkOut
  143.     public function checkoutAction(Request $requestTwigFolder $twigFolderAviaturWebService $aviaturWebServiceAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registrySessionInterface $sessionAviaturEncoder $aviaturEncoder)
  144.     {
  145.         $em $registry->getManager();
  146.         $whitemarkAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\Whitemark::class)->findOneBy(['referer' => $session->get('whitemark')]);
  147.         // Valida la existencia y configuración de tarjeta regalo en la agencia
  148.         $validateAgencyRequest $this->validateAgencyRequest($session->get('agencyId'), $request$em$aviaturErrorHandlertrue);
  149.         if(!isset($validateAgencyRequest["agency"])){
  150.             return $this->redirect($validateAgencyRequest);
  151.         }
  152.          if (null !== $whitemarkAgency) {
  153.             $phonesContact json_decode($whitemarkAgency->getPhonesContact(), true);
  154.             $whitemarkAgencyDataInfo = [
  155.                 'id'        => $whitemarkAgency->getId(),
  156.                 'name'      => $whitemarkAgency->getName(),
  157.                 'phone'     => $whitemarkAgency->getPhone(),
  158.                 'email'     => $whitemarkAgency->getEmail(),
  159.                 'address'   => $whitemarkAgency->getAddress(),
  160.                 'whatsapp'  => $phonesContact['whatsapp'] ?? null,
  161.             ];
  162.     $session->set('whitemarkData'$whitemarkAgencyDataInfo);
  163. }
  164.         //Información de agencia
  165.         $agency $validateAgencyRequest["agency"];
  166.         if ($agency->getDomainsecure() == $agency->getDomain() && '443' != $agency->getCustomport()) {
  167.             $safeUrl 'https://'.$agency->getDomain();
  168.         } else {
  169.             $safeUrl 'https://'.$agency->getDomainsecure();
  170.         }
  171.         // Información del bono escogido
  172.         $request = !empty($request->request->all()) ? $request->request $request->query;
  173.         $bonoInfo $request->all();
  174.         // Obtener el transactionId
  175.         $transactionId = (string) ($bonoInfo["bonoTransactionId"] ?? $bonoInfo['transactionRetryId']);
  176.         // Validar si es reintento de pago
  177.         $isretry = !empty($bonoInfo['transactionRetryId']);
  178.         if($isretry){
  179.             // Si ya no quedan intentos de compra, redirigir al home de bono regalo
  180.             $retryCount $session->get($transactionId '[bono][retry]');
  181.             if($retryCount <= 0){
  182.                 $titleError "Acceso no autorizado";
  183.                 $textError "Ha sido redirigido al home para que pueda seguir explorando opciones.";
  184.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($this->generateUrl("aviatur_gift_voucher_home", []), $titleError$textError));
  185.             }
  186.             // Información de bono regalo seleccionado
  187.             $bonoInfo json_decode(base64_decode($session->get($transactionId "[bono][bonoInfo]")), true);
  188.             // Información de formularios de usuario
  189.             $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId '[bono][userInfo]'));
  190.             $decodedResponseInfoUser json_decode($aviaturEncoder->AviaturDecode($formUserInfo->getInfo(), $formUserInfo->getPublicKey()), true);
  191.             $passangerInfo $decodedResponseInfoUser["PI"];
  192.             $billingData $decodedResponseInfoUser["BD"];
  193.         }
  194.         // Validación del precio del bono
  195.         $giftVoucherConfigObject $validateAgencyRequest["giftVoucherConfigObject"];
  196.         $validatePriceBono $this->validatePriceBono($giftVoucherConfigObject$bonoInfo$aviaturErrorHandler);
  197.         if(!isset($validatePriceBono["giftFarePrice"])){
  198.             return $this->redirect($validatePriceBono);
  199.         }
  200.         // Guardar información de bono regalo, encodeada en session
  201.         $session->set($transactionId '[bono][bonoInfo]'base64_encode(json_encode($validatePriceBono)));
  202.         // Datos formularios
  203.         $typeGender $em->getRepository(\Aviatur\CustomerBundle\Entity\Gender::class)->findAll();
  204.         $documentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAll();
  205.         $documentPassengerType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class)->findAllActiveConfigured();
  206.         $repositoryDocumentType $em->getRepository(\Aviatur\CustomerBundle\Entity\DocumentType::class);
  207.         $queryDocumentType $repositoryDocumentType
  208.                 ->createQueryBuilder('p')
  209.                 ->where('p.paymentcode != :paymentcode')
  210.                 ->setParameter('paymentcode''')
  211.                 ->getQuery();
  212.         $documentPaymentType $queryDocumentType->getResult();
  213.         $paymentMethodAgency $em->getRepository(\Aviatur\GeneralBundle\Entity\PaymentMethodAgency::class)->findBy(['agency' => $agency'isactive' => 1]);
  214.         $paymentOptions = [];
  215.         foreach ($paymentMethodAgency as $payMethod) {
  216.             $paymentCode $payMethod->getPaymentMethod()->getCode();
  217.             if (!in_array($paymentCode$paymentOptions) && 'safety' != $paymentCode) {
  218.                 $paymentOptions[] = $paymentCode;
  219.             }
  220.         }
  221.         $banks = [];
  222.         if (in_array('pse'$paymentOptions)) {
  223.             $banks $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findAll();
  224.         }
  225.         $cybersource = [];
  226.         if (in_array('cybersource'$paymentOptions)) {
  227.             $cybersource['merchant_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getSitecode();
  228.             $cybersource['org_id'] = $paymentMethodAgency[array_search('cybersource'$paymentOptions)]->getTrankey();
  229.         }
  230.         foreach ($paymentOptions as $key => $paymentOption) {
  231.             if ('cybersource' == $paymentOption) {
  232.                 unset($paymentOptions[$key]); // strip from other renderizable payment methods
  233.             }
  234.         }
  235.         $conditions $em->getRepository(\Aviatur\GeneralBundle\Entity\HistoricalInfo::class)->findMessageByAgencyOrNull($agency'reservation_conditions');
  236.         $passangerTypes = [];
  237.         $passangerTypes[1]['ADT'] = 1;
  238.         $passangerTypes[1]['CHD'] = 0;
  239.         $passangerTypes[1]['INF'] = 0;
  240.         /* Aplicando para vuelo, pero teniendo cuidado con los otros productos */
  241.         /* 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 */
  242.         $iinRecordsArray $aviaturWebService->getIINRanges($em);
  243.         // prefijos
  244.         $phoneService = new PhoneNumberService($em);
  245.         $phonePrefixes $phoneService->getActivePrefixes();
  246.         // Respuesta para el checkout
  247.         $detailData = [
  248.             'safeUrl' => $safeUrl,
  249.             'twig_readonly' => $isretry,
  250.             'bonoInfo' => $validatePriceBono,
  251.             'passengers' => $passangerInfo ?? null,
  252.             'billingData' => $billingData ?? null,
  253.             'contactData' => $contactData ?? null,
  254.             'gender' => $typeGender,
  255.             'payment_doc_type' => $documentPaymentType,
  256.             'doc_type' => $documentType,
  257.             'documentPassengerType' => $documentPassengerType,
  258.             'conditions' => $conditions,
  259.             'paymentOptions' => $paymentOptions,
  260.             'cybersource' => $cybersource,
  261.             'ccfranchises' => $iinRecordsArray["ccfranchises"],
  262.             'ccranges' => $iinRecordsArray["ccranges"],
  263.             'banks' => $banks,
  264.             'cards' => $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findAll(),
  265.             'payment_type_form_name' => 'paymentForm',
  266.             'services' => $passangerTypes,
  267.             'phone_prefixes' => $phonePrefixes,
  268.             'default_country' => 'CO',
  269.             'pse' => 1,
  270.             'isBono' => true
  271.         ];
  272.         // $whatsapp = $session->get('whitemarkDataInfo')['telefono'] ?? $session->get('agencyDataInfo')['agency_phones']['what']['whatsApp'] ?? null;
  273.         $agencyFolder $twigFolder->twigFlux();
  274.         return $this->render($twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/GiftVoucher/Default/checkout.html.twig'), $detailData);
  275.     }
  276.     // Inicio proceso de pago y facturación
  277.     public function prePaymentStep1Action(Request $requestTokenizerService $tokenizerCustomerMethodPaymentService $customerMethodPaymentServiceTokenStorageInterface $tokenStorageAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registrySessionInterface $sessionParameterBagInterface $parameterBag)
  278.     {
  279.         $em $registry->getManager();
  280.         // Valida la existencia y configuración de tarjeta regalo en la agencia
  281.         $validateAgencyRequest $this->validateAgencyRequest($session->get('agencyId'), $request$em$aviaturErrorHandlertrue);
  282.         if(!isset($validateAgencyRequest["agency"])){
  283.             return $this->json(['error' => true'message' => $validateAgencyRequest]);
  284.         }
  285.         // Traer el RQ enviado desde el front
  286.         $request = !empty($request->request->all()) ? $request->request $request->query;
  287.         $checkoutInfo $request->all();
  288.         // Obtener el transactionId y guardarlo
  289.         $transactionId = (string) $checkoutInfo["giftCardTransactionId"];
  290.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  291.         $session->set($transactionIdSessionName$transactionId);
  292.         // Guardar intentos de compra
  293.         $aviaturPaymentRetryTimes $parameterBag->get('aviatur_payment_retry_times');
  294.         $retryCount $session->get($transactionId '[bono][retry]');
  295.         if($retryCount == null){
  296.             $session->set($transactionId '[bono][retry]'$aviaturPaymentRetryTimes);
  297.         }
  298.         // Validar si ya hay userInfo en la sesión
  299.         $userInfoBono $session->get($transactionId '[bono][userInfo]');
  300.         $isFront $session->has('operatorId');
  301.         if($userInfoBono != null){
  302.             // Información de formularios de usuario
  303.             $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($userInfoBono);
  304.             $decodedResponseInfoUser json_decode($aviaturEncoder->AviaturDecode($formUserInfo->getInfo(), $formUserInfo->getPublicKey()), true);
  305.             if (!$isFront) {
  306.                 $decodedResponseInfoUser["PD"] = $checkoutInfo["PD"];
  307.             }
  308.             $checkoutInfo $decodedResponseInfoUser;
  309.         }else{
  310.             $formUserInfo = new FormUserInfo();
  311.         }
  312.         // Token de la tarjeta, en caso que exista
  313.         $publicKey $aviaturEncoder->aviaturRandomKey();
  314.         if (isset($checkoutInfo["PD"]["card_num"])) {
  315.             $postDataInfo $checkoutInfo;
  316.             if (isset($postDataInfo["PD"]["cusPOptSelected"])) {
  317.                 $customerLogin $tokenStorage->getToken()->getUser();
  318.                 $infoMethodPaymentByClient $customerMethodPaymentService->getMethodsByCustomer($customerLogintrue);
  319.                 $cardToken $infoMethodPaymentByClient["info"][$postDataInfo["PD"]["cusPOptSelected"]]["token"];
  320.                 $postDataInfo["PD"]["card_num"] = $cardToken;
  321.             } else {
  322.                 $postDataInfo["PD"]["card_num"] = $tokenizer->getToken($checkoutInfo["PD"]["card_num"]);
  323.             }
  324.             $checkoutInfo["PD"]["card_values"] = ["card_num_token" => $postDataInfo["PD"]["card_num"], "card_num" => $checkoutInfo["PD"]["card_num"]];
  325.         }
  326.         // Encodear y guardar la info de los formularios en la tabla form_user_info
  327.         $postDataInfo $postDataInfo ?? $checkoutInfo;
  328.         $encodedInfo $aviaturEncoder->AviaturEncode(json_encode($postDataInfo), $publicKey);
  329.         $formUserInfo->setInfo($encodedInfo);
  330.         $formUserInfo->setPublicKey($publicKey);
  331.         $em->persist($formUserInfo);
  332.         $em->flush();
  333.         // Guardar en session el id de la tabla
  334.         $session->set($transactionId "[bono][userInfo]"$formUserInfo->getId());
  335.         // Guardar en session el id proveedor de bono regalo
  336.         $provider $em->getRepository(\Aviatur\MpaBundle\Entity\Provider::class)->findBy(['name' => 'Bono de regalo']);
  337.         $session->set($transactionId.'[bono][provider]'$provider[0]->getProvideridentifier());
  338.         // Información facturador
  339.         $billingData $checkoutInfo["BD"];
  340.         $customer null;
  341.         $ordersProduct null;
  342.         if (!$isFront) {
  343.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  344.             $ordersProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->getOrderProductsPending($customer);
  345.         }
  346.         if (null == $ordersProduct) {
  347.             $session->set($transactionId '[bono][detailDataBono]'json_encode($postDataInfo));
  348.             // Información pasajeros
  349.             $passangersData $postDataInfo["PI"];
  350.             $passangerNames = [];
  351.             for ($i 1$i <= $passangersData['person_count_1']; ++$i) {
  352.                 $passangerNames[] = mb_strtolower($passangersData['first_name_1_'.$i]);
  353.                 $passangerNames[] = mb_strtolower($passangersData['last_name_1_'.$i]);
  354.             }
  355.             $nameWhitelist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameWhitelist::class)->findLikeWhitelist($passangerNames);
  356.             if (== sizeof($nameWhitelist)) {
  357.                 $nameBlacklist $em->getRepository(\Aviatur\GeneralBundle\Entity\NameBlacklist::class)->findLikeBlacklist($passangerNames);
  358.                 if ((sizeof(preg_grep("/^[a-z- *\.]+$/"$passangerNames)) != (sizeof($passangerNames))) ||
  359.                         (sizeof($nameBlacklist)) ||
  360.                         (sizeof(preg_grep('/(([b-df-hj-np-tv-xz])(?!\2)){4}/'$passangerNames)))) {
  361.                     return $this->json(['error' => 'error''message' => 'nombre inválido']);
  362.                 }
  363.             }
  364.             $ajaxUrl $this->generateUrl('aviatur_gift_voucher_prepayment_step_2_secure');
  365.             return $this->json(['ajax_url' => $ajaxUrl]);
  366.         } else {
  367.             $booking = [];
  368.             $cus = [];
  369.             foreach ($ordersProduct as $orderProduct) {
  370.                 $productResponse $aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey());
  371.                 $paymentResponse json_decode($productResponse);
  372.                 array_push($booking"ON" $orderProduct->getOrder()->getId() . "-PN" $orderProduct->getId());
  373.                 if (isset($paymentResponse->x_approval_code)) {
  374.                     array_push($cus$paymentResponse->x_approval_code);
  375.                 } elseif (isset($paymentResponse->createTransactionResult->trazabilityCode)) {
  376.                     array_push($cus$paymentResponse->createTransactionResult->trazabilityCode);
  377.                 }
  378.             }
  379.             $return = [
  380.                 "error" => "pending_payments",
  381.                 "message" => "pending_payments",
  382.                 "booking" => $booking,
  383.                 // "domain" => $domain ?? null,
  384.                 // "agencyId" => $this->agency ?? null,
  385.                 // "operatorId" => $operatorId ?? null,
  386.                 "cus" => $cus,
  387.             ];
  388.             return new JsonResponse($return);
  389.         }
  390.     }
  391.     // Creación de orden - addProductData
  392.     public function prePaymentStep2Action(Request $requestOrderController $orderControllerAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registrySessionInterface $sessionParameterBagInterface $parameterBagAviaturEncoder $aviaturEncoder)
  393.     {
  394.         $em $registry->getManager();
  395.         // Valida la existencia y configuración de tarjeta regalo en la agencia
  396.         $validateAgencyRequest $this->validateAgencyRequest($session->get('agencyId'), $request$em$aviaturErrorHandlertrue);
  397.         if(!isset($validateAgencyRequest["agency"])){
  398.             return $this->json(['error' => true'message' => $validateAgencyRequest]);
  399.         }
  400.         //Información de agencia
  401.         $agency $validateAgencyRequest["agency"];
  402.         // Traer el RQ enviado desde el front
  403.         $request = !empty($request->request->all()) ? $request->request $request->query;
  404.         $checkoutInfo $request->all();
  405.         // Obtener el transactionId
  406.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  407.         $transactionId = (string) ($checkoutInfo["giftCardTransactionId"] ?? $session->get($transactionIdSessionName));
  408.         // Validar si ya hay userInfo en la sesión
  409.         $userInfoBono $session->get($transactionId '[bono][userInfo]');
  410.         $isFront $session->has('operatorId');
  411.         if($userInfoBono != null){
  412.             // Información de formularios de usuario
  413.             $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($userInfoBono);
  414.             $decodedResponseInfoUser json_decode($aviaturEncoder->AviaturDecode($formUserInfo->getInfo(), $formUserInfo->getPublicKey()), true);
  415.             if (!$isFront) {
  416.                 $decodedResponseInfoUser["PD"] = $checkoutInfo["PD"];
  417.             }
  418.             $checkoutInfo $decodedResponseInfoUser;
  419.         }
  420.         // Información facturador
  421.         $billingData $checkoutInfo['BD'];
  422.         $isFront $session->has('operatorId');
  423.         if ($isFront) {
  424.             $customer $billingData;
  425.             $customer['isFront'] = true;
  426.             $status 'B2T';
  427.         } else {
  428.             $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($billingData['id']);
  429.             $status 'waiting';
  430.         }
  431.         $order = [];
  432.         if (true !== $session->has($transactionId.'[bono][order]')) {
  433.             // Crear Order y order product, con add_productData
  434.             $productType $em->getRepository(\Aviatur\MpaBundle\Entity\ProductType::class)->findByCode('BONO');
  435.             $orderIdentifier '{booking_id}';
  436.             $order $orderController->createAction($agency$customer$productType$orderIdentifier$status);
  437.             $orderId str_replace('ON'''$order['order']);
  438.             $orderEntity $em->getRepository(\Aviatur\GeneralBundle\Entity\Order::class)->find($orderId);
  439.             $formUserInfo $em->getRepository(\Aviatur\GeneralBundle\Entity\FormUserInfo::class)->find($session->get($transactionId.'[bono][userInfo]'));
  440.             $formUserInfo->setOrder($orderEntity);
  441.             $em->persist($formUserInfo);
  442.             $em->flush();
  443.         }
  444.         // Preparando información para Resume
  445.         $this->prepareInfoResume($session$registry$parameterBag$aviaturEncoder);
  446.         if ($isFront) {
  447.             // Ir a generar bono
  448.             $order['url'] = $this->generateUrl('aviatur_gift_voucher_generar_bono');
  449.         } else {
  450.             // Ir a pago
  451.             $order['url'] = $this->generateUrl('aviatur_gift_voucher_payment_secure');
  452.         }
  453.         return $this->json($order);
  454.     }
  455.     // Proceso de pago
  456.     public function paymentAction(Request $requestOrderController $orderController, \Swift_Mailer $mailerRouterInterface $routerP2PController $p2pPaymentControllerPSEController $psePaymentControllerPSERestController $PSERestControllerCashController $cashPaymentControllerAviaturErrorHandler $aviaturErrorHandlerManagerRegistry $registrySessionInterface $sessionParameterBagInterface $parameterBagTokenizerService $tokenizerCustomerMethodPaymentService $customerMethodPaymentServiceAviaturLogSave $logSave)
  457.     {
  458.         $em $registry->getManager();
  459.         // Valida la existencia y configuración de tarjeta regalo en la agencia
  460.         $validateAgencyRequest $this->validateAgencyRequest($session->get('agencyId'), $request$em$aviaturErrorHandlerfalse);
  461.         if(!isset($validateAgencyRequest["agency"])){
  462.             return $this->json(['error' => true'message' => $validateAgencyRequest]);
  463.         }
  464.         // Obtener el transactionId
  465.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  466.         $transactionId $session->get($transactionIdSessionName);
  467.         // IdOrder y IdOrderProduct
  468.         if (true !== $session->has($transactionId.'[bono][order]')) {
  469.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_home'), '''No se encontró orden asociada a este pago.'));
  470.         }
  471.         $orderInfo json_decode($session->get($transactionId '[bono][order]'));
  472.         $productId str_replace('PN'''$orderInfo->products);
  473.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  474.         // Actualizar reintentos de pago
  475.         $retryCount = (int) $session->get($transactionId '[bono][retry]');
  476.         $session->set($transactionId '[bono][retry]'$retryCount 1);
  477.         $arrayResume json_decode($orderProduct->getResume(), true);
  478.         if (isset($arrayResume["retry_count"])) {
  479.             $arrayResume["retry_count"] = $retryCount 1;
  480.             $orderProduct->setResume(json_encode($arrayResume));
  481.             $em->persist($orderProduct);
  482.             $em->flush();
  483.         }
  484.         // Obtener la información de la tarjeta regalo desde la sesión
  485.         $bonoInfo json_decode(base64_decode($session->get($transactionId "[bono][bonoInfo]")), true);
  486.         // Valores totalizados
  487.         $totalAmountCOP $bonoInfo["giftFarePrice"];
  488.         $x_amount_tax number_format(02'.''');
  489.         $x_amount_base number_format(round((float) $totalAmountCOP), 2'.''');
  490.         // Descripción del producto
  491.         $description 'Bono de Regalo - $'.$totalAmountCOP;
  492.         // Id del proveedor
  493.         $providerId $session->get($transactionId '[bono][provider]');
  494.         // Obtener información de los formularios del checkOut
  495.         $postData json_decode($session->get($transactionId '[bono][detailDataBono]'));
  496.         // Datos de pago y de facturador
  497.         $paymentData $postData->PD;
  498.         $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($postData->BD->id);
  499.         $recipientData $postData->PI;
  500.         // Datos de agencia
  501.         $agency $validateAgencyRequest["agency"];
  502.         $agencyName $agency->getName();
  503.         $agencyOfficeId $agency->getOfficeId();
  504.         // Pago
  505.         if ('p2p' == $paymentData->type) {
  506.             if (false !== strpos($paymentData->address'***')) {
  507.                 $paymentData->address $customer->getAddress();
  508.             }
  509.             if (false !== strpos($paymentData->phone'***')) {
  510.                 $paymentData->phone $customer->getPhone();
  511.             }
  512.             if (false !== strpos($paymentData->email'***')) {
  513.                 $paymentData->email $customer->getEmail();
  514.             }
  515.             $array = [
  516.                 'x_currency_code' => $bonoInfo["currency"],
  517.                 'x_amount' => $totalAmountCOP,
  518.                 'x_tax' => $x_amount_tax,
  519.                 'x_amount_base' => $x_amount_base,
  520.                 'x_invoice_num' => $orderInfo->order '-' $orderInfo->products,
  521.                 'x_first_name' => $paymentData->first_name,
  522.                 'x_last_name' => $paymentData->last_name,
  523.                 'x_description' => $description,
  524.                 'x_city' => $customer->getCity()->getIatacode(),
  525.                 'x_country_id' => $customer->getCountry()->getIatacode(),
  526.                 'x_cust_id' => $paymentData->doc_type ' ' $paymentData->doc_num,
  527.                 'x_address' => $paymentData->address,
  528.                 'x_phone' => $paymentData->phone,
  529.                 'x_email' => $paymentData->email,
  530.                 'x_card_num' => $paymentData->card_num,
  531.                 'x_exp_date' => $paymentData->exp_month $paymentData->exp_year,
  532.                 'x_card_code' => $paymentData->card_code,
  533.                 'x_differed' => $paymentData->differed,
  534.                 'x_client_id' => $postData->BD->id,
  535.                 'product_type' => 'bono',
  536.                 'productId' => str_replace('PN'''$orderInfo->products),
  537.                 'orderId' => str_replace('ON'''$orderInfo->order),
  538.                 'franchise' => $paymentData->franquise,
  539.                 'worldpay_validate' => true
  540.             ];
  541.             if (isset($paymentData->card_values)) {
  542.                 $array['card_values'] = (array) $paymentData->card_values;
  543.             }
  544.             if (isset($paymentData->cusPOptSelected)) {
  545.                 $array['isToken'] = (string) $paymentData->card_values->card_num_token;
  546.             }
  547.             if (isset($postData->PD->savePaymProc) || (isset($paymentData->cusPOptSelected) && isset($paymentData->cusPOptSelectedStatus) && 'NOTVERIFIED' == $paymentData->cusPOptSelectedStatus)) {
  548.                 $array['x_provider_id'] = 1;
  549.             } elseif (isset($paymentData->cusPOptSelected) && (!isset($paymentData->cusPOptSelectedStatus) || 'NOTVERIFIED' != $paymentData->cusPOptSelectedStatus)) {
  550.                 $array['x_provider_id'] = 2;
  551.             }
  552.             // Servicio de pago (payRequest y PayResponse)
  553.             $paymentResponse $p2pPaymentController->placetopayAction($parameterBag$tokenizer$customerMethodPaymentService$mailer$logSave$array);
  554.             unset($array['x_client_id']);
  555.             if (empty($paymentResponse)) {
  556.                 // No hay respuesta por parte del servicio de pago, estado pendiente
  557.                 $orderProduct->setStatus('pending');
  558.                 $em->persist($orderProduct);
  559.                 $em->flush();
  560.                 $urlRetry $this->generateUrl('aviatur_gift_voucher_retry_secure', ["transactionRetryId" => $transactionId]);
  561.                 $titleError "";
  562.                 $textError "No hay respuesta por parte del servicio de pago, por favor intenta nuevamente o comunícate con nosotros para finalizar tu transacción.";
  563.                 return $this->redirect($aviaturErrorHandler->errorRedirectNoEmail($urlRetry$titleError$textError));
  564.             }
  565.             return $this->redirect($this->generateUrl('aviatur_gift_voucher_payment_p2p_secure', [], true));
  566.         } elseif ('pse' == $paymentData->type) {
  567.             $array = [
  568.                 'x_invoice_num' => $orderInfo->order.'-'.$orderInfo->products,
  569.                 'x_doc_num' => $postData->PD->pse_doc_num,
  570.                 'x_doc_type' => $postData->PD->pse_doc_type,
  571.                 //'x_doc_num' => $customer->getDocumentnumber(),
  572.                 //'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  573.                 'x_first_name' => $customer->getFirstname(),
  574.                 'x_last_name' => $customer->getLastname(),
  575.                 'x_company' => $agencyName,
  576.                 'x_email' => $customer->getEmail(),
  577.                 'x_address' => $customer->getAddress(),
  578.                 'x_city' => $customer->getCity()->getDescription(),
  579.                 'x_province' => $customer->getCity()->getDescription(),
  580.                 'x_country' => $customer->getCountry()->getDescription(),
  581.                 'x_phone' => $customer->getPhone(),
  582.                 'x_mobile' => $customer->getCellphone(),
  583.                 'x_bank' => $postData->PD->pse_bank,
  584.                 'x_type' => $postData->PD->pse_type,
  585.                 'x_response_url' => $this->generateUrl('aviatur_gift_voucher_payment_pse_return_url_secure', [], true),
  586.                 'x_reference' => $orderInfo->order.'-'.$orderInfo->products,
  587.                 'x_description' => $description,
  588.                 'x_currency' => $bonoInfo["currency"],
  589.                 'x_total_amount' => $totalAmountCOP,
  590.                 'x_tax' => $x_amount_tax,
  591.                 'x_amount_base' => $x_amount_base,
  592.                 'x_devolution_base' => $x_amount_base,
  593.                 'x_tip_amount' => number_format(round(0), 2'.'''),
  594.                 'product_type' => 'bono',
  595.                 'x_providerId' => $providerId,
  596.                 'x_transactionId' => $transactionId
  597.             ];
  598.             // Servicio de pago pse - Realizar pago por opcion definida en payment_method
  599.             $paymentCode $this->paymentMethod->getCode() === 'pse' 'pse' 'pseRest';
  600.             if ($paymentCode === 'pse') {
  601.                 $paymentResponse $psePaymentController->sendPaymentAction($request$session$router$parameterBag$mailer$orderController$array, [$orderProduct]);
  602.             } else {
  603.                 $paymentResponse $PSERestController->sendRestPaymentAction($request$session$router$parameterBag$mailer$orderController$array, [$orderProduct], $logSave);
  604.             }
  605.             if (!isset($paymentResponse->error)) {
  606.                 if ($paymentCode === 'pse') {
  607.                     $returnStatusCode $paymentResponse->createTransactionResult->returnCode;
  608.                     $returnUrl = (string) $paymentResponse->createTransactionResult->bankURL ?? $paymentResponse->createTransactionResult->bankurl;
  609.                 } else {
  610.                     $returnStatusCode $paymentResponse->status->status;
  611.                     $returnUrl $paymentResponse->redirection->processURL;
  612.                 }
  613.                 switch ($returnStatusCode) {
  614.                     case 'SUCCESS':
  615.                     case 'PENDING':
  616.                         return $this->redirect($returnUrl);
  617.                     case 'FAIL_EXCEEDEDLIMIT':
  618.                         $textMsg 'Su reserva fue realizada exitosamente, sin embargo, el monto excede los límites establecidos, comunícate con nosotros a  los teléfonos 57 1 5879640 o 57 1 3821616 o  vía e-mail al correo soportepagoelectronico@aviatur.com.co para completar tu transacción.';
  619.                         return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_home'), ''$textMsg));
  620.                     case 'FAIL_BANKUNREACHEABLE':
  621.                     case 'FAILED':
  622.                         $textMsg 'Tu entidad financiera no pudo ser contactada para iniciar la transacción, por favor inténtalo nuevamente.';
  623.                         $urlRetry $this->generateUrl('aviatur_gift_voucher_retry_secure', ["transactionRetryId" => $transactionId]);
  624.                         return $this->redirect($aviaturErrorHandler->errorRedirect($urlRetry''$textMsg));
  625.                     default:
  626.                         $textMsg 'No se pudo crear la transacción con tu banco, por favor inténtalo nuevamente.';
  627.                         $urlRetry $this->generateUrl('aviatur_gift_voucher_retry_secure', ["transactionRetryId" => $transactionId]);
  628.                         return $this->redirect($aviaturErrorHandler->errorRedirect($urlRetry''$textMsg));
  629.                 }
  630.             } else {
  631.                 $urlRetry $this->generateUrl('aviatur_gift_voucher_retry_secure', ["transactionRetryId" => $transactionId]);
  632.                 return $this->redirect($aviaturErrorHandler->errorRedirect($urlRetry'Error al procesar el pago''Ocurrió un problema al intentar crear su transacción, '.$paymentResponse->error));
  633.             }
  634.         } elseif ('cash' == $paymentData->type) {
  635.             // Fecha de creacón de la orden
  636.             $fecha $orderProduct->getCreationDate()->format('Y-m-d H:i:s');
  637.             $fechalimite $orderProduct->getCreationDate()->format('Y-m-d 23:40:00');
  638.             $nuevafecha strtotime('+5 hour'strtotime($fecha));
  639.             $fechavigencia date('Y-m-d H:i:s'$nuevafecha);
  640.             if (strcmp($fechavigencia$fechalimite) > 0) {
  641.                 $fechavigencia $fechalimite;
  642.             }
  643.             // Generar bookingId
  644.             $bookingId $this->generateRamdonCode();
  645.             $array = [
  646.                 'x_officeId' => $agencyOfficeId,
  647.                 'x_doc_num' => $customer->getDocumentnumber(),
  648.                 'x_doc_type' => $customer->getDocumentType()->getPaymentcode(),
  649.                 'x_first_name' => $customer->getFirstname(),
  650.                 'x_last_name' => $customer->getLastname(),
  651.                 'x_company' => $agencyName,
  652.                 'x_email' => $customer->getEmail(),
  653.                 'x_address' => $customer->getAddress(),
  654.                 'x_city' => $customer->getCity()->getDescription(),
  655.                 'x_province' => $customer->getCity()->getDescription(),
  656.                 'x_country' => $customer->getCountry()->getDescription(),
  657.                 'x_phone' => $customer->getPhone(),
  658.                 'x_mobile' => $customer->getCellphone(),
  659.                 'x_payment_data' => $paymentData->type,
  660.                 'x_booking' => $bookingId,
  661.                 'x_type_description' => $orderProduct->getDescription(),
  662.                 'x_reference' => $orderInfo->products,
  663.                 'x_description' => $description,
  664.                 'x_currency' => $bonoInfo["currency"],
  665.                 'x_total_amount' => $totalAmountCOP,
  666.                 'x_fechavigencia' => $fechavigencia,
  667.                 'x_transactionId' => $transactionId
  668.             ];
  669.             if ($session->has($transactionId.'[bono][detail_cash]')) {
  670.                 $detail_cash json_decode($session->get($transactionId.'[bono][detail_cash]'));
  671.                 if ('error' == $detail_cash->status) {
  672.                     $cashPay $cashPaymentController->cashAction($logSave$array);
  673.                 } else {
  674.                     $cashPay json_decode($session->get($transactionId.'[bono][detail_cash]'));
  675.                 }
  676.             } else {
  677.                 $cashPay $cashPaymentController->cashAction($logSave$array);
  678.                 $session->set($transactionId.'[bono][detail_cash]'json_encode($cashPay));
  679.             }
  680.             if ('ok' == $cashPay->status) {
  681.                 $cashPay->bookingID $bookingId;
  682.                 $session->set($transactionId.'[bono][cash_result]'json_encode($cashPay));
  683.             } else {
  684.                 $emissionData['x_first_name'] = $array['x_first_name'];
  685.                 $emissionData['x_last_name'] = $array['x_last_name'];
  686.                 $emissionData['x_doc_num'] = $array['x_doc_num'];
  687.                 $emissionData['x_reference'] = $array['x_reference'];
  688.                 $emissionData['x_description'] = $array['x_description'];
  689.                 $emissionData['x_total_amount'] = $array['x_total_amount'];
  690.                 $emissionData['x_email'] = $array['x_email'];
  691.                 $emissionData['x_address'] = $array['x_address'];
  692.                 $emissionData['x_phone'] = $array['x_phone'];
  693.                 $emissionData['x_type_description'] = $array['x_type_description'];
  694.                 $emissionData['x_error'] = $cashPay->status;
  695.                 $mailInfo print_r($emissionDatatrue).'<br>'.print_r($cashPaytrue);
  696.                 $toEmails = ['soportepagoelectronico@aviatur.com.co''soptepagelectronic@aviatur.com''errores.prod.web@aviatur.com'];
  697.                 $emailNotification $parameterBag->get('email_notification');
  698.                 $message = (new \Swift_Message())
  699.                     ->setContentType('text/html')
  700.                     ->setFrom($session->get('emailNoReply'))
  701.                     ->setTo($toEmails)
  702.                     ->setBcc($emailNotification)
  703.                     ->setSubject('Error Creación Transacción Efectivo'.$emissionData['x_reference'])
  704.                     ->setBody($mailInfo);
  705.                 $mailer->send($message);
  706.                 $orderProduct->setEmissiondata('error');
  707.                 $orderProduct->setUpdatingdate(new \DateTime());
  708.                 $em->persist($orderProduct);
  709.                 $em->flush();
  710.                 $urlRetry $this->generateUrl('aviatur_gift_voucher_retry_secure', ["transactionRetryId" => $transactionId]);
  711.                 return $this->redirect($aviaturErrorHandler->errorRedirect($urlRetry'Error al procesar el pago''Ocurrió un problema al intentar crear su transacción.'));
  712.             }
  713.             $urlPayment 'aviatur_gift_voucher_payment_cash_return_url_secure';
  714.             return $this->redirect($this->generateUrl($urlPayment));
  715.         } else {
  716.             $urlRetry $this->generateUrl('aviatur_gift_voucher_retry_secure', ["transactionRetryId" => $transactionId]);
  717.             return $this->redirect($aviaturErrorHandler->errorRedirect($urlRetry'''El tipo de pago es inválido.'));
  718.         }
  719.     }
  720.     // Creación XML updatePaymentData y Control de estados de pago para P2P
  721.     public function p2pCallbackAction(ManagerRegistry $registryCustomerMethodPaymentService $customerMethodPaymentServiceOrderController $orderControllerTokenStorageInterface $tokenStorageAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionParameterBagInterface $parameterBagEmissionWebservice $emmisionWebServiceValidateSanctionsRenewal $validateSanctions)
  722.     {
  723.         $em $registry->getManager();
  724.         // Obtener el transactionId
  725.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  726.         $transactionId $session->get($transactionIdSessionName);
  727.         // IdOrder y IdOrderProduct
  728.         if (true !== $session->has($transactionId.'[bono][order]')) {
  729.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_home'), '''No se encontró orden asociada a este pago.'));
  730.         }
  731.         $orderInfo json_decode($session->get($transactionId '[bono][order]'));
  732.         $productId str_replace('PN'''$orderInfo->products);
  733.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  734.         // Obtener información de los formularios del checkOut
  735.         $detailInfo json_decode($session->get($transactionId '[bono][detailDataBono]'));
  736.         // Obtener la información de la tarjeta regalo desde la sesión
  737.         $bonoInfo json_decode(base64_decode($session->get($transactionId "[bono][bonoInfo]")), true);
  738.         // Traer información de pago
  739.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  740.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  741.         if (null != $decodedResponse) {
  742.             // Actualizar pago
  743.             $orderController->updatePaymentAction($orderProduct);
  744.             // Generar bookingId
  745.             $bookingId $this->generateRamdonCode();
  746.             $twig '';
  747.             // Datos para bono y email
  748.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  749.             $agencyFolder $agency->getAssetsFolder();
  750.             $voucherData = [
  751.                 'empresaId' => $agencyFolder == "octopus" '54' '10',
  752.                 'productId' => $productId,
  753.                 'bonoId' => $bookingId,
  754.                 'ammount' => $decodedRequest->x_amount,
  755.                 'currency' => $bonoInfo["currency"],
  756.                 'documentNumber' => $orderProduct->getOrder()->getCustomer()->getDocumentnumber(),
  757.                 'status' => 'EMT',
  758.                 'documentType' => $orderProduct->getOrder()->getCustomer()->getDocumentType()->getExternalcode(),
  759.                 'name' => $orderProduct->getOrder()->getCustomer()->getFirstname().' '.$orderProduct->getOrder()->getCustomer()->getLastname(),
  760.                 'email' => $orderProduct->getOrder()->getCustomer()->getEmail(),
  761.                 'phone' => $orderProduct->getOrder()->getCustomer()->getPhone(),
  762.                 'recipient_name' => $detailInfo->PI->first_name_1_1.' '.$detailInfo->PI->last_name_1_1,
  763.                 'recipient_mail' => $detailInfo->PI->email_1_1,
  764.                 'recipient_phone' => $detailInfo->CD->phone,
  765.                 'recipient_document' => $detailInfo->PI->doc_num_1_1,
  766.             ];
  767.             // Twigs y status de acuerdo al estado de pago
  768.             $bonoResult "";
  769.             switch ($decodedResponse->x_response_code) {
  770.                 case isset($decodedResponse->x_response_code_cyber) && (== $decodedResponse->x_response_code_cyber):
  771.                     //rechazado cybersource
  772.                     $parameters $em->getRepository(\Aviatur\GeneralBundle\Entity\Parameter::class)->findOneByName('aviatur_switch_rechazada_cyber');
  773.                     if ($parameters && == $parameters->getValue() && == $decodedResponse->x_response_code) {
  774.                         if (isset($detailInfo->PD->cusPOptSelected) && isset($detailInfo->PD->cusPOptSelectedStatus) && 'NOTVERIFIED' == $detailInfo->PD->cusPOptSelectedStatus) {
  775.                             $detailInfo->PD->cusPOptSelectedStatus 'ACTIVE';
  776.                             $customerLogin $tokenStorage->getToken()->getUser();
  777.                             $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($detailInfo), true));
  778.                         }
  779.                         if (isset($detailInfo->PD->savePaymProc)) {
  780.                             $customerLogin $tokenStorage->getToken()->getUser();
  781.                             $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($detailInfo), true));
  782.                         }
  783.                     }
  784.                     $twig 'aviatur_gift_voucher_payment_rejected_secure';
  785.                     $bookingId 'PN' $orderProduct->getId();
  786.                     break;
  787.                 case 3:// pendiente p2p
  788.                     $twig '' != $twig $twig 'aviatur_gift_voucher_payment_pending_secure';
  789.                     $bonoResult '{booking_id2}';
  790.                     $orderProduct->setEmissiondata($bookingId);
  791.                     $orderProduct->setEmail(json_encode($voucherData));
  792.                     $orderProduct->setUpdatingdate(new \DateTime());
  793.                     break;
  794.                     // no break
  795.                 case 2:// rechazada p2p
  796.                     $twig '' != $twig $twig 'aviatur_gift_voucher_payment_rejected_secure';
  797.                     $bookingId 'PN' $orderProduct->getId();
  798.                     break;
  799.                 case 1:// aprobado p2p
  800.                     if (isset($detailInfo->PD->cusPOptSelected) && isset($detailInfo->PD->cusPOptSelectedStatus) && 'NOTVERIFIED' == $detailInfo->PD->cusPOptSelectedStatus) {
  801.                         $detailInfo->PD->cusPOptSelectedStatus 'ACTIVE';
  802.                         $customerLogin $tokenStorage->getToken()->getUser();
  803.                         $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($detailInfo), true));
  804.                     }
  805.                     if (isset($detailInfo->PD->savePaymProc)) {
  806.                         $customerLogin $tokenStorage->getToken()->getUser();
  807.                         $customerMethodPaymentService->setMethodsByCustomer($customerLoginjson_decode(json_encode($detailInfo), true));
  808.                     }
  809.                     $emitirBono $this->emitirBono($emmisionWebService$session$orderProduct$voucherData$productId$transactionId$bookingId);
  810.                     $orderProduct $emitirBono["orderProduct"];
  811.                     $bonoResult $emitirBono["bonoResult"];
  812.                     $twig 'aviatur_gift_voucher_payment_success_secure';
  813.                     break;
  814.                 default: //error p2p - case 0, 4, others
  815.                     $twig 'aviatur_gift_voucher_payment_error_secure';
  816.                     $bookingId '';
  817.             }
  818.             // Update Payment
  819.             $orderUpdatePayment str_replace(
  820.                 ['{product_id}''{booking_id}''{booking_id2}'],
  821.                 [$orderProduct->getId(), $bookingId$bonoResult],
  822.                 $orderProduct->getUpdatePaymentData()
  823.             );
  824.             $orderProduct->setUpdatePaymentData($orderUpdatePayment);
  825.             // Update AddProductData
  826.             $orderAddProduct str_replace(
  827.                 ['{booking_id}''{booking_id2}''{reference_number}'],
  828.                 [$bookingId$bonoResult$bookingId],
  829.                 $orderProduct->getAddProductData()
  830.             );
  831.             $orderProduct->setAddProductData($orderAddProduct);
  832.             // Ejecución
  833.             $orderProduct->setBooking($bookingId);
  834.             $em->persist($orderProduct);
  835.             $em->flush($orderProduct);
  836.             /* Pero solo si hay condicionados (no bloqueados) y que paguen con Tarjeta */
  837.             if ($session->has('Marked_users')) {
  838.                 $validateSanctions->sendMarkedEmail($orderInfo$session$agency$orderProduct$transactionId'bono');
  839.             }
  840.             return $this->redirect($this->generateUrl($twig));
  841.         } else {
  842.             // No hay respuesta por parte del servicio de pago, estado pendiente
  843.             $orderProduct->setStatus('pending');
  844.             $em->persist($orderProduct);
  845.             $em->flush();
  846.             $urlRetry $this->generateUrl('aviatur_gift_voucher_retry_secure', ["transactionRetryId" => $transactionId]);
  847.             return $this->redirect($aviaturErrorHandler->errorRedirect($urlRetry'''No hay respuesta por parte del servicio de pago.'));
  848.         }
  849.     }
  850.     // Creación XML updatePaymentData y Control de estados de pago para PSE
  851.     public function pseCallbackAction(ManagerRegistry $registryPSEController $psePaymentControllerPSERestController $PSERestControllerOrderController $orderControllerAviaturEncoder $aviaturEncoderAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionParameterBagInterface $parameterBagEmissionWebservice $emmisionWebServiceAviaturLogSave $logSave)
  852.     {
  853.         $em $registry->getManager();
  854.         // Obtener el transactionId
  855.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  856.         $transactionId $session->get($transactionIdSessionName);
  857.         // IdOrder y IdOrderProduct
  858.         if (true !== $session->has($transactionId.'[bono][order]')) {
  859.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_home'), '''No se encontró orden asociada a este pago.'));
  860.         }
  861.         $orderInfo json_decode($session->get($transactionId '[bono][order]'));
  862.         $productId str_replace('PN'''$orderInfo->products);
  863.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  864.         // Obtener información de los formularios del checkOut
  865.         $detailInfo json_decode($session->get($transactionId '[bono][detailDataBono]'));
  866.         // Traer información de pago
  867.         $decodedRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  868.         $decodedResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayresponse(), $orderProduct->getPublicKey()));
  869.         if (!isset($decodedResponse) && !isset($decodedResponse->createTransactionResult) && !isset($decodedResponse->createTransactionPaymentResponseInformation)) {
  870.             $urlRetry $this->generateUrl('aviatur_gift_voucher_retry_secure', ["transactionRetryId" => $transactionId]);
  871.             return $this->redirect($aviaturErrorHandler->errorRedirect($urlRetry'''No se encontró información de la transacción.'));
  872.         }
  873.         // Consultar respuesta de pago de acuerdo a la opcion definida en payment_method
  874.         $paymentCode $this->paymentMethod->getCode() === 'pse' 'pse' 'pseRest';
  875.         $pseTransactionId '';
  876.         if ($paymentCode === 'pse') {
  877.             if (isset($decodedResponse->createTransactionResult)) {
  878.                 $pseTransactionId $decodedResponse->createTransactionResult->transactionID ?? $decodedResponse->createTransactionResult->trazabilityCode;
  879.             } elseif (isset($decodedResponse->createTransactionPaymentResponseInformation)) {
  880.                 $pseTransactionId $decodedResponse->createTransactionPaymentResponseInformation->transactionID ?? $decodedResponse->createTransactionPaymentResponseInformation->trazabilityCode;
  881.             }
  882.             $paymentResponse json_decode($psePaymentController->pseCallbackAction($orderController$pseTransactionId$decodedResponse));
  883.             $orderController->updatePaymentAction($orderProduct);
  884.         } else {
  885.             $pseTransactionId $decodedResponse->internalReference;
  886.             $paymentResponse $PSERestController->getTransactionInfo($pseTransactionId);
  887.             $logSave->logSave(json_encode($paymentResponse), '_pseRest'$decodedRequest->payment->reference .'_RS'$pseTransactionId);
  888.             $orderController->updateRestPaymentAction($orderProduct);
  889.         }
  890.         // Generar bookingId
  891.         $bookingId $this->generateRamdonCode();
  892.         // Valor total
  893.         $totalAmount $decodedRequest->payment->amount->total ?? $decodedRequest->x_total_amount;
  894.         $currency $decodedRequest->payment->amount->currency ?? $decodedRequest->x_currency;
  895.         // Datos para bono y email
  896.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  897.         $agencyFolder $agency->getAssetsFolder();
  898.         $voucherData = [
  899.             'empresaId' => $agencyFolder == "octopus" '54' '10',
  900.             'productId' => $productId,
  901.             'bonoId' => $bookingId,
  902.             'ammount' => $totalAmount,
  903.             'currency' => $currency,
  904.             'documentNumber' => $orderProduct->getOrder()->getCustomer()->getDocumentnumber(),
  905.             'status' => 'EMT',
  906.             'documentType' => $orderProduct->getOrder()->getCustomer()->getDocumentType()->getExternalcode(),
  907.             'name' => $orderProduct->getOrder()->getCustomer()->getFirstname().' '.$orderProduct->getOrder()->getCustomer()->getLastname(),
  908.             'email' => $orderProduct->getOrder()->getCustomer()->getEmail(),
  909.             'phone' => $orderProduct->getOrder()->getCustomer()->getPhone(),
  910.             'recipient_name' => $detailInfo->PI->first_name_1_1.' '.$detailInfo->PI->last_name_1_1,
  911.             'recipient_mail' => $detailInfo->PI->email_1_1,
  912.             'recipient_phone' => $detailInfo->CD->phone,
  913.             'recipient_document' => $detailInfo->PI->doc_num_1_1,
  914.         ];
  915.         if (!isset($paymentResponse->error)) {
  916.             if ($paymentCode === 'pse') {
  917.                 if (isset($paymentResponse->getTransactionInformationResponseBody)) {
  918.                     $decodedResponse->getTransactionInformationResult $paymentResponse->getTransactionInformationResponseBody;
  919.                     $paymentResponse->getTransactionInformationResult $paymentResponse->getTransactionInformationResponseBody;
  920.                 } else {
  921.                     $decodedResponse->getTransactionInformationResult $paymentResponse->getTransactionInformationResult;
  922.                 }
  923.             } else {
  924.                 $decodedResponse->getTransactionInformationResult $paymentResponse;
  925.                 // Aplica directamente en pserest, para actualizar la información del update_payment_data
  926.                 $currentUpdatePaymentData $orderProduct->getUpdatepaymentdata();
  927.                 $xmlParcial substr($currentUpdatePaymentDatastrpos($currentUpdatePaymentData'<FILTRO>') + 8strpos($currentUpdatePaymentData'</FILTRO>') - strpos($currentUpdatePaymentData'<FILTRO>') - 8);
  928.                 $xmlConvertido = \simplexml_load_string($xmlParcial);
  929.                 // Asignación de valores para update_payment_data (afectando name y reason_code, no se toca el ID)
  930.                 $xmlConvertido->products->product->payment_data->state->reason_code $decodedResponse->getTransactionInformationResult->status->reason;
  931.                 $decodeMessage $this->changeAcutes($decodedResponse->getTransactionInformationResult->status->message);
  932.                 $xmlConvertido->products->product->payment_data->state->name $decodeMessage;
  933.                 $xmlDefinitivo $xmlConvertido->asXML();
  934.                 $xmlDefinitivo str_replace('<?xml version="1.0"?>'''$xmlDefinitivo);
  935.                 $newUpdatePaymentData str_replace('<FILTRO>'.$xmlParcial.'</FILTRO>''<FILTRO>'.$xmlDefinitivo.'</FILTRO>'$currentUpdatePaymentData);
  936.                 $orderProduct->setUpdatepaymentdata($newUpdatePaymentData);
  937.             }
  938.             // Actualizar payResponse con el estado de pago
  939.             $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  940.             $orderProduct->setUpdatingdate(new \DateTime());
  941.             $em->persist($orderProduct);
  942.             $em->flush();
  943.             // Obtener el valor de returCode para continuar con logica existente
  944.             $returnCodeStatus 'SUCCESS';
  945.             if ((!isset($paymentResponse->getTransactionInformationResult->returnCode) || 'SUCCESS' != (string) $paymentResponse->getTransactionInformationResult->returnCode) && !isset($paymentResponse->status->status))
  946.             {
  947.                 $returnCodeStatus = (string) $paymentResponse->getTransactionInformationResult->returnCode;
  948.             }
  949.             // Twigs y status de acuerdo al estado de pago
  950.             $twig '';
  951.             $bonoResult "";
  952.             if ('SUCCESS' == (string) $returnCodeStatus) {
  953.                 $statusResponse $paymentResponse->getTransactionInformationResult->transactionState ?? $paymentResponse->status->status;
  954.                 switch ((string) $statusResponse) {
  955.                     case 'OK':
  956.                     case 'APPROVED':
  957.                         $twig 'aviatur_gift_voucher_payment_success_secure';
  958.                         $status 'approved';
  959.                         $emitirBono $this->emitirBono($emmisionWebService$session$orderProduct$voucherData$productId$transactionId$bookingId);
  960.                         $orderProduct $emitirBono["orderProduct"];
  961.                         $bonoResult $emitirBono["bonoResult"];
  962.                         break;
  963.                     case 'PENDING':
  964.                         $twig 'aviatur_gift_voucher_payment_pending_secure';
  965.                         $status 'pending';
  966.                         $orderProduct->setEmissiondata($bookingId);
  967.                         $orderProduct->setEmail(json_encode($voucherData));
  968.                         $orderProduct->setUpdatingdate(new \DateTime());
  969.                         $bonoResult '{booking_id2}';
  970.                         break;
  971.                     case 'NOT_AUTHORIZED':
  972.                     case 'REJECTED':
  973.                         $bookingId 'PN' $orderProduct->getId();
  974.                         $twig 'aviatur_gift_voucher_payment_rejected_secure';
  975.                         $status 'rejected';
  976.                         break;
  977.                     case 'FAILED':
  978.                         $bookingId '';
  979.                         $twig 'aviatur_gift_voucher_payment_error_secure';
  980.                         $status 'failed';
  981.                         break;
  982.                 }
  983.                 // Update Payment
  984.                 $orderUpdatePayment str_replace(
  985.                     ['{product_id}''{booking_id}''{booking_id2}'],
  986.                     [$orderProduct->getId(), $bookingId$bonoResult],
  987.                     $orderProduct->getUpdatePaymentData()
  988.                 );
  989.                 $orderProduct->setUpdatePaymentData($orderUpdatePayment);
  990.                 // Update AddProductData
  991.                 $orderAddProduct str_replace(
  992.                     ['{booking_id}''{booking_id2}''{reference_number}'],
  993.                     [$bookingId$bonoResult$bookingId],
  994.                     $orderProduct->getAddProductData()
  995.                 );
  996.                 $orderProduct->setAddProductData($orderAddProduct);
  997.                 $orderProduct->setUpdatePaymentData($orderUpdatePayment);// Update Payment
  998.                 $orderProduct->setStatus($status);
  999.                 $orderProduct->getOrder()->setStatus($status);
  1000.                 $orderProduct->setUpdatingdate(new \DateTime());
  1001.                 $orderProduct->getOrder()->setUpdatingdate(new \DateTime());
  1002.                 $orderProduct->setBooking($bookingId);
  1003.                 $em->persist($orderProduct);
  1004.                 $em->flush();
  1005.             } elseif ('FAIL_INVALIDTRAZABILITYCODE' == $returnCodeStatus || 'FAIL_ACCESSDENIED' == $returnCodeStatus || 'FAIL_TIMEOUT' == $returnCodeStatus) {
  1006.                 echo 'En este momento su #<referencia de factura> presenta un proceso de pago cuya transacción se encuentra
  1007.                 PENDIENTE de recibir información por parte de su entidad financiera, por favor espere
  1008.                 unos minutos y vuelva a consultar mas tarde para verificar sí su pago fue confirmado de
  1009.                 forma exitosa. Si desea mayor información sobre el estado actual de su operación puede
  1010.                 comunicarse a nuestras líneas de atención al cliente al teléfono XXXXXX o enviar
  1011.                 inquietudes al email mispagos@micomercio.com y pregunte por el estado de la
  1012.                 transacción <#CUS> .';
  1013.                 $orderProduct->setEmissiondata('error');
  1014.                 $orderProduct->setUpdatingdate(new \DateTime());
  1015.                 $em->persist($orderProduct);
  1016.                 $em->flush();
  1017.                 $twig 'aviatur_gift_voucher_payment_error_secure';
  1018.             }
  1019.             return $this->redirect($this->generateUrl($twig));
  1020.         } else {
  1021.             $decodedResponse->getTransactionInformationResult $paymentResponse;
  1022.             $orderProduct->setPayresponse($aviaturEncoder->AviaturEncode(json_encode($decodedResponse), $orderProduct->getPublicKey()));
  1023.             $orderProduct->setUpdatingdate(new \DateTime());
  1024.             $em->persist($orderProduct);
  1025.             $em->flush();
  1026.             $urlRetry $this->generateUrl('aviatur_gift_voucher_retry_secure', ["transactionRetryId" => $transactionId]);
  1027.             return $this->redirect($aviaturErrorHandler->errorRedirect($urlRetry'''Ocurrió un error al consultar el estado de la transacción.'));
  1028.         }
  1029.     }
  1030.     // Creación  para CASH
  1031.     public function cashCallbackAction(ManagerRegistry $registryOrderController $orderControllerAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionParameterBagInterface $parameterBag)
  1032.     {
  1033.         $em $registry->getManager();
  1034.         // Obtener el transactionId
  1035.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1036.         $transactionId $session->get($transactionIdSessionName);
  1037.         // IdOrder y IdOrderProduct
  1038.         if (true !== $session->has($transactionId.'[bono][order]')) {
  1039.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_home'), '''No se encontró orden asociada a este pago.'));
  1040.         }
  1041.         $orderInfo json_decode($session->get($transactionId '[bono][order]'));
  1042.         $productId str_replace('PN'''$orderInfo->products);
  1043.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1044.         // Obtener información de los formularios del checkOut
  1045.         $detailInfo json_decode($session->get($transactionId '[bono][detailDataBono]'));
  1046.         // Obtener la información de la tarjeta regalo desde la sesión
  1047.         $bonoInfo json_decode(base64_decode($session->get($transactionId "[bono][bonoInfo]")), true);
  1048.         $totalAmountCOP $bonoInfo["giftFarePrice"];
  1049.         $currencyBono $bonoInfo["currency"];
  1050.         if ($session->has($transactionId '[bono][cash_result]')) {
  1051.             // Obtener BookingId
  1052.             $cashPay json_decode($session->get($transactionId.'[bono][cash_result]'), true);
  1053.             $bookingId $cashPay["bookingID"];
  1054.             unset($cashPay["bookingID"]);
  1055.             $session->set($transactionId.'[bono][cash_result]'json_encode($cashPay));
  1056.             // Datos para bono y email
  1057.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  1058.             $agencyFolder $agency->getAssetsFolder();
  1059.             $voucherData = [
  1060.                 'empresaId' => $agencyFolder == "octopus" '54' '10',
  1061.                 'productId' => $productId,
  1062.                 'bonoId' => $bookingId,
  1063.                 'ammount' => $totalAmountCOP,
  1064.                 'currency' => $currencyBono,
  1065.                 'documentNumber' => $orderProduct->getOrder()->getCustomer()->getDocumentnumber(),
  1066.                 'status' => 'EMT',
  1067.                 'documentType' => $orderProduct->getOrder()->getCustomer()->getDocumentType()->getExternalcode(),
  1068.                 'name' => $orderProduct->getOrder()->getCustomer()->getFirstname().' '.$orderProduct->getOrder()->getCustomer()->getLastname(),
  1069.                 'email' => $orderProduct->getOrder()->getCustomer()->getEmail(),
  1070.                 'phone' => $orderProduct->getOrder()->getCustomer()->getPhone(),
  1071.                 'recipient_name' => $detailInfo->PI->first_name_1_1.' '.$detailInfo->PI->last_name_1_1,
  1072.                 'recipient_mail' => $detailInfo->PI->email_1_1,
  1073.                 'recipient_phone' => $detailInfo->CD->phone,
  1074.                 'recipient_document' => $detailInfo->PI->doc_num_1_1,
  1075.             ];
  1076.             // Actualizar pago en cash
  1077.             $orderController->updatePaymentAction($orderProduct);
  1078.             // Update Payment
  1079.             $orderUpdatePayment str_replace(
  1080.                 ['{product_id}''{booking_id}'],
  1081.                 [$orderProduct->getId(), $bookingId],
  1082.                 $orderProduct->getUpdatePaymentData()
  1083.             );
  1084.             $orderProduct->setUpdatePaymentData($orderUpdatePayment);
  1085.             // Update AddProductData
  1086.             $orderAddProduct str_replace(
  1087.                 ['{product_id}''{booking_id}'],
  1088.                 [$orderProduct->getId(), $bookingId],
  1089.                 $orderProduct->getAddProductData()
  1090.             );
  1091.             $orderProduct->setAddProductData($orderAddProduct);
  1092.             // Ejecución
  1093.             $orderProduct->setBooking($bookingId);
  1094.             $orderProduct->setEmissiondata($bookingId);
  1095.             $orderProduct->setEmail(json_encode($voucherData));
  1096.             $em->persist($orderProduct);
  1097.             $em->flush($orderProduct);
  1098.             return $this->redirect($this->generateUrl('aviatur_gift_voucher_confirmation_success_secure'));
  1099.         } else {
  1100.             // No hay respuesta por parte del servicio de pago, estado pendiente
  1101.             $orderProduct->setStatus('pending');
  1102.             $em->persist($orderProduct);
  1103.             $em->flush();
  1104.             $urlRetry $this->generateUrl('aviatur_gift_voucher_retry_secure', ["transactionRetryId" => $transactionId]);
  1105.             return $this->redirect($aviaturErrorHandler->errorRedirect($urlRetry'''No hay respuesta por parte del servicio de pago.'));
  1106.         }
  1107.     }
  1108.     // Generar bono en Front
  1109.     public function generarBonofrontAction(Request $requestManagerRegistry $registryAviaturErrorHandler $aviaturErrorHandlerSessionInterface $sessionParameterBagInterface $parameterBagEmissionWebservice $emmisionWebService)
  1110.     {
  1111.         $em $registry->getManager();
  1112.         // Valida la existencia y configuración de tarjeta regalo en la agencia
  1113.         $validateAgencyRequest $this->validateAgencyRequest($session->get('agencyId'), $request$em$aviaturErrorHandlerfalse);
  1114.         if(!isset($validateAgencyRequest["agency"])){
  1115.             return $this->json(['error' => true'message' => $validateAgencyRequest]);
  1116.         }
  1117.         // Obtener el transactionId
  1118.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1119.         $transactionId $session->get($transactionIdSessionName);
  1120.         // IdOrder y IdOrderProduct
  1121.         if (true !== $session->has($transactionId.'[bono][order]')) {
  1122.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_home'), '''No se encontró orden asociada a este pago.'));
  1123.         }
  1124.         $orderInfo json_decode($session->get($transactionId '[bono][order]'));
  1125.         $productId str_replace('PN'''$orderInfo->products);
  1126.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1127.         // Obtener la información de la tarjeta regalo desde la sesión
  1128.         $bonoInfo json_decode(base64_decode($session->get($transactionId "[bono][bonoInfo]")), true);
  1129.         $totalAmountCOP $bonoInfo["giftFarePrice"];
  1130.         // Obtener información de los formularios del checkOut
  1131.         $detailInfo json_decode($session->get($transactionId '[bono][detailDataBono]'));
  1132.         // Generar bookingId
  1133.         $bookingId $this->generateRamdonCode();
  1134.         // Información de usuario
  1135.         $datosAgente simplexml_load_string($session->get('front_user'));
  1136.         // Emitir bono
  1137.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  1138.         $agencyFolder $agency->getAssetsFolder();
  1139.         $voucherData = [
  1140.             'empresaId' => $agencyFolder == "octopus" '54' '10',
  1141.             'productId' => $productId,
  1142.             'bonoId' => $bookingId,
  1143.             'ammount' => $totalAmountCOP,
  1144.             'currency' => $bonoInfo["currency"],
  1145.             'documentNumber' => $detailInfo->BD->doc_num,
  1146.             'status' => 'EMT',
  1147.             'documentType' => $detailInfo->BD->doc_type,
  1148.             'name' => $detailInfo->BD->first_name.' '.$detailInfo->BD->last_name,
  1149.             'email' => $datosAgente->CORREO_ELECTRONICO,
  1150.             'phone' => $detailInfo->BD->phone,
  1151.             'recipient_name' => $detailInfo->PI->first_name_1_1.' '.$detailInfo->PI->last_name_1_1,
  1152.             'recipient_mail' => $detailInfo->PI->email_1_1,
  1153.             'recipient_phone' => $detailInfo->CD->phone,
  1154.             'recipient_document' => $detailInfo->PI->doc_num_1_1,
  1155.         ];
  1156.         $twig 'aviatur_gift_voucher_payment_success_secure';
  1157.         $emitirBono $this->emitirBono($emmisionWebService$session$orderProduct$voucherData$productId$transactionId$bookingId);
  1158.         $orderProduct $emitirBono["orderProduct"];
  1159.         $bonoResult $emitirBono["bonoResult"];
  1160.         // Update AddProductData
  1161.         $orderAddProduct str_replace(
  1162.             ['{booking_id}''{booking_id2}''{reference_number}'],
  1163.             [$bookingId$bonoResult$bookingId],
  1164.             $orderProduct->getAddProductData()
  1165.         );
  1166.         $orderProduct->setAddProductData($orderAddProduct);
  1167.         // Actualizar bookingId
  1168.         $orderProduct->setBooking($bookingId);
  1169.         $orderProduct->setEmail(json_encode($voucherData));
  1170.         $orderProduct->setUpdatingdate(new \DateTime());
  1171.         $em->persist($orderProduct);
  1172.         $em->flush();
  1173.         return $this->redirect($this->generateUrl($twig));
  1174.     }
  1175.     // Modificación en datos resume en BD y envío de correo
  1176.     public function paymentOutputAction(ManagerRegistry $registry, \Swift_Mailer $mailerTwigFolder $twigFolderSessionInterface $sessionParameterBagInterface $parameterBagAviaturEncoder $aviaturEncoderPdf $pdfExceptionLog $exceptionLog)
  1177.     {
  1178.         $em $registry->getManager();
  1179.         // Datos guardados en el resumen
  1180.         $this->prepareInfoResume($session$registry$parameterBag$aviaturEncoder);
  1181.         // Obtener el transactionId
  1182.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1183.         $transactionId $session->get($transactionIdSessionName);
  1184.         // IdOrder y IdOrderProduct
  1185.         $orderInfo json_decode($session->get($transactionId '[bono][order]'));
  1186.         $productId str_replace('PN'''$orderInfo->products);
  1187.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1188.         // Datos de resumen
  1189.         $resumeData json_decode($orderProduct->getResume(), true);
  1190.         $resumeData['agencyData']['agency_phones'] = $session->get('agencyDataInfo')['agency_phones'];
  1191.         $paymentResume $resumeData['paymentResume'];
  1192.         $facturationResume $resumeData['facturationResume'];
  1193.         $travelers $resumeData['travelers'];
  1194.         // Agencia
  1195.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get('agencyId'));
  1196.         // Correos destinatarios
  1197.         $giftVoucherConfigObject $em->getRepository(\Aviatur\GiftVoucherBundle\Entity\ConfigGiftVoucherAgency::class)->findBy(['agency' => $orderProduct->getOrder()->getAgency()]);
  1198.         $toAdminMails explode(';'$giftVoucherConfigObject[0]->getMails());
  1199.         $sendVoucherBcc $toAdminMails;
  1200.         $sendVoucherBcc[] = 'notificacionessitioweb@aviatur.com';
  1201.         // Alertas y correos, segun status de cyber
  1202.         $paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
  1203.         if (== $paymentResume['transaction_state_cyber']) {
  1204.             //In case Rejected Cybersource send mail to administratos Aviatur
  1205.             $sendTo $toAdminMails;
  1206.             $sendVoucherBcc = ['notificacionessitioweb@aviatur.com''soptepagelectronic@aviatur.com''soportepagoelectronico@aviatur.com.co']; // verificar correos....???
  1207.         }
  1208.         // Enviar correo usuario en caso de pago exitoso
  1209.         if (== $paymentResume['transaction_state']) {
  1210.             // TODOSG validar las rutas quemadas
  1211.             $emailCustomMessage $this->renderView($twigFolder->twigExists('@AviaturTwig/default/Flux/GiftVoucher/Default/emailUserGiftCard.html.twig'), ["resumeData" => $resumeData'agencyName' => $session->get('agencyShortName')]);
  1212.             $sendVoucherTo $sendTo ?? mb_strtolower($travelers[0]['Email']);
  1213.             $message = (new \Swift_Message())
  1214.                     ->setContentType('text/html')
  1215.                     ->setFrom($session->get('emailNoReply'))
  1216.                     ->setTo($sendVoucherTo)
  1217.                     ->setBCC('notificacionessitioweb@aviatur.com')
  1218.                     ->setSubject($session->get('agencyShortName').' - Gracias por su compra - Bono de Regalo')
  1219.                     ->setBody($emailCustomMessage);
  1220.             $mailer->send($message);
  1221.             // Actualizar tabla order-product en campo email
  1222.             $orderProduct->setEmail($emailCustomMessage);
  1223.             $em->persist($orderProduct);
  1224.             $em->flush();
  1225.             // Eliminar lo de session
  1226.             $session->remove($transactionId.'[bono][emission][error]');
  1227.             $session->remove($transactionId '[bono][retry]');
  1228.             $session->remove($transactionId "[bono][bonoInfo]");
  1229.             $session->remove($transactionId '[bono][userInfo]');
  1230.             $session->remove($transactionId.'[bono][provider]');
  1231.             $session->remove($transactionId '[bono][detailDataBono]');
  1232.         } else if (== $paymentResume['transaction_state']){
  1233.             // Datos de la agencia
  1234.             $agencyData = [
  1235.                 'agency_name' => $agency->getName(),
  1236.                 'agency_nit' => $agency->getNit(),
  1237.                 'agency_phone' => $agency->getPhone(),
  1238.                 'agency_email' => $agency->getMailContact(),
  1239.                 'agency_phones' =>  $agency->getPhonescontact()
  1240.             ];
  1241.             // Creación del pdf cuando es CASH
  1242.             if ($resumeData["paymentResume"]["paymentData_type"] == "cash" && !$session->has($transactionId '[emission_baloto_email]')) {
  1243.                 $agencyFolder $twigFolder->twigFlux();
  1244.                 $projectDir $parameterBag->get('kernel.project_dir');
  1245.                 $emailNotification $parameterBag->get('email_notification');
  1246.                 $voucherFile $projectDir '/app/serviceLogs/CashTransaction/' $paymentResume['id_context'] . '_' $transactionId '.pdf';
  1247.                 $paymentResume['exportPDF'] = true;
  1248.                 $paymentResume['infos'][0]['agencyData'] = $agencyData;
  1249.                 $paymentResume['infos'][0]['paymentResume']['id'] = $paymentResume['id_context'];
  1250.                 $paymentResume['infos'][0]['paymentResume']['total_amount'] = $paymentResume['total_amount'];
  1251.                 $paymentResume['infos'][0]['paymentResume']['fecha_vigencia'] = $paymentResume['fecha_vigencia'];
  1252.                 $paymentResume['infos'][0]['paymentResume']['description'] = $paymentResume['description'];
  1253.                 // $ruta = '@AviaturTwig/' . $agencyFolder . '/General/Templates/email_cash.html.twig';
  1254.                 $ruta '@AviaturTwig/default/Flux/GiftVoucher/Default/emailCashGiftCard.html.twig';
  1255.                 if (!file_exists($voucherFile)) {
  1256.                     $pdf->generateFromHtml($this->renderView($twigFolder->twigExists($ruta), $paymentResume), $voucherFile);
  1257.                 }
  1258.                 $clientEmail $paymentResume['client_email'];
  1259.                 $setTo = ['soportepagoelectronico@aviatur.com.co''soptepagelectronic@aviatur.com'$clientEmail];
  1260.                 $paymentResume['exportPDF'] = false;
  1261.                 $message = (new \Swift_Message())
  1262.                     ->setContentType('text/html')
  1263.                     ->setFrom($session->get('emailNoReply'))
  1264.                     ->setTo($setTo)
  1265.                     ->setBcc($emailNotification)
  1266.                     ->setSubject($session->get('agencyShortName').' - '.'Transacción Efectivo Creada '.$paymentResume['id_context'])
  1267.                     ->attach(\Swift_Attachment::fromPath($voucherFile))
  1268.                     ->setBody(
  1269.                         $this->renderView($twigFolder->twigExists($ruta), $paymentResume)
  1270.                 );
  1271.                 try {
  1272.                     $mailer->send($message);
  1273.                     $session->set($transactionId.'[emission_baloto_email]''emailed');
  1274.                 } catch (\Exception $ex) {
  1275.                     $exceptionLog->log(var_dump($message), $ex);
  1276.                 }
  1277.             }
  1278.         }
  1279.         // Correo de gracias por su compra
  1280.         if (!= $paymentResume['transaction_state_cyber'] && $resumeData["paymentResume"]["paymentData_type"] != "cash" ){
  1281.             $emailCustomerBody['admin'] = false;
  1282.             $emailCustomMessage $this->renderView($twigFolder->twigExists('@AviaturTwig/default/Flux/GiftVoucher/Default/emailThankYouPage.html.twig'), ['emailBodyContent' => $emailCustomerBody"resumeData" => $resumeData'agencyName'=> $session->get('agencyShortName')]);
  1283.             $emailFacturation $facturationResume["customer_email"];
  1284.             if (false !== strpos($emailFacturation'***')) {
  1285.                 $detailInfo json_decode($session->get($transactionId '[bono][detailDataBono]'));
  1286.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($detailInfo->BD->id);
  1287.                 $emailFacturation $customer->getEmail();
  1288.             }
  1289.             $sendThankYouPage $sendTo ?? $emailFacturation;
  1290.             $message = (new \Swift_Message())
  1291.                     ->setContentType('text/html')
  1292.                     ->setFrom($session->get('emailNoReply'))
  1293.                     ->setTo($sendThankYouPage)
  1294.                     ->setBCC($sendVoucherBcc)
  1295.                     ->setSubject($session->get('agencyShortName').' - Bono de Regalo')
  1296.                     ->setBody($emailCustomMessage);
  1297.             $mailer->send($message);
  1298.         }
  1299.         // Correo a administrador
  1300.         $emailAdminBody['admin'] = true;
  1301.         $emailAdminBody['messageText'] = 'Se ha realizado una compra de un bono de regalo virtual con los siguientes datos,<br> favor hacer las verificaciones correspondientes en sus respectivos departamentos.';
  1302.         if (== $paymentResume['transaction_state_cyber'] && == $paymentResume['transaction_state']) {
  1303.             $emailAdminBody['cyberReject'] = '<strong>ATENCIÓN!!!</strong> <br> <p>El Pago fué exitoso pero la transacción fué Rechazada por Cybersource. Por favor confirmar con el Departamento de Control Pago Electrónico la validez de la misma y en caso positivo realizar envío del Bono de Regalo al cliente.</p>';
  1304.             $rejectAlertText ' - **RECHAZO CYBERSOURCE**';
  1305.         }
  1306.         // TODOSG validar las rutas quemadas
  1307.         $emailAdminMessage $this->renderView($twigFolder->twigExists('@AviaturTwig/default/Flux/GiftVoucher/Default/emailThankYouPage.html.twig'), ['emailBodyContent' => $emailAdminBody"resumeData" => $resumeData]);
  1308.         $messageAdmin = (new \Swift_Message())
  1309.                 ->setContentType('text/html')
  1310.                 ->setFrom($session->get('emailNoReply'))
  1311.                 ->setTo($toAdminMails)
  1312.                 ->setBCC(['notificacionessitioweb@aviatur.com''soptepagelectronic@aviatur.com''soportepagoelectronico@aviatur.com.co'])
  1313.                 ->setSubject($session->get('agencyShortName').' - Se ha generado un Bono de Regalo con pago en estado ' $orderProduct->getStatus())
  1314.                 ->setBody($emailAdminMessage);
  1315.         $mailer->send($messageAdmin);
  1316.         $urlResume $this->generateUrl('aviatur_gift_voucher_thank_you_page_secure');
  1317.         return $this->redirect($urlResume);
  1318.     }
  1319.     // Vista de gracias por tu compra
  1320.     public function thankYouPageAction(SessionInterface $sessionManagerRegistry $registryTwigFolder $twigFolderParameterBagInterface $parameterBagAviaturErrorHandler $aviaturErrorHandler)
  1321.     {
  1322.         $em $registry->getManager();
  1323.         // Obtener el transactionId
  1324.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1325.         $transactionId $session->get($transactionIdSessionName);
  1326.         // Obtener order_product
  1327.         if (true !== $session->has($transactionId.'[bono][order]')) {
  1328.             return $this->redirect($aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_gift_voucher_home'), '''No se encontró orden asociada a este pago.'));
  1329.         }
  1330.         $orderProductCode $session->get($transactionId '[bono][order]');
  1331.         $productId str_replace('PN'''json_decode($orderProductCode)->products);
  1332.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1333.         // Datos de resumen
  1334.         $resumeData json_decode($orderProduct->getResume(), true);
  1335.         // Renderizar vista de thakyou page
  1336.         $agencyFolder $twigFolder->twigFlux();
  1337.         //$urlResume = $twigFolder->twigExists('@AviaturTwig/'.$agencyFolder.'/GiftVoucher/Default/resume.html.twig');
  1338.         // TODOSG validar las rutas quemadas
  1339.         $urlResume $twigFolder->twigExists('@AviaturTwig/default/Flux/GiftVoucher/Default/resume.html.twig', ['agencyName' => $session->get('agencyShortName')]);
  1340.         $resumeMessage $this->render(
  1341.             $urlResume,
  1342.             array_merge(
  1343.                 $resumeData,
  1344.                 ['agencyName' => $session->get('agencyShortName')]
  1345.             )
  1346.         );
  1347.         return $resumeMessage;
  1348.     }
  1349.     // Valida la existencia y configuración de tarjeta regalo en la agencia
  1350.     // Retorna una respuesta de error con redirección si la validación falla
  1351.     private function validateAgencyRequest($idAgency$request$em$aviaturErrorHandler$validateRQ)
  1352.     {
  1353.         // Si $request NO es null, validamos la petición
  1354.         if ($validateRQ && empty($request->query->all()) && empty($request->request->all())) {
  1355.             $titleError "Sección no disponible";
  1356.             $textError "Ha sido dirigido a la página de personalización para continuar explorando opciones sin inconvenientes.";
  1357.             return $aviaturErrorHandler->errorRedirect($this->generateUrl("aviatur_gift_voucher_personalize", []), $titleError$textError);
  1358.         }
  1359.         // Información de agencia
  1360.         $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($idAgency);
  1361.         if (!isset($agency)) {
  1362.             $host = ($request !== null) ? $request->getHost() : 'desconocido';
  1363.             $titleError "No se encontró la agencia con el dominio: " $host;
  1364.             $textError "Lo sentimos, ha sido redirigido al home para que pueda seguir explorando opciones.";
  1365.             return $aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), $titleError$textError);
  1366.         }
  1367.         // Configuración de precios y códigos de bono de regalo en BD
  1368.         $giftVoucherConfigObject $em->getRepository(\Aviatur\GiftVoucherBundle\Entity\ConfigGiftVoucherAgency::class)
  1369.             ->findParamsByAgency($agency);
  1370.             
  1371.         if (empty($giftVoucherConfigObject) || (is_countable($giftVoucherConfigObject) && count($giftVoucherConfigObject) == 0)) {
  1372.             return $aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), 'Acceso no autorizado''No se encontró configuración para esta Agencia.');
  1373.         }
  1374.         // Validar que se creo bien el objeto
  1375.         $giftVoucherConfigArray json_decode($giftVoucherConfigObject[0]['params'], true);
  1376.         if (empty($giftVoucherConfigArray)) {
  1377.             return $aviaturErrorHandler->errorRedirect($this->generateUrl('aviatur_general_homepage'), '''Lo sentimos, se ha redirigido a la página de inicio para continuar explorando opciones, debido a inconvenientes técnicos en la configuración.');
  1378.         }
  1379.         // Si todo está OK, no hay error
  1380.         return [
  1381.             "agency" => $agency,
  1382.             "giftVoucherConfigObject" => $giftVoucherConfigObject
  1383.         ];
  1384.     }
  1385.     // Validación del precio del bono
  1386.     // Retorna una respuesta de error con redirección si la validación falla
  1387.     private function validatePriceBono($giftVoucherConfigObject$bonoInfo$aviaturErrorHandler)
  1388.     {
  1389.         $giftVoucherConfigArray json_decode($giftVoucherConfigObject[0]['params'], true);
  1390.         if (ctype_digit($bonoInfo["giftFareCode"])) {
  1391.             // Si es un número entero en string, parsear y asignar directamente
  1392.             $bonoInfo["giftFarePrice"] = (int) $bonoInfo["giftFareCode"];
  1393.             $bonoInfo["giftFareCode"] = "";
  1394.         } else {
  1395.             // Si no es numérico, buscar en $giftVoucherConfigArray['fares'] el que coincida en 'code'
  1396.             $matchedFare array_values(array_filter($giftVoucherConfigArray['fares'], function($fare) use ($bonoInfo) {
  1397.                 return isset($fare['code']) && $fare['code'] === $bonoInfo["giftFareCode"];
  1398.             }));
  1399.             if(empty($matchedFare) || empty($matchedFare[0]['value'])){
  1400.                 $titleError "El valor de la tarjeta es inválido.";
  1401.                 $textError "Ha sido redirigido a la personalización de la tarjeta para que pueda seguir explorando opciones.";
  1402.                 return $aviaturErrorHandler->errorRedirect($this->generateUrl("aviatur_gift_voucher_personalize"), $titleError$textError);
  1403.             }
  1404.             $bonoInfo["giftFarePrice"] = $matchedFare[0]['value'];
  1405.         }
  1406.         // Si el precio no está dentro del rango
  1407.         if($giftVoucherConfigArray['minValue'] > $bonoInfo["giftFarePrice"] || $bonoInfo["giftFarePrice"] > $giftVoucherConfigArray['maxValue']){
  1408.             $titleError "El valor de la tarjeta no está dentro de los rangos.";
  1409.             $textError "Ha sido redirigido a la personalización de la tarjeta para que pueda seguir explorando opciones.";
  1410.             return $aviaturErrorHandler->errorRedirect($this->generateUrl("aviatur_gift_voucher_personalize"), $titleError$textError);
  1411.         }
  1412.         $bonoInfo["currency"] = "COP";
  1413.         return $bonoInfo;
  1414.     }
  1415.     // Generar código para bookingId
  1416.     private function generateRamdonCode($length 10)
  1417.     {
  1418.         $characters '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1419.         $charactersLength strlen($characters);
  1420.         $randomString '';
  1421.         for ($i 0$i $length; ++$i) {
  1422.             $randomString .= $characters[random_int(0$charactersLength 1)];
  1423.         }
  1424.         $randomCRC crc32(date('Y-m-d H:i:s'));
  1425.         $randomCode substr($randomString05).substr($randomCRC15);
  1426.         return $randomCode;
  1427.     }
  1428.     // Servicio de emissión de la tarjeta regalo
  1429.     private function emitirBono(EmissionWebservice $emissionWebserviceSessionInterface $session$orderProduct$voucherData$productId$transactionId$bookingId)
  1430.     {
  1431.         $sendVoucherStatus $emissionWebservice->callServiceEmission('purchaseBonus'$voucherData$productId);
  1432.         if (isset($sendVoucherStatus['error'])) {
  1433.             $session->set($transactionId.'[bono][emission][error]'true);
  1434.             $resultBono 'EmissionError';
  1435.             // Correo de solicitud de generación de bono internamente
  1436.             $ordersIdsString $orderProduct->getOrder() . '-PN' $productId;
  1437.             $emailContent '
  1438.                 <b>Error de emisión: emitir el bono internamente.</b><br/>
  1439.                 Info:<br/>
  1440.                 The booking id is: ' $bookingId '<br/>
  1441.                 The reference id is: ' $ordersIdsString '<br/>
  1442.                 The data is: ' json_encode($voucherData)
  1443.             ;
  1444.             $message = (new \Swift_Message())
  1445.                 ->setContentType('text/html')
  1446.                 ->setFrom($session->get('emailNoReply'))
  1447.                 ->setSubject($session->get('agencyShortName').' - Bono with approved payment: Bono NOT issued')
  1448.                 ->setTo(['soptepagelectronic@aviatur.com''soportepagoelectronico@aviatur.com.co'])
  1449.                 ->setBcc(['notificacionessitioweb@aviatur.com'])
  1450.                 ->setBody($emailContent)
  1451.             ;
  1452.             $this->mailer->send($message);
  1453.         } else {
  1454.             $resultBono $sendVoucherStatus->purchaseBonusResult;
  1455.         }
  1456.         $orderProduct->setEmissiondata($bookingId.'-'.$resultBono);
  1457.         return [
  1458.             "orderProduct" => $orderProduct,
  1459.             "bonoResult" => $resultBono
  1460.         ];
  1461.     }
  1462.     // Funcion para guardar info en resume, BD
  1463.     public function prepareInfoResume(SessionInterface $sessionManagerRegistry $registryParameterBagInterface $parameterBagAviaturEncoder $aviaturEncoder)
  1464.     {
  1465.         $em $registry->getManager();
  1466.         // Obtener el transactionId
  1467.         $transactionIdSessionName $parameterBag->get('transaction_id_session_name');
  1468.         $transactionId $session->get($transactionIdSessionName);
  1469.         // IdOrder y IdOrderProduct
  1470.         $orderInfo json_decode($session->get($transactionId '[bono][order]'));
  1471.         $productId str_replace('PN'''$orderInfo->products);
  1472.         $orderProduct $em->getRepository(\Aviatur\GeneralBundle\Entity\OrderProduct::class)->find($productId);
  1473.         // Request y response de respuesta de pago
  1474.         $opRequest json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayrequest(), $orderProduct->getPublicKey()));
  1475.         $opResponse json_decode($aviaturEncoder->AviaturDecode($orderProduct->getPayResponse(), $orderProduct->getPublicKey()));
  1476.         // Obtener información de los formularios del checkOut
  1477.         $detailInfo json_decode($session->get($transactionId '[bono][detailDataBono]'));
  1478.         // Información de medio de pago
  1479.         $isFront $session->has('operatorId');
  1480.         if (!$isFront) {
  1481.             $paymentData $detailInfo->PD;
  1482.         }
  1483.         // Mapeo de información
  1484.         if ((null != $opRequest) && (null != $opResponse)) {
  1485.             $resumeData json_decode($orderProduct->getResume(), true);
  1486.             if (isset($opResponse->x_franchise) && ('' != $opResponse->x_franchise)) {
  1487.                 $franquiceCode str_replace(['CR_''RM_''CDNSA'], ['''''CS'], $opResponse->x_franchise);
  1488.                 $clientFranquice $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findOneByPaymentgatewaycode($franquiceCode);
  1489.                 if(empty($clientFranquice)){
  1490.                     $franquiceCode str_replace(['CR_''RM_''CDNSA'], ['''''CS'], $opRequest->franchise);
  1491.                     $clientFranquice $em->getRepository(\Aviatur\GeneralBundle\Entity\Card::class)->findOneByPaymentgatewaycode($franquiceCode);
  1492.                 }
  1493.             } else {
  1494.                 $clientFranquice['description'] = 'error';
  1495.             }
  1496.             // paymentResume de acuerdo a la respuesta del pago
  1497.             if (isset($opResponse->x_description)) {
  1498.                 $paymentResume = [
  1499.                     'transaction_state' => $opResponse->x_response_code,
  1500.                     'ta_transaction_state' => $opResponse->x_ta_response_code,
  1501.                     'id' => $orderProduct->getBooking(),
  1502.                     'id_context' => $opRequest->x_invoice_num,
  1503.                     'total_amount' => $opResponse->x_amount,
  1504.                     'currency' => $opResponse->x_bank_currency,
  1505.                     'amount' => != $opRequest->x_amount_base $opRequest->x_amount_base $opResponse->x_amount,
  1506.                     'iva' => $opRequest->x_tax,
  1507.                     'ip_address' => $opRequest->x_customer_ip,
  1508.                     'bank_name' => $opResponse->x_bank_name,
  1509.                     'client_franquice' => ['description' => (is_object($clientFranquice) ? $clientFranquice->getDescription() : $clientFranquice['description'])],
  1510.                     'cuotas' => $opRequest->x_differed,
  1511.                     'card_num' => '************'.substr($opRequest->x_card_numstrlen($opRequest->x_card_num) - 4),
  1512.                     'reference' => $opResponse->x_transaction_id,
  1513.                     'auth' => $opResponse->x_approval_code,
  1514.                     'transaction_date' => $opResponse->x_transaction_date,
  1515.                     'description' => $opResponse->x_description,
  1516.                     'reason_code' => $opResponse->x_response_reason_code,
  1517.                     'reason_description' => $opResponse->x_response_reason_text,
  1518.                     'client_names' => $opResponse->x_first_name.' '.$opResponse->x_last_name,
  1519.                     'client_email' => $opResponse->x_email,
  1520.                 ];
  1521.             } elseif (isset($opRequest->infoCash)) {
  1522.                 $paymentResume = [
  1523.                     'transaction_state' => 3,
  1524.                     'id' => $orderProduct->getBooking(),
  1525.                     'id_context' => $opRequest->infoCash->x_reference,
  1526.                     'currency' => $opRequest->infoCash->x_currency,
  1527.                     'total_amount' => $opRequest->infoCash->x_total_amount,
  1528.                     'client_franquice' => ['description' => 'Efectivo'],
  1529.                     'amount' => $opRequest->infoCash->x_total_amount,
  1530.                     'iva' => null,
  1531.                     'ip_address' => $opRequest->infoCash->dirIp,
  1532.                     'airport_tax' => null,
  1533.                     'reference' => $opRequest->infoCash->x_reference,
  1534.                     'auth' => null,
  1535.                     'transaction_date' => $opRequest->infoCash->x_fechavigencia,
  1536.                     'description' => $opRequest->infoCash->x_description,
  1537.                     'reason_code' => 101,
  1538.                     'reason_description' => 'Transacción creada',
  1539.                     'client_names' => $opRequest->infoCash->x_first_name.' '.$opRequest->infoCash->x_last_name,
  1540.                     'client_email' => $opRequest->infoCash->x_email,
  1541.                     'fecha_vigencia' => $opRequest->infoCash->x_fechavigencia,
  1542.                 ];
  1543.                 // En caso de error en la emision de cash
  1544.                 $cash_result json_decode($session->get($transactionId.'[bono][cash_result]'));
  1545.                 if ('' == $cash_result) {
  1546.                     $paymentResume['transaction_state'] = 2;
  1547.                 }
  1548.             } else {
  1549.                 // Obtener codigo de banco por metodo de pago seleccionado
  1550.                 $paymentCode $this->paymentMethod->getCode() === 'pse' 'pse' 'pseRest';
  1551.                 if ($paymentCode === 'pse') {
  1552.                     $bank_code = isset($opRequest->bankCode) ? (int) $opRequest->bankCode 0;
  1553.                 } else {
  1554.                     $bank_code = isset($opRequest->instrument->redirection->additional->bankCode) ? (int) $opRequest->instrument->redirection->additional->bankCode 0;
  1555.                 }
  1556.                 $bank_info $em->getRepository(\Aviatur\PaymentBundle\Entity\PseBank::class)->findOneByCode($bank_code);
  1557.                 $bank_name $bank_info->getName();
  1558.                 $devolutionBase $paymentCode === 'pse' $opRequest->devolutionBase ?? $opRequest->x_devolution_base 0;
  1559.                 $taxAmount $paymentCode === 'pse' $opRequest->taxAmount ?? $opRequest->x_tax_amount 0;
  1560.                 $totalAmount $paymentCode === 'pse' $opRequest->totalAmount ?? $opRequest->x_total_amount $opRequest->payment->amount->total;
  1561.                 if ((== $devolutionBase) && (== $taxAmount)) {
  1562.                     $addProductXml explode('FILTRO'$orderProduct->getAddproductdata());
  1563.                     $addProductObj = \simplexml_load_string('<FILTRO' $addProductXml[1] . 'FILTRO>');
  1564.                     $amount = (string) $addProductObj->data->product->fare_data->fare->base_amount;
  1565.                     $airportTax $totalAmount $amount;
  1566.                 } else {
  1567.                     $amount $devolutionBase;
  1568.                     $airportTax $totalAmount - ($devolutionBase $taxAmount);
  1569.                 }
  1570.                 if($paymentCode != 'pse' && isset($opResponse->getTransactionInformationResult->status->status)) {
  1571.                     switch ($opResponse->getTransactionInformationResult->status->status) {
  1572.                         case 'OK':
  1573.                         case 'APPROVED':
  1574.                         case 'APPROVED_PARTIAL':
  1575.                         case 1:
  1576.                             $opResponse->getTransactionInformationResult->status->status "1";
  1577.                             break;
  1578.                         case 'REJECTED':
  1579.                         case 'PARTIAL_EXPIRED':
  1580.                         case 'NOT_AUTHORIZED':
  1581.                         case 2:
  1582.                             $opResponse->getTransactionInformationResult->status->status "2";
  1583.                             break;
  1584.                         case strpos($opResponse->getTransactionInformationResult->status->status"PENDING"):
  1585.                         case 'MANUAL':
  1586.                         case 3:
  1587.                             $opResponse->getTransactionInformationResult->status->status "3";
  1588.                             break;
  1589.                         default:
  1590.                             $opResponse->getTransactionInformationResult->status->status "0";
  1591.                             break;
  1592.                     }
  1593.                 }
  1594.                 $responseCode $paymentCode === 'pse' $opResponse->getTransactionInformationResult->responseCode ?? $opResponse->getTransactionInformationResult->transactionState
  1595.                     $opResponse->getTransactionInformationResult->status->status;
  1596.                 $currency $paymentCode === 'pse' $opRequest->currency ?? $opRequest->x_currency
  1597.                     $opRequest->payment->amount->currency ?? $opRequest->x_currency;
  1598.                 $reference $paymentCode === 'pse' $opRequest->reference ?? $opRequest->x_reference
  1599.                     $opRequest->payment->reference ?? $opRequest->x_reference;
  1600.                 $transactionID $paymentCode === 'pse' $opResponse->createTransactionResult->transactionID ?? $opResponse->id_transaccion
  1601.                     $opResponse->getTransactionInformationResult->receipt ?? $opResponse->internalReference ?? $opResponse->id_transaccion;
  1602.                 $responseReasonCode $paymentCode === 'pse' $opResponse->getTransactionInformationResult->responseReasonCode ?? null
  1603.                     $opResponse->getTransactionInformationResult->status->reason ?? null;
  1604.                 $responseReasonText $paymentCode === 'pse' $opResponse->getTransactionInformationResult->responseReasonText ?? null
  1605.                     $opResponse->getTransactionInformationResult->status->message ?? null;
  1606.                 $description $paymentCode === 'pse' $opRequest->description ?? $opRequest->x_description
  1607.                     $opRequest->payment->description ?? $opRequest->x_description;
  1608.                 $emailAddress $paymentCode === 'pse' $opRequest->payer->emailAddress ?? $opRequest->x_email
  1609.                     $opRequest->payer->email ?? $opRequest->x_email;
  1610.                 $auth $paymentCode === 'pse' $opResponse->getTransactionInformationResult->trazabilityCode $opResponse->getTransactionInformationResult->authorization ?? $opResponse->getTransactionInformationResult->receipt;
  1611.                 $transactionDate $paymentCode === 'pse' $opResponse->getTransactionInformationResult->bankProcessDate $opResponse->getTransactionInformationResult->status->date;
  1612.                 $clientNames $paymentCode === 'pse' $opRequest->payer->firstName ' ' $opRequest->payer->lastName $opRequest->payer->name ' ' $opRequest->payer->surname;
  1613.                 /* Datos complementarios */
  1614.                 $payerDocumentNumber = ($opRequest->payer->document ?? $opRequest->x_cust_id);
  1615.                 $payerMobile $opRequest->payer->mobile ?? $opRequest->x_phone ?? '';
  1616.                 $fee_base $opRequest->feeBase ?? $opRequest->x_service_fee_base ?? 0;
  1617.                 $fee_tax $opRequest->feeTax ?? $opRequest->x_service_fee_tax ?? 0;
  1618.                 $paymentResume = [
  1619.                     'transaction_state' => $responseCode,
  1620.                     'id' => $orderProduct->getBooking(),
  1621.                     'id_context' => $reference,
  1622.                     'currency' => $currency,
  1623.                     'total_amount' => $totalAmount,
  1624.                     'amount' => $amount,
  1625.                     'base_amount' => number_format(round((float) $totalAmount), 2'.'''),
  1626.                     'iva' => $taxAmount,
  1627.                     'airport_tax' => $airportTax,
  1628.                     'ip_address' => $opRequest->ipAddress,
  1629.                     'bank_name' => $bank_name,
  1630.                     'client_franquice' => ['description' => is_object($clientFranquice) ? $clientFranquice->getDescription() : 'PSE'],
  1631.                     'reference' => $transactionID,
  1632.                     'auth' => $auth,
  1633.                     'transaction_date' => $transactionDate,
  1634.                     'description' => $description,
  1635.                     'reason_code' => $responseReasonCode,
  1636.                     'reason_description' => $responseReasonText,
  1637.                     'client_names' => $clientNames,
  1638.                     'client_email' => $emailAddress,
  1639.                     'client_document_number' => $payerDocumentNumber,
  1640.                     'client_phone' => $payerMobile,
  1641.                     'card_num' => '--',
  1642.                     'cuotas' => '--',
  1643.                     'fee_base' => $fee_base,
  1644.                     'fee_tax' => $fee_tax,
  1645.                 ];
  1646.             }
  1647.             // Mapear estado de cyber y tipo de pago
  1648.             $paymentResume['transaction_state_cyber'] = $opResponse->x_response_code_cyber ?? '1';
  1649.             $paymentResume['paymentData_type'] = $paymentData->type ?? null;
  1650.             $resumeData["paymentResume"] = $paymentResume;
  1651.             // Formatear datos de facturador en caso de auto-complete
  1652.             $facturationResume $resumeData["facturationResume"];
  1653.             if (== $paymentResume['transaction_state'] && false !== strpos($facturationResume["customer_names"], '***')) {
  1654.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($detailInfo->BD->id);
  1655.                 $facturationResume = [
  1656.                     'customer_names' => $customer->getFirstname().' '.$customer->getLastname(),
  1657.                     'customer_address' => $customer->getAddress(),
  1658.                     'customer_doc_num' => $customer->getDocumentnumber(),
  1659.                     'customer_phone' => $customer->getPhone(),
  1660.                     'customer_email' => $customer->getEmail(),
  1661.                 ];
  1662.                 $resumeData["facturationResume"] = $facturationResume;
  1663.             }
  1664.         } else {
  1665.             // Información agencia
  1666.             $agency $em->getRepository(\Aviatur\AgencyBundle\Entity\Agency::class)->find($session->get("agencyId"));
  1667.             $agencyData = [
  1668.                 "agency_name" => $agency->getName(),
  1669.                 "agency_nit" => $agency->getNit(),
  1670.                 "agency_phone" => $agency->getPhone(),
  1671.                 "agency_email" => $agency->getMailContact(),
  1672.             ];
  1673.             //  Cantidad de intentos
  1674.             $retryCount = (int) $session->get($transactionId "[bono][retry]");
  1675.             // Obtener la información de la tarjeta regalo desde la sesión
  1676.             $bonoInfo json_decode(base64_decode($session->get($transactionId "[bono][bonoInfo]")), true);
  1677.             // Información pasajeros
  1678.             $passenger $detailInfo->PI;
  1679.             if (false !== strpos($passenger->first_name_1_1'***')) {
  1680.                 $customer $em->getRepository(\Aviatur\CustomerBundle\Entity\Customer::class)->find($detailInfo->BD->id);
  1681.                 $passenger->first_name_1_1 $customer->getFirstname();
  1682.                 $passenger->last_name_1_1 $customer->getLastname();
  1683.                 $passenger->phone_1_1 $customer->getPhone();
  1684.                 $passenger->email_1_1 $customer->getEmail();
  1685.                 $passenger->address_1_1 $customer->getAddress();
  1686.                 $passenger->doc_num_1_1 $customer->getDocumentnumber();
  1687.             }
  1688.             $passangersData json_decode(json_encode($passenger), true);
  1689.             $travelers = [];
  1690.             for ($i 1$i <= $passangersData["person_count_1"]; ++$i) {
  1691.                 $travelers[] = [
  1692.                     'typeCode' => $passangersData['passanger_type_1_'.$i],
  1693.                     'GivenName' => $passangersData['first_name_1_'.$i],
  1694.                     'Surname' => $passangersData['last_name_1_'.$i],
  1695.                     'Email' => $passangersData['email_1_'.$i],
  1696.                     'Phone' => $detailInfo->CD->phone,
  1697.                     'Doc_type' => $passangersData['doc_type_1_'.$i],
  1698.                     'Doc_number' => $passangersData['doc_num_1_'.$i],
  1699.                 ];
  1700.             }
  1701.             // Información del facturador
  1702.             $factInfo $detailInfo->BD;
  1703.             $facturationResume = [
  1704.                 "customer_names" => $factInfo->first_name " " $factInfo->last_name,
  1705.                 "customer_address" => $factInfo->address ?? null,
  1706.                 "customer_doc_num" => $factInfo->doc_num,
  1707.                 "customer_phone" => $factInfo->phone,
  1708.                 "customer_email" => $factInfo->email ?? null
  1709.             ];
  1710.             // Valor totalizado
  1711.             $totalAmountCOP $bonoInfo["giftFarePrice"];
  1712.             $x_amount_tax number_format(02'.''');
  1713.             $x_amount_base = (number_format(round((float) $totalAmountCOP), 2'.'''));
  1714.             // Descripción del producto
  1715.             $description 'Bono de Regalo - $'.$totalAmountCOP;
  1716.             // Información de pago
  1717.             $paymentResume = [
  1718.                 'id' => $orderProduct->getBooking(),
  1719.                 'id_context' => $orderInfo->order '-' $orderInfo->products,
  1720.                 'total_amount' => $totalAmountCOP,
  1721.                 'amount' => $x_amount_base,
  1722.                 'iva' => $x_amount_tax,
  1723.                 'currency' => $bonoInfo["currency"],
  1724.                 'ip_address' => $this->get_client_ip(),
  1725.                 'reference' => '',
  1726.                 'auth' => '',
  1727.                 'transaction_date' => $orderProduct->getCreationDate()->format('Y-m-d H:i:s'),
  1728.                 'description' => $description,
  1729.                 'reason_code' => '',
  1730.                 'reason_description' => '',
  1731.                 'paymentData_type' => $paymentData->type ?? null
  1732.             ];
  1733.             // Información a guardar en Resume en BD
  1734.             $resumeData = [
  1735.                 'agencyData' => $agencyData,
  1736.                 'retryCount' => $retryCount,
  1737.                 'facturationResume' => $facturationResume,
  1738.                 'bonoInfo' => $bonoInfo,
  1739.                 'paymentResume' => $paymentResume,
  1740.                 'transactionID' => $transactionId,
  1741.                 'travelers' => $travelers
  1742.             ];
  1743.         }
  1744.         // En caso de cash
  1745.         if ($session->has($transactionId '[bono][cash_result]')) {
  1746.             $resumeData['paymentResume']['cash_result'] = json_decode($session->get($transactionId '[bono][cash_result]'));
  1747.             // Fecha de creación de la orden
  1748.             $fecha $orderProduct->getCreationDate()->format('Y-m-d H:i:s');
  1749.             $fechalimite $orderProduct->getCreationDate()->format('Y-m-d 23:40:00');
  1750.             $nuevafecha strtotime('+5 hour'strtotime($fecha));
  1751.             $fechavigencia date('Y-m-d H:i:s'$nuevafecha);
  1752.             if (strcmp($fechavigencia$fechalimite) > 0) {
  1753.                 $fechavigencia $fechalimite;
  1754.             }
  1755.             $resumeData['paymentResume']['fecha_vigencia'] = $fechavigencia;
  1756.             // NameArchive pdf en CASH
  1757.             $resumeData['paymentResume']['NameArchive'] = $paymentResume['id_context'] . '_' $transactionId '.pdf';
  1758.         }
  1759.          // En caso de ser front
  1760.         if ($isFront) {
  1761.             $resumeData['paymentResume']['transaction_state'] = 1;
  1762.         }
  1763.         // reintento de pago
  1764.         $resumeData['backDetail'] = $this->generateUrl('aviatur_gift_voucher_retry_secure');
  1765.         // En caso de error en la emision del Bono
  1766.         if ($session->has($transactionId.'[bono][emission][error]')) {
  1767.             $resumeData['emission_error'] = true;
  1768.         }
  1769.         $orderProduct->setResume(json_encode($resumeData));
  1770.         $em->persist($orderProduct);
  1771.         $em->flush();
  1772.     }
  1773.     // Obtener ip del cliente
  1774.     private function get_client_ip()
  1775.     {
  1776.         $ipaddress '';
  1777.         if (getenv('HTTP_CLIENT_IP')) {
  1778.             $ipaddress getenv('HTTP_CLIENT_IP');
  1779.         } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
  1780.             $ipaddress getenv('HTTP_X_FORWARDED_FOR');
  1781.         } elseif (getenv('HTTP_X_FORWARDED')) {
  1782.             $ipaddress getenv('HTTP_X_FORWARDED');
  1783.         } elseif (getenv('HTTP_FORWARDED_FOR')) {
  1784.             $ipaddress getenv('HTTP_FORWARDED_FOR');
  1785.         } elseif (getenv('HTTP_FORWARDED')) {
  1786.             $ipaddress getenv('HTTP_FORWARDED');
  1787.         } elseif (getenv('REMOTE_ADDR')) {
  1788.             $ipaddress getenv('REMOTE_ADDR');
  1789.         } else {
  1790.             $ipaddress 'UNKNOWN';
  1791.         }
  1792.         return (strpos($ipaddress',') !== false) ? trim(explode(','$ipaddress)[0]) : (substr_count($ipaddress':') > $ipaddress explode(':'$ipaddress)[0]);
  1793.     }
  1794.     /**
  1795.      * changeAcutes()
  1796.      * Cambia los acentos para que no lleguen cadenas dañadas a un XML.
  1797.      * Author: Ing. David Rincon
  1798.      * Email: david.rincon@aviatur.com
  1799.      * Date: 2025/05/08
  1800.      * @param $cadena (Cadena original)
  1801.      * @return $cadena (Cadena sin acentos)
  1802.      */
  1803.     function changeAcutes($cadena){
  1804.         //Reemplazamos la A y a
  1805.         $cadena str_replace(
  1806.             array('Á''À''Â''Ä''á''à''ä''â''ª'),
  1807.             array('A''A''A''A''a''a''a''a''a'),
  1808.             $cadena );
  1809.         //Reemplazamos la E y e
  1810.         $cadena str_replace(
  1811.             array('É''È''Ê''Ë''é''è''ë''ê'),
  1812.             array('E''E''E''E''e''e''e''e'),
  1813.             $cadena );
  1814.         //Reemplazamos la I y i
  1815.         $cadena str_replace(
  1816.             array('Í''Ì''Ï''Î''í''ì''ï''î'),
  1817.             array('I''I''I''I''i''i''i''i'),
  1818.             $cadena );
  1819.         //Reemplazamos la O y o
  1820.         $cadena str_replace(
  1821.             array('Ó''Ò''Ö''Ô''ó''ò''ö''ô'),
  1822.             array('O''O''O''O''o''o''o''o'),
  1823.             $cadena );
  1824.         //Reemplazamos la U y u
  1825.         $cadena str_replace(
  1826.             array('Ú''Ù''Û''Ü''ú''ù''ü''û'),
  1827.             array('U''U''U''U''u''u''u''u'),
  1828.             $cadena );
  1829.         //Reemplazamos la N, n, C y c
  1830.         $cadena str_replace(
  1831.             array('Ñ''ñ''Ç''ç'),
  1832.             array('N''n''C''c'),
  1833.             $cadena );
  1834.         return $cadena;
  1835.     }
  1836. }