src/Controller/CarritoController.php line 1178

  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpFoundation\RedirectResponse;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  9. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  10. use Symfony\Component\HttpFoundation\Cookie;
  11. use Symfony\Component\HttpFoundation\RequestStack;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. use Symfony\Component\Cache\Adapter\FilesystemAdapter;
  14. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  15. use Symfony\Component\HttpKernel\KernelInterface;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. use Symfony\Contracts\Cache\ItemInterface;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use Doctrine\Persistence\ManagerRegistry as PersistenceManagerRegistry;
  20. use Knp\Component\Pager\PaginatorInterface;
  21. // use FOS\UserBundle\Form\Factory\FactoryInterface;
  22. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  23. use App\Utils\ApiRedsys;
  24. use App\Services\ConfigurationManager;
  25. use App\Services\SettingsManager;
  26. use App\Services\WebServiceUsuarios;
  27. use App\Services\WebServiceReservas;
  28. use App\Services\WebServiceTPV;
  29. use App\Services\WebServiceFunciones;
  30. use App\Services\Mailer;
  31. use App\Entity\Pedido;
  32. use App\Entity\Carro;
  33. use App\Entity\Invitado;
  34. use App\Entity\User;
  35. use App\Entity\HorarioReducido;
  36. use App\Entity\Divisa;
  37. use App\Entity\Oficina;
  38. use App\Entity\Cotizaciones;
  39. use App\Entity\Reserva;
  40. use App\Entity\ReservaLinea;
  41. use App\Entity\Transaccion;
  42. use App\Entity\TransaccionAfiliado;
  43. use App\Entity\TransaccionLinea;
  44. use App\Entity\Existencia;
  45. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  46. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  47. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  48. use Symfony\Component\Form\Extension\Core\Type\IntegerType;
  49. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  50. use Symfony\Component\Form\Extension\Core\Type\TextType;
  51. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  52. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  53. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  54. use Symfony\Component\Form\Extension\Core\Type\FormType;
  55. use App\Form\Carrito\CarroType;
  56. use App\Form\LoginType;
  57. use App\Form\InvitadoType;
  58. use App\Form\Carrito\CartDeliver;
  59. use App\Form\Carrito\CartShop;
  60. use App\Form\Carrito\TransactionType;
  61. use App\Form\Type\UserRegistrationType;
  62. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  63. use App\Event\BookingCompleteEvent;
  64. use App\Event\OrderCompleteEvent;
  65. use Psr\Log\LoggerInterface;
  66. class CarritoController extends AbstractController
  67. {  
  68.         
  69.         private $authorizationChecker;
  70.         private $kernel;
  71.         private $registrationFormFactory;
  72.         public function __construct(AuthorizationCheckerInterface $authorizationCheckerKernelInterface $kernel/*, FactoryInterface $registrationFormFactory*/)
  73.         {
  74.             $this->authorizationChecker $authorizationChecker;
  75.             $this->kernel $kernel;
  76. //             $this->registrationFormFactory = $registrationFormFactory;
  77.         }
  78.     
  79.          #[Route(path: [
  80.         'es' => '/cupon-check',
  81.         'en' => '/en/cupon-check'
  82.         ], name'app_cupon_check')]
  83.         public function checkPromotionalCode(Request $request,PersistenceManagerRegistry $doctrineSettingsManager $smWebServiceFunciones $wsf){
  84.         
  85.             $locale $request->getLocale();
  86.             $em $doctrine->getManager();
  87.             $valor $_POST['valor'];
  88.             $importe $_POST['importe'];
  89.             $cupAplicado $_POST['cupAplicado'];
  90.             $repository $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $valor ]);
  91.             if($repository == null) {
  92.                 $respuesta = new JsonResponse();
  93.                 $respuesta->setData(['ok' => 0'msg' => $sm->getValue('cart.step1.cupon_no_valido')]);
  94.             } else if($cupAplicado != '') {
  95.                 $respuesta = new JsonResponse();
  96.                 $respuesta->setData(['ok' => 0'msg' => $sm->getValue('cart.step1.cupon_ya_aplicado')]);
  97.             } else {
  98.                 $permIds = [];
  99.                 if ($repository->getDivisas()->isEmpty()) {
  100.                     $divP $em->getRepository('App\Entity\Divisa')->findBy(['visible' => 1]);
  101.                 } else {
  102.                     $divP $repository->getDivisas();
  103.                 }
  104.                 foreach($divP as $perm) {
  105.                     if ($perm->getId() != 10) {
  106.                         $permIds[] = $perm->getId();
  107.                     }
  108.                 }
  109.                 if( $this->comprobarCupon($request$doctrine$valor)){
  110.                     $respuesta = new JsonResponse();
  111.                     $respuesta->setData(['ok' => 1'msg' => $sm->getValue('cart.step1.cupon_valido'), 'tipo' => Carro::TIPO_PROMO_DIVISA'rate' => $repository->getPorcentajeDescuento(), 'permDiv' => $permIds ]);
  112.                 }else{
  113.                     //comprobar codigo codigo promocion
  114.                     $resultado $wsf->ComprobarImporteMinimoPromocion($valor,$importe);
  115. //                     var_dump($resultado); die();
  116.                     if ($resultado and $resultado['valido']) {
  117.                         $respuesta = new JsonResponse();
  118.                         $respuesta->setData(['ok' => 1'msg' => $sm->getValue('cart.step1.cupon_valido'), 'tipo' => Carro::TIPO_PROMO_CUPON]);
  119.                     }
  120.                     elseif ($resultado and !$resultado['valido']) {
  121.                         $respuesta = new JsonResponse();
  122.                         //$respuesta->setData(['ok' => 0, 'msg' => $sm->getValue('cart.step1.cupon_no_valido')]);
  123.                         $respuesta->setData(['ok' => 0'msg' => $sm->getValue('cart.cupon_error_'.trim($resultado['error']))]);
  124.                     }
  125.                     else {
  126.                         $respuesta = new JsonResponse();
  127.                         $respuesta->setData(['ok' => 0'msg' => $sm->getValue('cart.step1.cupon_no_valido')]);
  128.                     }
  129.                 }
  130.             }
  131.             return $respuesta;
  132.         }
  133.         
  134.         #[Route(path: [
  135.             'es' => '/cotizacion-cart-check',
  136.             'en' => '/en/cotizacion-cart-check'
  137.         ], name'app_cotizacion_check_cart')]
  138.         public function checkCotizacion(Request $request,PersistenceManagerRegistry $doctrineSettingsManager $sm){
  139.         
  140.             $locale $request->getLocale();
  141.             $em $doctrine->getManager();
  142.             $valor=$_POST['valor'];
  143.             $repository $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $valor ]);
  144. //             $options = $this->container->get('dinamic_settings.manager');
  145.             if( $this->comprobarCupon($request$doctrine$valor)){
  146.                 $respuesta = new JsonResponse();
  147.                 $respuesta->setData(['ok' => 1'msg' => $sm->getValue('cart.step1.cupon_valido'), 'tipo' => Carro::TIPO_PROMO_DIVISA ]);
  148.             }else{
  149.                 $respuesta = new JsonResponse();
  150.                 $respuesta->setData(['ok' => 0'msg' => $sm->getValue('cart.step1.cupon_no_valido')]);
  151.             }
  152.             return $respuesta;
  153.         }
  154.         // Valida Cupon de TIPO_PROMO_CUPON
  155.         public function comprobarCuponCodigo($valor$importeWebServiceFunciones $wsf) {
  156.             //comprobar codigo codigo promocion
  157.             $resultado $wsf->ComprobarImporteMinimoPromocion($valor$importe);
  158.             if ($resultado and $resultado['valido']) {
  159.                 return true;
  160.             }
  161.             elseif ($resultado and !$resultado['valido']) {
  162.                 return ['error' => 'cart.cupon_error_'.trim($resultado['error'])];
  163.             }
  164.             else {
  165.                 return ['error' => 'cart.step1.cupon_no_valido'];
  166.             }
  167.         }
  168.         public function comprobarCupon(Request $request,PersistenceManagerRegistry $doctrine$valor) {
  169.         
  170.             $locale $request->getLocale();
  171.             $em $doctrine->getManager();
  172.             $usuarioActual $this->getUser();
  173.             $repository $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $valor ]);
  174.             if(!$repository){
  175.                 return false;
  176.             }
  177.             
  178.             $cod $repository->getCodigo();
  179.             $activo $repository->getActivo();
  180.             $inicio $repository->getInicio();
  181.             $fin $repository->getFin();
  182.             $fechas false;
  183.             $current = new \DateTime();
  184.             if($inicio == NULL AND $fin == NULL){
  185.                 $fechas true;
  186.             }
  187.             else if($inicio != NULL AND $fin != NULL){
  188.                 if($current >= $inicio AND $current<= $fin){
  189.                     $fechas=true;
  190.                 }else{
  191.                     $fechas false;
  192.                 }
  193.             }else if($inicio != NULL AND $fin == NULL){
  194.                 if($current >= $inicio){
  195.                     $fechas=true;
  196.                 }else{
  197.                     $fechas false;
  198.                 }
  199.             }else{
  200.                 if($current <= $fin){
  201.                     $fechas=true;
  202.                 }else{
  203.                     $fechas false;
  204.                 }
  205.             }
  206.             $repository1 $em->getRepository('App\Entity\Transaccion')->findBy([ 'cupon' => $valor'usuario' => $usuarioActual ]);
  207.             $repository2 $em->getRepository('App\Entity\Reserva')->findBy([ 'cupon' => $valor 'usuario' => $usuarioActual]);
  208.             $totalUsosUsuario 0;
  209.             foreach($repository1 as $rep){
  210.                 $totalUsosUsuario $totalUsosUsuario +1;
  211.             }
  212.             foreach($repository2 as $repo){
  213.                 $totalUsosUsuario $totalUsosUsuario +1;
  214.             }
  215.             $totalUsosUsu $repository->getTotalUsosUsuario() - $totalUsosUsuario;
  216.             $user_id $repository->getUsuario();
  217.             if($cod == $valor AND $activo == AND $totalUsosUsu>AND $fechas==true) {
  218.                 if( !$user_id OR $user_id == $usuarioActual){
  219.                     $cupon $repository;
  220.                     $respuesta true;
  221.                 }else{
  222.                     $cupon "";
  223.                     $respuesta false;
  224.                 }
  225.             }else{
  226.                 $respuesta false;
  227.             }
  228.             return $respuesta;
  229.         }
  230.         
  231.         
  232.         /* TODO revisar si es necesario y cambiar envio email*/
  233.         #[Route(path: [
  234.             'es' => '/reclamacion-send',
  235.             'en' => '/en/reclamacion-send'
  236.         ], name'app_cart_reclamacion')]
  237.         public function reclamacionesFormAction(Request $requestSettingsManager $sm$scenario "desktop")
  238.         {
  239.             $idioma $request->getLocale();
  240. //             $options = $this->container->get('dinamic_settings.manager');
  241.             $form $this->createForm(new ReclamacionesType($sm));
  242.             $form->handleRequest($request);
  243.             $recaptcha = new \ReCaptcha\ReCaptcha($this->container->getParameter('captcha_reclamaciones_key_private'));
  244.             $resp $recaptcha->verify($request->request->get('g-recaptcha-response'), $request->getClientIp());
  245.             $recaptcha1 = new \ReCaptcha\ReCaptcha($this->container->getParameter('captcha_movil_key_private'));
  246.             $resp1 $recaptcha1->verify($request->request->get('g-recaptcha-response'), $request->getClientIp());
  247.             $captchaError null;
  248.             $msg null;
  249.             if ($form->isValid() && ($resp->isSuccess() || $resp1->isSuccess())) {
  250.                 $message \Swift_Message::newInstance()
  251.                     ->setContentType("text/html")
  252.                     ->setSubject('Reclamación realizada por formulario web')
  253.                     ->setFrom($form->get('email')->getData())
  254.                     //->setTo('eurochange@eurochange.es')
  255.                     ->setTo('eurochange@eurochange.es')
  256.                     ->setBody('<h2>Un cliente ha enviado una reclamación:</h2><br/>
  257.                         Nombre y apellidos: ' $form->get('fullname')->getData() . '<br/>
  258.                         Email: ' $form->get('email')->getData() . '<br>
  259.                         TelĆ©fono: ' $form->get('phone')->getData() . '<br/>
  260.                         Tipo de documento: ' $form->get('documentType')->getData()->getNombreEs() . '<br/>
  261.                         NĆŗmero de documento: ' $form->get('documentNumber')->getData() . '<br/>
  262.                         Reclamación relacionada con: ' $form->get('subject')->getData() . '<br/>
  263.                         Argumentos: <br>' nl2br($form->get('comments')->getData()))//->setBody($adminHTML)
  264.                 ;
  265.                 $this->get('swiftmailer.mailer.default')->send($message);
  266.                 if ($request->isXmlHttpRequest()) {
  267.                     if ($idioma == 'es') {
  268.                         $msg "Su reclamación ha sido enviada con Ć©xito, en breve nos pondremos en contacto con usted.";
  269.                     } else {
  270.                         $msg "Your claim has been successfully sent, we will contact you shortly.";
  271.                     }
  272.                     return new JsonResponse([
  273.                         'status' => true,
  274.                         'msg' => $msg
  275.                     ], 200);
  276.                 }
  277.             } elseif (!empty($_POST) && !$resp->isSuccess()) {
  278.                 if ($idioma == 'es') {
  279.                     $captchaError "Ha ocurrido un error con el captcha, vuelva a intentarlo.";
  280.                 } else {
  281.                     $captchaError "An error occurred with the captcha, try again.";
  282.                 }
  283.                 if ($request->isXmlHttpRequest()) {
  284.                     return new JsonResponse([
  285.                         'status' => false,
  286.                         'msg' => $captchaError
  287.                     ], 200);
  288.                 }
  289.             }
  290.             $returnArray = [
  291.                 'form' => $form->createView(),
  292.                 'tipo' => $scenario,
  293.             ];
  294.             if ($request->isXmlHttpRequest()) {
  295.                 $html $this->renderView("default/reclamaciones_form.html.twig"$returnArray);
  296.                 return new JsonResponse([
  297.                     'status' => false,
  298.                     'html' => $html
  299.                 ], 200);
  300.             }
  301.             return $this->render('default/reclamaciones_form.html.twig'$returnArray);
  302.         }
  303.         
  304.         
  305.         /**
  306.         * Por alguna razon json_encode ignora el depth y el servicio del seralizer
  307.         * casca al invocarlo
  308.         * @Route( "getHorarios",   name="app_get_horarios" )
  309.         */
  310.         public function getHorariosAction($request$em)
  311.         {
  312.             
  313.             $locale $request->getLocale();
  314.             $oficinas $em->getRepository("App\Entity\Oficina")->findfullOffices($locale);
  315.             foreach ($oficinas as $oficina) {
  316.                 $horarios[] = json_encode($oficina->getOficina());
  317.             }
  318.             $horarios = (json_encode($horariostrue100));
  319.             $horarios str_replace('/'''$horarios);
  320.             $horarios str_replace('\\'''$horarios);
  321.             $horarios str_replace('":["{''":[{'$horarios);
  322.             $horarios str_replace('}","{''},{'$horarios);
  323.             $horarios str_replace('}"]''}]'$horarios);
  324.             $horarios str_replace('["{"''[{"'$horarios);
  325.             return $horarios;
  326.         }
  327.         
  328.         
  329.         /**
  330.         * Autentica un usuario
  331.         * @param User $user
  332.         * @param Response $response
  333.         */
  334.         protected function authenticateUser($userResponse $response)
  335.         {
  336.             try {
  337.                 $this->container->get('fos_user.security.login_manager')->loginUser(
  338.                     $this->container->getParameter('fos_user.firewall_name'),
  339.                     $user,
  340.                     $response);
  341.             } catch (AccountStatusException $ex) {
  342.                 // We simply do not authenticate users which do not pass the user
  343.                 // checker (not enabled, expired, etc.).
  344.             }
  345.         }
  346.         
  347.         
  348.         public function createShopFormAction(PersistenceManagerRegistry $doctrine)
  349.         {
  350.             $em $doctrine->getManager();
  351.             $pedido = new Pedido();
  352.             $form $this->createForm(new CartStep1Type($em), $pedido);
  353.             return $this->render('default/FastShop.html.twig', array(
  354.                 'form' => $form->createView(),
  355.             ));
  356.         }
  357.         
  358.         
  359.         /**
  360.         * Guarda en sesión los pasos del carro completados
  361.         * @return mixed
  362.         */
  363.         private function StepControl(Request $request)
  364.         {
  365.             $sesion $request->getSession();
  366.             // $logeado = $this->authorizationChecker->isGranted('ROLE_USER');
  367.             //No existe sesion de control
  368.             if ($sesion->get('cartStep') == null) {
  369.                 $cartStep[1] = false;
  370.                 $cartStep[2] = false;
  371.                 $cartStep[3] = false;
  372.                 $cartStep[4] = false;
  373.                 $cartStep[5] = false;
  374.             } //Existe sesion de control
  375.             else {
  376.                 $cartStep $sesion->get('cartStep');
  377.             }
  378.             //Si esta logueado se valida el paso 2
  379.             // if ($logeado) {
  380.             //     $cartStep[2] = true;
  381.             // }
  382.             $sesion->set('cartStep'$cartStep);
  383.             return $cartStep;
  384.         }
  385.         private function retomarSesion(Request $request, )
  386.         {
  387.             $cartStep $this->StepControl($request);
  388.             $carro = new Carro();
  389.             return $cartStep;
  390.         }
  391.         
  392.         
  393.         /**
  394.         * Guarda los datos del primer carro en sesión
  395.         * @param $carro
  396.         */
  397.         private function setCart1(Request $request$carro)
  398.         {
  399.             $sesion $request->getSession();
  400.             $cartStep $sesion->get('cartStep');
  401.             $cartStep[1] = true;
  402.             $sesion->set('cartStep'$cartStep);
  403.             $carroSesion $sesion->get('carro');
  404.             
  405.             
  406.             //Hay carro en sesion
  407.             if (isset($carroSesion)) {
  408.                 //Actualizamos el carro
  409.                 $carroSesion->setPedidos($carro->getPedidos());
  410.                 $carroSesion->setReserva($carro->getReserva());
  411.                 $sesion->set('carro'$carroSesion);
  412.             } else {
  413.                 //Metemos el carro nuevo
  414.                 $sesion->set('carro'$carro);
  415.             }
  416. //             dump($carro);die();
  417.         }
  418.         
  419.         /**
  420.         * @Route("/carro1", name="carro1error")
  421.         */
  422.         public function redirectCarro1()
  423.         {
  424.             return $this->redirectToRoute('index_es');
  425.         }
  426.         
  427.         /**
  428.         * @Route("/en/cart1", name="cart1error")
  429.         */
  430.         public function redirectCart1()
  431.         {
  432.             return $this->redirectToRoute('index_en');
  433.         }
  434.         #[Route(path: [
  435.             'es' => '/verCarro',
  436.             'en' => '/en/showBarrow'
  437.         ], name'app_cart_1')]
  438.         public function Cart1Action(Request $requestPersistenceManagerRegistry $doctrine,  WebServiceTPV $wstpv)
  439.         {
  440.             $locale $request->getLocale();
  441.             $pedido = new Pedido();
  442.             $carro = new Carro();
  443.             $predefined null;
  444.             $em $doctrine->getManager();
  445.             //Si pasan valores por GET
  446.             if ($request->query->get('dinamic_shop_cartStep1') || $request->query->get('divisaOrigen') || $request->query->get('divisaFinal')) {
  447.                 $predefined $request->query->get('dinamic_shop_cartStep1');
  448. //                 dump($predefined);die();
  449.                 if (!$predefined) {
  450.                     $predefined['divisaOrigen'] = $request->query->get('divisaOrigen');
  451.                     $predefined['divisaFinal'] = $request->query->get('divisaFinal');
  452.                     $predefined['cantidadOrigen'] = $request->query->get('cantidadOrigen');
  453.                     $predefined['cantidadFinal'] = $request->query->get('cantidadFinal');
  454.                     $predefined['codigoPromo'] = $request->query->get('codigoPromo');
  455.                     $predefined['tipoPromo'] = $request->query->get('tipoPromo');
  456.                 }
  457.                 $predefined['cantidadOrigen'] = str_replace(',''.'$predefined['cantidadOrigen']);
  458.                 $predefined['cantidadFinal'] = str_replace(',''.'$predefined['cantidadFinal']);
  459.                 $pedido->setDivisaOrigen($em->getRepository('App\Entity\Divisa')->findOneById($predefined['divisaOrigen']));
  460.                 $pedido->setDivisaFinal($em->getRepository('App\Entity\Divisa')->findOneById($predefined['divisaFinal']));
  461.                 $pedido->setCantidadOrigen($predefined['cantidadOrigen']);
  462.                 $pedido->setCantidadFinal($predefined['cantidadFinal']);
  463.             //    $pedido->setCupon($predefined['codigoProm']);
  464.                 $carro->addPedido($pedido);
  465.                 $div_f_nombre $pedido->getDivisaFinal()->getSimbolo();
  466.                 $div_o_nombre $pedido->getDivisaOrigen()->getSimbolo();
  467.             } //Si vuelve atrĆ”s
  468.             else if ($this->getCart($request)) {
  469.                 $carro $this->getCart($request);
  470.                 $carro->setOficina(NULL);
  471.                 $carro->setHoraEntrega(NULL);
  472.                 $carro->setFechaEntrega(NULL);
  473.                 $carro->setFreeShipping(0);
  474.                 //Reiniciamos la oficina por si ha elegido una en el paso 3
  475.                 //No todas las divisas estĆ”n disponibles en todas las oficinas
  476.                 $sesion $request->getSession();
  477.                 $sesion->set('carro'$carro);
  478.                 $cartStep $sesion->get('cartStep');
  479.                 $cartStep[3] = NULL;
  480.                 $sesion->set('cartStep'$cartStep);
  481.             } //Si ponen la URL vacĆ­a en el navegador
  482.             else {
  483.                 $predefined['divisaOrigen'] = 12;
  484.                 $predefined['divisaFinal'] = 10;
  485.                 $predefined['cantidadFinal'] = 100;
  486.                 $pedido->setDivisaOrigen($em->getRepository('App\Entity\Divisa')->findOneById(10));
  487.                 $pedido->setDivisaFinal($em->getRepository('App\Entity\Divisa')->findOneById(12));
  488.                 $pedido->setCantidadFinal(100);
  489.                 $carro->addPedido($pedido);
  490.             }
  491. //             die();
  492.             $oficina $em->getRepository("App\Entity\Oficina")->findAll();
  493.             
  494.             $formCarro $this->createForm(CarroType::class, $carro, [
  495.                 'tipo_value' => 0,
  496.                 'em' => $em,
  497.                 'locale' => $locale,
  498.                 'csrf_protection' => false
  499.             ]);
  500.             if(isset($div_f_nombre) && isset($div_o_nombre)){
  501.             }else{
  502.                 $div_f_nombre $em->getRepository('App\Entity\Divisa')->findOneBy(['id' => 12]);
  503.                 $div_o_nombre $em->getRepository('App\Entity\Divisa')->findOneBy(['id' => 10]);
  504.                 $div_f_nombre $div_f_nombre->getSimbolo();
  505.                 $div_o_nombre $div_o_nombre->getSimbolo();
  506.             }
  507.             //Procesar Datos
  508.             if ($request->getMethod() == 'POST' ) {
  509.             
  510.                 $formCarro->handleRequest($request);
  511.                 
  512.                 if ($formCarro->isValid()) {
  513.                     $codigoPromocional $formCarro->get('codigoPromo')->getData();
  514.                     $carro->setCodigoPromo($codigoPromocional);
  515.                     $carro->setTipoPromo($formCarro->get('tipoPromo')->getData());
  516.                     // $carro->setTipoPromo($formCarro->get('tipoPromo')->getData());
  517.                     $this->setCart1($request$carro);
  518.                     if($formCarro->get('tipo')->getData() == 0){
  519.                         $response $this->redirect($this->generateUrl('app_cart_2'));
  520.                     }
  521.                     else{
  522.                         $response $this->redirect($this->generateUrl('app_cart_1'));
  523.                     }
  524.                     $sesion $request->getSession();
  525.                     $sesion->set('metodoEntrega'$formCarro->get('metodoEntrega')->getData());
  526.                     if ($formCarro->get('metodoEntrega')->getData() == 1) {
  527.                         $carro->setOficina((integer)($_COOKIE['cookieoficina']));
  528.                     }
  529.                     if ($carro->getTotalTransaccion()) {
  530.                         $this->deleteErpSale($carro,$wstpv);
  531.                     }
  532.                     return $response;
  533.                 }
  534.             }
  535.             $repository $em->getRepository('App\Entity\Cotizaciones');
  536.             $permiteCompra 1;
  537.             if(isset($_COOKIE['cookieoficina'])){
  538.                 $ofi = (integer)($_COOKIE['cookieoficina']);
  539.                 $rep $em->getRepository('App\Entity\Oficina')->findOneById($ofi);
  540.                 if($rep){
  541.                     if($rep->permiteCompra() != 1){
  542.                         $permiteCompra 0;
  543.                     }
  544.                 }
  545.                 $cotizaciones $repository->getLastChangesOffice($ofi);
  546.                 if($ofi == 1){
  547.                     $cotizaciones $repository->getLastChangesOffice($this->getParameter('oficina_por_defecto'));
  548.                 }
  549.                 $pedido->setOficina($ofi);
  550.             }else{
  551.                 $ofi $this->getParameter('oficina_por_defecto');
  552.                 $cotizaciones $repository->getLastChanges($ofi);
  553.             }
  554.             $cartStep $this->StepControl($request);
  555.             $divisas $em->getRepository('App\Entity\Divisa')->findBy(['visible' => 1]);
  556.             
  557.             
  558.             $cotizacionesOnline $repository->getLastChangesOffice($this->getParameter('oficina_por_defecto'));
  559.             
  560.             $cotizacionesOnlineJson = [];
  561.             foreach($cotizacionesOnline as $n)
  562.                 $cotizacionesOnlineJson[$n['shortName']] = $n;
  563.             
  564.             $cotizacionesJson = [];
  565.             foreach($cotizaciones as $c)
  566.                 $cotizacionesJson[$c['shortName']] = $c;
  567.             
  568. //             dump($divisas); die();
  569.             $divisasJson = [];
  570.             foreach($divisas as $d)
  571.                 $divisasJson[$d->getId()] = [
  572.                     'shortName' => $d->getShortName(),
  573.                     'redondeoMinimo' => $d->getRedondeoMinimo(),
  574.                     'compraMinima' => $d->getCompraMinima(),
  575.                 ];
  576. //           dump($formCarro->createView()); die();
  577.             /****/
  578.             $provincias $em->getRepository('App\Entity\Provincia')->findAll();
  579.             /****/
  580.             
  581.             return $this->render('default/carrito/carrito1.html.twig', array(
  582.                 'cotizaciones' => $cotizaciones,
  583.                 'cotizacionesJson' => json_encode($cotizacionesJson),
  584.                 'cotizacionesOnlineJson' => json_encode($cotizacionesOnlineJson),
  585.                 'stepBread' => $cartStep,
  586.                 'carro' => $formCarro->createView(),
  587.                 'currentStep' => 1,
  588.                 'divisas' => $divisas,
  589.                 'divisasJson' => json_encode($divisasJson),
  590.                 'predefined' => $predefined,
  591.                 'ofi_var' => $ofi,
  592.                 'oficina' => $oficina,
  593.                 'div_f_nombre' => $div_f_nombre,
  594.                 'div_o_nombre' => $div_o_nombre,
  595.                 'permiteCompra' => $permiteCompra,
  596.                 /****/
  597.                 'provincias' => $provincias
  598.                 /****/
  599.             ));
  600.         }
  601.         
  602.         
  603.         private function setCart2($request$em)
  604.         {
  605.             $sesion $request->getSession();
  606.             $cartStep $sesion->get('cartStep');
  607.             $cartStep[2] = true;
  608.             $sesion->set('cartStep'$cartStep);
  609.             $carro $sesion->get('carro');
  610.             $oficina1 $_COOKIE['cookieoficina'];
  611.             if($oficina1 == 1){
  612.                 $oficina $em->getRepository('App\Entity\Oficina')->findOneById($this->getParameter('oficina_por_defecto'));
  613.             }else{
  614.                 $oficina $em->getRepository('App\Entity\Oficina')->findOneById($oficina1);
  615.             }
  616.             
  617.             $provincia $oficina->getProvincia();
  618.             $carro->setProvincia($provincia);
  619.             $carro->setOficina($oficina);
  620.             $carro->setUsuario($this->getUser());
  621.             $sesion->set('carro'$carro);
  622.         }
  623.         private function setInvitado($request$invitado)
  624.         {
  625.             $sesion $request->getSession();
  626.             $cartStep $sesion->get('cartStep');
  627.             $cartStep[2] = true;
  628.             $sesion->set('cartStep'$cartStep);
  629.             $carro $sesion->get('carro');
  630.             $carro->setInvitado($invitado);
  631.             $sesion->set('carro'$carro);
  632.         }
  633.         private function createFormNoCorreo($options)
  634.         {
  635.             $formCorreo $this->createFormBuilder()
  636.                 ->add('Dni_correo_sin'HiddenType::class, array()
  637.                 )
  638.                 ->add('email'TextType::class, array(
  639.                         'label' => false,
  640.                         'attr' => array(
  641.                             'placeholder' => 'Email'
  642.                         )
  643.                     )
  644.                 )
  645.                 ->add('password1'TextType::class, array(
  646.                         'label' => false,
  647.                         'attr' => array(
  648.                             'placeholder' => $options->getValue('cart2.password')
  649.                         )
  650.                     )
  651.                 )
  652.                 ->add('password2'TextType::class, array(
  653.                         'label' => false,
  654.                         'attr' => array(
  655.                             'placeholder' => $options->getValue('cart2.repassword')
  656.                         )
  657.                     )
  658.                 )
  659.                 ->add('submitNoCorreo'SubmitType::class, array(
  660.                         'label' => false,
  661.                         'attr' => array(
  662.                             'placeholder' => $options->getValue('cart2.repassword')
  663.                         )
  664.                     )
  665.                 )
  666.                 ->getForm();
  667.             return $formCorreo;
  668.         }
  669.         private function createFormCorreo($options)
  670.         {
  671.             $formCorreo $this->createFormBuilder()
  672.                 ->add('Dni_correo_con'HiddenType::class, array()
  673.                 )
  674.                 ->add('codigo_correo'TextType::class, array(
  675.                         'label' => false,
  676.                         'attr' => array(
  677.                             'placeholder' => $options->getValue('cart2.code')
  678.                         )
  679.                     )
  680.                 )
  681.                 ->add('password1'PasswordType::class, array(
  682.                         'label' => false,
  683.                         'attr' => array(
  684.                             'placeholder' => $options->getValue('cart2.password')
  685.                         )
  686.                     )
  687.                 )
  688.                 ->add('password2'PasswordType::class, array(
  689.                         'label' => false,
  690.                         'attr' => array(
  691.                             'placeholder' => $options->getValue('cart2.repassword')
  692.                         )
  693.                     )
  694.                 )
  695.                 ->add('submitCorreo'SubmitType::class, array(
  696.                         'label' => false,
  697.                         'attr' => array(
  698.                             'placeholder' => $options->getValue('cart2.repassword')
  699.                         )
  700.                     )
  701.                 )
  702.                 ->getForm();
  703.             return $formCorreo;
  704.         }
  705.         private function createFormSinPago($options)
  706.         {
  707.             $formCorreo $this->createFormBuilder()
  708.                 ->add('Dni_sin_pago'HiddenType::class, array()
  709.                 )
  710.                 ->add('email'TextType::class, array(
  711.                         'label' => false,
  712.                         'required' => true,
  713.                         'attr' => array(
  714.                             'placeholder' => 'Email'
  715.                         )
  716.                     )
  717.                 )
  718.                 ->add('nombre'TextType::class, array(
  719.                         'label' => false,
  720.                         'required' => true,
  721.                         'attr' => array(
  722.                             'placeholder' => $options->getValue('cart2.nombre.titular')
  723.                         )
  724.                     )
  725.                 )
  726.                 ->add('telefono'TextType::class, array(
  727.                         'label' => false,
  728.                         'required' => false,
  729.                         'attr' => array(
  730.                             'placeholder' => $options->getValue('cart2.telefono.titular')
  731.                         )
  732.                     )
  733.                 )
  734.                 ->add('submitSinPago'SubmitType::class, array(
  735.                         'label' => $options->getValue('cart2.compraPaga')
  736.                     )
  737.                 )
  738.                 ->getForm();
  739.             return $formCorreo;
  740.         }
  741.         private function getErrorMessages(\Symfony\Component\Form\Form $form) {
  742.             $errors = array();
  743.             foreach ($form->getErrors() as $key => $error) {
  744.                 if ($form->isRoot()) {
  745.                     $errors['#'][] = $error->getMessage();
  746.                 } else {
  747.                     $errors[] = $error->getMessage();
  748.                 }
  749.             }
  750.             foreach ($form->all() as $child) {
  751.                 if (!$child->isValid()) {
  752.                     $errors[$child->getName()] = $this->getErrorMessages($child);
  753.                 }
  754.             }
  755.             return $errors;
  756.         }
  757.         
  758.         public function ComprobarStock($request$doctrine$carro)
  759.         {
  760.             $pedidos $carro->getPedidos();
  761. //             dump($carro);dump($pedidos);die();
  762.             $em $doctrine->getManager();
  763.             foreach ($pedidos as $pedido) {
  764. //                     $oficina = $carro->getOficina();
  765.                     $oficina $em->getRepository('App\Entity\Oficina')->findOneBy(array('id' => $carro->getOficina()->getId()));
  766.                     $divisa $pedido->getDivisaFinal();
  767.                     $StockMax $em->getRepository('App\Entity\Stock')->findOneBy(array('oficina' => $oficina'divisa' => $divisa));
  768.                     if ($StockMax) {
  769.                         
  770.                     } else {
  771.                         $this->addFlash(
  772.                             'danger',
  773.                             'La oficina ' $oficina->getNombre() . ' no dispone de stock de la moneda ' $divisa->getNombre()
  774.                         );
  775.                         return false;
  776.                     }
  777.             }
  778.             return true;
  779.         }
  780.         
  781.         #[Route(path: [
  782.             'es' => '/carro2',
  783.             'en' => '/en/cart2'
  784.         ], name'app_cart_2')]
  785.         public function Cart2Action(Request $request,PersistenceManagerRegistry $doctrineSettingsManager $smWebServiceUsuarios $wsuWebServiceFunciones $wsfMailer $mailer)
  786.         {
  787.             $locale $request->getLocale();
  788.             $em $doctrine->getManager();
  789.             // dump($sesion = $request->getSession());die();
  790.             
  791.             if ($request->query->has('t')) {
  792.                 $t $request->query->get('t');
  793.                 return $this->redirect($this->generateUrl('app_cart_3', ['t' => $t]));
  794.             }
  795.             if ($re $this->CartRedirect($request2)) {
  796.                 return $re;
  797.             }
  798. //             $options = $this->container->get('dinamic_settings.manager');
  799.             //Formulario de busqueda de cliente
  800.             // $formShortReg = $this->createFormBuilder()
  801.             //     ->add('DNI', NumberType::class, array(
  802.             //             'label' => false,
  803.             //             'attr' => array(
  804.             //                 'placeholder' => $sm->getValue('cart2.idnumber')
  805.             //             )
  806.             //         )
  807.             //     )
  808.             //     ->getForm();
  809.             //Formulario para usuarios venidos del ERP con correo
  810.             // $formCorreo = $this->createFormCorreo($sm);
  811.             //Formulario para usuarios venidos del ERP sin correo
  812.             // $formNoCorreo = $this->createFormNoCorreo($sm);
  813.             /****/
  814.             $formSinPago $this->createFormSinPago($sm);
  815.             /****/
  816.             try {
  817.                 $stepBread $this->StepControl($request);
  818. //                 $request = $this->get('request');
  819.                 $local $request->getLocale();
  820.                 $invitado = new Invitado();
  821.                 $options = ['settings' => $sm];
  822.                 $invitadoForm $this->createForm(InvitadoType::class, $invitado$options);
  823.                 /****/
  824.                 $nameLogeado null;
  825.                 $emailLogeado null;
  826.                 if ($this->getUser()) {
  827.                     // $this->setCart2($request, $em);
  828.                     // return $this->redirect($this->generateUrl('app_cart_3'));
  829.                     $nameLogeado $this->getUser()->getName();
  830.                     $emailLogeado $this->getUser()->getEmail();
  831.                 }
  832.                 /****/
  833.                 // $user = new User();
  834.                 // $loginForm = $this->createForm(LoginType::class, $user);
  835.                 //Usuario invitado
  836.                 $invitadoForm->handleRequest($request);
  837.                 if ($invitadoForm->isSubmitted()) {
  838.                     if ($invitadoForm->isValid()) {
  839.                         $this->setInvitado($request$invitado);
  840.                         return $this->redirect($this->generateUrl('app_cart_3'));
  841.                     }
  842.                 }
  843.                 //Registro de usuarios desde el ERP sin email
  844.     //             $formNoCorreo->handleRequest($request);
  845.     //             if ($formNoCorreo->isSubmitted()) {
  846.     //                 if ($formNoCorreo->isValid()) {
  847.     //                     $data = $formNoCorreo->getData();
  848.     // //                     $WSF = $this->container->get('web.service.funciones', $em);
  849.     //                     $userERP = $wsf->getClienteporNumId($data['Dni_correo_sin']);
  850.     //                     if ($userERP) {
  851.     //                         $wsf->modificarEmail($userERP, $data['email']);
  852.     //                         $user = new User();
  853.     //                         $user->setIdCard($data['Dni_correo_sin']);
  854.     //                         $user->setEmail($data['email']);
  855.     //                         $user->setPassword($data['password1']);
  856.     //                         $user->setPlainPassword($data['password1']);
  857.     //                         $user->setErpId($userERP);
  858.     //                         $user->setEnabled(1);
  859.     //                         $user->setIdiomaPreferido($request->getLocale());
  860.     // //                         $userManager = $this->container->get('fos_user.user_manager');
  861.     // //                         $userManager->updatePassword($user);
  862.     //                         $em->persist($user);
  863.     //                         $em->flush();
  864.     //                         $route = 'app_cart_3';
  865.     //                         $url = $this->container->get('router')->generate($route);
  866.     //                         $response = new RedirectResponse($url);
  867.     //                         $this->authenticateUser($user, $response);
  868.     //                         return $response;
  869.     //                     }
  870.     //                 }
  871.     //             }
  872.     //
  873.     //             //Registro de usuarios desde el ERP con email
  874.     //             $formCorreo->handleRequest($request);
  875.     //             if ($formCorreo->isSubmitted()) {
  876.     //                 if ($formCorreo->isValid()) {
  877.     //                     $data = $formCorreo->getData();
  878.     //                     if ($data['password1'] == $data['password2']) {
  879.     //                         $user = $em->getRepository('App\Entity\User')->findOneByUsernameCanonical(strtolower($data['Dni_correo_con']));
  880.     //                         if ($user && $user->getConfirmationToken() == $data['codigo_correo']) {
  881.     //                             $user->setPlainPassword($data['password1']);
  882.     //                             $user->setConfirmationToken(null);
  883.     //                             $user->setPasswordRequestedAt(null);
  884.     //                             $user->setIdiomaPreferido($request->getLocale());
  885.     //                             $em->persist($user);
  886.     //                             $em->flush();
  887.     //                             $route = 'app_cart_3';
  888.     //                             $url = $this->container->get('router')->generate($route);
  889.     //                             $response = new RedirectResponse($url);
  890.     //                             $this->authenticateUser($user, $response);
  891.     //                             return $response;
  892.     //                         }
  893.     //                     }
  894.     //                 }
  895.     //             }
  896.                 $carro $this->getCart($request);
  897.                 // dump($carro);die();
  898.                 $reserva $carro->getReserva();
  899.                 if(isset($_COOKIE['cookieoficina'])) {
  900.                     $ofi = (integer)($_COOKIE['cookieoficina']);
  901.                     if ($ofi == 1) {
  902.                         $ofi $this->getParameter('oficina_por_defecto');
  903.                     }
  904. //                     if (!$this->ComprobarStock($request, $doctrine, $carro, $ofi))
  905. //                         return $this->redirect($this->generateUrl('app_cart_1'));
  906.                 } else {
  907.                     $ofi $this->getParameter('oficina_por_defecto');
  908.                 }
  909.                 // dump($carro);die();
  910.                 /****/
  911.                 $sesion $request->getSession();
  912.                 $metodoEntrega $sesion->get('metodoEntrega');
  913.                 if ($metodoEntrega == 1) {
  914.                     $oficina $em->getRepository('App\Entity\Oficina')->findOneBy(['id' => $carro->getOficina()]);
  915.                     if ($oficina->permiteCompra()) {
  916.                         $gastosEnv 0;
  917.                     } else {
  918.                         $gastosEnv $oficina->getProvincia()->getGastos();
  919.                     }
  920.                     $nomOfi $oficina->getNombre();
  921.                 } else if ($metodoEntrega == 2) {
  922.                     $provDest $em->getRepository('App\Entity\Provincia')->findOneBy(['id' => $carro->getProvincia()]);
  923.                     $gastosEnv $provDest->getGastos();
  924.                     $nomOfi null;
  925.                 }
  926.                 $totalPagar 0;
  927.                 $vaAComprar '';
  928.                 $listResumen '';
  929.                 foreach ($carro->getPedidos() as $pedido) {
  930.                     // dump($pedido->getDivisaFinal()->getImagen()->getId());die();
  931.                     if ($totalPagar != 0) {
  932.                         $vaAComprar $vaAComprar ' + ' $pedido->getCantidadFinal() . ' ' $pedido->getDivisaFinal()->getNombre();
  933.                     } else {
  934.                         $vaAComprar $pedido->getCantidadFinal() . ' ' $pedido->getDivisaFinal()->getNombre();
  935.                     }
  936.                     $totalPagar $totalPagar $pedido->getCantidadOrigen();
  937.                     $imgDiv $em->getRepository('App\Entity\Imagen')->findOneBy(['id' => $pedido->getDivisaFinal()->getImagen()->getId()]);
  938.                     $providerName $imgDiv->getProviderReference();
  939.                     $listResumen $listResumen '<li><img src="/upload/media/divisa/0001/01/' $providerName '" width="30px"> <span>' $pedido->getCantidadFinal() . '</span> ' $pedido->getDivisaFinal()->getNombre() . '</li>';
  940.                 }
  941.                 if ($totalPagar >= 500) {
  942.                     $carro->setFreeShipping(1);
  943.                     $gastosEnv 0;
  944.                 }
  945.                 // $codProm =
  946.                 $formSinPago->handleRequest($request);
  947.                 if ($formSinPago->isSubmitted()) {
  948.                     if ($formSinPago->isValid()) {
  949.                         $data $formSinPago->getData();
  950.                         $transaccion = new Transaccion();
  951.                         $user $em->getRepository('App\Entity\User')->findOneBy(['email' => $data['email']]);
  952.                         if ($user) {
  953.                             $carro->setUsuario($user);
  954.                             $sesion->set('carro'$carro);
  955.                             $transaccion->setUsuario($user);
  956.                         }
  957.                         $timestamp = (new \DateTime())->format('Y-m-d H:i:s');
  958.                         $base $data['email'] . '||' $timestamp;
  959.                         $random bin2hex(random_bytes(16));
  960.                         $token hash('sha256'$base '||' $random);
  961.                         $transaccion->setTokenEmail($token);
  962.                         $transaccion->setTitular($data['nombre']);
  963.                         $transaccion->setEmailTitular($data['email']);
  964.                         $transaccion->setTelefono($data['telefono']);
  965.                         if ($metodoEntrega == 1) {
  966.                             $oficina $em->getRepository('App\Entity\Oficina')->findOneBy(['id' => $ofi]);
  967.                             $transaccion->setOficina($oficina);
  968.                         } else if ($metodoEntrega == 2) {
  969.                             $transaccion->setProvincia($provDest);
  970.                         }
  971.                         $transaccion->setCupon($carro->getCodigoPromo());
  972.                         $transaccion->setTipoPromo($carro->getTipoPromo());
  973.                         $transaccion->setEstado('En pasarela de pago');
  974.                         $transaccion->setTipoPago('TPV');
  975.                         foreach ($carro->getPedidos() as $pedido) {
  976.                             $transaccionLinea = new TransaccionLinea();
  977.                             $transaccionLinea->setDivisaDestino($em->getReference('App\Entity\Divisa'$pedido->getDivisaFinal()->getId()));
  978.                             $transaccionLinea->setCantidad($pedido->getCantidadFinal());
  979.                             $transaccionLinea->setErpCode($pedido->getErpCode());
  980.                             $transaccion->addLinea($transaccionLinea);
  981.                         }
  982.                         $transaccion->setTotalLineas($totalPagar);
  983.                         $transaccion->setGastosEnvio((float)$gastosEnv);
  984.                         $transaccion->setTotal($totalPagar $gastosEnv);
  985.                         $transaccion->setIdioma(strtoupper($locale));
  986.                         // dump($transaccion->getTotal());die();
  987.                         $sesion->set('transaccion'$transaccion);
  988.                         $em->persist($transaccion);
  989.                         $em->flush();
  990.                         // dump($transaccion);die();
  991.                         $redsysData $this->buildRedsys($request$transaccion);
  992.                         $formTPV $this->container->get('form.factory')->createNamedBuilder(''FormType::class, array(), array(
  993.                             'action' => $this->getParameter('redsys_gateway'),
  994.                             'method' => 'POST',
  995.                             'csrf_protection' => false,
  996.                             'attr' => array('name' => 'tpv''id' => 'formTPV'),
  997.                         ))
  998.                             ->add('Ds_SignatureVersion'HiddenType::class, ['data' => $this->getParameter('redsys_version')])
  999.                             ->add('Ds_MerchantParameters',  HiddenType::class, ['data' => $redsysData['params']])
  1000.                             ->add('Ds_Signature'HiddenType::class, ['data' => $redsysData['signature']])
  1001.                             ->getForm();
  1002.                         return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
  1003.                     }
  1004.                 }
  1005.                 /****/
  1006.                 // dump($gastosEnv + $totalPagar);die();
  1007.                 $returnArray = array(
  1008.                     // 'loginForm' => $loginForm->createView(),
  1009.                     'stepBread' => $stepBread,
  1010.                     // 'formShortReg' => $formShortReg->createView(),
  1011. //                     'fullForm' => $fullForm->createView(),
  1012.                     // 'formCorreo' => $formCorreo->createView(),
  1013.                     // 'formNoCorreo' => $formNoCorreo->createView(),
  1014.                     'clienteInvitado' => $invitadoForm->createView(),
  1015.                     'sm' => $sm,
  1016.                     'reserva' => $reserva,
  1017.                     'currentStep' => 2,
  1018.                     /****/
  1019.                     'formSinPago' => $formSinPago->createView(),
  1020.                     'metodoEntrega' => $metodoEntrega,
  1021.                     'gastosEnv' => $gastosEnv,
  1022.                     'totalPagar' => $totalPagar,
  1023.                     'vaAComprar' => $vaAComprar,
  1024.                     'codProm' => $carro->getCodigoPromo(),
  1025.                     'listResumen' => $listResumen,
  1026.                     'nameLogeado' => $nameLogeado,
  1027.                     'emailLogeado' => $emailLogeado,
  1028.                     'nomOfi' => $nomOfi
  1029.                     /****/
  1030.                 );
  1031.                 
  1032.                 return $this->render('default/carrito/carrito2.html.twig'$returnArray);
  1033.                 
  1034.             } catch (\Exception $e) {
  1035.                 if ($this->kernel->getEnvironment() == 'dev') throw $e;
  1036.                 $this->resetCart($request);
  1037.                 $catcher $this->container->get('web.service.catchException');
  1038.                 $log = new Log();
  1039.                 $log->setLocation('carro2');
  1040.                 $log->setUser($this->getUser());
  1041.                 $log->setText(json_encode($e->getTrace()));
  1042.                 $error $e->getMessage();
  1043.                 $catcher->saveException($log);
  1044.                 return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $error'currentStep' => 5));
  1045.             }
  1046.         }
  1047.         
  1048.         
  1049.         /**
  1050.         * @return Carro
  1051.         */
  1052.         private function getCart($request)
  1053.         {
  1054.             $sesion $request->getSession();
  1055.             return $sesion->get('carro');
  1056.         }
  1057.         
  1058.         
  1059.         public function CartRedirect(Request $request$paso)
  1060.         {
  1061.             $local $request->getLocale();
  1062.             $sesion $request->getSession();
  1063.             $cartStep $sesion->get('cartStep');
  1064.             // dump($cartStep);
  1065.             // dump($paso);
  1066.             // die();
  1067.             if ($logeado $this->authorizationChecker->isGranted('ROLE_ADMIN')) {
  1068.                 $this->addFlash(
  1069.                     'danger',
  1070.                     'Tu usuario no permite realizar compras (ADMIN)'
  1071.                 );
  1072.                 $response $this->redirect($this->generateUrl('app_cart_1'));
  1073.                 return $response;
  1074.             }
  1075.             if ($cartStep == null) {
  1076.                 //No ha hecho nada
  1077.                 $response $this->redirect($this->generateUrl('app_cart_1'));
  1078.                 return $response;
  1079.             } elseif ($paso and (!isset($cartStep[1]) or !$cartStep[1])) {
  1080.                 //No ha completado el primer paso
  1081.                 $response $this->redirect($this->generateUrl('app_cart_1'));
  1082.                 return $response;
  1083.             } elseif ($paso and (!isset($cartStep[2]) or !$cartStep[2])) {
  1084.                 //No ha completado el segundo paso
  1085.                 $response $this->redirect($this->generateUrl('app_cart_2'));
  1086.                 return $response;
  1087.             } elseif ($paso and (!isset($cartStep[3]) or !$cartStep[3])) {
  1088.                 //No ha completado el tercer paso
  1089.                 $response $this->redirect($this->generateUrl('app_cart_3'));
  1090.                 return $response;
  1091.             }
  1092.             $response false;
  1093.             return $response;
  1094.         }
  1095.         
  1096.         private function SaveCartShop(Request $request$carro3)
  1097.         {
  1098.             $sesion $request->getSession();
  1099.             //Validamos el paso 3
  1100.             $cartStep $sesion->get('cartStep');
  1101.             $cartStep[3] = true;
  1102.             $sesion->set('cartStep'$cartStep);
  1103.             //Guardamos los datos de la tienda
  1104.             $carro $sesion->get('carro');
  1105.             $carro->setOficina($carro3->getOficina());
  1106.             $carro->setFechaEntrega($carro3->getFechaEntrega());
  1107.             $carro->setHoraEntrega($carro3->getHoraEntrega());
  1108.             $carro->setComentario($carro3->getComentario());
  1109.             //Reset del otro metodo de entrega
  1110.             $carro->setDireccion(NULL);
  1111.             $carro->setCodigoPostal(NULL);
  1112.             $carro->setCiudad(NULL);
  1113.             $carro->setProvincia(NULL);
  1114.             $carro->setPais(NULL);
  1115.             $carro->setTipoPago($carro3->getTipoPago());
  1116. //             dump($carro3);die();
  1117.             $carro->setTitular($carro3->getTitular());
  1118.             $sesion->set('carro'$carro);
  1119.         }
  1120.         
  1121.         private function SaveDeliver(Request $request$carro3)
  1122.         {
  1123.             $sesion $request->getSession();
  1124.             $cartStep $sesion->get('cartStep');
  1125.             $cartStep[3] = true;
  1126.             $sesion->set('cartStep'$cartStep);
  1127.             //Guardamos la direccion de la tienda
  1128.             $carro $sesion->get('carro');
  1129.             $carro->setDireccion($carro3->getDireccion());
  1130.             $carro->setCodigoPostal($carro3->getCodigoPostal());
  1131.             $carro->setCiudad($carro3->getCiudad());
  1132.             $carro->setProvincia($carro3->getProvincia());
  1133.             $carro->setPais($carro3->getPais());
  1134.             $carro->setComentario($carro3->getComentario());
  1135.             $carro->setNameSend($carro3->getNameSend());
  1136.             $carro->setCardSend($carro3->getCardSend());
  1137.             //Reset del otro metodo de entrega
  1138.             $carro->setOficina(NULL);
  1139.             $carro->setFechaEntrega(NULL);
  1140.             $carro->setHoraEntrega(NULL);
  1141.             $carro->setTipoPago($carro3->getTipoPago());
  1142.             $carro->setTitular($carro3->getTitular());
  1143.             $sesion->set('carro'$carro);
  1144.         }
  1145.         #[Route(path: [
  1146.             'es' => '/carro3',
  1147.             'en' => '/en/cart3'
  1148.         ], name'app_cart_3')]
  1149.         public function Cart3Action(Request $requestPersistenceManagerRegistry $doctrineSettingsManager $sm,  WebServiceTPV $wstpvWebServiceFunciones $wsf)
  1150.         {
  1151.             try {
  1152.                 if ($request->query->has('t')) {
  1153.                     $em $doctrine->getManager();
  1154.                     $t $request->query->get('t');
  1155.                     $transaccion $em->getRepository('App\Entity\Transaccion')->findOneBy(['tokenEmail' => $t]);
  1156.                 } else {
  1157.                     return $this->redirect($this->generateUrl('app_cart_1'));
  1158.                 }
  1159.                 if ($transaccion && $transaccion->getEstado() == 'En pasarela de pago') {
  1160.                     $redsysData $this->buildRedsys($request$transaccion);
  1161.                     $formTPV $this->container->get('form.factory')->createNamedBuilder(''FormType::class, array(), array(
  1162.                         'action' => $this->getParameter('redsys_gateway'),
  1163.                         'method' => 'POST',
  1164.                         'csrf_protection' => false,
  1165.                         'attr' => array('name' => 'tpv''id' => 'formTPV'),
  1166.                     ))
  1167.                         ->add('Ds_SignatureVersion'HiddenType::class, ['data' => $this->getParameter('redsys_version')])
  1168.                         ->add('Ds_MerchantParameters',  HiddenType::class, ['data' => $redsysData['params']])
  1169.                         ->add('Ds_Signature'HiddenType::class, ['data' => $redsysData['signature']])
  1170.                         ->getForm();
  1171.                     return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
  1172.                 }
  1173.                 
  1174.                 //limpiamos el carro par no tenerlo ahĆ­, ya que la transaccion estĆ” creada
  1175.                 $this->resetCart($request);
  1176.                 if ($transaccion && ($transaccion->getFechaRecogida() != null || $transaccion->getDireccionCompleta() != null)) {
  1177.                     return $this->redirect($this->generateUrl('app_cart_5', ['t' => $transaccion->getTokenEmail()]));
  1178.                 }
  1179.                 // dump($transaccion);die();
  1180.                 //Redirect is something failed
  1181.                 // if ($re = $this->CartRedirect($request, 3)) {
  1182.                 //     return $re;//$this->CartRedirect($request, 3);
  1183.                 // }
  1184.                 // $carro = $this->getCart($request);
  1185.                 $json $this->getHorariosAction($request$em);
  1186.                 // $pedido = new Pedido();
  1187.                 // $nCarro = new Carro();
  1188.                 
  1189.                 $formShortReg $this->createFormBuilder()
  1190.                     ->add('DNI'NumberType::class, array(
  1191.                             'label' => false,
  1192.                             'attr' => array(
  1193.                                 'placeholder' => $sm->getValue('cart2.idnumber')
  1194.                             )
  1195.                         )
  1196.                     )
  1197.                     ->getForm();
  1198.                 $user = new User();
  1199.                 $loginForm $this->createForm(LoginType::class, $user);
  1200.                 if ($this->getUser()) {
  1201.                     $userLog true;
  1202.                 } else {
  1203.                     $userLog false;
  1204.                 }
  1205.                 //HACKS para que la divisa pase la validación del carro
  1206.                 // $pedido->setDivisaOrigen($em->getRepository('App\Entity\Divisa')->findOneByMaestro(1));
  1207.                 // $nCarro->setReserva(1);
  1208.                 // $formShop = $this->createForm(CartShop::class, $nCarro, array('carro' => $carro));
  1209.                 // $formDeliver = $this->createForm(CartDeliver::class, $nCarro);
  1210.                 $nTransaccion = new Transaccion();
  1211.                 $formShop $this->createForm(TransactionType::class, $nTransaccion);
  1212.                 $formDeliver $this->createForm(CartDeliver::class, $nTransaccion, array('transaccion' => $transaccion));
  1213.                 // $stepBread = $this->StepControl($request);
  1214.                 $local $request->getLocale();
  1215.                 $total $transaccion->getTotalLineas();
  1216.                 $ahora = new \DateTime('now');
  1217.                 $domingo false;
  1218.                 if ($ahora->format('N') == 7) {
  1219.                     $domingo true;
  1220.                 }
  1221.                 $totalEntregar 0;
  1222.                 foreach ($transaccion->getLineas() as $linea) {
  1223.                     $totalEntregar $totalEntregar $linea->getCantidad();
  1224.                 }
  1225.                 $listResumen '';
  1226.                 foreach ($transaccion->getLineas() as $linea) {
  1227.                     $imgDiv $em->getRepository('App\Entity\Imagen')->findOneBy(['id' => $linea->getDivisaDestino()->getImagen()->getId()]);
  1228.                     $providerName $imgDiv->getProviderReference();
  1229.                     $listResumen $listResumen '<li><img src="/upload/media/divisa/0001/01/' $providerName '" width="30px"> <span>' $linea->getCantidad() . '</span> ' $linea->getDivisaDestino()->getNombre() . '</li>';
  1230.                 }
  1231.                 if($transaccion->getOficina() != null){
  1232.                     $ofi $transaccion->getOficina()->getId();
  1233.                     $festivos $em->getRepository("App\Entity\DayOff")->findBy(array('oficina' => $ofi));
  1234.                 } else {
  1235.                     $ofi = (integer)0;
  1236.                     $festivos $em->getRepository("App\Entity\DayOff")->findBy(array('oficina' => $ofi));
  1237.                 }
  1238.                 $oficina $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => $ofi));
  1239.                 if (!$oficina) {
  1240.                     $oficina $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => 20));
  1241.                 }
  1242.                 
  1243.                 if ($request->getMethod() == 'POST') {
  1244.     //
  1245.                     //Pasamos los datos del carro 1 a la validacion del formulario
  1246.                     // $formShop->getData()->setPedidos($carro->getPedidos());
  1247.                     // $formShop->getData()->setReserva($carro->getReserva());
  1248.                     $formShop->handleRequest($request);
  1249.                     
  1250.                     $currentDateTime = new \DateTime('now');
  1251.                     $currentTime $currentDateTime->format('H:i');
  1252.                     
  1253.                     // Restricciones de recogida si son Libra o Dolar Estadounidense
  1254.                     if ($currentTime '14:00') {
  1255.                         if ($currentDateTime->format('N') == 5) {                      // Si el pedido entra Viernes por la maƱana
  1256.                             $currentDateTime->add(new \DateInterval('P3D'));
  1257.                         } elseif ($currentDateTime->format('N') == 6){                 // Si el pedido entra SĆ”bado por la maƱana
  1258.                             $currentDateTime->add(new \DateInterval('P2D'));
  1259.                         } else {                                                       // Si el pedido entra de Domingo a Jueves, por la maƱana
  1260.                             $currentDateTime->add(new \DateInterval('P1D'));
  1261.                         }
  1262.                     } else {
  1263.                         if ($currentDateTime->format('N') == 4) {                      // Si el pedido entra Jueves por la tarde
  1264.                             $currentDateTime->add(new \DateInterval('P4D'));
  1265.                             $currentDateTime->setTime(120);
  1266.                         } elseif ($currentDateTime->format('N') == 5){                 // Si el pedido entra Viernes por la tarde
  1267.                             $currentDateTime->add(new \DateInterval('P4D'));
  1268.                             $currentDateTime->setTime(120);
  1269.                         } elseif ($currentDateTime->format('N') == 6){                 // Si el pedido entra SĆ”bado por la tarde
  1270.                             $currentDateTime->add(new \DateInterval('P3D'));
  1271.                             $currentDateTime->setTime(120);
  1272.                         } else {                                                       // Si el pedido entra de Domingo a MiĆ©rcoles, por la tarde
  1273.                             $currentDateTime->add(new \DateInterval('P2D'));
  1274.                             $currentDateTime->setTime(120);
  1275.                         }
  1276.                     }
  1277.                     $restriccionDivisa false;
  1278.                     foreach ($transaccion->getLineas() as $linea) {
  1279.                         if ($linea->getDivisaDestino()->getId() != 24 && $linea->getDivisaDestino()->getId() != 12) {
  1280.                             $restriccionDivisa true;
  1281.                         }
  1282.                     }
  1283.                     // Restricciones de recogida si NO son ni Libra ni Dolar Estadounidense
  1284.                     if ($restriccionDivisa) {
  1285.                         $fechaRestriccion = new \DateTime('now');
  1286.                         // $fechaRestriccion->add(new \DateInterval('P2D'));
  1287.                         $currentTime $fechaRestriccion->format('H:i');
  1288.                         if ($currentTime '14:00') {
  1289.                             if ($fechaRestriccion->format('N') == 4) {                      // Si el pedido entra Jueves por la maƱana
  1290.                                 $fechaRestriccion->add(new \DateInterval('P4D'));
  1291.                             } elseif ($fechaRestriccion->format('N') == 5) {                // Si el pedido entra Viernes por la maƱana
  1292.                                 $fechaRestriccion->add(new \DateInterval('P4D'));
  1293.                             } elseif ($fechaRestriccion->format('N') == 6){                 // Si el pedido entra SĆ”bado por la maƱana
  1294.                                 $fechaRestriccion->add(new \DateInterval('P3D'));
  1295.                             } else {                                                        // Si el pedido entra de Domingo a Miercoles, por la maƱana
  1296.                                 $fechaRestriccion->add(new \DateInterval('P2D'));
  1297.                             }
  1298.                         } else {
  1299.                             if ($fechaRestriccion->format('N') == 3) {                      // Si el pedido entra MiĆ©rcoles por la tarde
  1300.                                 $fechaRestriccion->add(new \DateInterval('P5D'));
  1301.                                 $fechaRestriccion->setTime(120);
  1302.                             } elseif ($fechaRestriccion->format('N') == 4) {                // Si el pedido entra Jueves por la tarde
  1303.                                 $fechaRestriccion->add(new \DateInterval('P5D'));
  1304.                                 $fechaRestriccion->setTime(120);
  1305.                             } elseif ($fechaRestriccion->format('N') == 5){                 // Si el pedido entra Viernes por la tarde
  1306.                                 $fechaRestriccion->add(new \DateInterval('P5D'));
  1307.                                 $fechaRestriccion->setTime(120);
  1308.                             } elseif ($fechaRestriccion->format('N') == 6){                 // Si el pedido entra SĆ”bado por la tarde
  1309.                                 $fechaRestriccion->add(new \DateInterval('P4D'));
  1310.                                 $fechaRestriccion->setTime(120);
  1311.                             } else {                                                        // Si el pedido entra de Domingo a Martes, por la tarde
  1312.                                 $fechaRestriccion->add(new \DateInterval('P3D'));
  1313.                                 $fechaRestriccion->setTime(120);
  1314.                             }
  1315.                         }
  1316.                         if ($fechaRestriccion $currentDateTime) {
  1317.                             $currentDateTime $fechaRestriccion;
  1318.                         }
  1319.                     }
  1320.                     
  1321.                     
  1322.                     // $carro->setFechaDisponible($currentDateTime);
  1323.                     
  1324.                     //Formulario de oficina
  1325.                     if ($formShop->isSubmitted()) {
  1326.                         if ($formShop->isValid()) {
  1327.                             // $this->SaveCartShop($request, $nCarro);
  1328.                             if($transaccion->getOficina() != null) {
  1329.                                 foreach($festivos as $fest) {
  1330.                                     if ($nTransaccion->getFechaRecogida()->format('d/m/y') == $fest->getDate()->format('d/m/y')) {
  1331.                                         $this->addFlash(
  1332.                                             'danger',
  1333.                                             'El dia seleccionado es festivo en esta oficina.'
  1334.                                         );
  1335.                                         return $this->redirect($this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()]));
  1336.                                     }
  1337.                                 }
  1338.                                 $fecha $nTransaccion->getFechaRecogida()->format('Y-m-d');
  1339.                                 $hora $nTransaccion->getHoraRecogida();
  1340.                                 $fechaHoraRecogida = new \DateTime("$fecha $hora"$nTransaccion->getFechaRecogida()->getTimezone());
  1341.                                 if ($totalEntregar >= 50 || !$transaccion->getOficina()->permiteCompra()) {
  1342.                                     if ($fechaHoraRecogida $currentDateTime) {
  1343.                                         $this->addFlash(
  1344.                                             'danger',
  1345.                                             'El dia seleccionado es anterior a la fecha en la que estarĆ” disponible el pedido. EstarĆ” listo a partir del dĆ­a ' $currentDateTime->format("d/m/y") . ' a las ' $currentDateTime->format("H:i")
  1346.                                         );
  1347.                                         return $this->redirect($this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()]));
  1348.                                     }
  1349.                                 } else if ($restriccionDivisa) {
  1350.                                     $this->addFlash(
  1351.                                         'danger',
  1352.                                         'El dia seleccionado es anterior a la fecha en la que estarĆ” disponible el pedido. EstarĆ” listo a partir del dĆ­a ' $currentDateTime->format("d/m/y") . ' a las ' $currentDateTime->format("H:i")
  1353.                                     );
  1354.                                     return $this->redirect($this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()]));
  1355.                                 }
  1356.                             }
  1357.                             // dump('Ha pasado el flash');die();
  1358.                             $transaccion->setUsuario($this->getUser());
  1359.                             $transaccion->setFechaRecogida($nTransaccion->getFechaRecogida());
  1360.                             $hora \DateTime::createFromFormat('H:i'$nTransaccion->getHoraRecogida());
  1361.                             $transaccion->setHoraRecogida($hora);
  1362.                             $transaccion->setAnotacion($nTransaccion->getAnotacion());
  1363.                             $transaccion->setEmailTitular($this->getUser()->getEmail());
  1364.                             // dump($transaccion);die();
  1365.                             $em->persist($transaccion);
  1366.                             $em->flush();
  1367.                             
  1368.                             return $this->redirect($this->generateUrl('app_cart_5', ['t' => $transaccion->getTokenEmail()]));
  1369.                         }
  1370.                     }
  1371.                     //Formulario de envio
  1372.                     $formDeliver->handleRequest($request);
  1373.                     if ($formDeliver->isSubmitted()) {
  1374.                         if ($formDeliver->isValid()) {
  1375.                             // $this->SaveDeliver($request, $nCarro);
  1376.                             $transaccion->setUsuario($this->getUser());
  1377.                             $transaccion->setDireccionCompleta($nTransaccion->getDireccionCompleta());
  1378.                             $transaccion->setCodigoPostal($nTransaccion->getCodigoPostal());
  1379.                             $transaccion->setCiudad($nTransaccion->getCiudad());
  1380.                             $transaccion->setPais($nTransaccion->getPais());
  1381.                             $transaccion->setAnotacion($nTransaccion->getAnotacion());
  1382.                             $transaccion->setCardSend($nTransaccion->getCardSend());
  1383.                             $transaccion->setNameSend($nTransaccion->getNameSend());
  1384.                             $transaccion->setEmailTitular($this->getUser()->getEmail());
  1385.                             // dump($transaccion);die();
  1386.                             $em->persist($transaccion);
  1387.                             $em->flush();
  1388.                             $response $this->redirect($this->generateUrl('app_cart_5', ['t' => $transaccion->getTokenEmail()]));
  1389.                             
  1390.                             return $response;
  1391.                         }
  1392.                     }
  1393.                 }
  1394.                 // foreach($oficina->getDayoffs() as $dayo) {
  1395.                 //     dump($dayo);
  1396.                 // }
  1397.                 // die();
  1398.                 $provincias $em->getRepository("App\Entity\Provincia")->findAll();
  1399.                 $localidades $em->getRepository("App\Entity\Localidad")->findAll();
  1400.                 $metodosPago $em->getRepository("App\Entity\MetodoPago")->findBy([], ['position' => 'ASC']);
  1401.                 
  1402.                 // $totalEntregar = 0;
  1403.                 // foreach ($carro->getPedidos() as $pedido) {
  1404.                 //     $totalEntregar = $totalEntregar + $pedido->getCantidadFinal();
  1405.                 // }
  1406.                 
  1407. //                 $metodosPagoJson = [];
  1408. //                 foreach($metodosPago as $d)
  1409. //                     $metodosPagoJson[$d->getId()] = [
  1410. //                         'activo' => $d->isActivo(),
  1411. //                         'nombre' => $d->getNombre(),
  1412. //                     ];
  1413. //                 dump($metodosPagoJson);die();
  1414.                 
  1415.                 return $this->render('default/carrito/carrito3.html.twig', array(
  1416.                     // 'stepBread' => $stepBread,
  1417.                     // 'carro' => $carro,
  1418.                     'formShop' => $formShop->createView(),
  1419.                     'formDeliver' => $formDeliver->createView(),
  1420.                     'json' => $json,
  1421.                     'localidades' => $localidades,
  1422.                     'provincias' => $provincias,
  1423.                     'ofi_var' => $ofi,
  1424.                     'sm' => $sm,
  1425.                     'currentStep' => 3,
  1426.                     'total' => $total,
  1427.                     'ofii' => $oficina,
  1428.                     'metodosPago' =>$metodosPago,
  1429.                     'festivos' => $festivos,
  1430.                     'totalEntregar' => $totalEntregar,
  1431.                     'domingo' => $domingo,
  1432.                     'loginForm' => $loginForm->createView(),
  1433.                     'formShortReg' => $formShortReg->createView(),
  1434.                     'userLog' => $userLog,
  1435.                     'transaccion' => $transaccion,
  1436.                     'listResumen' => $listResumen,
  1437.                 ));
  1438.             } catch (\Exception $e) {
  1439.                 if ($this->kernel->getEnvironment() == 'dev') throw $e;
  1440.                 $this->resetCart($request);
  1441.                 $this->deleteErpSale($carro,$wstpv);
  1442.                 $catcher $this->container->get('web.service.catchException');
  1443.                 $log = new Log();
  1444.                 $log->setLocation('carro3');
  1445.                 $log->setUser($this->getUser());
  1446.                 $log->setText(json_encode($e->getTrace()));
  1447.                 $error $e->getMessage();
  1448.                 $catcher->saveException($log);
  1449.                 return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $error'currentStep' => 5));
  1450.             }
  1451.         }
  1452.         
  1453.         
  1454.         public function obtenerDatosOficina($idPersistenceManagerRegistry $doctrineSettingsManager $smRequest $request)
  1455.         {
  1456.             $em $doctrine->getManager();
  1457.             $oficina $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => $id));
  1458.             $festivos $em->getRepository("App\Entity\DayOff")->findBy(array('oficina' => $id));
  1459.             $carro $this->getCart($request);
  1460.             $totalEntregar 0;
  1461.             foreach ($carro->getPedidos() as $pedido) {
  1462.                 $totalEntregar $totalEntregar $pedido->getCantidadFinal();
  1463.             }
  1464.             $ahora = new \DateTime('now');
  1465.             $domingo false;
  1466.             if ($ahora->format('N') == 7) {
  1467.                 $domingo true;
  1468.             }
  1469. //             dump($totalEntregar);die();
  1470.             
  1471.             return $this->render('default/carrito/horarioOficina.html.twig', array(
  1472.                     'ofii' => $oficina,
  1473.                     'festivos' => $festivos,
  1474.                     'sm' => $sm,
  1475.                     'totalEntregar' => $totalEntregar,
  1476.                     'domingo' => $domingo,
  1477.                 ));
  1478.         }
  1479.         
  1480.         public function comprobarTitular(Request $request)
  1481.         {
  1482.             $igual 'No igual';
  1483.             try{
  1484.                 $user $this->getUser();
  1485.                 $titular $request->request->get('titular');
  1486.                 
  1487.                 /*$palabrasTitutar = explode(' ', $titular);
  1488.                 $palabrasUser = explode(' ', $user->getName());
  1489.                 $nomTitular = strtolower($palabrasTitutar[0]);
  1490.                 $nomUser = strtolower($palabrasUser[0]);*/
  1491.                 $nomUser mb_strtolower($user->getName());
  1492.                 $nomTitular mb_strtolower($titular);
  1493.                 
  1494.                 if ($nomUser == $nomTitular) {
  1495.                     $igual 'Igual';
  1496.                 }
  1497.             } catch (\Exception $e) {
  1498.                 return new JsonResponse(['error' => $e->getMessage()], 500);
  1499.             }
  1500.             
  1501.             return new Response($igual);
  1502.         }
  1503.         
  1504.         
  1505.         /**
  1506.         * Tras realizar la compra actualizamos el stock
  1507.         * de la tienda
  1508.         * @param $carro
  1509.         * @throws \Exception
  1510.         */
  1511.         public function ActualizarStock($doctrine$carro)
  1512.         {
  1513.             $pedidos $carro->getPedidos();
  1514.             $divisas = array();
  1515.             $em $doctrine->getManager();
  1516.             $repo $em->getRepository('App\Entity\Existencia');
  1517.             foreach ($pedidos as $pedido) {
  1518.                 $Existencia $repo->findOneBy(array('oficina' => $carro->getOficina(), 'dia' => $carro->getFechaEntrega(), 'divisa' => $pedido->getDivisaFinal()));
  1519.                 //La validacion del stock se realiza en el carro 1 y 3
  1520.                 //Una vez llegados aqui damos por senteado que no estĆ”
  1521.                 //haciendo nada raro con el stock
  1522.                 if ($Existencia) {
  1523.                     //Si ya estĆ” en la tabla de stock se resta la cantidad actual
  1524.                     $stock $Existencia->getCantidad();
  1525.                     $resta $stock $pedido->getCantidadFinal();
  1526.                     $Existencia->setCantidad($resta);
  1527.                     $em->persist($Existencia);
  1528.                     $em->flush();
  1529.                 } else {
  1530.                     //Si no estĆ” en la tabla de stocks se crea una nueva fila y
  1531.                     //se resta la cantidad final
  1532.                     $Existencia = new Existencia();
  1533.                     $oficina $carro->getOficina();
  1534.                     $divisa $pedido->getDivisaFinal();
  1535.                     $StockMax $em->getRepository('App\Entity\Stock')->findOneBy(array('oficina' => $oficina'divisa' => $divisa));
  1536.                     if ($StockMax) {
  1537.                         $resta $StockMax->getStockMaximo() - $pedido->getCantidadFinal();
  1538.                         $Existencia->setDivisa($em->getReference('App\Entity\Oficina'$divisa->getId()));
  1539.                         $Existencia->setOficina($em->getReference('App\Entity\Oficina'$carro->getOficina()->getId()));
  1540.                         $Existencia->setCantidad($resta);
  1541.                         $Existencia->setDia($carro->getFechaEntrega());
  1542.                         if (!$em->isOpen()) {
  1543.                             "NO Esta abierta";
  1544.                         }
  1545.                         $em->persist($Existencia);
  1546.                         $em->flush();
  1547.                     } else {
  1548. //                         throw new \Exception('La oficina: [' . $oficina . '] no dispone de stock de la mondea:[' . $divisa->getNombre() . ']');
  1549.                     }
  1550.                 }
  1551.             }
  1552.         }
  1553.         
  1554.         
  1555.         /**
  1556.         * Saca la Reserva del carro, la persiste en el ERP y en local.
  1557.         * Y manda el correo de notificación al usuario
  1558.         * @param Carro $carro carro de compra
  1559.         * @return Reserva Estado de la operación
  1560.         * @throws \Exception Fallo en el ERP
  1561.         *
  1562.         */
  1563.         private function persistBooking(PersistenceManagerRegistry $doctrineWebServiceUsuarios $wsuWebServiceFunciones $wsfMailer $mailer$carro)
  1564.         {
  1565.             $em $doctrine->getManager();
  1566. //             $WSF = $this->container->get('web.service.funciones', $em);
  1567. //             $WSU = $this->container->get('web.service.usuarios', $em);
  1568. //             $mailer = $this->container->get('dinamic_shop.mailer');
  1569.             if ($this->getUser()) {
  1570.                 $userERP $this->getUser()->getErpId();
  1571.             } else {
  1572.                 $userERP 'INVITADO';
  1573.             }
  1574.             $Reserva = new Reserva();
  1575.             //PEDIDO DE USUARIO REGISTRADO
  1576.             if ($userERP != 'INVITADO') {
  1577.                 $clienteERP $wsu->findOne($userERP);
  1578.                 $Reserva->setUsuario($em->getReference('App\Entity\User'$this->getUser()->getId()));
  1579.                 $tipoC 'USUARIO';
  1580.             } //PEDIDO DE USUARIO INVITADO
  1581.             else {
  1582.                 $tipoC 'INVITADO';
  1583.                 $Reserva->setNombre($carro->getInvitado()->getNombre());
  1584.                 $Reserva->setApellido($carro->getInvitado()->getApellidos());
  1585.                 $Reserva->setTelefono($carro->getInvitado()->getTelefono());
  1586.                 $Reserva->setEmail($carro->getInvitado()->getEmail());
  1587.                 $clienteERP $carro->getInvitado();
  1588.             }
  1589.             $oficina $em->getRepository("App\Entity\Oficina")->findOneById($carro->getOficina()->getId());
  1590.             $Reserva->setOficina($em->getReference('App\Entity\Oficina'$oficina->getId()));
  1591.             $Reserva->setHoraRecogida($carro->getHoraEntrega());
  1592.             $Reserva->setCupon($carro->getCodigoPromo());
  1593.             $Reserva->setFechaRecogida($carro->getFechaEntrega());
  1594.             $Reserva->setEstado('ACEPTADA');
  1595.             $carro->setOficina($oficina);
  1596.             $cupon $carro->getCodigoPromo();
  1597.             $rep_cup $em->getRepository('App\Entity\Cupon')->findOneBy(['codigo'=>$cupon]);
  1598.             if($rep_cup){
  1599.             $aux $rep_cup->getTotalUsos();
  1600.             $rep_cup->setTotalUsos($aux-1);
  1601.             $em->persist($rep_cup);
  1602.             }
  1603.             //Mandamos linea a linea la reserva y la guardamos en
  1604.             //la BBDD
  1605.             foreach ($carro->getPedidos() as $linea) {
  1606.                 $respuesta $wsf->RegistrarReserva($carro$linea$clienteERP$tipoC);
  1607.                 if ($respuesta) {
  1608.                     $ReservaLinea = new ReservaLinea();
  1609.                     $ReservaLinea->setErpCode($respuesta);
  1610.                     $ReservaLinea->setDivisaOrigen($em->getReference('App\Entity\Divisa'$linea->getDivisaOrigen()->getId()));
  1611.                     $ReservaLinea->setDivisaDestino($em->getReference('App\Entity\Divisa'$linea->getDivisaFinal()->getId()));
  1612.                     $ReservaLinea->setCantidad($linea->getCantidadFinal());
  1613.                     $Reserva->addLinea($ReservaLinea);
  1614.                     $em->persist($ReservaLinea);
  1615.                 } else {
  1616.                     throw new \Exception("Fallo al registrar al reserva");
  1617.                 }
  1618.             }
  1619.             $em->persist($Reserva);
  1620.             $em->flush($Reserva);
  1621.             if ($tipoC == 'INVITADO') {
  1622.                 $mailer->successReserve(NULL$Reserva);
  1623.             } else {
  1624.                 $mailer->successReserve($this->getUser(), $Reserva);
  1625.             }
  1626.             return $Reserva;
  1627.         }
  1628.         /**
  1629.         * Actualiza la transacción en la base de datos
  1630.         * @param $request
  1631.         * @param $estado
  1632.         * @return Transaccion
  1633.         */
  1634.         private function persistTransaccion($doctrine$request$estado)
  1635.         {
  1636.             $em $doctrine->getManager();
  1637.             $sesion $request->getSession();
  1638.             /** @var Carro $carro */
  1639.             $carro $sesion->get('carro');
  1640.             $Transaccion = new Transaccion();
  1641.             if ($carro->getOficina()) {
  1642.                 $Transaccion->setOficina($em->getReference('App\Entity\Oficina'$carro->getOficina()->getId()));
  1643.             }
  1644.             $Transaccion->setUsuario($em->getReference('App\Entity\User'$carro->getUsuario()->getId()));
  1645.             $Transaccion->sethoraRecogida($carro->getHoraEntrega());
  1646.             $Transaccion->setFechaRecogida($carro->getFechaEntrega());
  1647.             $Transaccion->setTipoPago($carro->getTipoPago());
  1648.             $Transaccion->setCupon($carro->getCodigoPromo());
  1649.             $Transaccion->setTipoPromo($carro->getTipoPromo());
  1650.             $Transaccion->setDireccionCompleta($carro->getDireccion());
  1651.             $Transaccion->setCodigoPostal($carro->getCodigoPostal());
  1652.             $Transaccion->setCiudad($carro->getCiudad());
  1653.             $Transaccion->setEstado($estado);
  1654.             $Transaccion->setPais($carro->getPais());
  1655.             $Transaccion->setAnotacion($carro->getComentario());
  1656.             $Transaccion->setTiempoEnvio($carro->getFechaEntrega());
  1657.             //si el descuento es de tipo divisa descontar usos
  1658.             if ($carro->getTipoPromo() == Carro::TIPO_PROMO_DIVISA) {
  1659.                 $cupon $carro->getCodigoPromo();
  1660.                 $rep_cup $em->getRepository('App\Entity\Cupon')->findOneBy(['codigo'=>$cupon]);
  1661.                 if($rep_cup){
  1662.                 $aux $rep_cup->getTotalUsos();
  1663.                 $rep_cup->setTotalUsos($aux-1);
  1664.                 $em->persist($rep_cup);
  1665.                 }
  1666.             }
  1667.             if ($carro->getProvincia() && !$carro->getFreeShipping()) {
  1668.                 $Transaccion->setProvincia($em->getReference('App\Entity\Provincia'$carro->getProvincia()->getId()));
  1669.             }
  1670.             if ($carro->getCardSend() != null) {
  1671.                 $Transaccion->setCardSend($carro->getCardSend());
  1672.                 $Transaccion->setNameSend($carro->getNameSend());
  1673.                 $Transaccion->setTitular($carro->getTitular());
  1674.             }
  1675.             if ($carro->getTipoPago() == "TPV") {
  1676.                 $Transaccion->setTitular($carro->getTitular());
  1677.             }
  1678.             foreach ($carro->getPedidos() as $pedido) {
  1679.                 $TransaccionLinea = new TransaccionLinea();
  1680.                 $TransaccionLinea->setDivisaDestino($em->getReference('App\Entity\Divisa'$pedido->getDivisaFinal()->getId()));
  1681.                 $TransaccionLinea->setCantidad($pedido->getCantidadFinal());
  1682.                 $TransaccionLinea->setErpCode($pedido->getErpCode());
  1683.                 $Transaccion->addLinea($TransaccionLinea);
  1684.             }
  1685.             $Transaccion->setTotalLineas($carro->getTotalTransaccion()-$carro->getGastosEnvio());
  1686.             $Transaccion->setGastosEnvio($carro->getGastosEnvio());
  1687.             
  1688. //             dump($Transaccion);die();
  1689.             $valor_trans $Transaccion->getId();
  1690.             if(isset($_COOKIE['afcodigo'])){
  1691.                 //  $numero = substr($_COOKIE['afcodigo'], 0);
  1692.                 $numero Utils::decode_afcode($_COOKIE['afcodigo']);
  1693.             //    var_dump($numero);die();
  1694.                 //No se puede asignar la transaccion al afiliado
  1695.                 if ($numero and $carro->getUsuario()->getId() != (int)$numero) {
  1696.                     $numero $em->getRepository('App\Entity\User')->findOneById($numero);
  1697.                     $Transaccion->setUsuarioAfiliado($numero);
  1698.                 }
  1699.             }else{
  1700.             }
  1701.             //Guardamos en sesion y base de datos
  1702.             $sesion->set('transaccion'$Transaccion);
  1703.             $em->persist($Transaccion);
  1704.             $em->flush();
  1705.             return $Transaccion;
  1706.         }
  1707.         /**
  1708.         * Parche para cargar las traducciones ya que las entidades
  1709.         * se persisten con las relaciones por referencia.
  1710.         * @return array
  1711.         */
  1712.         protected function loadDivisaTraducciones(PersistenceManagerRegistry $doctrineRequest $request)
  1713.         {
  1714.             $em $doctrine->getManager();
  1715.             $repo $em->getRepository('App\Entity\DivisaTranslation');
  1716.             $sesion $request->getSession();
  1717.             $carro $sesion->get('carro');
  1718. //             $idioma = $request->getLocale();
  1719. //             $idioma = $em->getRepository('App\Entity\Idioma')->findOneByUrl($idioma);
  1720.             $pedidos $carro->getPedidos();
  1721.             foreach ($pedidos as $key => $pedido) {
  1722.                 $origenes[$key] = $repo->findOneBy(['translatable' => $pedido->getDivisaOrigen()/*, 'idioma' => $idioma*/]);
  1723.                 $destinos[$key] = $repo->findOneBy(['translatable' => $pedido->getDivisaFinal()/*, 'idioma' => $idioma*/]);
  1724.             }
  1725.             return ['origenes' => $origenes'destinos' => $destinos];
  1726.         }
  1727.         /**
  1728.         * Borras las ventas del ERP.
  1729.         * Se llama a esta función cuando el usuario va para atrĆ”s,
  1730.         * hay una excepción o algĆŗn fallo en el ERP.
  1731.         * @param Carro $cart
  1732.         * @return bool Estado de la operación
  1733.         */
  1734.         protected function deleteErpSale($cart,  WebServiceTPV $wstpv)
  1735.         {
  1736. //             $WSTPV = $this->container->get('web.service.tpv', $em);
  1737.             $success 1;
  1738.             foreach ($cart->getPedidos() as $pedido) {
  1739.                 $success *= $wstpv->BorrarVenta($pedido->getErpCode());
  1740.                 $pedido->setErpCode(NULL);
  1741.             }
  1742.             $cart->setTotalTransaccion(NULL);
  1743.             return $success;
  1744.         }
  1745.         private function buildRedsys($request$transaccion)
  1746.         {
  1747.             $local $request->getLocale();
  1748.             $redsys = new ApiRedsys();
  1749.             
  1750.             // Valores de entrada
  1751.             $terminal "001";
  1752.             $moneda "978";
  1753.             $trans "1";
  1754.             //PASARELA DE PAGO
  1755.             $url $this->generateUrl('app_cart_notification', [], UrlGeneratorInterface::ABSOLUTE_URL);
  1756.             // $urlOK = $this->generateUrl('app_cart_5', ['t' => $transaccion->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
  1757.             $urlOK $this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()], UrlGeneratorInterface::ABSOLUTE_URL);
  1758.             $urlKO $this->generateUrl('app_cart_critical', ['t' => $transaccion->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
  1759.             $id str_pad($transaccion->getId(), 4"0"STR_PAD_LEFT);
  1760. //             $amount = money_format($transaccion->getTotal() * 100, 2);
  1761.             $amount number_format($transaccion->getTotal(),2,"","");
  1762.             // Se Rellenan los campos
  1763.             $redsys->setParameter("DS_MERCHANT_AMOUNT"$amount);
  1764.             $redsys->setParameter("DS_MERCHANT_ORDER"strval($id));
  1765.             $redsys->setParameter("DS_MERCHANT_MERCHANTCODE"$this->getParameter('redsys_fuc'));
  1766.             $redsys->setParameter("DS_MERCHANT_CURRENCY"$moneda);
  1767.             $redsys->setParameter("DS_MERCHANT_TRANSACTIONTYPE"$trans);
  1768.             $redsys->setParameter("DS_MERCHANT_TERMINAL"$terminal);
  1769.             $redsys->setParameter("DS_MERCHANT_MERCHANTURL"$url);
  1770.             $redsys->setParameter("DS_MERCHANT_URLOK"$urlOK);
  1771.             $redsys->setParameter("DS_MERCHANT_URLKO"$urlKO);
  1772.             $redsys->setParameter("Ds_Merchant_MerchantData"$transaccion->getTitular());
  1773.             $return['params'] = $redsys->createMerchantParameters();
  1774.             
  1775.             $return['signature'] = $redsys->createMerchantSignature($this->getParameter('redsys_key'));
  1776.             return $return;
  1777.         }
  1778.         
  1779.         
  1780.         #[Route(path: [
  1781.             'es' => '/carro4',
  1782.             'en' => '/en/cart4'
  1783.         ], name'app_cart_4')]
  1784.         public function Cart4Action(Request $request,PersistenceManagerRegistry $doctrineSettingsManager $smWebServiceTPV $wstpvMailer $mailerWebServiceFunciones $wsf)
  1785.         {
  1786.             $fullCart $this->getCart($request);
  1787.             // dump($fullCart);die();
  1788.             $ped $fullCart->getPedidos();
  1789.             
  1790. //             dump($fullCart);
  1791.             try {
  1792.                 if ($re $this->CartRedirect($request4)) {
  1793.                     return $re;
  1794.                 }
  1795.                 $gastosEnv 0;
  1796.                 $now = new \DateTime();
  1797.                 $day date('l'strtotime($now->format("Y-m-d H:i:s")));
  1798.                 $time date("H:i"strtotime($now->format("Y-m-d H:i:s")));
  1799.                 $em $doctrine->getManager();
  1800. //                 $options = $this->container->get('dinamic_settings.manager');
  1801.                 $fullCart $this->getCart($request);
  1802.                 
  1803.                 // Comprobar stock en tienda
  1804.                 
  1805.                 if ($fullCart->getOficina() != null) {
  1806. //                     if (!$this->ComprobarStock($request, $doctrine, $fullCart))
  1807. //                             return $this->redirect($this->generateUrl('app_cart_3'));
  1808.                     
  1809.                     $fest $em->getRepository('App\Entity\DayOff')->findBy(['oficina'=>$fullCart->getOficina()->getId()]);
  1810.                     
  1811.                     for ($i 0$i count($fest); $i++) { 
  1812.                         $fechFest $fest[$i]->getDate()->format("d/m/y");
  1813.                         $fechRec $fullCart->getFechaEntrega()->format("d/m/y");
  1814.                         if($fechFest == $fechRec) {
  1815.                             $this->addFlash(
  1816.                                 'danger',
  1817.                                 'Seleccione otro dĆ­a de recogida. El que ha seleccionado es festivo en esta oficina.'
  1818.                             );
  1819.                             return $this->redirect($this->generateUrl('app_cart_3'));
  1820.                         }
  1821.                     }
  1822.                     
  1823.                     
  1824.                     if ($fullCart->getReserva() == 1) {
  1825.                         $fullCart->setTotalEstimado(0);
  1826.                         for ($i 0$i count($ped); $i++) { 
  1827.                             $short $ped[$i]->getDivisaFinal()->getId();
  1828.                             
  1829.                             $maxDia $em->getRepository('App\Entity\Cotizaciones')->getMaxDia($fullCart->getOficina()->getId());
  1830.                             $fechaMax = new \DateTime($maxDia);
  1831.                             $nuevaCotizacion $em->getRepository('App\Entity\Cotizaciones')->findBy(['oficina'=>$fullCart->getOficina()->getId(), 'shortName'=>$short'dia'=>$fechaMax]);
  1832.                             
  1833.                             $nCant $nuevaCotizacion[0]->getPrecioVenta() * $ped[$i]->getCantidadFinal();
  1834.                             $ped[$i]->setCantidadOrigen($nCant);
  1835.                             $tot $fullCart->getTotalEstimado() + $nCant;
  1836.                             $fullCart->setTotalEstimado($tot);
  1837.                         }
  1838.                     } else {
  1839.                         $fullCart->setTotalEstimado(0);
  1840.                         for ($i 0$i count($ped); $i++) { 
  1841.                             $short $ped[$i]->getDivisaFinal()->getId();
  1842.                             
  1843.                             $maxDia $em->getRepository('App\Entity\Cotizaciones')->getMaxDia($fullCart->getOficina()->getId());
  1844.                             $fechaMax = new \DateTime($maxDia);
  1845.                             $nuevaCotizacion $em->getRepository('App\Entity\Cotizaciones')->findBy(['oficina'=>$this->getParameter('oficina_por_defecto'), 'shortName'=>$short'dia'=>$fechaMax]);
  1846.                             
  1847.                             $nCant $nuevaCotizacion[0]->getPrecioVenta() * $ped[$i]->getCantidadFinal();
  1848.                             $ped[$i]->setCantidadOrigen($nCant);
  1849.                             $tot $fullCart->getTotalEstimado() + $nCant;
  1850.                             $fullCart->setTotalEstimado($tot);
  1851.                         }
  1852.                     }
  1853. //                     $fullCart->getOficina()
  1854.                 }
  1855.                 $local $request->getLocale();
  1856.                 $total 0;
  1857.                 $formCard $this->createFormBuilder()
  1858.                     ->add('save40'SubmitType::class,
  1859.                         array('label' => $sm->getValue('cart4.pay'),
  1860.                             'attr' => array('class' => 'pagar bcol1')))
  1861.                     ->getForm();
  1862.                 $formTrans $this->createFormBuilder()
  1863.                     ->add('save41'SubmitType::class,
  1864.                         array('label' => $sm->getValue('cart4.pushOrder'),
  1865.                             'attr' => array('class' => 'pagar bcol1')))
  1866.                     ->getForm();
  1867.                 $formReserv $this->createFormBuilder()
  1868.                     ->add('save42'SubmitType::class,
  1869.                         array('label' => $sm->getValue('cart4.book'),
  1870.                             'attr' => array('class' => 'pagar bcol1')))
  1871.                     ->getForm();
  1872.             $repository $em->getRepository('App\Entity\Oficina');
  1873.             
  1874.             
  1875.             if(isset($_COOKIE['cookieoficina']) ){
  1876.                 $ofi = (integer)($_COOKIE['cookieoficina']);
  1877.                 $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$ofi));
  1878.                 if($ofi == 1){
  1879.                     $ofi $this->getParameter('oficina_por_defecto');
  1880.                     $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$this->getParameter('oficina_por_defecto')));
  1881.                 }
  1882.             } else {
  1883.                 $ofi = (integer)0;
  1884.                 $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChanges($local));
  1885.             }
  1886. //             $oficina = $repository->findOneBy(['id' => $ofi]);
  1887. //             $fullCart->setOficina($oficina);
  1888.                 //Si no es una reserva y no se ha guardado antes (por si refrescan la vista)
  1889.                 if (!$fullCart->getReserva() && !$fullCart->getTotalTransaccion()) {
  1890. //                 $WSTPV = $this->container->get('web.service.tpv', $em);
  1891.                     $gastosEnvio 0;
  1892.                     if (( $ofi == && !$fullCart->getFreeShipping()) || (!$fullCart->getOficina() && !$fullCart->getFreeShipping())) {
  1893.                         $gastosEnvio $fullCart->getProvincia()->getGastos();
  1894.                     }
  1895.                     
  1896. //                     var_dump($gastosEnvio); die();
  1897.                     $pedidos $fullCart->getPedidos();
  1898.                     //Persistir en ERP REMOTO
  1899.                     $fail false;
  1900.                     $total 0;
  1901.                     if($fullCart->getOficina() != null){
  1902.                         $ofC $em->getRepository('App\Entity\Oficina')->findOneById($fullCart->getOficina()->getId());
  1903.                         if ($ofC->permiteCompra()) {
  1904.                             $gastosEnv 0;
  1905.                             $fullCart->setGastosEnvio(0);
  1906.                         } else {
  1907.                             $gastosEnv $ofC->getProvincia()->getGastos();
  1908.                             $fullCart->setGastosEnvio($gastosEnv);
  1909.                         }
  1910.                     }else{
  1911.                         $gastosEnv $fullCart->getProvincia()->getGastos();
  1912.                     }
  1913.                     $cupon $fullCart->getCodigoPromo();
  1914.                     
  1915.                     if($fullCart->getFreeShipping()){
  1916.                         $gastosEnv 0;
  1917.                     }
  1918.                     for ($i 0$i count($pedidos); $i++) {
  1919.                         $extra = ($i == 0) ? $gastosEnv 0;
  1920.                         if($gastosEnv == 0){
  1921.                         $extra 0;
  1922.                         }
  1923.                         //  var_dump($extra);die();
  1924.                         if($cupon) {
  1925.                             if ($fullCart->getTipoPromo() == Carro::TIPO_PROMO_DIVISA AND $this->comprobarCupon($request$doctrine$cupon)) {
  1926.                                 // dump('a'); die();
  1927.                                 $rep_cup $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $cupon ]);
  1928.                                 $respuesta $wstpv->CrearVentaV2($fullCart$pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra$rep_cup->getCodigoTPV(), Carro::TIPO_PROMO_DIVISA);
  1929.                             } elseif ($fullCart->getTipoPromo() == Carro::TIPO_PROMO_CUPON) {
  1930.                             
  1931.                                 $resultado_cupon $this->comprobarCuponCodigo($cupon$fullCart->getTotalEstimado(),$wsf);
  1932.                                 if ($resultado_cupon === true) {
  1933.                                     $respuesta $wstpv->CrearVentaV2($fullCart$pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra$cuponCarro::TIPO_PROMO_CUPON);
  1934.                                 }
  1935.                                 else {
  1936.                                     $this->addFlash(
  1937.                                     'danger',
  1938.                                     $sm->getValue($resultado_cupon['error'])
  1939.                                     );
  1940.                                     return $this->redirect($this->generateUrl('app_cart_1'));
  1941.                                 }
  1942.                                 
  1943.                             }
  1944.                             else {
  1945.                                 // dump($fullCart->getTipoPromo()); die();
  1946.                                 $respuesta false;
  1947.                             }
  1948.                         }
  1949.                         else {
  1950.                             $respuesta $wstpv->CrearVenta($fullCart$pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra);
  1951.                         }
  1952.                         if (!$respuesta) {
  1953.                             throw new \Exception('Una de las lļæ½neas ha fallado en el ERP');
  1954.                         } else {
  1955.                             $descuento 0;
  1956.                             if (isset($respuesta['DescuentoTicket']) and $respuesta['DescuentoTicket'] > 0) {
  1957.                                 $descuento $respuesta['DescuentoTicket'];
  1958.                                 $fullCart->setDescuentoPromo($descuento);
  1959.                             }
  1960.                             //En local pillmamos el estimado porque Navision nos devolveria el importe de otro carrito
  1961.                             if ($this->kernel->getEnvironment() == 'dev')
  1962.                                 $total $fullCart->getTotalEstimado()+$gastosEnv-$descuento ;
  1963.                             else
  1964.                                 $total += $respuesta['importe'];
  1965.                             $pedidos[$i]->setErpCode($respuesta['erpCode']);
  1966.                             // dump($respuesta); die();
  1967.                         }
  1968.                     }
  1969.                     $fullCart->setTotalTransaccion($total);
  1970.                     $fullCart->setGastosEnvio($gastosEnv);
  1971.                     
  1972. //                     dump($hhh->getProvincia()->getGastos());die();
  1973.                     
  1974.                     //Si hay un problema en el ERP con alguna lļæ½nea
  1975.                     //reiniciamos el proceso
  1976.                     if ($fail) {
  1977.                         throw new \Exception('Una de las lļæ½neas ha fallado en el ERP');
  1978.                     }
  1979.                 }
  1980.                 
  1981.                 $reducido null;
  1982.                 if ($fullCart->getReserva()) {
  1983. //                     $dayoffs = $em->getRepository("App\Entity\HorarioReducido")->findOficinaDate($fullCart->getOficina(), $fullCart->getFechaEntrega());
  1984. //                     $dayoffs = $em->getRepository("App\Entity\DayOff")->findBy(array('id' => $ofi));
  1985. //                     $now = $fullCart->getFechaEntrega();
  1986. // 
  1987. //                     if ($dayoffs) {
  1988. // 
  1989. //                         if ($request->getLocale() == "es") {
  1990. //                             $reducido = "Horario reducido de " . $dayoffs->getHoraInicio()->format("H:i") . " a " . $dayoffs->getHoraFin()->format("H:i");
  1991. //                         } else {
  1992. //                             $reducido = "Reduced hours of " . $dayoffs->getHoraInicio()->format("H:i") . " to " . $dayoffs->getHoraFin()->format("H:i");
  1993. //                         }
  1994. //                     }
  1995.                 } else {
  1996.                     if ($fullCart->getTipoPago() == "TPV") {
  1997.                         $em $doctrine->getManager();
  1998.                         $repository $em->getRepository('App\Entity\Oficina');
  1999.                         if(isset($_COOKIE['cookieoficina']) ){
  2000.                             $ofi = (integer)($_COOKIE['cookieoficina']);
  2001.                             $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$ofi));
  2002.                             if($ofi == 1){
  2003.                                 $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$this->getParameter('oficina_por_defecto')));
  2004.                             }
  2005.                         } else {
  2006.                             $ofi = (integer)0;
  2007.                             $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$this->getParameter('oficina_por_defecto')));
  2008.                         }
  2009. //                         $oficina = $repository->findOneBy(['id' => $ofi]);
  2010. //                         $fullCart->setOficina($oficina);
  2011.                         //comprobamos stock
  2012.                         foreach ($fullCart->getPedidos() as $linea) {
  2013.                             if ($fullCart->getOficina()) { //Compromas los tiempos para recogida con tarjeta
  2014.                                 foreach ($fullCart->getOficina()->getStocks() as $stock) {
  2015.                                     if (!$stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //con stock con tarjeta
  2016.                                         if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2017.                                             $now->modify('+3 days');
  2018.                                         } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2019.                                             $now->modify('+4 days');
  2020.                                         } elseif ($day == "Saturday") { //sabado
  2021.                                             $now->modify('+3 days');
  2022.                                         } elseif ($day == "Sunday") {//domingo
  2023.                                             $now->modify('+2 days');
  2024.                                         } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2025.                                             $now->modify('+4 days');
  2026.                                         } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday" || $day == "Wednesday")) { //Lunes, martes o miercoles despues de las 3
  2027.                                             $now->modify('+2 days');
  2028.                                         } else {
  2029.                                             $now->modify('+1 days');
  2030.                                         }
  2031.                                     } elseif ($stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //sin stock
  2032.                                         if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2033.                                             $now->modify('+3 days');
  2034.                                         } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2035.                                             $now->modify('+4 days');
  2036.                                         } elseif ($day == "Saturday") { //sabado
  2037.                                             $now->modify('+3 days');
  2038.                                         } elseif ($day == "Sunday") {//domingo
  2039.                                             $now->modify('+2 days');
  2040.                                         } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2041.                                             $now->modify('+4 days');
  2042.                                         } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday" || $day == "Wednesday")) { //Lunes, martes o miercoles despues de las 3
  2043.                                             $now->modify('+2 days');
  2044.                                         } else {
  2045.                                             $now->modify('+1 days');
  2046.                                         }
  2047.                                     }
  2048.                                 }
  2049.                                 $now $this->comprobarFecha($now$fullCart->getOficina(), $em);
  2050. //                                 $dayoffs = $em->getRepository("App\Entity\HorarioReducido")->findOficinaDate($fullCart->getOficina(), $now);
  2051. // 
  2052. //                                 if ($dayoffs) {
  2053. // 
  2054. //                                     if ($request->getLocale() == "es") {
  2055. //                                         $reducido = "Horario reducido de " . $dayoffs->getHoraInicio()->format("H:i") . " a " . $dayoffs->getHoraFin()->format("H:i");
  2056. // 
  2057. //                                     } else {
  2058. //                                         $reducido = "Reduced hours of " . $dayoffs->getHoraInicio()->format("H:i") . " to " . $dayoffs->getHoraFin()->format("H:i");
  2059. //                                     }
  2060. //                                 }
  2061.                             } else { //sino es a domicilio
  2062.                                 //Y si es festivo y la oficina 1 de Benidorm estļæ½ cerrada, se suma un dļæ½a tambiļæ½n al envļæ½o a domicilio ya que los pedidos a domicilio salen desde esta oficina.                     $oficina = $this->getRepository("DinamicShopBundle:Oficina")->findOneById(20);
  2063.                                 $oficina $em->getRepository("App\Entity\Oficina")->findOneById($this->getParameter('oficina_por_defecto'));
  2064.                                 $now $this->comprobarFecha($now$oficina$em);
  2065.                                 $day date('l'strtotime($now->format("Y-m-d H:i:s")));
  2066.                                 if ($linea->getDivisaFinal()->getCompraMinima() == 0) { //con stock con tarjeta
  2067.                                     if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2068.                                         $now->modify('+3 days');
  2069.                                     } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2070.                                         $now->modify('+4 days');
  2071.                                     } elseif ($day == "Saturday") { //sabado
  2072.                                         $now->modify('+3 days');
  2073.                                     } elseif ($day == "Sunday") {//domingo
  2074.                                         $now->modify('+2 days');
  2075.                                     } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2076.                                         $now->modify('+4 days');
  2077.                                     } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday" || $day == "Wednesday")) { //Lunes, martes o miercoles despues de las 3
  2078.                                         $now->modify('+2 days');
  2079.                                     } else {
  2080.                                         $now->modify('+1 days');
  2081.                                     }
  2082.                                 } elseif ($linea->getDivisaFinal()->getCompraMinima() != 0) { //sin stock
  2083.                                     if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2084.                                         $now->modify('+4 days');
  2085.                                     } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2086.                                         $now->modify('+5 days');
  2087.                                     } elseif ($day == "Saturday") { //sabado
  2088.                                         $now->modify('+4 days');
  2089.                                     } elseif ($day == "Sunday") {//domingo
  2090.                                         $now->modify('+3 days');
  2091.                                     } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2092.                                         $now->modify('+6 days');
  2093.                                     } elseif ($time >= "15:00" and $day == "Wednesday") { //jueves despues de las 3
  2094.                                         $now->modify('+5 days');
  2095.                                     } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
  2096.                                         $now->modify('+3 days');
  2097.                                     } else {
  2098.                                         $now->modify('+2 days');
  2099.                                     }
  2100.                                 }
  2101.                                 if ($day == "Sunday") { //sunday
  2102.                                     $now $this->comprobarFecha($now->modify('+1 days'), $oficina$em);
  2103.                                 }
  2104.                             }
  2105.                         }
  2106.                     } else if ($fullCart->getTipoPago() == "TRANSFERENCIA") { //tranferencia
  2107.                     
  2108.                         $em $doctrine->getManager();
  2109.                         $repository $em->getRepository('App\Entity\Oficina');
  2110.                         if(isset($_COOKIE['cookieoficina']) ){
  2111.                             $ofi = (integer)($_COOKIE['cookieoficina']);
  2112.                             $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$ofi));
  2113.                             if($ofi == 1){
  2114.                                 $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$this->getParameter('oficina_por_defecto')));
  2115.                             }
  2116.                         } else {
  2117.                             $ofi = (integer)0;
  2118.                             $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$this->getParameter('oficina_por_defecto')));
  2119.                         }
  2120. //                         $oficina = $repository->findOneBy(['id' => $ofi]);
  2121. //                         $fullCart->setOficina($oficina);
  2122.                         //comprobamos stock
  2123.                         foreach ($fullCart->getPedidos() as $linea) {
  2124.                             if ($fullCart->getOficina()) { //Compromas los tiempos para recogida con tarjeta
  2125.                                 foreach ($fullCart->getOficina()->getStocks() as $stock) {
  2126.                                     if (!$stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //con stock con transferencia
  2127.                                         if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2128.                                             $now->modify('+4 days');
  2129.                                         } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2130.                                             $now->modify('+4 days');
  2131.                                         } elseif ($day == "Saturday") { //sabado
  2132.                                             $now->modify('+4 days');
  2133.                                         } elseif ($day == "Sunday") {//domingo
  2134.                                             $now->modify('+3 days');
  2135.                                         } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
  2136.                                             $now->modify('+5 days');
  2137.                                         } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2138.                                             $now->modify('+5 days');
  2139.                                         } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
  2140.                                             $now->modify('+3 days');
  2141.                                         } else {
  2142.                                             $now->modify('+2 days');
  2143.                                         }
  2144.                                     } elseif ($stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //sin stock
  2145.                                         if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2146.                                             $now->modify('+4 days');
  2147.                                         } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2148.                                             $now->modify('+5 days');
  2149.                                         } elseif ($day == "Saturday") { //sabado
  2150.                                             $now->modify('+4 days');
  2151.                                         } elseif ($day == "Sunday") {//domingo
  2152.                                             $now->modify('+3 days');
  2153.                                         } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
  2154.                                             $now->modify('+5 days');
  2155.                                         } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2156.                                             $now->modify('+5 days');
  2157.                                         } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
  2158.                                             $now->modify('+3 days');
  2159.                                         } else {
  2160.                                             $now->modify('+2 days');
  2161.                                         }
  2162.                                     }
  2163.                                 }
  2164.                                 $now $this->comprobarFecha($now$fullCart->getOficina(), $em);
  2165.                             } else { //sino es a domicilio
  2166.                                 //Y si es festivo y la oficina 1 de Benidorm estļæ½ cerrada, se suma un dļæ½a tambiļæ½n al envļæ½o a domicilio ya que los pedidos a domicilio salen desde esta oficina.
  2167.                                 $oficina $em->getRepository("App\Entity\Oficina")->findOneById($this->getParameter('oficina_por_defecto'));
  2168.                                 $dateBefore $now;
  2169.                                 $now $this->comprobarFecha($now$oficina$em);
  2170.                                 $dateAfter $now;
  2171.                                 $day date('l'strtotime($now->format("Y-m-d H:i:s")));
  2172.                                 if ($linea->getDivisaFinal()->getCompraMinima() == 0) { //con stock con transferencia
  2173.                                     if ($dateBefore->diff($dateAfter)->format('%R%a') == "+1" and $day == "Friday") { //viernes cerrado el jueves
  2174.                                         $now->modify('+3 days');
  2175.                                     } elseif ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2176.                                         $now->modify('+4 days');
  2177.                                     } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2178.                                         $now->modify('+4 days');
  2179.                                     } elseif ($day == "Saturday") { //sabado
  2180.                                         $now->modify('+4 days');
  2181.                                     } elseif ($day == "Sunday") {//domingo
  2182.                                         $now->modify('+3 days');
  2183.                                     } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
  2184.                                         $now->modify('+5 days');
  2185.                                     } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2186.                                         $now->modify('+5 days');
  2187.                                     } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
  2188.                                         $now->modify('+3 days');
  2189.                                     } else {
  2190.                                         $now->modify('+2 days');
  2191.                                     }
  2192.                                 } elseif ($linea->getDivisaFinal()->getCompraMinima() != 0) { //sin stock
  2193.                                     if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2194.                                         $now->modify('+5 days');
  2195.                                     } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2196.                                         $now->modify('+6 days');
  2197.                                     } elseif ($day == "Saturday") { //sabado
  2198.                                         $now->modify('+5 days');
  2199.                                     } elseif ($day == "Sunday") {//domingo
  2200.                                         $now->modify('+4 days');
  2201.                                     } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
  2202.                                         $now->modify('+6 days');
  2203.                                     } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2204.                                         $now->modify('+6 days');
  2205.                                     } elseif ($time >= "15:00" and $day == "Tuesday") { //martes despues de las 3
  2206.                                         $now->modify('+6 days');
  2207.                                     } elseif ($time >= "15:00" and $day == "Monday") { //Lunes  despues de las 3
  2208.                                         $now->modify('+4 days');
  2209.                                     } else {
  2210.                                         $now->modify('+3 days');
  2211.                                     }
  2212.                                 }
  2213.                                 if ($day == "Sunday") { //sunday
  2214.                                     $now $this->comprobarFecha($now->modify('+1 days'), $oficina$em);
  2215.                                 }
  2216.                             }
  2217.                         }
  2218.                     } else if ($fullCart->getTipoPago() == "PAYPAL") {
  2219.                         
  2220.                         
  2221.                         
  2222.                     } else if ($fullCart->getTipoPago() == "BIZUM") {
  2223.                         
  2224.                         
  2225.                         
  2226.                     }
  2227.                     
  2228.                 }
  2229.                 
  2230. //                 $fullCart->setFechaEntrega($now);
  2231.                 $totalEntregar 0;
  2232.                 foreach ($fullCart->getPedidos() as $pedido) {
  2233.                     $totalEntregar $totalEntregar $pedido->getCantidadFinal();
  2234.                 }
  2235.                 $nuevaFechaDisponible = new \DateTime('now');
  2236.                 $domingo false;
  2237.                 if ($nuevaFechaDisponible->format('N') == 7) {
  2238.                     $domingo true;
  2239.                 }
  2240.                 
  2241.                 
  2242.                 if($fullCart->getOficina() != null) {
  2243.                     $oficinaE $em->getRepository('App\Entity\Oficina')->findOneById($fullCart->getOficina()->getId());
  2244.                     if ($totalEntregar >= 50 || !$oficinaE->permiteCompra()) {
  2245.                         if ($fullCart->getFechaEntrega() < $fullCart->getFechaDisponible() || $fullCart->getFechaEntrega() == $fullCart->getFechaDisponible() && $fullCart->getHoraEntrega()->format("H:i") < $fullCart->getFechaDisponible()->format("H:i")) {
  2246.                             $this->addFlash(
  2247.                                 'danger',
  2248.                                 'El dia seleccionado es anterior a la fecha en la que estarĆ” disponible el pedido. EstarĆ” listo a partir del dĆ­a ' $fullCart->getFechaDisponible()->format("d/m/y") . ' a las ' $fullCart->getFechaDisponible()->format("H:i")
  2249.                             );
  2250.                             return $this->redirect($this->generateUrl('app_cart_3'));
  2251.                         }
  2252.                     } else if ($domingo == true) {
  2253.                         $nuevaFechaDisponible->add(new \DateInterval('PT10H'));
  2254.                         $fullCart->setFechaDisponible($nuevaFechaDisponible);
  2255.                     } else {
  2256.                         $fullCart->setFechaDisponible($nuevaFechaDisponible);
  2257.                     }
  2258.                 }
  2259.                 
  2260. //                 dump($fullCart);die();
  2261. //                 $dayoffs = $em->getRepository('App\Entity\HorarioReducido')->findOficinaDate($fullCart->getOficina(), $now);
  2262. // 
  2263. //                 if ($dayoffs) {
  2264. // 
  2265. //                     if ($request->getLocale() == "es") {
  2266. //                         $reducido = "Horario reducido de " . $dayoffs->getHoraInicio()->format("H:i") . " a " . $dayoffs->getHoraFin()->format("H:i");
  2267. // 
  2268. //                     } else {
  2269. //                         $reducido = "Reduced hours of " . $dayoffs->getHoraInicio()->format("H:i") . " to " . $dayoffs->getHoraFin()->format("H:i");
  2270. //                     }
  2271. //                 }
  2272.                 
  2273.                 //Pago con tarjeta
  2274.                 $formCard->handleRequest($request);
  2275.                 if ($formCard->isSubmitted() and $formCard->isValid()) {
  2276.                     //PERSISTIR EN BASE DE DATOS LOCAL
  2277.                     $transaccion $this->persistTransaccion($doctrine$request'En pasarela de pago');
  2278.                     // Creamos un formulario oculto para enviar la informaciļæ½n mediante POST a los servidores del TPV
  2279.                     $redsysData $this->buildRedsys($request$transaccion);
  2280.                     
  2281.                     $formTPV $this->container->get('form.factory')->createNamedBuilder(''FormType::class, array(), array(
  2282.                         'action' => $this->getParameter('redsys_gateway'),
  2283.                         'method' => 'POST',
  2284.                         'csrf_protection' => false,
  2285.                         'attr' => array('name' => 'tpv''id' => 'formTPV'),
  2286.                     ))
  2287.                         ->add('Ds_SignatureVersion'HiddenType::class, ['data' => $this->getParameter('redsys_version')])
  2288.                         ->add('Ds_MerchantParameters',  HiddenType::class, ['data' => $redsysData['params']])
  2289.                         ->add('Ds_Signature'HiddenType::class, ['data' => $redsysData['signature']])
  2290.                         ->getForm();
  2291.                     return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
  2292.                 }
  2293.                 //Pago con transferencia
  2294.                 $formTrans->handleRequest($request);
  2295.                 if ($formTrans->isSubmitted() and $formTrans->isValid()) {
  2296.                 
  2297.                     
  2298.                     $transaccion $this->persistTransaccion($doctrine$request'Pendiente de pago');
  2299.                     $response $this->redirect($this->generateUrl('app_cart_5'));
  2300.                     $transaccion $em->getRepository("App\Entity\Transaccion")->findOneById($transaccion->getId());
  2301. //                     $WSTPV = $this->container->get('web.service.tpv', $em);
  2302.                     foreach ($transaccion->getLineas() as $linea) {
  2303.                         $upLinea $em->getRepository("App\Entity\TransaccionLinea")->findOneById($linea->getId());
  2304.                         
  2305.                         // ACTIVAR EN PRODUCCION
  2306.                         
  2307. //                         $respuesta = $wstpv->RegistrarVenta($upLinea);
  2308. //                         $upLinea = $upLinea->setTicket($respuesta);
  2309. //                         $upLinea->setTicket($respuesta);
  2310.                         
  2311.                         //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
  2312.                         
  2313.                         $em->merge($upLinea);
  2314.                         $em->flush();
  2315.                     }
  2316.                     // ACTIVAR EN PRODUCCION
  2317.                     $mailer->pendingTransaction($this->getUser(), $transaccion);
  2318.                     return $response;
  2319.                     //Proceso de pago con transferencia
  2320.                 }
  2321.                 //RESERVA
  2322.                 $formReserv->handleRequest($request);
  2323.                 if ($formReserv->isSubmitted() and $formReserv->isValid()) {
  2324.                     $this->ActualizarStock($doctrine$fullCart);
  2325.                     $response $this->redirect($this->generateUrl('app_cart_5'));
  2326.                     return $response;
  2327.                 }
  2328.                 $stepBread $this->StepControl($request);
  2329.                 $user $this->getUser();
  2330.                 $invitado $fullCart->getInvitado();
  2331.                 $traducciones $this->loadDivisaTraducciones($doctrine$request);
  2332.                 
  2333.                 $idPago $fullCart->getTipoPago();
  2334.                 $metodoPago $em->getRepository("App\Entity\MetodoPago")->findOneBy(array('id' => $idPago));
  2335.                 
  2336.                 return $this->render('default/carrito/carrito4.html.twig', array(
  2337. //                     'reducido' => $reducido,
  2338.                     'formReserva' => $formReserv->createView(),
  2339.                     'stepBread' => $stepBread,
  2340.                     'carro' => $fullCart,
  2341.                     'usuario' => $user,
  2342.                     'invitado' => $invitado,
  2343.                     'formCard' => $formCard->createView(),
  2344.                     'formTrans' => $formTrans->createView(),
  2345.                     'currentStep' => 4,
  2346.                     'total' => $fullCart->getTotalTransaccion(),
  2347.                     'descuentoPromo' => $fullCart->getDescuentoPromo(),
  2348.                     'gastosEnvio' => $gastosEnv,
  2349.                     'sm' => $sm,
  2350.                     'traducciones' => $traducciones,
  2351.                     'tiempoenvio' => $fullCart->getFechaDisponible(),
  2352.                     'tiemporecogida' => $fullCart->getFechaEntrega(),
  2353.                     'metodoPago' => $metodoPago
  2354.                 ));
  2355.             } catch
  2356.             (\Exception $e) {
  2357.                 if ($this->kernel->getEnvironment() == 'dev') throw $e;
  2358.                 $this->resetCart($request);
  2359.                 $catcher $this->container->get('web.service.catchException');
  2360.                 $log = new Log();
  2361.                 $this->deleteErpSale($fullCart,$wstpv);
  2362.                 $log->setLocation('carro4');
  2363.                 $log->setUser($this->getUser());
  2364.                 $log->setText(json_encode($e->getTrace()));
  2365.                 $error $e->getMessage();
  2366.                 $catcher->saveException($log);
  2367.                 return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $error'currentStep' => 5));
  2368.             }
  2369.         }
  2370.         
  2371.         public function resetCart($request)
  2372.         {
  2373.             $sesion $request->getSession();
  2374.             $sesion->set('cartStep'null);
  2375.             $sesion->set('carro'null);
  2376.             $sesion->set('transferencia'null);
  2377.         }
  2378.         
  2379.         
  2380.         
  2381.         
  2382.     #[Route(path: [
  2383.         'es' => '/carro5',
  2384.         'en' => '/en/cart5'
  2385.     ], name'app_cart_5')]
  2386.     public function Cart5Action(Request $request,PersistenceManagerRegistry $doctrineWebServiceUsuarios $wsuWebServiceFunciones $wsfLoggerInterface $loggerMailer $mailerEventDispatcherInterface $EventDispatcherWebServiceTPV $wstpv)
  2387.     {
  2388.         try {
  2389.             if ($request->query->has('t')) {
  2390.                 $em $doctrine->getManager();
  2391.                 $t $request->query->get('t');
  2392.                 $transaccion $em->getRepository('App\Entity\Transaccion')->findOneBy(['tokenEmail' => $t]);
  2393.             } else {
  2394.                 return $this->redirect($this->generateUrl('app_cart_1'));
  2395.             }
  2396.             if ($transaccion && $transaccion->getEstado() == 'En pasarela de pago') {
  2397.                 $redsysData $this->buildRedsys($request$transaccion);
  2398.                 $formTPV $this->container->get('form.factory')->createNamedBuilder(''FormType::class, array(), array(
  2399.                     'action' => $this->getParameter('redsys_gateway'),
  2400.                     'method' => 'POST',
  2401.                     'csrf_protection' => false,
  2402.                     'attr' => array('name' => 'tpv''id' => 'formTPV'),
  2403.                 ))
  2404.                     ->add('Ds_SignatureVersion'HiddenType::class, ['data' => $this->getParameter('redsys_version')])
  2405.                     ->add('Ds_MerchantParameters',  HiddenType::class, ['data' => $redsysData['params']])
  2406.                     ->add('Ds_Signature'HiddenType::class, ['data' => $redsysData['signature']])
  2407.                     ->getForm();
  2408.                 return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
  2409.             }
  2410.             // $EventDispatcher->dispatch(new OrderCompleteEvent($transaccion,$request), OrderCompleteEvent::NAME);
  2411.             // $respuesta = $wstpv->CrearVentaV2($fullCart, $pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra, $cupon, Carro::TIPO_PROMO_CUPON);
  2412.             $cupon $transaccion->getCupon();
  2413.             foreach ($transaccion->getLineas() as $linea) {
  2414.                 if ($linea->getErpCode() == null) {
  2415.                     if($cupon) {
  2416.                         if ($transaccion->getTipoPromo() == Carro::TIPO_PROMO_DIVISA) {
  2417.                             $rep_cup $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $cupon ]);
  2418.                             $respuesta $wstpv->CrearVentaV2($transaccion$linea$this->getUser(), $transaccion->getTipoPago(), $transaccion->getGastosEnvio(), $rep_cup->getCodigoTPV(), Carro::TIPO_PROMO_DIVISA);
  2419.                         } elseif ($transaccion->getTipoPromo() == Carro::TIPO_PROMO_CUPON) {
  2420.                             $respuesta $wstpv->CrearVentaV2($transaccion$linea$this->getUser(), $transaccion->getTipoPago(), $transaccion->getGastosEnvio(), $cuponCarro::TIPO_PROMO_CUPON);
  2421.                         } else {
  2422.                             $respuesta false;
  2423.                         }
  2424.                     } else {
  2425.                         $respuesta $wstpv->CrearVenta($transaccion$linea$this->getUser(), $transaccion->getTipoPago(), $transaccion->getGastosEnvio());
  2426.                     }
  2427.                     if (!$respuesta) {
  2428.                         throw new \Exception('Una de las lĆ­neas ha fallado en el ERP al crearse');
  2429.                     }
  2430.                     $linea->setErpCode($respuesta['erpCode']);
  2431.                     $em->persist($linea);
  2432.                     $em->flush();
  2433.                     $respuesta $wstpv->RegistrarVenta($linea);
  2434.                     if (!$respuesta) {
  2435.                         throw new \Exception('Una de las lĆ­neas ha fallado en el ERP al registrarse');
  2436.                     }
  2437.                     $linea->setTicket($respuesta);
  2438.                     $em->persist($linea);
  2439.                     $em->flush();
  2440.                 }
  2441.             }
  2442.             $mailer->succcessBought($transaccion->getUsuario(), $transaccion);
  2443.             // $mailer->transactionNotification($transaccion);
  2444.             $returnArray = array(
  2445.                 'currentStep' => 5,
  2446.                 'transaccion' => $transaccion,
  2447.             );
  2448.             return $this->render('default/carrito/carrito5.html.twig'$returnArray);
  2449.             
  2450. //             if ($this->getCart($request)) {
  2451. //                 $Reserva = $transaccion = NULL;
  2452. //                 if ($re = $this->CartRedirect($request, 5)) {
  2453. //                     return $re;
  2454. //                 }
  2455. //                 $carro = $this->getCart($request);
  2456. //
  2457. //                 //Es una COMPRA SIN cerrar
  2458. //                 if (!$carro->getReserva()) {
  2459. //                     $sesion = $request->getSession();
  2460. //                     $transaccion = $sesion->get('transaccion');
  2461. //                     //AVISAMOS AL ERP DE QUE LA COMPRA FUE BIEN
  2462. //                     $transaccion = $em->getRepository("App\Entity\Transaccion")->findOneById($transaccion->getId());
  2463. //
  2464. //                     //SI ES UNA COMPRA RECOGIDA EN OFICINA ACTUALIZAMOS EL STOCK
  2465. //                     if ($carro->getOficina()) {
  2466. //                         $this->ActualizarStock($doctrine, $carro);
  2467. //                     }
  2468. //
  2469. //                     $EventDispatcher->dispatch(new OrderCompleteEvent($transaccion,$request), OrderCompleteEvent::NAME);
  2470. //                 }
  2471. //                 //Es una RESERVA
  2472. //                 else if ($carro->getReserva()) {
  2473. //                     $Reserva = $this->persistBooking($doctrine, $wsu, $wsf, $mailer, $carro);
  2474. //                     $EventDispatcher->dispatch(new BookingCompleteEvent($Reserva,$request), BookingCompleteEvent::NAME);
  2475. //                 }
  2476. //                 $stepBread = $this->StepControl($request);
  2477. //
  2478. //                 $returnArray = array(
  2479. //                     'stepBread' => $stepBread,
  2480. //                     'reserva' => $Reserva,
  2481. //                     'currentStep' => 5,
  2482. //                     'transaccion' => $transaccion,
  2483. //                 );
  2484. //
  2485. //                 /**
  2486. //                  * Para depurar el carro sin que saque del paso 5
  2487. //                  * comenta esta linea
  2488. //                  */
  2489. // //                 $this->resetCart($request);
  2490. //
  2491. // //                 return $returnArray;
  2492. //
  2493. //                 return $this->render('default/carrito/carrito5.html.twig', $returnArray);
  2494.             // } else {
  2495.             //     $response = $this->redirect($this->generateUrl('index'));
  2496.             //     return $response;
  2497.             // }
  2498.         } catch (\Exception $e)
  2499.         {
  2500.             $logger->error($e->getMessage(). ' | '.$e->getTraceAsString());
  2501.             if($this->getParameter('kernel.debug')) {
  2502.                 throw $e;
  2503.             }
  2504.             return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $e->getMessage(), 'currentStep' => 5));
  2505.         }
  2506.     }
  2507.     
  2508.     
  2509.     #[Route(path: [
  2510.         'es' => '/notificacion',
  2511.         'en' => 'en/notification'
  2512.     ], name'app_cart_notification')]
  2513.     public function notificationAction(Request $requestPersistenceManagerRegistry $doctrineSettingsManager $smWebServiceTPV $wstpvMailer $mailerLoggerInterface $redsysLogger)
  2514.     {
  2515. //         $logger = $this->get('monolog.logger.redsys');
  2516.         try {
  2517.             $em $doctrine->getManager();
  2518. //             $options = $this->container->get('dinamic_settings.manager');
  2519. //             $WSTPV = $this->container->get('web.service.tpv', $em);
  2520. //             $wstpv2 = $this->container->get('App\Services\WebServiceTPV');
  2521.             $sesion $request->getSession();
  2522.             $transaccion $sesion->get('transaccion');
  2523.             // Se crea Objeto
  2524.             $redsys = new ApiRedsys();
  2525.             $redsysLogger->info('[NTFA] Empezamos la notificacion.');
  2526.             $version $request->get("Ds_SignatureVersion");
  2527.             $redsysLogger->info('[NTFA] Versión: ' $version);
  2528.             $datos $request->get("Ds_MerchantParameters");
  2529. //             dump($datos);die();
  2530.             $redsysLogger->info('[NTFA] Datos: ' $datos);
  2531.             $signatureRecibida $request->get("Ds_Signature");
  2532.             $redsysLogger->info('[NTFA] Firma: ' $signatureRecibida);
  2533.             $decodec $redsys->decodeMerchantParameters($datos);
  2534.             $response json_decode($decodectrue);
  2535.             
  2536.             $firma $redsys->createMerchantSignatureNotif($this->getParameter('redsys_key'), $datos);
  2537.             
  2538.                         
  2539.             $dsResponse intval($response['Ds_Response']);
  2540.             if ($firma === $signatureRecibida && ($dsResponse <= 99 || $dsResponse == 900 || $dsResponse == 400)) {
  2541.                 //PERSISTIR EN ERP
  2542.                 $firmado "FIRMA OK";
  2543.                 $transaccionId ltrim($redsys->getParameter('Ds_Order'), '0');
  2544.                 $em $doctrine->getManager();
  2545.                 $transaccion $em->getRepository('App\Entity\Transaccion')->findOneById($transaccionId);
  2546.                 if ($transaccion) {
  2547.                     $redsysLogger->info('Poniendo pagado a: ' $transaccion->getId());
  2548. //                     $mailer = $this->container->get('dinamic_shop.mailer');
  2549.                     $transaccion->setEstado('Pagado');
  2550.                     $pago = new \DateTime();
  2551.                     $transaccion->setFechaPagado($pago);
  2552.                     $em->persist($transaccion);
  2553.                     $em->flush();
  2554.                     foreach ($transaccion->getLineas() as $linea) {
  2555.                         $upLinea $em->getRepository("App\Entity\TransaccionLinea")->findOneById($linea->getId());
  2556.                         // ACTIVAR EN PRODUCCION
  2557.                         
  2558. //                         dump($wstpv); die();
  2559. //                         $respuesta = $wstpv->RegistrarVenta($upLinea);
  2560. //                         $upLinea = $upLinea->setTicket($respuesta);
  2561. //                         $upLinea->setTicket($respuesta);
  2562.                         //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
  2563.                         $em->merge($upLinea);
  2564.                         $em->flush();
  2565.                     }
  2566.                     $mailer->completeTransation($transaccion->getEmailTitular(), $transaccion);
  2567. //                     $mailer->pendingTransaction($this->getUser(), $transaccion);
  2568. //                     dump($mailer);die();
  2569.                 } else {
  2570.                     $redsysLogger->info('[NTFA] La transaccion ' $transaccionId ' NO ha sido encontrada.');
  2571.                 }
  2572.                 $redsysLogger->info('[NTFA] Final de Firma ok');
  2573.             } else {
  2574.                 $redsysLogger->info('[NTFA] Error en la pasarela');
  2575.                 $transaccion->setEstado('ERROR EN PASARELA');
  2576.                 $em->persist($transaccion);
  2577.                 $em->flush();
  2578.                 $firmado "FIRMA KO";
  2579.             }
  2580.             return new Response($firmado);
  2581.         } catch (\Exception $e) {
  2582.             $redsysLogger->critical('[NTFA][1/2][CRITICAL]' $e->getMessage());
  2583.             $redsysLogger->critical('[NTFA][2/2][CRITICAL]' $e->getTraceAsString());
  2584.             return new Response("ERROR");
  2585.         }
  2586.         
  2587.         
  2588.     }
  2589.     
  2590.     #[Route(path: [
  2591.         'es' => '/error-carro',
  2592.         'en' => 'en/cart-error'
  2593.     ], name'app_cart_critical')]
  2594.     public function pasarelaCritical(Request $request)
  2595.     {
  2596.         $this->resetCart($request);
  2597.         $response $request->request->get("Ds_Response");
  2598.         //print_r($response);
  2599.         $version $request->request->get("Ds_SignatureVersion");
  2600.         //print_r($version);
  2601.         return $this->render('default/carrito/errorcart.html.twig');
  2602.     }
  2603.     
  2604.     
  2605.     public function comprobarFecha($nowOficina $oficina$em)
  2606.     {
  2607.         $dayoffs $em->getRepository("App\Entity\DayOff")->findBy(array('id' => $oficina));
  2608.         $validDate = clone $now;
  2609.         foreach ($dayoffs as $dayoff) {
  2610.             $formatted $validDate->format("Y-m-d");
  2611.             if (!in_array($formatted$dayoffs) and $this->isOpenOffice($validDate$oficina)) {
  2612.                 return $validDate;
  2613.             }
  2614.             $validDate->modify('+1 days');
  2615.         }
  2616.         return $validDate;
  2617.     }
  2618.     
  2619.     public function isOpenOffice($dateOficina $oficina)
  2620.     {
  2621.         $fechaValida false;
  2622.         $date $date->format('D');
  2623.         $franjas $oficina->getFranjas();
  2624.         for ($i 0$i count($franjas) && !$fechaValida$i++) {
  2625.             switch ($date) {
  2626.                 case 'Mon':
  2627.                     if ($franjas[$i]->getLunes()) $fechaValida true;
  2628.                     break;
  2629.                 case 'Tue':
  2630.                     if ($franjas[$i]->getMartes()) $fechaValida true;
  2631.                     break;
  2632.                 case 'Wed':
  2633.                     if ($franjas[$i]->getMiercoles()) $fechaValida true;
  2634.                     break;
  2635.                 case 'Thu':
  2636.                     if ($franjas[$i]->getJueves()) $fechaValida true;
  2637.                     break;
  2638.                 case 'Fri':
  2639.                     if ($franjas[$i]->getViernes()) $fechaValida true;
  2640.                     break;
  2641.                 case 'Sat':
  2642.                     if ($franjas[$i]->getSabado()) $fechaValida true;
  2643.                     break;
  2644.                 case 'Sun':
  2645.                     if ($franjas[$i]->getDomingo()) $fechaValida true;
  2646.                     break;
  2647.                 default:
  2648.                     break;
  2649.             }
  2650.         }
  2651.         return $fechaValida;
  2652.     }
  2653.         
  2654.         
  2655.         
  2656.         
  2657.         
  2658.         
  2659.         
  2660.         
  2661.         
  2662.         
  2663.         
  2664.         
  2665.         
  2666.         
  2667.         
  2668.         
  2669.         
  2670.         
  2671.         
  2672.         
  2673.         
  2674.         
  2675.         
  2676.         
  2677.         
  2678.         
  2679.         
  2680. }