src/Controller/CarritoController.php line 431

  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 $wstpvSettingsManager $sm)
  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.                     $tp 0;
  533.                     foreach($carro->getPedidos() as $ped) {
  534.                         $tp $tp $ped->getCantidadOrigen();
  535.                     }
  536.                     if ($tp 100) {
  537.                         $this->addFlash(
  538.                             'danger',
  539.                             $sm->getValue('cart1.error.mas_de_100')
  540.                         );
  541.                         return $this->redirect($this->generateUrl('app_cart_1'));
  542.                     }
  543.                     return $response;
  544.                 }
  545.             }
  546.             $repository $em->getRepository('App\Entity\Cotizaciones');
  547.             $permiteCompra 1;
  548.             if(isset($_COOKIE['cookieoficina'])){
  549.                 $ofi = (integer)($_COOKIE['cookieoficina']);
  550.                 $rep $em->getRepository('App\Entity\Oficina')->findOneById($ofi);
  551.                 if($rep){
  552.                     if($rep->permiteCompra() != 1){
  553.                         $permiteCompra 0;
  554.                     }
  555.                 }
  556.                 $cotizaciones $repository->getLastChangesOffice($ofi);
  557.                 if($ofi == 1){
  558.                     $cotizaciones $repository->getLastChangesOffice($this->getParameter('oficina_por_defecto'));
  559.                 }
  560.                 $pedido->setOficina($ofi);
  561.             }else{
  562.                 $ofi $this->getParameter('oficina_por_defecto');
  563.                 $cotizaciones $repository->getLastChanges($ofi);
  564.             }
  565.             $cartStep $this->StepControl($request);
  566.             $divisas $em->getRepository('App\Entity\Divisa')->findBy(['visible' => 1]);
  567.             
  568.             
  569.             $cotizacionesOnline $repository->getLastChangesOffice($this->getParameter('oficina_por_defecto'));
  570.             
  571.             $cotizacionesOnlineJson = [];
  572.             foreach($cotizacionesOnline as $n)
  573.                 $cotizacionesOnlineJson[$n['shortName']] = $n;
  574.             
  575.             $cotizacionesJson = [];
  576.             foreach($cotizaciones as $c)
  577.                 $cotizacionesJson[$c['shortName']] = $c;
  578.             
  579. //             dump($divisas); die();
  580.             $divisasJson = [];
  581.             foreach($divisas as $d)
  582.                 $divisasJson[$d->getId()] = [
  583.                     'shortName' => $d->getShortName(),
  584.                     'redondeoMinimo' => $d->getRedondeoMinimo(),
  585.                     'compraMinima' => $d->getCompraMinima(),
  586.                 ];
  587. //           dump($formCarro->createView()); die();
  588.             /****/
  589.             $provincias $em->getRepository('App\Entity\Provincia')->findAll();
  590.             /****/
  591.             
  592.             return $this->render('default/carrito/carrito1.html.twig', array(
  593.                 'cotizaciones' => $cotizaciones,
  594.                 'cotizacionesJson' => json_encode($cotizacionesJson),
  595.                 'cotizacionesOnlineJson' => json_encode($cotizacionesOnlineJson),
  596.                 'stepBread' => $cartStep,
  597.                 'carro' => $formCarro->createView(),
  598.                 'currentStep' => 1,
  599.                 'divisas' => $divisas,
  600.                 'divisasJson' => json_encode($divisasJson),
  601.                 'predefined' => $predefined,
  602.                 'ofi_var' => $ofi,
  603.                 'oficina' => $oficina,
  604.                 'div_f_nombre' => $div_f_nombre,
  605.                 'div_o_nombre' => $div_o_nombre,
  606.                 'permiteCompra' => $permiteCompra,
  607.                 /****/
  608.                 'provincias' => $provincias
  609.                 /****/
  610.             ));
  611.         }
  612.         
  613.         
  614.         private function setCart2($request$em)
  615.         {
  616.             $sesion $request->getSession();
  617.             $cartStep $sesion->get('cartStep');
  618.             $cartStep[2] = true;
  619.             $sesion->set('cartStep'$cartStep);
  620.             $carro $sesion->get('carro');
  621.             $oficina1 $_COOKIE['cookieoficina'];
  622.             if($oficina1 == 1){
  623.                 $oficina $em->getRepository('App\Entity\Oficina')->findOneById($this->getParameter('oficina_por_defecto'));
  624.             }else{
  625.                 $oficina $em->getRepository('App\Entity\Oficina')->findOneById($oficina1);
  626.             }
  627.             
  628.             $provincia $oficina->getProvincia();
  629.             $carro->setProvincia($provincia);
  630.             $carro->setOficina($oficina);
  631.             $carro->setUsuario($this->getUser());
  632.             $sesion->set('carro'$carro);
  633.         }
  634.         private function setInvitado($request$invitado)
  635.         {
  636.             $sesion $request->getSession();
  637.             $cartStep $sesion->get('cartStep');
  638.             $cartStep[2] = true;
  639.             $sesion->set('cartStep'$cartStep);
  640.             $carro $sesion->get('carro');
  641.             $carro->setInvitado($invitado);
  642.             $sesion->set('carro'$carro);
  643.         }
  644.         private function createFormNoCorreo($options)
  645.         {
  646.             $formCorreo $this->createFormBuilder()
  647.                 ->add('Dni_correo_sin'HiddenType::class, array()
  648.                 )
  649.                 ->add('email'TextType::class, array(
  650.                         'label' => false,
  651.                         'attr' => array(
  652.                             'placeholder' => 'Email'
  653.                         )
  654.                     )
  655.                 )
  656.                 ->add('password1'TextType::class, array(
  657.                         'label' => false,
  658.                         'attr' => array(
  659.                             'placeholder' => $options->getValue('cart2.password')
  660.                         )
  661.                     )
  662.                 )
  663.                 ->add('password2'TextType::class, array(
  664.                         'label' => false,
  665.                         'attr' => array(
  666.                             'placeholder' => $options->getValue('cart2.repassword')
  667.                         )
  668.                     )
  669.                 )
  670.                 ->add('submitNoCorreo'SubmitType::class, array(
  671.                         'label' => false,
  672.                         'attr' => array(
  673.                             'placeholder' => $options->getValue('cart2.repassword')
  674.                         )
  675.                     )
  676.                 )
  677.                 ->getForm();
  678.             return $formCorreo;
  679.         }
  680.         private function createFormCorreo($options)
  681.         {
  682.             $formCorreo $this->createFormBuilder()
  683.                 ->add('Dni_correo_con'HiddenType::class, array()
  684.                 )
  685.                 ->add('codigo_correo'TextType::class, array(
  686.                         'label' => false,
  687.                         'attr' => array(
  688.                             'placeholder' => $options->getValue('cart2.code')
  689.                         )
  690.                     )
  691.                 )
  692.                 ->add('password1'PasswordType::class, array(
  693.                         'label' => false,
  694.                         'attr' => array(
  695.                             'placeholder' => $options->getValue('cart2.password')
  696.                         )
  697.                     )
  698.                 )
  699.                 ->add('password2'PasswordType::class, array(
  700.                         'label' => false,
  701.                         'attr' => array(
  702.                             'placeholder' => $options->getValue('cart2.repassword')
  703.                         )
  704.                     )
  705.                 )
  706.                 ->add('submitCorreo'SubmitType::class, array(
  707.                         'label' => false,
  708.                         'attr' => array(
  709.                             'placeholder' => $options->getValue('cart2.repassword')
  710.                         )
  711.                     )
  712.                 )
  713.                 ->getForm();
  714.             return $formCorreo;
  715.         }
  716.         private function createFormSinPago($options)
  717.         {
  718.             $formCorreo $this->createFormBuilder()
  719.                 ->add('Dni_sin_pago'HiddenType::class, array()
  720.                 )
  721.                 ->add('email'TextType::class, array(
  722.                         'label' => false,
  723.                         'required' => true,
  724.                         'attr' => array(
  725.                             'placeholder' => 'Email'
  726.                         )
  727.                     )
  728.                 )
  729.                 ->add('nombre'TextType::class, array(
  730.                         'label' => false,
  731.                         'required' => true,
  732.                         'attr' => array(
  733.                             'placeholder' => $options->getValue('cart2.nombre.titular')
  734.                         )
  735.                     )
  736.                 )
  737.                 ->add('telefono'TextType::class, array(
  738.                         'label' => false,
  739.                         'required' => false,
  740.                         'attr' => array(
  741.                             'placeholder' => $options->getValue('cart2.telefono.titular')
  742.                         )
  743.                     )
  744.                 )
  745.                 ->add('submitSinPago'SubmitType::class, array(
  746.                         'label' => $options->getValue('cart2.compraPaga')
  747.                     )
  748.                 )
  749.                 ->getForm();
  750.             return $formCorreo;
  751.         }
  752.         private function getErrorMessages(\Symfony\Component\Form\Form $form) {
  753.             $errors = array();
  754.             foreach ($form->getErrors() as $key => $error) {
  755.                 if ($form->isRoot()) {
  756.                     $errors['#'][] = $error->getMessage();
  757.                 } else {
  758.                     $errors[] = $error->getMessage();
  759.                 }
  760.             }
  761.             foreach ($form->all() as $child) {
  762.                 if (!$child->isValid()) {
  763.                     $errors[$child->getName()] = $this->getErrorMessages($child);
  764.                 }
  765.             }
  766.             return $errors;
  767.         }
  768.         
  769.         public function ComprobarStock($request$doctrine$carro)
  770.         {
  771.             $pedidos $carro->getPedidos();
  772. //             dump($carro);dump($pedidos);die();
  773.             $em $doctrine->getManager();
  774.             foreach ($pedidos as $pedido) {
  775. //                     $oficina = $carro->getOficina();
  776.                     $oficina $em->getRepository('App\Entity\Oficina')->findOneBy(array('id' => $carro->getOficina()->getId()));
  777.                     $divisa $pedido->getDivisaFinal();
  778.                     $StockMax $em->getRepository('App\Entity\Stock')->findOneBy(array('oficina' => $oficina'divisa' => $divisa));
  779.                     if ($StockMax) {
  780.                         
  781.                     } else {
  782.                         $this->addFlash(
  783.                             'danger',
  784.                             'La oficina ' $oficina->getNombre() . ' no dispone de stock de la moneda ' $divisa->getNombre()
  785.                         );
  786.                         return false;
  787.                     }
  788.             }
  789.             return true;
  790.         }
  791.         
  792.         #[Route(path: [
  793.             'es' => '/carro2',
  794.             'en' => '/en/cart2'
  795.         ], name'app_cart_2')]
  796.         public function Cart2Action(Request $request,PersistenceManagerRegistry $doctrineSettingsManager $smWebServiceUsuarios $wsuWebServiceFunciones $wsfMailer $mailer)
  797.         {
  798.             $locale $request->getLocale();
  799.             $em $doctrine->getManager();
  800.             // dump($sesion = $request->getSession());die();
  801.             
  802.             if ($request->query->has('t')) {
  803.                 $t $request->query->get('t');
  804.                 return $this->redirect($this->generateUrl('app_cart_3', ['t' => $t]));
  805.             }
  806.             if ($re $this->CartRedirect($request2)) {
  807.                 return $re;
  808.             }
  809. //             $options = $this->container->get('dinamic_settings.manager');
  810.             //Formulario de busqueda de cliente
  811.             // $formShortReg = $this->createFormBuilder()
  812.             //     ->add('DNI', NumberType::class, array(
  813.             //             'label' => false,
  814.             //             'attr' => array(
  815.             //                 'placeholder' => $sm->getValue('cart2.idnumber')
  816.             //             )
  817.             //         )
  818.             //     )
  819.             //     ->getForm();
  820.             //Formulario para usuarios venidos del ERP con correo
  821.             // $formCorreo = $this->createFormCorreo($sm);
  822.             //Formulario para usuarios venidos del ERP sin correo
  823.             // $formNoCorreo = $this->createFormNoCorreo($sm);
  824.             /****/
  825.             $formSinPago $this->createFormSinPago($sm);
  826.             /****/
  827.             try {
  828.                 $stepBread $this->StepControl($request);
  829. //                 $request = $this->get('request');
  830.                 $local $request->getLocale();
  831.                 $invitado = new Invitado();
  832.                 $options = ['settings' => $sm];
  833.                 $invitadoForm $this->createForm(InvitadoType::class, $invitado$options);
  834.                 /****/
  835.                 $nameLogeado null;
  836.                 $emailLogeado null;
  837.                 if ($this->getUser()) {
  838.                     // $this->setCart2($request, $em);
  839.                     // return $this->redirect($this->generateUrl('app_cart_3'));
  840.                     $nameLogeado $this->getUser()->getName();
  841.                     $emailLogeado $this->getUser()->getEmail();
  842.                 }
  843.                 /****/
  844.                 // $user = new User();
  845.                 // $loginForm = $this->createForm(LoginType::class, $user);
  846.                 //Usuario invitado
  847.                 $invitadoForm->handleRequest($request);
  848.                 if ($invitadoForm->isSubmitted()) {
  849.                     if ($invitadoForm->isValid()) {
  850.                         $this->setInvitado($request$invitado);
  851.                         return $this->redirect($this->generateUrl('app_cart_3'));
  852.                     }
  853.                 }
  854.                 //Registro de usuarios desde el ERP sin email
  855.     //             $formNoCorreo->handleRequest($request);
  856.     //             if ($formNoCorreo->isSubmitted()) {
  857.     //                 if ($formNoCorreo->isValid()) {
  858.     //                     $data = $formNoCorreo->getData();
  859.     // //                     $WSF = $this->container->get('web.service.funciones', $em);
  860.     //                     $userERP = $wsf->getClienteporNumId($data['Dni_correo_sin']);
  861.     //                     if ($userERP) {
  862.     //                         $wsf->modificarEmail($userERP, $data['email']);
  863.     //                         $user = new User();
  864.     //                         $user->setIdCard($data['Dni_correo_sin']);
  865.     //                         $user->setEmail($data['email']);
  866.     //                         $user->setPassword($data['password1']);
  867.     //                         $user->setPlainPassword($data['password1']);
  868.     //                         $user->setErpId($userERP);
  869.     //                         $user->setEnabled(1);
  870.     //                         $user->setIdiomaPreferido($request->getLocale());
  871.     // //                         $userManager = $this->container->get('fos_user.user_manager');
  872.     // //                         $userManager->updatePassword($user);
  873.     //                         $em->persist($user);
  874.     //                         $em->flush();
  875.     //                         $route = 'app_cart_3';
  876.     //                         $url = $this->container->get('router')->generate($route);
  877.     //                         $response = new RedirectResponse($url);
  878.     //                         $this->authenticateUser($user, $response);
  879.     //                         return $response;
  880.     //                     }
  881.     //                 }
  882.     //             }
  883.     //
  884.     //             //Registro de usuarios desde el ERP con email
  885.     //             $formCorreo->handleRequest($request);
  886.     //             if ($formCorreo->isSubmitted()) {
  887.     //                 if ($formCorreo->isValid()) {
  888.     //                     $data = $formCorreo->getData();
  889.     //                     if ($data['password1'] == $data['password2']) {
  890.     //                         $user = $em->getRepository('App\Entity\User')->findOneByUsernameCanonical(strtolower($data['Dni_correo_con']));
  891.     //                         if ($user && $user->getConfirmationToken() == $data['codigo_correo']) {
  892.     //                             $user->setPlainPassword($data['password1']);
  893.     //                             $user->setConfirmationToken(null);
  894.     //                             $user->setPasswordRequestedAt(null);
  895.     //                             $user->setIdiomaPreferido($request->getLocale());
  896.     //                             $em->persist($user);
  897.     //                             $em->flush();
  898.     //                             $route = 'app_cart_3';
  899.     //                             $url = $this->container->get('router')->generate($route);
  900.     //                             $response = new RedirectResponse($url);
  901.     //                             $this->authenticateUser($user, $response);
  902.     //                             return $response;
  903.     //                         }
  904.     //                     }
  905.     //                 }
  906.     //             }
  907.                 $carro $this->getCart($request);
  908.                 // dump($carro);die();
  909.                 $reserva $carro->getReserva();
  910.                 if(isset($_COOKIE['cookieoficina'])) {
  911.                     $ofi = (integer)($_COOKIE['cookieoficina']);
  912.                     if ($ofi == 1) {
  913.                         $ofi $this->getParameter('oficina_por_defecto');
  914.                     }
  915. //                     if (!$this->ComprobarStock($request, $doctrine, $carro, $ofi))
  916. //                         return $this->redirect($this->generateUrl('app_cart_1'));
  917.                 } else {
  918.                     $ofi $this->getParameter('oficina_por_defecto');
  919.                 }
  920.                 // dump($carro);die();
  921.                 /****/
  922.                 $sesion $request->getSession();
  923.                 $metodoEntrega $sesion->get('metodoEntrega');
  924.                 if ($metodoEntrega == 1) {
  925.                     $oficina $em->getRepository('App\Entity\Oficina')->findOneBy(['id' => $carro->getOficina()]);
  926.                     if ($oficina->permiteCompra()) {
  927.                         $gastosEnv 0;
  928.                     } else {
  929.                         $gastosEnv $oficina->getProvincia()->getGastos();
  930.                     }
  931.                     $nomOfi $oficina->getNombre();
  932.                 } else if ($metodoEntrega == 2) {
  933.                     $provDest $em->getRepository('App\Entity\Provincia')->findOneBy(['id' => $carro->getProvincia()]);
  934.                     $gastosEnv $provDest->getGastos();
  935.                     $nomOfi null;
  936.                 }
  937.                 $totalPagar 0;
  938.                 $vaAComprar '';
  939.                 $listResumen '';
  940.                 foreach ($carro->getPedidos() as $pedido) {
  941.                     // dump($pedido->getDivisaFinal()->getImagen()->getId());die();
  942.                     if ($totalPagar != 0) {
  943.                         $vaAComprar $vaAComprar ' + ' $pedido->getCantidadFinal() . ' ' $pedido->getDivisaFinal()->getNombre();
  944.                     } else {
  945.                         $vaAComprar $pedido->getCantidadFinal() . ' ' $pedido->getDivisaFinal()->getNombre();
  946.                     }
  947.                     $totalPagar $totalPagar $pedido->getCantidadOrigen();
  948.                     $imgDiv $em->getRepository('App\Entity\Imagen')->findOneBy(['id' => $pedido->getDivisaFinal()->getImagen()->getId()]);
  949.                     $providerName $imgDiv->getProviderReference();
  950.                     $listResumen $listResumen '<li><img src="/upload/media/divisa/0001/01/' $providerName '" width="30px"> <span>' $pedido->getCantidadFinal() . '</span> ' $pedido->getDivisaFinal()->getNombre() . '</li>';
  951.                 }
  952.                 if ($totalPagar >= 500) {
  953.                     $carro->setFreeShipping(1);
  954.                     $gastosEnv 0;
  955.                 }
  956.                 // $codProm =
  957.                 $formSinPago->handleRequest($request);
  958.                 if ($formSinPago->isSubmitted()) {
  959.                     if ($formSinPago->isValid()) {
  960.                         $data $formSinPago->getData();
  961.                         $transaccion = new Transaccion();
  962.                         $user $em->getRepository('App\Entity\User')->findOneBy(['email' => $data['email']]);
  963.                         if ($user) {
  964.                             $carro->setUsuario($user);
  965.                             $sesion->set('carro'$carro);
  966.                             $transaccion->setUsuario($user);
  967.                         }
  968.                         $timestamp = (new \DateTime())->format('Y-m-d H:i:s');
  969.                         $base $data['email'] . '||' $timestamp;
  970.                         $random bin2hex(random_bytes(16));
  971.                         $token hash('sha256'$base '||' $random);
  972.                         $transaccion->setTokenEmail($token);
  973.                         $transaccion->setTitular($data['nombre']);
  974.                         $transaccion->setEmailTitular($data['email']);
  975.                         $transaccion->setTelefono($data['telefono']);
  976.                         if ($metodoEntrega == 1) {
  977.                             $oficina $em->getRepository('App\Entity\Oficina')->findOneBy(['id' => $ofi]);
  978.                             $transaccion->setOficina($oficina);
  979.                         } else if ($metodoEntrega == 2) {
  980.                             $transaccion->setProvincia($provDest);
  981.                         }
  982.                         $transaccion->setCupon($carro->getCodigoPromo());
  983.                         $transaccion->setTipoPromo($carro->getTipoPromo());
  984.                         $transaccion->setEstado('En pasarela de pago');
  985.                         $transaccion->setTipoPago('TPV');
  986.                         foreach ($carro->getPedidos() as $pedido) {
  987.                             $transaccionLinea = new TransaccionLinea();
  988.                             $transaccionLinea->setDivisaDestino($em->getReference('App\Entity\Divisa'$pedido->getDivisaFinal()->getId()));
  989.                             $transaccionLinea->setCantidad($pedido->getCantidadFinal());
  990.                             $transaccionLinea->setErpCode($pedido->getErpCode());
  991.                             $transaccion->addLinea($transaccionLinea);
  992.                         }
  993.                         $transaccion->setTotalLineas($totalPagar);
  994.                         $transaccion->setGastosEnvio((float)$gastosEnv);
  995.                         $transaccion->setTotal($totalPagar $gastosEnv);
  996.                         $transaccion->setIdioma(strtoupper($locale));
  997.                         // dump($transaccion->getTotal());die();
  998.                         $sesion->set('transaccion'$transaccion);
  999.                         $em->persist($transaccion);
  1000.                         $em->flush();
  1001.                         // dump($transaccion);die();
  1002.                         $redsysData $this->buildRedsys($request$transaccion);
  1003.                         $formTPV $this->container->get('form.factory')->createNamedBuilder(''FormType::class, array(), array(
  1004.                             'action' => $this->getParameter('redsys_gateway'),
  1005.                             'method' => 'POST',
  1006.                             'csrf_protection' => false,
  1007.                             'attr' => array('name' => 'tpv''id' => 'formTPV'),
  1008.                         ))
  1009.                             ->add('Ds_SignatureVersion'HiddenType::class, ['data' => $this->getParameter('redsys_version')])
  1010.                             ->add('Ds_MerchantParameters',  HiddenType::class, ['data' => $redsysData['params']])
  1011.                             ->add('Ds_Signature'HiddenType::class, ['data' => $redsysData['signature']])
  1012.                             ->getForm();
  1013.                         return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
  1014.                     }
  1015.                 }
  1016.                 /****/
  1017.                 // dump($gastosEnv + $totalPagar);die();
  1018.                 $returnArray = array(
  1019.                     // 'loginForm' => $loginForm->createView(),
  1020.                     'stepBread' => $stepBread,
  1021.                     // 'formShortReg' => $formShortReg->createView(),
  1022. //                     'fullForm' => $fullForm->createView(),
  1023.                     // 'formCorreo' => $formCorreo->createView(),
  1024.                     // 'formNoCorreo' => $formNoCorreo->createView(),
  1025.                     'clienteInvitado' => $invitadoForm->createView(),
  1026.                     'sm' => $sm,
  1027.                     'reserva' => $reserva,
  1028.                     'currentStep' => 2,
  1029.                     /****/
  1030.                     'formSinPago' => $formSinPago->createView(),
  1031.                     'metodoEntrega' => $metodoEntrega,
  1032.                     'gastosEnv' => $gastosEnv,
  1033.                     'totalPagar' => $totalPagar,
  1034.                     'vaAComprar' => $vaAComprar,
  1035.                     'codProm' => $carro->getCodigoPromo(),
  1036.                     'listResumen' => $listResumen,
  1037.                     'nameLogeado' => $nameLogeado,
  1038.                     'emailLogeado' => $emailLogeado,
  1039.                     'nomOfi' => $nomOfi
  1040.                     /****/
  1041.                 );
  1042.                 
  1043.                 return $this->render('default/carrito/carrito2.html.twig'$returnArray);
  1044.                 
  1045.             } catch (\Exception $e) {
  1046.                 if ($this->kernel->getEnvironment() == 'dev') throw $e;
  1047.                 $this->resetCart($request);
  1048.                 $catcher $this->container->get('web.service.catchException');
  1049.                 $log = new Log();
  1050.                 $log->setLocation('carro2');
  1051.                 $log->setUser($this->getUser());
  1052.                 $log->setText(json_encode($e->getTrace()));
  1053.                 $error $e->getMessage();
  1054.                 $catcher->saveException($log);
  1055.                 return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $error'currentStep' => 5));
  1056.             }
  1057.         }
  1058.         
  1059.         
  1060.         /**
  1061.         * @return Carro
  1062.         */
  1063.         private function getCart($request)
  1064.         {
  1065.             $sesion $request->getSession();
  1066.             return $sesion->get('carro');
  1067.         }
  1068.         
  1069.         
  1070.         public function CartRedirect(Request $request$paso)
  1071.         {
  1072.             $local $request->getLocale();
  1073.             $sesion $request->getSession();
  1074.             $cartStep $sesion->get('cartStep');
  1075.             // dump($cartStep);
  1076.             // dump($paso);
  1077.             // die();
  1078.             if ($logeado $this->authorizationChecker->isGranted('ROLE_ADMIN')) {
  1079.                 $this->addFlash(
  1080.                     'danger',
  1081.                     'Tu usuario no permite realizar compras (ADMIN)'
  1082.                 );
  1083.                 $response $this->redirect($this->generateUrl('app_cart_1'));
  1084.                 return $response;
  1085.             }
  1086.             if ($cartStep == null) {
  1087.                 //No ha hecho nada
  1088.                 $response $this->redirect($this->generateUrl('app_cart_1'));
  1089.                 return $response;
  1090.             } elseif ($paso and (!isset($cartStep[1]) or !$cartStep[1])) {
  1091.                 //No ha completado el primer paso
  1092.                 $response $this->redirect($this->generateUrl('app_cart_1'));
  1093.                 return $response;
  1094.             } elseif ($paso and (!isset($cartStep[2]) or !$cartStep[2])) {
  1095.                 //No ha completado el segundo paso
  1096.                 $response $this->redirect($this->generateUrl('app_cart_2'));
  1097.                 return $response;
  1098.             } elseif ($paso and (!isset($cartStep[3]) or !$cartStep[3])) {
  1099.                 //No ha completado el tercer paso
  1100.                 $response $this->redirect($this->generateUrl('app_cart_3'));
  1101.                 return $response;
  1102.             }
  1103.             $response false;
  1104.             return $response;
  1105.         }
  1106.         
  1107.         private function SaveCartShop(Request $request$carro3)
  1108.         {
  1109.             $sesion $request->getSession();
  1110.             //Validamos el paso 3
  1111.             $cartStep $sesion->get('cartStep');
  1112.             $cartStep[3] = true;
  1113.             $sesion->set('cartStep'$cartStep);
  1114.             //Guardamos los datos de la tienda
  1115.             $carro $sesion->get('carro');
  1116.             $carro->setOficina($carro3->getOficina());
  1117.             $carro->setFechaEntrega($carro3->getFechaEntrega());
  1118.             $carro->setHoraEntrega($carro3->getHoraEntrega());
  1119.             $carro->setComentario($carro3->getComentario());
  1120.             //Reset del otro metodo de entrega
  1121.             $carro->setDireccion(NULL);
  1122.             $carro->setCodigoPostal(NULL);
  1123.             $carro->setCiudad(NULL);
  1124.             $carro->setProvincia(NULL);
  1125.             $carro->setPais(NULL);
  1126.             $carro->setTipoPago($carro3->getTipoPago());
  1127. //             dump($carro3);die();
  1128.             $carro->setTitular($carro3->getTitular());
  1129.             $sesion->set('carro'$carro);
  1130.         }
  1131.         
  1132.         private function SaveDeliver(Request $request$carro3)
  1133.         {
  1134.             $sesion $request->getSession();
  1135.             $cartStep $sesion->get('cartStep');
  1136.             $cartStep[3] = true;
  1137.             $sesion->set('cartStep'$cartStep);
  1138.             //Guardamos la direccion de la tienda
  1139.             $carro $sesion->get('carro');
  1140.             $carro->setDireccion($carro3->getDireccion());
  1141.             $carro->setCodigoPostal($carro3->getCodigoPostal());
  1142.             $carro->setCiudad($carro3->getCiudad());
  1143.             $carro->setProvincia($carro3->getProvincia());
  1144.             $carro->setPais($carro3->getPais());
  1145.             $carro->setComentario($carro3->getComentario());
  1146.             $carro->setNameSend($carro3->getNameSend());
  1147.             $carro->setCardSend($carro3->getCardSend());
  1148.             //Reset del otro metodo de entrega
  1149.             $carro->setOficina(NULL);
  1150.             $carro->setFechaEntrega(NULL);
  1151.             $carro->setHoraEntrega(NULL);
  1152.             $carro->setTipoPago($carro3->getTipoPago());
  1153.             $carro->setTitular($carro3->getTitular());
  1154.             $sesion->set('carro'$carro);
  1155.         }
  1156.         #[Route(path: [
  1157.             'es' => '/carro3',
  1158.             'en' => '/en/cart3'
  1159.         ], name'app_cart_3')]
  1160.         public function Cart3Action(Request $requestPersistenceManagerRegistry $doctrineSettingsManager $sm,  WebServiceTPV $wstpvWebServiceFunciones $wsf)
  1161.         {
  1162.             try {
  1163.                 if ($request->query->has('t')) {
  1164.                     $em $doctrine->getManager();
  1165.                     $t $request->query->get('t');
  1166.                     $transaccion $em->getRepository('App\Entity\Transaccion')->findOneBy(['tokenEmail' => $t]);
  1167.                 } else {
  1168.                     return $this->redirect($this->generateUrl('app_cart_1'));
  1169.                 }
  1170.                 if ($transaccion && $transaccion->getEstado() == 'En pasarela de pago') {
  1171.                     $redsysData $this->buildRedsys($request$transaccion);
  1172.                     $formTPV $this->container->get('form.factory')->createNamedBuilder(''FormType::class, array(), array(
  1173.                         'action' => $this->getParameter('redsys_gateway'),
  1174.                         'method' => 'POST',
  1175.                         'csrf_protection' => false,
  1176.                         'attr' => array('name' => 'tpv''id' => 'formTPV'),
  1177.                     ))
  1178.                         ->add('Ds_SignatureVersion'HiddenType::class, ['data' => $this->getParameter('redsys_version')])
  1179.                         ->add('Ds_MerchantParameters',  HiddenType::class, ['data' => $redsysData['params']])
  1180.                         ->add('Ds_Signature'HiddenType::class, ['data' => $redsysData['signature']])
  1181.                         ->getForm();
  1182.                     return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
  1183.                 }
  1184.                 
  1185.                 //limpiamos el carro par no tenerlo ahĆ­, ya que la transaccion estĆ” creada
  1186.                 $this->resetCart($request);
  1187.                 if ($transaccion && ($transaccion->getFechaRecogida() != null || $transaccion->getDireccionCompleta() != null)) {
  1188.                     return $this->redirect($this->generateUrl('app_cart_5', ['t' => $transaccion->getTokenEmail()]));
  1189.                 }
  1190.                 // dump($transaccion);die();
  1191.                 //Redirect is something failed
  1192.                 // if ($re = $this->CartRedirect($request, 3)) {
  1193.                 //     return $re;//$this->CartRedirect($request, 3);
  1194.                 // }
  1195.                 // $carro = $this->getCart($request);
  1196.                 $json $this->getHorariosAction($request$em);
  1197.                 // $pedido = new Pedido();
  1198.                 // $nCarro = new Carro();
  1199.                 
  1200.                 $formShortReg $this->createFormBuilder()
  1201.                     ->add('DNI'NumberType::class, array(
  1202.                             'label' => false,
  1203.                             'attr' => array(
  1204.                                 'placeholder' => $sm->getValue('cart2.idnumber')
  1205.                             )
  1206.                         )
  1207.                     )
  1208.                     ->getForm();
  1209.                 $user = new User();
  1210.                 $loginForm $this->createForm(LoginType::class, $user);
  1211.                 if ($this->getUser()) {
  1212.                     $userLog true;
  1213.                 } else {
  1214.                     $userLog false;
  1215.                 }
  1216.                 //HACKS para que la divisa pase la validación del carro
  1217.                 // $pedido->setDivisaOrigen($em->getRepository('App\Entity\Divisa')->findOneByMaestro(1));
  1218.                 // $nCarro->setReserva(1);
  1219.                 // $formShop = $this->createForm(CartShop::class, $nCarro, array('carro' => $carro));
  1220.                 // $formDeliver = $this->createForm(CartDeliver::class, $nCarro);
  1221.                 $nTransaccion = new Transaccion();
  1222.                 $formShop $this->createForm(TransactionType::class, $nTransaccion);
  1223.                 $formDeliver $this->createForm(CartDeliver::class, $nTransaccion, array('transaccion' => $transaccion));
  1224.                 // $stepBread = $this->StepControl($request);
  1225.                 $local $request->getLocale();
  1226.                 $total $transaccion->getTotalLineas();
  1227.                 $ahora = new \DateTime('now');
  1228.                 $domingo false;
  1229.                 if ($ahora->format('N') == 7) {
  1230.                     $domingo true;
  1231.                 }
  1232.                 $totalEntregar 0;
  1233.                 foreach ($transaccion->getLineas() as $linea) {
  1234.                     $totalEntregar $totalEntregar $linea->getCantidad();
  1235.                 }
  1236.                 $listResumen '';
  1237.                 foreach ($transaccion->getLineas() as $linea) {
  1238.                     $imgDiv $em->getRepository('App\Entity\Imagen')->findOneBy(['id' => $linea->getDivisaDestino()->getImagen()->getId()]);
  1239.                     $providerName $imgDiv->getProviderReference();
  1240.                     $listResumen $listResumen '<li><img src="/upload/media/divisa/0001/01/' $providerName '" width="30px"> <span>' $linea->getCantidad() . '</span> ' $linea->getDivisaDestino()->getNombre() . '</li>';
  1241.                 }
  1242.                 if($transaccion->getOficina() != null){
  1243.                     $ofi $transaccion->getOficina()->getId();
  1244.                     $festivos $em->getRepository("App\Entity\DayOff")->findBy(array('oficina' => $ofi));
  1245.                 } else {
  1246.                     $ofi = (integer)0;
  1247.                     $festivos $em->getRepository("App\Entity\DayOff")->findBy(array('oficina' => $ofi));
  1248.                 }
  1249.                 $oficina $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => $ofi));
  1250.                 if (!$oficina) {
  1251.                     $oficina $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => 20));
  1252.                 }
  1253.                 
  1254.                 if ($request->getMethod() == 'POST') {
  1255.     //
  1256.                     //Pasamos los datos del carro 1 a la validacion del formulario
  1257.                     // $formShop->getData()->setPedidos($carro->getPedidos());
  1258.                     // $formShop->getData()->setReserva($carro->getReserva());
  1259.                     $formShop->handleRequest($request);
  1260.                     
  1261.                     $currentDateTime = new \DateTime('now');
  1262.                     $currentTime $currentDateTime->format('H:i');
  1263.                     
  1264.                     // Restricciones de recogida si son Libra o Dolar Estadounidense
  1265.                     if ($currentTime '14:00') {
  1266.                         if ($currentDateTime->format('N') == 5) {                      // Si el pedido entra Viernes por la maƱana
  1267.                             $currentDateTime->add(new \DateInterval('P3D'));
  1268.                         } elseif ($currentDateTime->format('N') == 6){                 // Si el pedido entra SĆ”bado por la maƱana
  1269.                             $currentDateTime->add(new \DateInterval('P2D'));
  1270.                         } else {                                                       // Si el pedido entra de Domingo a Jueves, por la maƱana
  1271.                             $currentDateTime->add(new \DateInterval('P1D'));
  1272.                         }
  1273.                     } else {
  1274.                         if ($currentDateTime->format('N') == 4) {                      // Si el pedido entra Jueves por la tarde
  1275.                             $currentDateTime->add(new \DateInterval('P4D'));
  1276.                             $currentDateTime->setTime(120);
  1277.                         } elseif ($currentDateTime->format('N') == 5){                 // Si el pedido entra Viernes por la tarde
  1278.                             $currentDateTime->add(new \DateInterval('P4D'));
  1279.                             $currentDateTime->setTime(120);
  1280.                         } elseif ($currentDateTime->format('N') == 6){                 // Si el pedido entra SĆ”bado por la tarde
  1281.                             $currentDateTime->add(new \DateInterval('P3D'));
  1282.                             $currentDateTime->setTime(120);
  1283.                         } else {                                                       // Si el pedido entra de Domingo a MiĆ©rcoles, por la tarde
  1284.                             $currentDateTime->add(new \DateInterval('P2D'));
  1285.                             $currentDateTime->setTime(120);
  1286.                         }
  1287.                     }
  1288.                     $restriccionDivisa false;
  1289.                     foreach ($transaccion->getLineas() as $linea) {
  1290.                         if ($linea->getDivisaDestino()->getId() != 24 && $linea->getDivisaDestino()->getId() != 12) {
  1291.                             $restriccionDivisa true;
  1292.                         }
  1293.                     }
  1294.                     // Restricciones de recogida si NO son ni Libra ni Dolar Estadounidense
  1295.                     if ($restriccionDivisa) {
  1296.                         $fechaRestriccion = new \DateTime('now');
  1297.                         // $fechaRestriccion->add(new \DateInterval('P2D'));
  1298.                         $currentTime $fechaRestriccion->format('H:i');
  1299.                         if ($currentTime '14:00') {
  1300.                             if ($fechaRestriccion->format('N') == 4) {                      // Si el pedido entra Jueves por la maƱana
  1301.                                 $fechaRestriccion->add(new \DateInterval('P4D'));
  1302.                             } elseif ($fechaRestriccion->format('N') == 5) {                // Si el pedido entra Viernes por la maƱana
  1303.                                 $fechaRestriccion->add(new \DateInterval('P4D'));
  1304.                             } elseif ($fechaRestriccion->format('N') == 6){                 // Si el pedido entra SĆ”bado por la maƱana
  1305.                                 $fechaRestriccion->add(new \DateInterval('P3D'));
  1306.                             } else {                                                        // Si el pedido entra de Domingo a Miercoles, por la maƱana
  1307.                                 $fechaRestriccion->add(new \DateInterval('P2D'));
  1308.                             }
  1309.                         } else {
  1310.                             if ($fechaRestriccion->format('N') == 3) {                      // Si el pedido entra MiĆ©rcoles por la tarde
  1311.                                 $fechaRestriccion->add(new \DateInterval('P5D'));
  1312.                                 $fechaRestriccion->setTime(120);
  1313.                             } elseif ($fechaRestriccion->format('N') == 4) {                // Si el pedido entra Jueves por la tarde
  1314.                                 $fechaRestriccion->add(new \DateInterval('P5D'));
  1315.                                 $fechaRestriccion->setTime(120);
  1316.                             } elseif ($fechaRestriccion->format('N') == 5){                 // Si el pedido entra Viernes por la tarde
  1317.                                 $fechaRestriccion->add(new \DateInterval('P5D'));
  1318.                                 $fechaRestriccion->setTime(120);
  1319.                             } elseif ($fechaRestriccion->format('N') == 6){                 // Si el pedido entra SĆ”bado por la tarde
  1320.                                 $fechaRestriccion->add(new \DateInterval('P4D'));
  1321.                                 $fechaRestriccion->setTime(120);
  1322.                             } else {                                                        // Si el pedido entra de Domingo a Martes, por la tarde
  1323.                                 $fechaRestriccion->add(new \DateInterval('P3D'));
  1324.                                 $fechaRestriccion->setTime(120);
  1325.                             }
  1326.                         }
  1327.                         if ($fechaRestriccion $currentDateTime) {
  1328.                             $currentDateTime $fechaRestriccion;
  1329.                         }
  1330.                     }
  1331.                     
  1332.                     
  1333.                     // $carro->setFechaDisponible($currentDateTime);
  1334.                     
  1335.                     //Formulario de oficina
  1336.                     if ($formShop->isSubmitted()) {
  1337.                         if ($formShop->isValid()) {
  1338.                             // $this->SaveCartShop($request, $nCarro);
  1339.                             if($transaccion->getOficina() != null) {
  1340.                                 foreach($festivos as $fest) {
  1341.                                     if ($nTransaccion->getFechaRecogida()->format('d/m/y') == $fest->getDate()->format('d/m/y')) {
  1342.                                         if ($fest->getHorarioReducidos()->isEmpty()) {
  1343.                                             $this->addFlash(
  1344.                                                 'danger',
  1345.                                                 'El dia seleccionado es festivo en esta oficina.'
  1346.                                             );
  1347.                                             return $this->redirect($this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()]));
  1348.                                         } else {
  1349.                                             foreach ($fest->getHorarioReducidos() as $horFest) {
  1350.                                                 $h1 \DateTime::createFromFormat('H:i'$horFest->getHoraInicio()->format('H:i'));
  1351.                                                 $h2 \DateTime::createFromFormat('H:i'$horFest->getHoraFin()->format('H:i'));
  1352.                                                 $h3 \DateTime::createFromFormat('H:i'$nTransaccion->getHoraRecogida());
  1353.                                                 if (($h1 $h3 || $h2 $h3) || ($horFest->getHoraInicio()->format('H:i') == '00:00' && $horFest->getHoraFin()->format('H:i') == '00:00')) {
  1354.                                                     $this->addFlash(
  1355.                                                         'danger',
  1356.                                                         'El dia seleccionado es festivo en esta oficina.'
  1357.                                                     );
  1358.                                                     return $this->redirect($this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()]));
  1359.                                                 }
  1360.                                             }
  1361.                                         }
  1362.                                     }
  1363.                                 }
  1364.                                 $fecha $nTransaccion->getFechaRecogida()->format('Y-m-d');
  1365.                                 $hora $nTransaccion->getHoraRecogida();
  1366.                                 $fechaHoraRecogida = new \DateTime("$fecha $hora"$nTransaccion->getFechaRecogida()->getTimezone());
  1367.                                 if ($totalEntregar >= 50 || !$transaccion->getOficina()->permiteCompra()) {
  1368.                                     if ($fechaHoraRecogida $currentDateTime) {
  1369.                                         $this->addFlash(
  1370.                                             'danger',
  1371.                                             '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")
  1372.                                         );
  1373.                                         return $this->redirect($this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()]));
  1374.                                     }
  1375.                                 } else if ($restriccionDivisa) {
  1376.                                     $this->addFlash(
  1377.                                         'danger',
  1378.                                         '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")
  1379.                                     );
  1380.                                     return $this->redirect($this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()]));
  1381.                                 }
  1382.                             }
  1383.                             $transaccion->setUsuario($this->getUser());
  1384.                             $transaccion->setFechaRecogida($nTransaccion->getFechaRecogida());
  1385.                             $hora \DateTime::createFromFormat('H:i'$nTransaccion->getHoraRecogida());
  1386.                             $transaccion->setHoraRecogida($hora);
  1387.                             $transaccion->setAnotacion($nTransaccion->getAnotacion());
  1388.                             $transaccion->setEmailTitular($this->getUser()->getEmail());
  1389.                             // dump($transaccion);die();
  1390.                             $em->persist($transaccion);
  1391.                             $em->flush();
  1392.                             
  1393.                             return $this->redirect($this->generateUrl('app_cart_5', ['t' => $transaccion->getTokenEmail()]));
  1394.                         }
  1395.                     }
  1396.                     //Formulario de envio
  1397.                     $formDeliver->handleRequest($request);
  1398.                     if ($formDeliver->isSubmitted()) {
  1399.                         if ($formDeliver->isValid()) {
  1400.                             // $this->SaveDeliver($request, $nCarro);
  1401.                             $transaccion->setUsuario($this->getUser());
  1402.                             $transaccion->setDireccionCompleta($nTransaccion->getDireccionCompleta());
  1403.                             $transaccion->setCodigoPostal($nTransaccion->getCodigoPostal());
  1404.                             $transaccion->setCiudad($nTransaccion->getCiudad());
  1405.                             $transaccion->setPais($nTransaccion->getPais());
  1406.                             $transaccion->setAnotacion($nTransaccion->getAnotacion());
  1407.                             $transaccion->setCardSend($nTransaccion->getCardSend());
  1408.                             $transaccion->setNameSend($nTransaccion->getNameSend());
  1409.                             $transaccion->setEmailTitular($this->getUser()->getEmail());
  1410.                             // dump($transaccion);die();
  1411.                             $em->persist($transaccion);
  1412.                             $em->flush();
  1413.                             $response $this->redirect($this->generateUrl('app_cart_5', ['t' => $transaccion->getTokenEmail()]));
  1414.                             
  1415.                             return $response;
  1416.                         }
  1417.                     }
  1418.                 }
  1419.                 // foreach($oficina->getDayoffs() as $dayo) {
  1420.                 //     dump($dayo);
  1421.                 // }
  1422.                 // die();
  1423.                 $provincias $em->getRepository("App\Entity\Provincia")->findAll();
  1424.                 $localidades $em->getRepository("App\Entity\Localidad")->findAll();
  1425.                 $metodosPago $em->getRepository("App\Entity\MetodoPago")->findBy([], ['position' => 'ASC']);
  1426.                 
  1427.                 // $totalEntregar = 0;
  1428.                 // foreach ($carro->getPedidos() as $pedido) {
  1429.                 //     $totalEntregar = $totalEntregar + $pedido->getCantidadFinal();
  1430.                 // }
  1431.                 
  1432. //                 $metodosPagoJson = [];
  1433. //                 foreach($metodosPago as $d)
  1434. //                     $metodosPagoJson[$d->getId()] = [
  1435. //                         'activo' => $d->isActivo(),
  1436. //                         'nombre' => $d->getNombre(),
  1437. //                     ];
  1438. //                 dump($metodosPagoJson);die();
  1439.                 
  1440.                 return $this->render('default/carrito/carrito3.html.twig', array(
  1441.                     // 'stepBread' => $stepBread,
  1442.                     // 'carro' => $carro,
  1443.                     'formShop' => $formShop->createView(),
  1444.                     'formDeliver' => $formDeliver->createView(),
  1445.                     'json' => $json,
  1446.                     'localidades' => $localidades,
  1447.                     'provincias' => $provincias,
  1448.                     'ofi_var' => $ofi,
  1449.                     'sm' => $sm,
  1450.                     'currentStep' => 3,
  1451.                     'total' => $total,
  1452.                     'ofii' => $oficina,
  1453.                     'metodosPago' =>$metodosPago,
  1454.                     'festivos' => $festivos,
  1455.                     'totalEntregar' => $totalEntregar,
  1456.                     'domingo' => $domingo,
  1457.                     'loginForm' => $loginForm->createView(),
  1458.                     'formShortReg' => $formShortReg->createView(),
  1459.                     'userLog' => $userLog,
  1460.                     'transaccion' => $transaccion,
  1461.                     'listResumen' => $listResumen,
  1462.                 ));
  1463.             } catch (\Exception $e) {
  1464.                 if ($this->kernel->getEnvironment() == 'dev') throw $e;
  1465.                 $this->resetCart($request);
  1466.                 $this->deleteErpSale($carro,$wstpv);
  1467.                 $catcher $this->container->get('web.service.catchException');
  1468.                 $log = new Log();
  1469.                 $log->setLocation('carro3');
  1470.                 $log->setUser($this->getUser());
  1471.                 $log->setText(json_encode($e->getTrace()));
  1472.                 $error $e->getMessage();
  1473.                 $catcher->saveException($log);
  1474.                 return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $error'currentStep' => 5));
  1475.             }
  1476.         }
  1477.         
  1478.         
  1479.         public function obtenerDatosOficina($idPersistenceManagerRegistry $doctrineSettingsManager $smRequest $request)
  1480.         {
  1481.             $em $doctrine->getManager();
  1482.             $oficina $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => $id));
  1483.             $festivos $em->getRepository("App\Entity\DayOff")->findBy(array('oficina' => $id));
  1484.             $carro $this->getCart($request);
  1485.             $totalEntregar 0;
  1486.             foreach ($carro->getPedidos() as $pedido) {
  1487.                 $totalEntregar $totalEntregar $pedido->getCantidadFinal();
  1488.             }
  1489.             $ahora = new \DateTime('now');
  1490.             $domingo false;
  1491.             if ($ahora->format('N') == 7) {
  1492.                 $domingo true;
  1493.             }
  1494. //             dump($totalEntregar);die();
  1495.             
  1496.             return $this->render('default/carrito/horarioOficina.html.twig', array(
  1497.                     'ofii' => $oficina,
  1498.                     'festivos' => $festivos,
  1499.                     'sm' => $sm,
  1500.                     'totalEntregar' => $totalEntregar,
  1501.                     'domingo' => $domingo,
  1502.                 ));
  1503.         }
  1504.         
  1505.         public function comprobarTitular(Request $request)
  1506.         {
  1507.             $igual 'No igual';
  1508.             try{
  1509.                 $user $this->getUser();
  1510.                 $titular $request->request->get('titular');
  1511.                 
  1512.                 /*$palabrasTitutar = explode(' ', $titular);
  1513.                 $palabrasUser = explode(' ', $user->getName());
  1514.                 $nomTitular = strtolower($palabrasTitutar[0]);
  1515.                 $nomUser = strtolower($palabrasUser[0]);*/
  1516.                 $nomUser mb_strtolower($user->getName());
  1517.                 $nomTitular mb_strtolower($titular);
  1518.                 
  1519.                 if ($nomUser == $nomTitular) {
  1520.                     $igual 'Igual';
  1521.                 }
  1522.             } catch (\Exception $e) {
  1523.                 return new JsonResponse(['error' => $e->getMessage()], 500);
  1524.             }
  1525.             
  1526.             return new Response($igual);
  1527.         }
  1528.         
  1529.         
  1530.         /**
  1531.         * Tras realizar la compra actualizamos el stock
  1532.         * de la tienda
  1533.         * @param $carro
  1534.         * @throws \Exception
  1535.         */
  1536.         public function ActualizarStock($doctrine$carro)
  1537.         {
  1538.             $pedidos $carro->getPedidos();
  1539.             $divisas = array();
  1540.             $em $doctrine->getManager();
  1541.             $repo $em->getRepository('App\Entity\Existencia');
  1542.             foreach ($pedidos as $pedido) {
  1543.                 $Existencia $repo->findOneBy(array('oficina' => $carro->getOficina(), 'dia' => $carro->getFechaEntrega(), 'divisa' => $pedido->getDivisaFinal()));
  1544.                 //La validacion del stock se realiza en el carro 1 y 3
  1545.                 //Una vez llegados aqui damos por senteado que no estĆ”
  1546.                 //haciendo nada raro con el stock
  1547.                 if ($Existencia) {
  1548.                     //Si ya estĆ” en la tabla de stock se resta la cantidad actual
  1549.                     $stock $Existencia->getCantidad();
  1550.                     $resta $stock $pedido->getCantidadFinal();
  1551.                     $Existencia->setCantidad($resta);
  1552.                     $em->persist($Existencia);
  1553.                     $em->flush();
  1554.                 } else {
  1555.                     //Si no estĆ” en la tabla de stocks se crea una nueva fila y
  1556.                     //se resta la cantidad final
  1557.                     $Existencia = new Existencia();
  1558.                     $oficina $carro->getOficina();
  1559.                     $divisa $pedido->getDivisaFinal();
  1560.                     $StockMax $em->getRepository('App\Entity\Stock')->findOneBy(array('oficina' => $oficina'divisa' => $divisa));
  1561.                     if ($StockMax) {
  1562.                         $resta $StockMax->getStockMaximo() - $pedido->getCantidadFinal();
  1563.                         $Existencia->setDivisa($em->getReference('App\Entity\Oficina'$divisa->getId()));
  1564.                         $Existencia->setOficina($em->getReference('App\Entity\Oficina'$carro->getOficina()->getId()));
  1565.                         $Existencia->setCantidad($resta);
  1566.                         $Existencia->setDia($carro->getFechaEntrega());
  1567.                         if (!$em->isOpen()) {
  1568.                             "NO Esta abierta";
  1569.                         }
  1570.                         $em->persist($Existencia);
  1571.                         $em->flush();
  1572.                     } else {
  1573. //                         throw new \Exception('La oficina: [' . $oficina . '] no dispone de stock de la mondea:[' . $divisa->getNombre() . ']');
  1574.                     }
  1575.                 }
  1576.             }
  1577.         }
  1578.         
  1579.         
  1580.         /**
  1581.         * Saca la Reserva del carro, la persiste en el ERP y en local.
  1582.         * Y manda el correo de notificación al usuario
  1583.         * @param Carro $carro carro de compra
  1584.         * @return Reserva Estado de la operación
  1585.         * @throws \Exception Fallo en el ERP
  1586.         *
  1587.         */
  1588.         private function persistBooking(PersistenceManagerRegistry $doctrineWebServiceUsuarios $wsuWebServiceFunciones $wsfMailer $mailer$carro)
  1589.         {
  1590.             $em $doctrine->getManager();
  1591. //             $WSF = $this->container->get('web.service.funciones', $em);
  1592. //             $WSU = $this->container->get('web.service.usuarios', $em);
  1593. //             $mailer = $this->container->get('dinamic_shop.mailer');
  1594.             if ($this->getUser()) {
  1595.                 $userERP $this->getUser()->getErpId();
  1596.             } else {
  1597.                 $userERP 'INVITADO';
  1598.             }
  1599.             $Reserva = new Reserva();
  1600.             //PEDIDO DE USUARIO REGISTRADO
  1601.             if ($userERP != 'INVITADO') {
  1602.                 $clienteERP $wsu->findOne($userERP);
  1603.                 $Reserva->setUsuario($em->getReference('App\Entity\User'$this->getUser()->getId()));
  1604.                 $tipoC 'USUARIO';
  1605.             } //PEDIDO DE USUARIO INVITADO
  1606.             else {
  1607.                 $tipoC 'INVITADO';
  1608.                 $Reserva->setNombre($carro->getInvitado()->getNombre());
  1609.                 $Reserva->setApellido($carro->getInvitado()->getApellidos());
  1610.                 $Reserva->setTelefono($carro->getInvitado()->getTelefono());
  1611.                 $Reserva->setEmail($carro->getInvitado()->getEmail());
  1612.                 $clienteERP $carro->getInvitado();
  1613.             }
  1614.             $oficina $em->getRepository("App\Entity\Oficina")->findOneById($carro->getOficina()->getId());
  1615.             $Reserva->setOficina($em->getReference('App\Entity\Oficina'$oficina->getId()));
  1616.             $Reserva->setHoraRecogida($carro->getHoraEntrega());
  1617.             $Reserva->setCupon($carro->getCodigoPromo());
  1618.             $Reserva->setFechaRecogida($carro->getFechaEntrega());
  1619.             $Reserva->setEstado('ACEPTADA');
  1620.             $carro->setOficina($oficina);
  1621.             $cupon $carro->getCodigoPromo();
  1622.             $rep_cup $em->getRepository('App\Entity\Cupon')->findOneBy(['codigo'=>$cupon]);
  1623.             if($rep_cup){
  1624.             $aux $rep_cup->getTotalUsos();
  1625.             $rep_cup->setTotalUsos($aux-1);
  1626.             $em->persist($rep_cup);
  1627.             }
  1628.             //Mandamos linea a linea la reserva y la guardamos en
  1629.             //la BBDD
  1630.             foreach ($carro->getPedidos() as $linea) {
  1631.                 $respuesta $wsf->RegistrarReserva($carro$linea$clienteERP$tipoC);
  1632.                 if ($respuesta) {
  1633.                     $ReservaLinea = new ReservaLinea();
  1634.                     $ReservaLinea->setErpCode($respuesta);
  1635.                     $ReservaLinea->setDivisaOrigen($em->getReference('App\Entity\Divisa'$linea->getDivisaOrigen()->getId()));
  1636.                     $ReservaLinea->setDivisaDestino($em->getReference('App\Entity\Divisa'$linea->getDivisaFinal()->getId()));
  1637.                     $ReservaLinea->setCantidad($linea->getCantidadFinal());
  1638.                     $Reserva->addLinea($ReservaLinea);
  1639.                     $em->persist($ReservaLinea);
  1640.                 } else {
  1641.                     throw new \Exception("Fallo al registrar al reserva");
  1642.                 }
  1643.             }
  1644.             $em->persist($Reserva);
  1645.             $em->flush($Reserva);
  1646.             if ($tipoC == 'INVITADO') {
  1647.                 $mailer->successReserve(NULL$Reserva);
  1648.             } else {
  1649.                 $mailer->successReserve($this->getUser(), $Reserva);
  1650.             }
  1651.             return $Reserva;
  1652.         }
  1653.         /**
  1654.         * Actualiza la transacción en la base de datos
  1655.         * @param $request
  1656.         * @param $estado
  1657.         * @return Transaccion
  1658.         */
  1659.         private function persistTransaccion($doctrine$request$estado)
  1660.         {
  1661.             $em $doctrine->getManager();
  1662.             $sesion $request->getSession();
  1663.             /** @var Carro $carro */
  1664.             $carro $sesion->get('carro');
  1665.             $Transaccion = new Transaccion();
  1666.             if ($carro->getOficina()) {
  1667.                 $Transaccion->setOficina($em->getReference('App\Entity\Oficina'$carro->getOficina()->getId()));
  1668.             }
  1669.             $Transaccion->setUsuario($em->getReference('App\Entity\User'$carro->getUsuario()->getId()));
  1670.             $Transaccion->sethoraRecogida($carro->getHoraEntrega());
  1671.             $Transaccion->setFechaRecogida($carro->getFechaEntrega());
  1672.             $Transaccion->setTipoPago($carro->getTipoPago());
  1673.             $Transaccion->setCupon($carro->getCodigoPromo());
  1674.             $Transaccion->setTipoPromo($carro->getTipoPromo());
  1675.             $Transaccion->setDireccionCompleta($carro->getDireccion());
  1676.             $Transaccion->setCodigoPostal($carro->getCodigoPostal());
  1677.             $Transaccion->setCiudad($carro->getCiudad());
  1678.             $Transaccion->setEstado($estado);
  1679.             $Transaccion->setPais($carro->getPais());
  1680.             $Transaccion->setAnotacion($carro->getComentario());
  1681.             $Transaccion->setTiempoEnvio($carro->getFechaEntrega());
  1682.             //si el descuento es de tipo divisa descontar usos
  1683.             if ($carro->getTipoPromo() == Carro::TIPO_PROMO_DIVISA) {
  1684.                 $cupon $carro->getCodigoPromo();
  1685.                 $rep_cup $em->getRepository('App\Entity\Cupon')->findOneBy(['codigo'=>$cupon]);
  1686.                 if($rep_cup){
  1687.                 $aux $rep_cup->getTotalUsos();
  1688.                 $rep_cup->setTotalUsos($aux-1);
  1689.                 $em->persist($rep_cup);
  1690.                 }
  1691.             }
  1692.             if ($carro->getProvincia() && !$carro->getFreeShipping()) {
  1693.                 $Transaccion->setProvincia($em->getReference('App\Entity\Provincia'$carro->getProvincia()->getId()));
  1694.             }
  1695.             if ($carro->getCardSend() != null) {
  1696.                 $Transaccion->setCardSend($carro->getCardSend());
  1697.                 $Transaccion->setNameSend($carro->getNameSend());
  1698.                 $Transaccion->setTitular($carro->getTitular());
  1699.             }
  1700.             if ($carro->getTipoPago() == "TPV") {
  1701.                 $Transaccion->setTitular($carro->getTitular());
  1702.             }
  1703.             foreach ($carro->getPedidos() as $pedido) {
  1704.                 $TransaccionLinea = new TransaccionLinea();
  1705.                 $TransaccionLinea->setDivisaDestino($em->getReference('App\Entity\Divisa'$pedido->getDivisaFinal()->getId()));
  1706.                 $TransaccionLinea->setCantidad($pedido->getCantidadFinal());
  1707.                 $TransaccionLinea->setErpCode($pedido->getErpCode());
  1708.                 $Transaccion->addLinea($TransaccionLinea);
  1709.             }
  1710.             $Transaccion->setTotalLineas($carro->getTotalTransaccion()-$carro->getGastosEnvio());
  1711.             $Transaccion->setGastosEnvio($carro->getGastosEnvio());
  1712.             
  1713. //             dump($Transaccion);die();
  1714.             $valor_trans $Transaccion->getId();
  1715.             if(isset($_COOKIE['afcodigo'])){
  1716.                 //  $numero = substr($_COOKIE['afcodigo'], 0);
  1717.                 $numero Utils::decode_afcode($_COOKIE['afcodigo']);
  1718.             //    var_dump($numero);die();
  1719.                 //No se puede asignar la transaccion al afiliado
  1720.                 if ($numero and $carro->getUsuario()->getId() != (int)$numero) {
  1721.                     $numero $em->getRepository('App\Entity\User')->findOneById($numero);
  1722.                     $Transaccion->setUsuarioAfiliado($numero);
  1723.                 }
  1724.             }else{
  1725.             }
  1726.             //Guardamos en sesion y base de datos
  1727.             $sesion->set('transaccion'$Transaccion);
  1728.             $em->persist($Transaccion);
  1729.             $em->flush();
  1730.             return $Transaccion;
  1731.         }
  1732.         /**
  1733.         * Parche para cargar las traducciones ya que las entidades
  1734.         * se persisten con las relaciones por referencia.
  1735.         * @return array
  1736.         */
  1737.         protected function loadDivisaTraducciones(PersistenceManagerRegistry $doctrineRequest $request)
  1738.         {
  1739.             $em $doctrine->getManager();
  1740.             $repo $em->getRepository('App\Entity\DivisaTranslation');
  1741.             $sesion $request->getSession();
  1742.             $carro $sesion->get('carro');
  1743. //             $idioma = $request->getLocale();
  1744. //             $idioma = $em->getRepository('App\Entity\Idioma')->findOneByUrl($idioma);
  1745.             $pedidos $carro->getPedidos();
  1746.             foreach ($pedidos as $key => $pedido) {
  1747.                 $origenes[$key] = $repo->findOneBy(['translatable' => $pedido->getDivisaOrigen()/*, 'idioma' => $idioma*/]);
  1748.                 $destinos[$key] = $repo->findOneBy(['translatable' => $pedido->getDivisaFinal()/*, 'idioma' => $idioma*/]);
  1749.             }
  1750.             return ['origenes' => $origenes'destinos' => $destinos];
  1751.         }
  1752.         /**
  1753.         * Borras las ventas del ERP.
  1754.         * Se llama a esta función cuando el usuario va para atrĆ”s,
  1755.         * hay una excepción o algĆŗn fallo en el ERP.
  1756.         * @param Carro $cart
  1757.         * @return bool Estado de la operación
  1758.         */
  1759.         protected function deleteErpSale($cart,  WebServiceTPV $wstpv)
  1760.         {
  1761. //             $WSTPV = $this->container->get('web.service.tpv', $em);
  1762.             $success 1;
  1763.             foreach ($cart->getPedidos() as $pedido) {
  1764.                 $success *= $wstpv->BorrarVenta($pedido->getErpCode());
  1765.                 $pedido->setErpCode(NULL);
  1766.             }
  1767.             $cart->setTotalTransaccion(NULL);
  1768.             return $success;
  1769.         }
  1770.         private function buildRedsys($request$transaccion)
  1771.         {
  1772.             $local $request->getLocale();
  1773.             $redsys = new ApiRedsys();
  1774.             
  1775.             // Valores de entrada
  1776.             $terminal "001";
  1777.             $moneda "978";
  1778.             $trans "1";
  1779.             //PASARELA DE PAGO
  1780.             $url $this->generateUrl('app_cart_notification', [], UrlGeneratorInterface::ABSOLUTE_URL);
  1781.             // $urlOK = $this->generateUrl('app_cart_5', ['t' => $transaccion->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
  1782.             $urlOK $this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()], UrlGeneratorInterface::ABSOLUTE_URL);
  1783.             $urlKO $this->generateUrl('app_cart_critical', ['t' => $transaccion->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
  1784.             $id str_pad($transaccion->getId(), 4"0"STR_PAD_LEFT);
  1785. //             $amount = money_format($transaccion->getTotal() * 100, 2);
  1786.             $amount number_format($transaccion->getTotal(),2,"","");
  1787.             // Se Rellenan los campos
  1788.             $redsys->setParameter("DS_MERCHANT_AMOUNT"$amount);
  1789.             $redsys->setParameter("DS_MERCHANT_ORDER"strval($id));
  1790.             $redsys->setParameter("DS_MERCHANT_MERCHANTCODE"$this->getParameter('redsys_fuc'));
  1791.             $redsys->setParameter("DS_MERCHANT_CURRENCY"$moneda);
  1792.             $redsys->setParameter("DS_MERCHANT_TRANSACTIONTYPE"$trans);
  1793.             $redsys->setParameter("DS_MERCHANT_TERMINAL"$terminal);
  1794.             $redsys->setParameter("DS_MERCHANT_MERCHANTURL"$url);
  1795.             $redsys->setParameter("DS_MERCHANT_URLOK"$urlOK);
  1796.             $redsys->setParameter("DS_MERCHANT_URLKO"$urlKO);
  1797.             $redsys->setParameter("Ds_Merchant_MerchantData"$transaccion->getTitular());
  1798.             $return['params'] = $redsys->createMerchantParameters();
  1799.             
  1800.             $return['signature'] = $redsys->createMerchantSignature($this->getParameter('redsys_key'));
  1801.             return $return;
  1802.         }
  1803.         
  1804.         
  1805.         #[Route(path: [
  1806.             'es' => '/carro4',
  1807.             'en' => '/en/cart4'
  1808.         ], name'app_cart_4')]
  1809.         public function Cart4Action(Request $request,PersistenceManagerRegistry $doctrineSettingsManager $smWebServiceTPV $wstpvMailer $mailerWebServiceFunciones $wsf)
  1810.         {
  1811.             $fullCart $this->getCart($request);
  1812.             // dump($fullCart);die();
  1813.             $ped $fullCart->getPedidos();
  1814.             
  1815. //             dump($fullCart);
  1816.             try {
  1817.                 if ($re $this->CartRedirect($request4)) {
  1818.                     return $re;
  1819.                 }
  1820.                 $gastosEnv 0;
  1821.                 $now = new \DateTime();
  1822.                 $day date('l'strtotime($now->format("Y-m-d H:i:s")));
  1823.                 $time date("H:i"strtotime($now->format("Y-m-d H:i:s")));
  1824.                 $em $doctrine->getManager();
  1825. //                 $options = $this->container->get('dinamic_settings.manager');
  1826.                 $fullCart $this->getCart($request);
  1827.                 
  1828.                 // Comprobar stock en tienda
  1829.                 
  1830.                 if ($fullCart->getOficina() != null) {
  1831. //                     if (!$this->ComprobarStock($request, $doctrine, $fullCart))
  1832. //                             return $this->redirect($this->generateUrl('app_cart_3'));
  1833.                     
  1834.                     $fest $em->getRepository('App\Entity\DayOff')->findBy(['oficina'=>$fullCart->getOficina()->getId()]);
  1835.                     
  1836.                     for ($i 0$i count($fest); $i++) { 
  1837.                         $fechFest $fest[$i]->getDate()->format("d/m/y");
  1838.                         $fechRec $fullCart->getFechaEntrega()->format("d/m/y");
  1839.                         if($fechFest == $fechRec) {
  1840.                             $this->addFlash(
  1841.                                 'danger',
  1842.                                 'Seleccione otro dĆ­a de recogida. El que ha seleccionado es festivo en esta oficina.'
  1843.                             );
  1844.                             return $this->redirect($this->generateUrl('app_cart_3'));
  1845.                         }
  1846.                     }
  1847.                     
  1848.                     
  1849.                     if ($fullCart->getReserva() == 1) {
  1850.                         $fullCart->setTotalEstimado(0);
  1851.                         for ($i 0$i count($ped); $i++) { 
  1852.                             $short $ped[$i]->getDivisaFinal()->getId();
  1853.                             
  1854.                             $maxDia $em->getRepository('App\Entity\Cotizaciones')->getMaxDia($fullCart->getOficina()->getId());
  1855.                             $fechaMax = new \DateTime($maxDia);
  1856.                             $nuevaCotizacion $em->getRepository('App\Entity\Cotizaciones')->findBy(['oficina'=>$fullCart->getOficina()->getId(), 'shortName'=>$short'dia'=>$fechaMax]);
  1857.                             
  1858.                             $nCant $nuevaCotizacion[0]->getPrecioVenta() * $ped[$i]->getCantidadFinal();
  1859.                             $ped[$i]->setCantidadOrigen($nCant);
  1860.                             $tot $fullCart->getTotalEstimado() + $nCant;
  1861.                             $fullCart->setTotalEstimado($tot);
  1862.                         }
  1863.                     } else {
  1864.                         $fullCart->setTotalEstimado(0);
  1865.                         for ($i 0$i count($ped); $i++) { 
  1866.                             $short $ped[$i]->getDivisaFinal()->getId();
  1867.                             
  1868.                             $maxDia $em->getRepository('App\Entity\Cotizaciones')->getMaxDia($fullCart->getOficina()->getId());
  1869.                             $fechaMax = new \DateTime($maxDia);
  1870.                             $nuevaCotizacion $em->getRepository('App\Entity\Cotizaciones')->findBy(['oficina'=>$this->getParameter('oficina_por_defecto'), 'shortName'=>$short'dia'=>$fechaMax]);
  1871.                             
  1872.                             $nCant $nuevaCotizacion[0]->getPrecioVenta() * $ped[$i]->getCantidadFinal();
  1873.                             $ped[$i]->setCantidadOrigen($nCant);
  1874.                             $tot $fullCart->getTotalEstimado() + $nCant;
  1875.                             $fullCart->setTotalEstimado($tot);
  1876.                         }
  1877.                     }
  1878. //                     $fullCart->getOficina()
  1879.                 }
  1880.                 $local $request->getLocale();
  1881.                 $total 0;
  1882.                 $formCard $this->createFormBuilder()
  1883.                     ->add('save40'SubmitType::class,
  1884.                         array('label' => $sm->getValue('cart4.pay'),
  1885.                             'attr' => array('class' => 'pagar bcol1')))
  1886.                     ->getForm();
  1887.                 $formTrans $this->createFormBuilder()
  1888.                     ->add('save41'SubmitType::class,
  1889.                         array('label' => $sm->getValue('cart4.pushOrder'),
  1890.                             'attr' => array('class' => 'pagar bcol1')))
  1891.                     ->getForm();
  1892.                 $formReserv $this->createFormBuilder()
  1893.                     ->add('save42'SubmitType::class,
  1894.                         array('label' => $sm->getValue('cart4.book'),
  1895.                             'attr' => array('class' => 'pagar bcol1')))
  1896.                     ->getForm();
  1897.             $repository $em->getRepository('App\Entity\Oficina');
  1898.             
  1899.             
  1900.             if(isset($_COOKIE['cookieoficina']) ){
  1901.                 $ofi = (integer)($_COOKIE['cookieoficina']);
  1902.                 $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$ofi));
  1903.                 if($ofi == 1){
  1904.                     $ofi $this->getParameter('oficina_por_defecto');
  1905.                     $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$this->getParameter('oficina_por_defecto')));
  1906.                 }
  1907.             } else {
  1908.                 $ofi = (integer)0;
  1909.                 $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChanges($local));
  1910.             }
  1911. //             $oficina = $repository->findOneBy(['id' => $ofi]);
  1912. //             $fullCart->setOficina($oficina);
  1913.                 //Si no es una reserva y no se ha guardado antes (por si refrescan la vista)
  1914.                 if (!$fullCart->getReserva() && !$fullCart->getTotalTransaccion()) {
  1915. //                 $WSTPV = $this->container->get('web.service.tpv', $em);
  1916.                     $gastosEnvio 0;
  1917.                     if (( $ofi == && !$fullCart->getFreeShipping()) || (!$fullCart->getOficina() && !$fullCart->getFreeShipping())) {
  1918.                         $gastosEnvio $fullCart->getProvincia()->getGastos();
  1919.                     }
  1920.                     
  1921. //                     var_dump($gastosEnvio); die();
  1922.                     $pedidos $fullCart->getPedidos();
  1923.                     //Persistir en ERP REMOTO
  1924.                     $fail false;
  1925.                     $total 0;
  1926.                     if($fullCart->getOficina() != null){
  1927.                         $ofC $em->getRepository('App\Entity\Oficina')->findOneById($fullCart->getOficina()->getId());
  1928.                         if ($ofC->permiteCompra()) {
  1929.                             $gastosEnv 0;
  1930.                             $fullCart->setGastosEnvio(0);
  1931.                         } else {
  1932.                             $gastosEnv $ofC->getProvincia()->getGastos();
  1933.                             $fullCart->setGastosEnvio($gastosEnv);
  1934.                         }
  1935.                     }else{
  1936.                         $gastosEnv $fullCart->getProvincia()->getGastos();
  1937.                     }
  1938.                     $cupon $fullCart->getCodigoPromo();
  1939.                     
  1940.                     if($fullCart->getFreeShipping()){
  1941.                         $gastosEnv 0;
  1942.                     }
  1943.                     for ($i 0$i count($pedidos); $i++) {
  1944.                         $extra = ($i == 0) ? $gastosEnv 0;
  1945.                         if($gastosEnv == 0){
  1946.                         $extra 0;
  1947.                         }
  1948.                         //  var_dump($extra);die();
  1949.                         if($cupon) {
  1950.                             if ($fullCart->getTipoPromo() == Carro::TIPO_PROMO_DIVISA AND $this->comprobarCupon($request$doctrine$cupon)) {
  1951.                                 // dump('a'); die();
  1952.                                 $rep_cup $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $cupon ]);
  1953.                                 $respuesta $wstpv->CrearVentaV2($fullCart$pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra$rep_cup->getCodigoTPV(), Carro::TIPO_PROMO_DIVISA);
  1954.                             } elseif ($fullCart->getTipoPromo() == Carro::TIPO_PROMO_CUPON) {
  1955.                             
  1956.                                 $resultado_cupon $this->comprobarCuponCodigo($cupon$fullCart->getTotalEstimado(),$wsf);
  1957.                                 if ($resultado_cupon === true) {
  1958.                                     $respuesta $wstpv->CrearVentaV2($fullCart$pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra$cuponCarro::TIPO_PROMO_CUPON);
  1959.                                 }
  1960.                                 else {
  1961.                                     $this->addFlash(
  1962.                                     'danger',
  1963.                                     $sm->getValue($resultado_cupon['error'])
  1964.                                     );
  1965.                                     return $this->redirect($this->generateUrl('app_cart_1'));
  1966.                                 }
  1967.                                 
  1968.                             }
  1969.                             else {
  1970.                                 // dump($fullCart->getTipoPromo()); die();
  1971.                                 $respuesta false;
  1972.                             }
  1973.                         }
  1974.                         else {
  1975.                             $respuesta $wstpv->CrearVenta($fullCart$pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra);
  1976.                         }
  1977.                         if (!$respuesta) {
  1978.                             throw new \Exception('Una de las lļæ½neas ha fallado en el ERP');
  1979.                         } else {
  1980.                             $descuento 0;
  1981.                             if (isset($respuesta['DescuentoTicket']) and $respuesta['DescuentoTicket'] > 0) {
  1982.                                 $descuento $respuesta['DescuentoTicket'];
  1983.                                 $fullCart->setDescuentoPromo($descuento);
  1984.                             }
  1985.                             //En local pillmamos el estimado porque Navision nos devolveria el importe de otro carrito
  1986.                             if ($this->kernel->getEnvironment() == 'dev')
  1987.                                 $total $fullCart->getTotalEstimado()+$gastosEnv-$descuento ;
  1988.                             else
  1989.                                 $total += $respuesta['importe'];
  1990.                             $pedidos[$i]->setErpCode($respuesta['erpCode']);
  1991.                             // dump($respuesta); die();
  1992.                         }
  1993.                     }
  1994.                     $fullCart->setTotalTransaccion($total);
  1995.                     $fullCart->setGastosEnvio($gastosEnv);
  1996.                     
  1997. //                     dump($hhh->getProvincia()->getGastos());die();
  1998.                     
  1999.                     //Si hay un problema en el ERP con alguna lļæ½nea
  2000.                     //reiniciamos el proceso
  2001.                     if ($fail) {
  2002.                         throw new \Exception('Una de las lļæ½neas ha fallado en el ERP');
  2003.                     }
  2004.                 }
  2005.                 
  2006.                 $reducido null;
  2007.                 if ($fullCart->getReserva()) {
  2008. //                     $dayoffs = $em->getRepository("App\Entity\HorarioReducido")->findOficinaDate($fullCart->getOficina(), $fullCart->getFechaEntrega());
  2009. //                     $dayoffs = $em->getRepository("App\Entity\DayOff")->findBy(array('id' => $ofi));
  2010. //                     $now = $fullCart->getFechaEntrega();
  2011. // 
  2012. //                     if ($dayoffs) {
  2013. // 
  2014. //                         if ($request->getLocale() == "es") {
  2015. //                             $reducido = "Horario reducido de " . $dayoffs->getHoraInicio()->format("H:i") . " a " . $dayoffs->getHoraFin()->format("H:i");
  2016. //                         } else {
  2017. //                             $reducido = "Reduced hours of " . $dayoffs->getHoraInicio()->format("H:i") . " to " . $dayoffs->getHoraFin()->format("H:i");
  2018. //                         }
  2019. //                     }
  2020.                 } else {
  2021.                     if ($fullCart->getTipoPago() == "TPV") {
  2022.                         $em $doctrine->getManager();
  2023.                         $repository $em->getRepository('App\Entity\Oficina');
  2024.                         if(isset($_COOKIE['cookieoficina']) ){
  2025.                             $ofi = (integer)($_COOKIE['cookieoficina']);
  2026.                             $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$ofi));
  2027.                             if($ofi == 1){
  2028.                                 $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$this->getParameter('oficina_por_defecto')));
  2029.                             }
  2030.                         } else {
  2031.                             $ofi = (integer)0;
  2032.                             $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$this->getParameter('oficina_por_defecto')));
  2033.                         }
  2034. //                         $oficina = $repository->findOneBy(['id' => $ofi]);
  2035. //                         $fullCart->setOficina($oficina);
  2036.                         //comprobamos stock
  2037.                         foreach ($fullCart->getPedidos() as $linea) {
  2038.                             if ($fullCart->getOficina()) { //Compromas los tiempos para recogida con tarjeta
  2039.                                 foreach ($fullCart->getOficina()->getStocks() as $stock) {
  2040.                                     if (!$stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //con stock con tarjeta
  2041.                                         if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2042.                                             $now->modify('+3 days');
  2043.                                         } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2044.                                             $now->modify('+4 days');
  2045.                                         } elseif ($day == "Saturday") { //sabado
  2046.                                             $now->modify('+3 days');
  2047.                                         } elseif ($day == "Sunday") {//domingo
  2048.                                             $now->modify('+2 days');
  2049.                                         } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2050.                                             $now->modify('+4 days');
  2051.                                         } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday" || $day == "Wednesday")) { //Lunes, martes o miercoles despues de las 3
  2052.                                             $now->modify('+2 days');
  2053.                                         } else {
  2054.                                             $now->modify('+1 days');
  2055.                                         }
  2056.                                     } elseif ($stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //sin stock
  2057.                                         if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2058.                                             $now->modify('+3 days');
  2059.                                         } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2060.                                             $now->modify('+4 days');
  2061.                                         } elseif ($day == "Saturday") { //sabado
  2062.                                             $now->modify('+3 days');
  2063.                                         } elseif ($day == "Sunday") {//domingo
  2064.                                             $now->modify('+2 days');
  2065.                                         } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2066.                                             $now->modify('+4 days');
  2067.                                         } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday" || $day == "Wednesday")) { //Lunes, martes o miercoles despues de las 3
  2068.                                             $now->modify('+2 days');
  2069.                                         } else {
  2070.                                             $now->modify('+1 days');
  2071.                                         }
  2072.                                     }
  2073.                                 }
  2074.                                 $now $this->comprobarFecha($now$fullCart->getOficina(), $em);
  2075. //                                 $dayoffs = $em->getRepository("App\Entity\HorarioReducido")->findOficinaDate($fullCart->getOficina(), $now);
  2076. // 
  2077. //                                 if ($dayoffs) {
  2078. // 
  2079. //                                     if ($request->getLocale() == "es") {
  2080. //                                         $reducido = "Horario reducido de " . $dayoffs->getHoraInicio()->format("H:i") . " a " . $dayoffs->getHoraFin()->format("H:i");
  2081. // 
  2082. //                                     } else {
  2083. //                                         $reducido = "Reduced hours of " . $dayoffs->getHoraInicio()->format("H:i") . " to " . $dayoffs->getHoraFin()->format("H:i");
  2084. //                                     }
  2085. //                                 }
  2086.                             } else { //sino es a domicilio
  2087.                                 //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);
  2088.                                 $oficina $em->getRepository("App\Entity\Oficina")->findOneById($this->getParameter('oficina_por_defecto'));
  2089.                                 $now $this->comprobarFecha($now$oficina$em);
  2090.                                 $day date('l'strtotime($now->format("Y-m-d H:i:s")));
  2091.                                 if ($linea->getDivisaFinal()->getCompraMinima() == 0) { //con stock con tarjeta
  2092.                                     if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2093.                                         $now->modify('+3 days');
  2094.                                     } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2095.                                         $now->modify('+4 days');
  2096.                                     } elseif ($day == "Saturday") { //sabado
  2097.                                         $now->modify('+3 days');
  2098.                                     } elseif ($day == "Sunday") {//domingo
  2099.                                         $now->modify('+2 days');
  2100.                                     } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2101.                                         $now->modify('+4 days');
  2102.                                     } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday" || $day == "Wednesday")) { //Lunes, martes o miercoles despues de las 3
  2103.                                         $now->modify('+2 days');
  2104.                                     } else {
  2105.                                         $now->modify('+1 days');
  2106.                                     }
  2107.                                 } elseif ($linea->getDivisaFinal()->getCompraMinima() != 0) { //sin stock
  2108.                                     if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2109.                                         $now->modify('+4 days');
  2110.                                     } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2111.                                         $now->modify('+5 days');
  2112.                                     } elseif ($day == "Saturday") { //sabado
  2113.                                         $now->modify('+4 days');
  2114.                                     } elseif ($day == "Sunday") {//domingo
  2115.                                         $now->modify('+3 days');
  2116.                                     } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2117.                                         $now->modify('+6 days');
  2118.                                     } elseif ($time >= "15:00" and $day == "Wednesday") { //jueves despues de las 3
  2119.                                         $now->modify('+5 days');
  2120.                                     } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
  2121.                                         $now->modify('+3 days');
  2122.                                     } else {
  2123.                                         $now->modify('+2 days');
  2124.                                     }
  2125.                                 }
  2126.                                 if ($day == "Sunday") { //sunday
  2127.                                     $now $this->comprobarFecha($now->modify('+1 days'), $oficina$em);
  2128.                                 }
  2129.                             }
  2130.                         }
  2131.                     } else if ($fullCart->getTipoPago() == "TRANSFERENCIA") { //tranferencia
  2132.                     
  2133.                         $em $doctrine->getManager();
  2134.                         $repository $em->getRepository('App\Entity\Oficina');
  2135.                         if(isset($_COOKIE['cookieoficina']) ){
  2136.                             $ofi = (integer)($_COOKIE['cookieoficina']);
  2137.                             $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$ofi));
  2138.                             if($ofi == 1){
  2139.                                 $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$this->getParameter('oficina_por_defecto')));
  2140.                             }
  2141.                         } else {
  2142.                             $ofi = (integer)0;
  2143.                             $cotizaciones json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local$this->getParameter('oficina_por_defecto')));
  2144.                         }
  2145. //                         $oficina = $repository->findOneBy(['id' => $ofi]);
  2146. //                         $fullCart->setOficina($oficina);
  2147.                         //comprobamos stock
  2148.                         foreach ($fullCart->getPedidos() as $linea) {
  2149.                             if ($fullCart->getOficina()) { //Compromas los tiempos para recogida con tarjeta
  2150.                                 foreach ($fullCart->getOficina()->getStocks() as $stock) {
  2151.                                     if (!$stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //con stock con transferencia
  2152.                                         if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2153.                                             $now->modify('+4 days');
  2154.                                         } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2155.                                             $now->modify('+4 days');
  2156.                                         } elseif ($day == "Saturday") { //sabado
  2157.                                             $now->modify('+4 days');
  2158.                                         } elseif ($day == "Sunday") {//domingo
  2159.                                             $now->modify('+3 days');
  2160.                                         } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
  2161.                                             $now->modify('+5 days');
  2162.                                         } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2163.                                             $now->modify('+5 days');
  2164.                                         } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
  2165.                                             $now->modify('+3 days');
  2166.                                         } else {
  2167.                                             $now->modify('+2 days');
  2168.                                         }
  2169.                                     } elseif ($stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //sin stock
  2170.                                         if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2171.                                             $now->modify('+4 days');
  2172.                                         } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2173.                                             $now->modify('+5 days');
  2174.                                         } elseif ($day == "Saturday") { //sabado
  2175.                                             $now->modify('+4 days');
  2176.                                         } elseif ($day == "Sunday") {//domingo
  2177.                                             $now->modify('+3 days');
  2178.                                         } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
  2179.                                             $now->modify('+5 days');
  2180.                                         } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2181.                                             $now->modify('+5 days');
  2182.                                         } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
  2183.                                             $now->modify('+3 days');
  2184.                                         } else {
  2185.                                             $now->modify('+2 days');
  2186.                                         }
  2187.                                     }
  2188.                                 }
  2189.                                 $now $this->comprobarFecha($now$fullCart->getOficina(), $em);
  2190.                             } else { //sino es a domicilio
  2191.                                 //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.
  2192.                                 $oficina $em->getRepository("App\Entity\Oficina")->findOneById($this->getParameter('oficina_por_defecto'));
  2193.                                 $dateBefore $now;
  2194.                                 $now $this->comprobarFecha($now$oficina$em);
  2195.                                 $dateAfter $now;
  2196.                                 $day date('l'strtotime($now->format("Y-m-d H:i:s")));
  2197.                                 if ($linea->getDivisaFinal()->getCompraMinima() == 0) { //con stock con transferencia
  2198.                                     if ($dateBefore->diff($dateAfter)->format('%R%a') == "+1" and $day == "Friday") { //viernes cerrado el jueves
  2199.                                         $now->modify('+3 days');
  2200.                                     } elseif ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2201.                                         $now->modify('+4 days');
  2202.                                     } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2203.                                         $now->modify('+4 days');
  2204.                                     } elseif ($day == "Saturday") { //sabado
  2205.                                         $now->modify('+4 days');
  2206.                                     } elseif ($day == "Sunday") {//domingo
  2207.                                         $now->modify('+3 days');
  2208.                                     } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
  2209.                                         $now->modify('+5 days');
  2210.                                     } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2211.                                         $now->modify('+5 days');
  2212.                                     } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
  2213.                                         $now->modify('+3 days');
  2214.                                     } else {
  2215.                                         $now->modify('+2 days');
  2216.                                     }
  2217.                                 } elseif ($linea->getDivisaFinal()->getCompraMinima() != 0) { //sin stock
  2218.                                     if ($time "15:00" and $day == "Friday") { //viernes antes del as 3
  2219.                                         $now->modify('+5 days');
  2220.                                     } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
  2221.                                         $now->modify('+6 days');
  2222.                                     } elseif ($day == "Saturday") { //sabado
  2223.                                         $now->modify('+5 days');
  2224.                                     } elseif ($day == "Sunday") {//domingo
  2225.                                         $now->modify('+4 days');
  2226.                                     } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
  2227.                                         $now->modify('+6 days');
  2228.                                     } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
  2229.                                         $now->modify('+6 days');
  2230.                                     } elseif ($time >= "15:00" and $day == "Tuesday") { //martes despues de las 3
  2231.                                         $now->modify('+6 days');
  2232.                                     } elseif ($time >= "15:00" and $day == "Monday") { //Lunes  despues de las 3
  2233.                                         $now->modify('+4 days');
  2234.                                     } else {
  2235.                                         $now->modify('+3 days');
  2236.                                     }
  2237.                                 }
  2238.                                 if ($day == "Sunday") { //sunday
  2239.                                     $now $this->comprobarFecha($now->modify('+1 days'), $oficina$em);
  2240.                                 }
  2241.                             }
  2242.                         }
  2243.                     } else if ($fullCart->getTipoPago() == "PAYPAL") {
  2244.                         
  2245.                         
  2246.                         
  2247.                     } else if ($fullCart->getTipoPago() == "BIZUM") {
  2248.                         
  2249.                         
  2250.                         
  2251.                     }
  2252.                     
  2253.                 }
  2254.                 
  2255. //                 $fullCart->setFechaEntrega($now);
  2256.                 $totalEntregar 0;
  2257.                 foreach ($fullCart->getPedidos() as $pedido) {
  2258.                     $totalEntregar $totalEntregar $pedido->getCantidadFinal();
  2259.                 }
  2260.                 $nuevaFechaDisponible = new \DateTime('now');
  2261.                 $domingo false;
  2262.                 if ($nuevaFechaDisponible->format('N') == 7) {
  2263.                     $domingo true;
  2264.                 }
  2265.                 
  2266.                 
  2267.                 if($fullCart->getOficina() != null) {
  2268.                     $oficinaE $em->getRepository('App\Entity\Oficina')->findOneById($fullCart->getOficina()->getId());
  2269.                     if ($totalEntregar >= 50 || !$oficinaE->permiteCompra()) {
  2270.                         if ($fullCart->getFechaEntrega() < $fullCart->getFechaDisponible() || $fullCart->getFechaEntrega() == $fullCart->getFechaDisponible() && $fullCart->getHoraEntrega()->format("H:i") < $fullCart->getFechaDisponible()->format("H:i")) {
  2271.                             $this->addFlash(
  2272.                                 'danger',
  2273.                                 '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")
  2274.                             );
  2275.                             return $this->redirect($this->generateUrl('app_cart_3'));
  2276.                         }
  2277.                     } else if ($domingo == true) {
  2278.                         $nuevaFechaDisponible->add(new \DateInterval('PT10H'));
  2279.                         $fullCart->setFechaDisponible($nuevaFechaDisponible);
  2280.                     } else {
  2281.                         $fullCart->setFechaDisponible($nuevaFechaDisponible);
  2282.                     }
  2283.                 }
  2284.                 
  2285. //                 dump($fullCart);die();
  2286. //                 $dayoffs = $em->getRepository('App\Entity\HorarioReducido')->findOficinaDate($fullCart->getOficina(), $now);
  2287. // 
  2288. //                 if ($dayoffs) {
  2289. // 
  2290. //                     if ($request->getLocale() == "es") {
  2291. //                         $reducido = "Horario reducido de " . $dayoffs->getHoraInicio()->format("H:i") . " a " . $dayoffs->getHoraFin()->format("H:i");
  2292. // 
  2293. //                     } else {
  2294. //                         $reducido = "Reduced hours of " . $dayoffs->getHoraInicio()->format("H:i") . " to " . $dayoffs->getHoraFin()->format("H:i");
  2295. //                     }
  2296. //                 }
  2297.                 
  2298.                 //Pago con tarjeta
  2299.                 $formCard->handleRequest($request);
  2300.                 if ($formCard->isSubmitted() and $formCard->isValid()) {
  2301.                     //PERSISTIR EN BASE DE DATOS LOCAL
  2302.                     $transaccion $this->persistTransaccion($doctrine$request'En pasarela de pago');
  2303.                     // Creamos un formulario oculto para enviar la informaciļæ½n mediante POST a los servidores del TPV
  2304.                     $redsysData $this->buildRedsys($request$transaccion);
  2305.                     
  2306.                     $formTPV $this->container->get('form.factory')->createNamedBuilder(''FormType::class, array(), array(
  2307.                         'action' => $this->getParameter('redsys_gateway'),
  2308.                         'method' => 'POST',
  2309.                         'csrf_protection' => false,
  2310.                         'attr' => array('name' => 'tpv''id' => 'formTPV'),
  2311.                     ))
  2312.                         ->add('Ds_SignatureVersion'HiddenType::class, ['data' => $this->getParameter('redsys_version')])
  2313.                         ->add('Ds_MerchantParameters',  HiddenType::class, ['data' => $redsysData['params']])
  2314.                         ->add('Ds_Signature'HiddenType::class, ['data' => $redsysData['signature']])
  2315.                         ->getForm();
  2316.                     return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
  2317.                 }
  2318.                 //Pago con transferencia
  2319.                 $formTrans->handleRequest($request);
  2320.                 if ($formTrans->isSubmitted() and $formTrans->isValid()) {
  2321.                 
  2322.                     
  2323.                     $transaccion $this->persistTransaccion($doctrine$request'Pendiente de pago');
  2324.                     $response $this->redirect($this->generateUrl('app_cart_5'));
  2325.                     $transaccion $em->getRepository("App\Entity\Transaccion")->findOneById($transaccion->getId());
  2326. //                     $WSTPV = $this->container->get('web.service.tpv', $em);
  2327.                     foreach ($transaccion->getLineas() as $linea) {
  2328.                         $upLinea $em->getRepository("App\Entity\TransaccionLinea")->findOneById($linea->getId());
  2329.                         
  2330.                         // ACTIVAR EN PRODUCCION
  2331.                         
  2332. //                         $respuesta = $wstpv->RegistrarVenta($upLinea);
  2333. //                         $upLinea = $upLinea->setTicket($respuesta);
  2334. //                         $upLinea->setTicket($respuesta);
  2335.                         
  2336.                         //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
  2337.                         
  2338.                         $em->merge($upLinea);
  2339.                         $em->flush();
  2340.                     }
  2341.                     // ACTIVAR EN PRODUCCION
  2342.                     $mailer->pendingTransaction($this->getUser(), $transaccion);
  2343.                     return $response;
  2344.                     //Proceso de pago con transferencia
  2345.                 }
  2346.                 //RESERVA
  2347.                 $formReserv->handleRequest($request);
  2348.                 if ($formReserv->isSubmitted() and $formReserv->isValid()) {
  2349.                     $this->ActualizarStock($doctrine$fullCart);
  2350.                     $response $this->redirect($this->generateUrl('app_cart_5'));
  2351.                     return $response;
  2352.                 }
  2353.                 $stepBread $this->StepControl($request);
  2354.                 $user $this->getUser();
  2355.                 $invitado $fullCart->getInvitado();
  2356.                 $traducciones $this->loadDivisaTraducciones($doctrine$request);
  2357.                 
  2358.                 $idPago $fullCart->getTipoPago();
  2359.                 $metodoPago $em->getRepository("App\Entity\MetodoPago")->findOneBy(array('id' => $idPago));
  2360.                 
  2361.                 return $this->render('default/carrito/carrito4.html.twig', array(
  2362. //                     'reducido' => $reducido,
  2363.                     'formReserva' => $formReserv->createView(),
  2364.                     'stepBread' => $stepBread,
  2365.                     'carro' => $fullCart,
  2366.                     'usuario' => $user,
  2367.                     'invitado' => $invitado,
  2368.                     'formCard' => $formCard->createView(),
  2369.                     'formTrans' => $formTrans->createView(),
  2370.                     'currentStep' => 4,
  2371.                     'total' => $fullCart->getTotalTransaccion(),
  2372.                     'descuentoPromo' => $fullCart->getDescuentoPromo(),
  2373.                     'gastosEnvio' => $gastosEnv,
  2374.                     'sm' => $sm,
  2375.                     'traducciones' => $traducciones,
  2376.                     'tiempoenvio' => $fullCart->getFechaDisponible(),
  2377.                     'tiemporecogida' => $fullCart->getFechaEntrega(),
  2378.                     'metodoPago' => $metodoPago
  2379.                 ));
  2380.             } catch
  2381.             (\Exception $e) {
  2382.                 if ($this->kernel->getEnvironment() == 'dev') throw $e;
  2383.                 $this->resetCart($request);
  2384.                 $catcher $this->container->get('web.service.catchException');
  2385.                 $log = new Log();
  2386.                 $this->deleteErpSale($fullCart,$wstpv);
  2387.                 $log->setLocation('carro4');
  2388.                 $log->setUser($this->getUser());
  2389.                 $log->setText(json_encode($e->getTrace()));
  2390.                 $error $e->getMessage();
  2391.                 $catcher->saveException($log);
  2392.                 return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $error'currentStep' => 5));
  2393.             }
  2394.         }
  2395.         
  2396.         public function resetCart($request)
  2397.         {
  2398.             $sesion $request->getSession();
  2399.             $sesion->set('cartStep'null);
  2400.             $sesion->set('carro'null);
  2401.             $sesion->set('transferencia'null);
  2402.         }
  2403.         
  2404.         
  2405.         
  2406.         
  2407.     #[Route(path: [
  2408.         'es' => '/carro5',
  2409.         'en' => '/en/cart5'
  2410.     ], name'app_cart_5')]
  2411.     public function Cart5Action(Request $request,PersistenceManagerRegistry $doctrineWebServiceUsuarios $wsuWebServiceFunciones $wsfLoggerInterface $loggerMailer $mailerEventDispatcherInterface $EventDispatcherWebServiceTPV $wstpv)
  2412.     {
  2413.         try {
  2414.             if ($request->query->has('t')) {
  2415.                 $em $doctrine->getManager();
  2416.                 $t $request->query->get('t');
  2417.                 $transaccion $em->getRepository('App\Entity\Transaccion')->findOneBy(['tokenEmail' => $t]);
  2418.             } else {
  2419.                 return $this->redirect($this->generateUrl('app_cart_1'));
  2420.             }
  2421.             if ($transaccion && $transaccion->getEstado() == 'En pasarela de pago') {
  2422.                 $redsysData $this->buildRedsys($request$transaccion);
  2423.                 $formTPV $this->container->get('form.factory')->createNamedBuilder(''FormType::class, array(), array(
  2424.                     'action' => $this->getParameter('redsys_gateway'),
  2425.                     'method' => 'POST',
  2426.                     'csrf_protection' => false,
  2427.                     'attr' => array('name' => 'tpv''id' => 'formTPV'),
  2428.                 ))
  2429.                     ->add('Ds_SignatureVersion'HiddenType::class, ['data' => $this->getParameter('redsys_version')])
  2430.                     ->add('Ds_MerchantParameters',  HiddenType::class, ['data' => $redsysData['params']])
  2431.                     ->add('Ds_Signature'HiddenType::class, ['data' => $redsysData['signature']])
  2432.                     ->getForm();
  2433.                 return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
  2434.             }
  2435.             // $EventDispatcher->dispatch(new OrderCompleteEvent($transaccion,$request), OrderCompleteEvent::NAME);
  2436.             // $respuesta = $wstpv->CrearVentaV2($fullCart, $pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra, $cupon, Carro::TIPO_PROMO_CUPON);
  2437.             $cupon $transaccion->getCupon();
  2438.             foreach ($transaccion->getLineas() as $linea) {
  2439.                 if ($linea->getErpCode() == null) {
  2440.                     if($cupon) {
  2441.                         if ($transaccion->getTipoPromo() == Carro::TIPO_PROMO_DIVISA) {
  2442.                             $rep_cup $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $cupon ]);
  2443.                             $respuesta $wstpv->CrearVentaV2($transaccion$linea$this->getUser(), $transaccion->getTipoPago(), $transaccion->getGastosEnvio(), $rep_cup->getCodigoTPV(), Carro::TIPO_PROMO_DIVISA);
  2444.                         } elseif ($transaccion->getTipoPromo() == Carro::TIPO_PROMO_CUPON) {
  2445.                             $respuesta $wstpv->CrearVentaV2($transaccion$linea$this->getUser(), $transaccion->getTipoPago(), $transaccion->getGastosEnvio(), $cuponCarro::TIPO_PROMO_CUPON);
  2446.                         } else {
  2447.                             $respuesta false;
  2448.                         }
  2449.                     } else {
  2450.                         $respuesta $wstpv->CrearVenta($transaccion$linea$this->getUser(), $transaccion->getTipoPago(), $transaccion->getGastosEnvio());
  2451.                     }
  2452.                     if (!$respuesta) {
  2453.                         throw new \Exception('Una de las lĆ­neas ha fallado en el ERP al crearse');
  2454.                     }
  2455.                     $linea->setErpCode($respuesta['erpCode']);
  2456.                     $em->persist($linea);
  2457.                     $em->flush();
  2458.                     $respuesta $wstpv->RegistrarVenta($linea);
  2459.                     if (!$respuesta) {
  2460.                         throw new \Exception('Una de las lĆ­neas ha fallado en el ERP al registrarse');
  2461.                     }
  2462.                     $linea->setTicket($respuesta);
  2463.                     $em->persist($linea);
  2464.                     $em->flush();
  2465.                 }
  2466.             }
  2467.             $mailer->succcessBought($transaccion->getUsuario(), $transaccion);
  2468.             // $mailer->transactionNotification($transaccion);
  2469.             $returnArray = array(
  2470.                 'currentStep' => 5,
  2471.                 'transaccion' => $transaccion,
  2472.             );
  2473.             return $this->render('default/carrito/carrito5.html.twig'$returnArray);
  2474.             
  2475. //             if ($this->getCart($request)) {
  2476. //                 $Reserva = $transaccion = NULL;
  2477. //                 if ($re = $this->CartRedirect($request, 5)) {
  2478. //                     return $re;
  2479. //                 }
  2480. //                 $carro = $this->getCart($request);
  2481. //
  2482. //                 //Es una COMPRA SIN cerrar
  2483. //                 if (!$carro->getReserva()) {
  2484. //                     $sesion = $request->getSession();
  2485. //                     $transaccion = $sesion->get('transaccion');
  2486. //                     //AVISAMOS AL ERP DE QUE LA COMPRA FUE BIEN
  2487. //                     $transaccion = $em->getRepository("App\Entity\Transaccion")->findOneById($transaccion->getId());
  2488. //
  2489. //                     //SI ES UNA COMPRA RECOGIDA EN OFICINA ACTUALIZAMOS EL STOCK
  2490. //                     if ($carro->getOficina()) {
  2491. //                         $this->ActualizarStock($doctrine, $carro);
  2492. //                     }
  2493. //
  2494. //                     $EventDispatcher->dispatch(new OrderCompleteEvent($transaccion,$request), OrderCompleteEvent::NAME);
  2495. //                 }
  2496. //                 //Es una RESERVA
  2497. //                 else if ($carro->getReserva()) {
  2498. //                     $Reserva = $this->persistBooking($doctrine, $wsu, $wsf, $mailer, $carro);
  2499. //                     $EventDispatcher->dispatch(new BookingCompleteEvent($Reserva,$request), BookingCompleteEvent::NAME);
  2500. //                 }
  2501. //                 $stepBread = $this->StepControl($request);
  2502. //
  2503. //                 $returnArray = array(
  2504. //                     'stepBread' => $stepBread,
  2505. //                     'reserva' => $Reserva,
  2506. //                     'currentStep' => 5,
  2507. //                     'transaccion' => $transaccion,
  2508. //                 );
  2509. //
  2510. //                 /**
  2511. //                  * Para depurar el carro sin que saque del paso 5
  2512. //                  * comenta esta linea
  2513. //                  */
  2514. // //                 $this->resetCart($request);
  2515. //
  2516. // //                 return $returnArray;
  2517. //
  2518. //                 return $this->render('default/carrito/carrito5.html.twig', $returnArray);
  2519.             // } else {
  2520.             //     $response = $this->redirect($this->generateUrl('index'));
  2521.             //     return $response;
  2522.             // }
  2523.         } catch (\Exception $e)
  2524.         {
  2525.             $logger->error($e->getMessage(). ' | '.$e->getTraceAsString());
  2526.             if($this->getParameter('kernel.debug')) {
  2527.                 throw $e;
  2528.             }
  2529.             return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $e->getMessage(), 'currentStep' => 5));
  2530.         }
  2531.     }
  2532.     
  2533.     
  2534.     #[Route(path: [
  2535.         'es' => '/notificacion',
  2536.         'en' => 'en/notification'
  2537.     ], name'app_cart_notification')]
  2538.     public function notificationAction(Request $requestPersistenceManagerRegistry $doctrineSettingsManager $smWebServiceTPV $wstpvMailer $mailerLoggerInterface $redsysLogger)
  2539.     {
  2540. //         $logger = $this->get('monolog.logger.redsys');
  2541.         try {
  2542.             $em $doctrine->getManager();
  2543. //             $options = $this->container->get('dinamic_settings.manager');
  2544. //             $WSTPV = $this->container->get('web.service.tpv', $em);
  2545. //             $wstpv2 = $this->container->get('App\Services\WebServiceTPV');
  2546.             $sesion $request->getSession();
  2547.             $transaccion $sesion->get('transaccion');
  2548.             // Se crea Objeto
  2549.             $redsys = new ApiRedsys();
  2550.             $redsysLogger->info('[NTFA] Empezamos la notificacion.');
  2551.             $version $request->get("Ds_SignatureVersion");
  2552.             $redsysLogger->info('[NTFA] Versión: ' $version);
  2553.             $datos $request->get("Ds_MerchantParameters");
  2554. //             dump($datos);die();
  2555.             $redsysLogger->info('[NTFA] Datos: ' $datos);
  2556.             $signatureRecibida $request->get("Ds_Signature");
  2557.             $redsysLogger->info('[NTFA] Firma: ' $signatureRecibida);
  2558.             $decodec $redsys->decodeMerchantParameters($datos);
  2559.             $response json_decode($decodectrue);
  2560.             
  2561.             $firma $redsys->createMerchantSignatureNotif($this->getParameter('redsys_key'), $datos);
  2562.             
  2563.                         
  2564.             $dsResponse intval($response['Ds_Response']);
  2565.             if ($firma === $signatureRecibida && ($dsResponse <= 99 || $dsResponse == 900 || $dsResponse == 400)) {
  2566.                 //PERSISTIR EN ERP
  2567.                 $firmado "FIRMA OK";
  2568.                 $transaccionId ltrim($redsys->getParameter('Ds_Order'), '0');
  2569.                 $em $doctrine->getManager();
  2570.                 $transaccion $em->getRepository('App\Entity\Transaccion')->findOneById($transaccionId);
  2571.                 if ($transaccion) {
  2572.                     $redsysLogger->info('Poniendo pagado a: ' $transaccion->getId());
  2573. //                     $mailer = $this->container->get('dinamic_shop.mailer');
  2574.                     $transaccion->setEstado('Pagado');
  2575.                     $pago = new \DateTime();
  2576.                     $transaccion->setFechaPagado($pago);
  2577.                     $em->persist($transaccion);
  2578.                     $em->flush();
  2579.                     foreach ($transaccion->getLineas() as $linea) {
  2580.                         $upLinea $em->getRepository("App\Entity\TransaccionLinea")->findOneById($linea->getId());
  2581.                         // ACTIVAR EN PRODUCCION
  2582.                         
  2583. //                         dump($wstpv); die();
  2584. //                         $respuesta = $wstpv->RegistrarVenta($upLinea);
  2585. //                         $upLinea = $upLinea->setTicket($respuesta);
  2586. //                         $upLinea->setTicket($respuesta);
  2587.                         //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
  2588.                         $em->merge($upLinea);
  2589.                         $em->flush();
  2590.                     }
  2591.                     $mailer->completeTransation($transaccion->getEmailTitular(), $transaccion);
  2592. //                     $mailer->pendingTransaction($this->getUser(), $transaccion);
  2593. //                     dump($mailer);die();
  2594.                 } else {
  2595.                     $redsysLogger->info('[NTFA] La transaccion ' $transaccionId ' NO ha sido encontrada.');
  2596.                 }
  2597.                 $redsysLogger->info('[NTFA] Final de Firma ok');
  2598.             } else {
  2599.                 $redsysLogger->info('[NTFA] Error en la pasarela');
  2600.                 $transaccion->setEstado('ERROR EN PASARELA');
  2601.                 $em->persist($transaccion);
  2602.                 $em->flush();
  2603.                 $firmado "FIRMA KO";
  2604.             }
  2605.             return new Response($firmado);
  2606.         } catch (\Exception $e) {
  2607.             $redsysLogger->critical('[NTFA][1/2][CRITICAL]' $e->getMessage());
  2608.             $redsysLogger->critical('[NTFA][2/2][CRITICAL]' $e->getTraceAsString());
  2609.             return new Response("ERROR");
  2610.         }
  2611.         
  2612.         
  2613.     }
  2614.     
  2615.     #[Route(path: [
  2616.         'es' => '/error-carro',
  2617.         'en' => 'en/cart-error'
  2618.     ], name'app_cart_critical')]
  2619.     public function pasarelaCritical(Request $request)
  2620.     {
  2621.         $this->resetCart($request);
  2622.         $response $request->request->get("Ds_Response");
  2623.         //print_r($response);
  2624.         $version $request->request->get("Ds_SignatureVersion");
  2625.         //print_r($version);
  2626.         return $this->render('default/carrito/errorcart.html.twig');
  2627.     }
  2628.     
  2629.     
  2630.     public function comprobarFecha($nowOficina $oficina$em)
  2631.     {
  2632.         $dayoffs $em->getRepository("App\Entity\DayOff")->findBy(array('id' => $oficina));
  2633.         $validDate = clone $now;
  2634.         foreach ($dayoffs as $dayoff) {
  2635.             $formatted $validDate->format("Y-m-d");
  2636.             if (!in_array($formatted$dayoffs) and $this->isOpenOffice($validDate$oficina)) {
  2637.                 return $validDate;
  2638.             }
  2639.             $validDate->modify('+1 days');
  2640.         }
  2641.         return $validDate;
  2642.     }
  2643.     
  2644.     public function isOpenOffice($dateOficina $oficina)
  2645.     {
  2646.         $fechaValida false;
  2647.         $date $date->format('D');
  2648.         $franjas $oficina->getFranjas();
  2649.         for ($i 0$i count($franjas) && !$fechaValida$i++) {
  2650.             switch ($date) {
  2651.                 case 'Mon':
  2652.                     if ($franjas[$i]->getLunes()) $fechaValida true;
  2653.                     break;
  2654.                 case 'Tue':
  2655.                     if ($franjas[$i]->getMartes()) $fechaValida true;
  2656.                     break;
  2657.                 case 'Wed':
  2658.                     if ($franjas[$i]->getMiercoles()) $fechaValida true;
  2659.                     break;
  2660.                 case 'Thu':
  2661.                     if ($franjas[$i]->getJueves()) $fechaValida true;
  2662.                     break;
  2663.                 case 'Fri':
  2664.                     if ($franjas[$i]->getViernes()) $fechaValida true;
  2665.                     break;
  2666.                 case 'Sat':
  2667.                     if ($franjas[$i]->getSabado()) $fechaValida true;
  2668.                     break;
  2669.                 case 'Sun':
  2670.                     if ($franjas[$i]->getDomingo()) $fechaValida true;
  2671.                     break;
  2672.                 default:
  2673.                     break;
  2674.             }
  2675.         }
  2676.         return $fechaValida;
  2677.     }
  2678.         
  2679.         
  2680.         
  2681.         
  2682.         
  2683.         
  2684.         
  2685.         
  2686.         
  2687.         
  2688.         
  2689.         
  2690.         
  2691.         
  2692.         
  2693.         
  2694.         
  2695.         
  2696.         
  2697.         
  2698.         
  2699.         
  2700.         
  2701.         
  2702.         
  2703.         
  2704.         
  2705. }