src/Controller/CarritoController.php line 1186
- <?php
- namespace App\Controller;
- use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Component\HttpFoundation\Request;
- use Symfony\Component\HttpFoundation\Response;
- use Symfony\Component\HttpFoundation\RedirectResponse;
- use Symfony\Component\HttpFoundation\JsonResponse;
- use Symfony\Component\HttpFoundation\ResponseHeaderBag;
- use Symfony\Component\HttpFoundation\BinaryFileResponse;
- use Symfony\Component\HttpFoundation\Cookie;
- use Symfony\Component\HttpFoundation\RequestStack;
- use Symfony\Component\Routing\Annotation\Route;
- use Symfony\Component\Cache\Adapter\FilesystemAdapter;
- use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
- use Symfony\Component\HttpKernel\KernelInterface;
- use Symfony\Contracts\Translation\TranslatorInterface;
- use Symfony\Contracts\Cache\ItemInterface;
- use Doctrine\ORM\EntityManagerInterface;
- use Doctrine\Persistence\ManagerRegistry as PersistenceManagerRegistry;
- use Knp\Component\Pager\PaginatorInterface;
- // use FOS\UserBundle\Form\Factory\FactoryInterface;
- use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
- use App\Utils\ApiRedsys;
- use App\Services\ConfigurationManager;
- use App\Services\SettingsManager;
- use App\Services\WebServiceUsuarios;
- use App\Services\WebServiceReservas;
- use App\Services\WebServiceTPV;
- use App\Services\WebServiceFunciones;
- use App\Services\Mailer;
- use App\Entity\Pedido;
- use App\Entity\Carro;
- use App\Entity\Invitado;
- use App\Entity\User;
- use App\Entity\HorarioReducido;
- use App\Entity\Divisa;
- use App\Entity\Oficina;
- use App\Entity\Cotizaciones;
- use App\Entity\Reserva;
- use App\Entity\ReservaLinea;
- use App\Entity\Transaccion;
- use App\Entity\TransaccionAfiliado;
- use App\Entity\TransaccionLinea;
- use App\Entity\Existencia;
- use Symfony\Component\Form\Extension\Core\Type\CollectionType;
- use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
- use Symfony\Component\Form\Extension\Core\Type\NumberType;
- use Symfony\Component\Form\Extension\Core\Type\IntegerType;
- use Symfony\Component\Form\Extension\Core\Type\HiddenType;
- use Symfony\Component\Form\Extension\Core\Type\TextType;
- use Symfony\Component\Form\Extension\Core\Type\PasswordType;
- use Symfony\Component\Form\Extension\Core\Type\SubmitType;
- use Symfony\Bridge\Doctrine\Form\Type\EntityType;
- use Symfony\Component\Form\Extension\Core\Type\FormType;
- use App\Form\Carrito\CarroType;
- use App\Form\LoginType;
- use App\Form\InvitadoType;
- use App\Form\Carrito\CartDeliver;
- use App\Form\Carrito\CartShop;
- use App\Form\Carrito\TransactionType;
- use App\Form\Type\UserRegistrationType;
- use Symfony\Component\EventDispatcher\EventDispatcherInterface;
- use App\Event\BookingCompleteEvent;
- use App\Event\OrderCompleteEvent;
- use Psr\Log\LoggerInterface;
- class CarritoController extends AbstractController
- {
- private $authorizationChecker;
- private $kernel;
- private $registrationFormFactory;
- public function __construct(AuthorizationCheckerInterface $authorizationChecker, KernelInterface $kernel/*, FactoryInterface $registrationFormFactory*/)
- {
- $this->authorizationChecker = $authorizationChecker;
- $this->kernel = $kernel;
- // $this->registrationFormFactory = $registrationFormFactory;
- }
- #[Route(path: [
- 'es' => '/cupon-check',
- 'en' => '/en/cupon-check'
- ], name: 'app_cupon_check')]
- public function checkPromotionalCode(Request $request,PersistenceManagerRegistry $doctrine, SettingsManager $sm, WebServiceFunciones $wsf){
- $locale = $request->getLocale();
- $em = $doctrine->getManager();
- $valor = $_POST['valor'];
- $importe = $_POST['importe'];
- $cupAplicado = $_POST['cupAplicado'];
- $repository = $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $valor ]);
- if($repository == null) {
- $respuesta = new JsonResponse();
- $respuesta->setData(['ok' => 0, 'msg' => $sm->getValue('cart.step1.cupon_no_valido')]);
- } else if($cupAplicado != '') {
- $respuesta = new JsonResponse();
- $respuesta->setData(['ok' => 0, 'msg' => $sm->getValue('cart.step1.cupon_ya_aplicado')]);
- } else {
- $permIds = [];
- if ($repository->getDivisas()->isEmpty()) {
- $divP = $em->getRepository('App\Entity\Divisa')->findBy(['visible' => 1]);
- } else {
- $divP = $repository->getDivisas();
- }
- foreach($divP as $perm) {
- if ($perm->getId() != 10) {
- $permIds[] = $perm->getId();
- }
- }
- if( $this->comprobarCupon($request, $doctrine, $valor)){
- $respuesta = new JsonResponse();
- $respuesta->setData(['ok' => 1, 'msg' => $sm->getValue('cart.step1.cupon_valido'), 'tipo' => Carro::TIPO_PROMO_DIVISA, 'rate' => $repository->getPorcentajeDescuento(), 'permDiv' => $permIds ]);
- }else{
- //comprobar codigo codigo promocion
- $resultado = $wsf->ComprobarImporteMinimoPromocion($valor,$importe);
- // var_dump($resultado); die();
- if ($resultado and $resultado['valido']) {
- $respuesta = new JsonResponse();
- $respuesta->setData(['ok' => 1, 'msg' => $sm->getValue('cart.step1.cupon_valido'), 'tipo' => Carro::TIPO_PROMO_CUPON]);
- }
- elseif ($resultado and !$resultado['valido']) {
- $respuesta = new JsonResponse();
- //$respuesta->setData(['ok' => 0, 'msg' => $sm->getValue('cart.step1.cupon_no_valido')]);
- $respuesta->setData(['ok' => 0, 'msg' => $sm->getValue('cart.cupon_error_'.trim($resultado['error']))]);
- }
- else {
- $respuesta = new JsonResponse();
- $respuesta->setData(['ok' => 0, 'msg' => $sm->getValue('cart.step1.cupon_no_valido')]);
- }
- }
- }
- return $respuesta;
- }
- #[Route(path: [
- 'es' => '/cotizacion-cart-check',
- 'en' => '/en/cotizacion-cart-check'
- ], name: 'app_cotizacion_check_cart')]
- public function checkCotizacion(Request $request,PersistenceManagerRegistry $doctrine, SettingsManager $sm){
- $locale = $request->getLocale();
- $em = $doctrine->getManager();
- $valor=$_POST['valor'];
- $repository = $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $valor ]);
- // $options = $this->container->get('dinamic_settings.manager');
- if( $this->comprobarCupon($request, $doctrine, $valor)){
- $respuesta = new JsonResponse();
- $respuesta->setData(['ok' => 1, 'msg' => $sm->getValue('cart.step1.cupon_valido'), 'tipo' => Carro::TIPO_PROMO_DIVISA ]);
- }else{
- $respuesta = new JsonResponse();
- $respuesta->setData(['ok' => 0, 'msg' => $sm->getValue('cart.step1.cupon_no_valido')]);
- }
- return $respuesta;
- }
- // Valida Cupon de TIPO_PROMO_CUPON
- public function comprobarCuponCodigo($valor, $importe, WebServiceFunciones $wsf) {
- //comprobar codigo codigo promocion
- $resultado = $wsf->ComprobarImporteMinimoPromocion($valor, $importe);
- if ($resultado and $resultado['valido']) {
- return true;
- }
- elseif ($resultado and !$resultado['valido']) {
- return ['error' => 'cart.cupon_error_'.trim($resultado['error'])];
- }
- else {
- return ['error' => 'cart.step1.cupon_no_valido'];
- }
- }
- public function comprobarCupon(Request $request,PersistenceManagerRegistry $doctrine, $valor) {
- $locale = $request->getLocale();
- $em = $doctrine->getManager();
- $usuarioActual = $this->getUser();
- $repository = $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $valor ]);
- if(!$repository){
- return false;
- }
- $cod = $repository->getCodigo();
- $activo = $repository->getActivo();
- $inicio = $repository->getInicio();
- $fin = $repository->getFin();
- $fechas = false;
- $current = new \DateTime();
- if($inicio == NULL AND $fin == NULL){
- $fechas = true;
- }
- else if($inicio != NULL AND $fin != NULL){
- if($current >= $inicio AND $current<= $fin){
- $fechas=true;
- }else{
- $fechas = false;
- }
- }else if($inicio != NULL AND $fin == NULL){
- if($current >= $inicio){
- $fechas=true;
- }else{
- $fechas = false;
- }
- }else{
- if($current <= $fin){
- $fechas=true;
- }else{
- $fechas = false;
- }
- }
- $repository1 = $em->getRepository('App\Entity\Transaccion')->findBy([ 'cupon' => $valor, 'usuario' => $usuarioActual ]);
- $repository2 = $em->getRepository('App\Entity\Reserva')->findBy([ 'cupon' => $valor , 'usuario' => $usuarioActual]);
- $totalUsosUsuario = 0;
- foreach($repository1 as $rep){
- $totalUsosUsuario = $totalUsosUsuario +1;
- }
- foreach($repository2 as $repo){
- $totalUsosUsuario = $totalUsosUsuario +1;
- }
- $totalUsosUsu = $repository->getTotalUsosUsuario() - $totalUsosUsuario;
- $user_id = $repository->getUsuario();
- if($cod == $valor AND $activo == 1 AND $totalUsosUsu>0 AND $fechas==true) {
- if( !$user_id OR $user_id == $usuarioActual){
- $cupon = $repository;
- $respuesta = true;
- }else{
- $cupon = "";
- $respuesta = false;
- }
- }else{
- $respuesta = false;
- }
- return $respuesta;
- }
- /* TODO revisar si es necesario y cambiar envio email*/
- #[Route(path: [
- 'es' => '/reclamacion-send',
- 'en' => '/en/reclamacion-send'
- ], name: 'app_cart_reclamacion')]
- public function reclamacionesFormAction(Request $request, SettingsManager $sm, $scenario = "desktop")
- {
- $idioma = $request->getLocale();
- // $options = $this->container->get('dinamic_settings.manager');
- $form = $this->createForm(new ReclamacionesType($sm));
- $form->handleRequest($request);
- $recaptcha = new \ReCaptcha\ReCaptcha($this->container->getParameter('captcha_reclamaciones_key_private'));
- $resp = $recaptcha->verify($request->request->get('g-recaptcha-response'), $request->getClientIp());
- $recaptcha1 = new \ReCaptcha\ReCaptcha($this->container->getParameter('captcha_movil_key_private'));
- $resp1 = $recaptcha1->verify($request->request->get('g-recaptcha-response'), $request->getClientIp());
- $captchaError = null;
- $msg = null;
- if ($form->isValid() && ($resp->isSuccess() || $resp1->isSuccess())) {
- $message = \Swift_Message::newInstance()
- ->setContentType("text/html")
- ->setSubject('Reclamación realizada por formulario web')
- ->setFrom($form->get('email')->getData())
- //->setTo('eurochange@eurochange.es')
- ->setTo('eurochange@eurochange.es')
- ->setBody('<h2>Un cliente ha enviado una reclamación:</h2><br/>
- Nombre y apellidos: ' . $form->get('fullname')->getData() . '<br/>
- Email: ' . $form->get('email')->getData() . '<br>
- TelƩfono: ' . $form->get('phone')->getData() . '<br/>
- Tipo de documento: ' . $form->get('documentType')->getData()->getNombreEs() . '<br/>
- NĆŗmero de documento: ' . $form->get('documentNumber')->getData() . '<br/>
- Reclamación relacionada con: ' . $form->get('subject')->getData() . '<br/>
- Argumentos: <br>' . nl2br($form->get('comments')->getData()))//->setBody($adminHTML)
- ;
- $this->get('swiftmailer.mailer.default')->send($message);
- if ($request->isXmlHttpRequest()) {
- if ($idioma == 'es') {
- $msg = "Su reclamación ha sido enviada con éxito, en breve nos pondremos en contacto con usted.";
- } else {
- $msg = "Your claim has been successfully sent, we will contact you shortly.";
- }
- return new JsonResponse([
- 'status' => true,
- 'msg' => $msg
- ], 200);
- }
- } elseif (!empty($_POST) && !$resp->isSuccess()) {
- if ($idioma == 'es') {
- $captchaError = "Ha ocurrido un error con el captcha, vuelva a intentarlo.";
- } else {
- $captchaError = "An error occurred with the captcha, try again.";
- }
- if ($request->isXmlHttpRequest()) {
- return new JsonResponse([
- 'status' => false,
- 'msg' => $captchaError
- ], 200);
- }
- }
- $returnArray = [
- 'form' => $form->createView(),
- 'tipo' => $scenario,
- ];
- if ($request->isXmlHttpRequest()) {
- $html = $this->renderView("default/reclamaciones_form.html.twig", $returnArray);
- return new JsonResponse([
- 'status' => false,
- 'html' => $html
- ], 200);
- }
- return $this->render('default/reclamaciones_form.html.twig', $returnArray);
- }
- /**
- * Por alguna razon json_encode ignora el depth y el servicio del seralizer
- * casca al invocarlo
- * @Route( "getHorarios", name="app_get_horarios" )
- */
- public function getHorariosAction($request, $em)
- {
- $locale = $request->getLocale();
- $oficinas = $em->getRepository("App\Entity\Oficina")->findfullOffices($locale);
- foreach ($oficinas as $oficina) {
- $horarios[] = json_encode($oficina->getOficina());
- }
- $horarios = (json_encode($horarios, true, 100));
- $horarios = str_replace('/', '', $horarios);
- $horarios = str_replace('\\', '', $horarios);
- $horarios = str_replace('":["{', '":[{', $horarios);
- $horarios = str_replace('}","{', '},{', $horarios);
- $horarios = str_replace('}"]', '}]', $horarios);
- $horarios = str_replace('["{"', '[{"', $horarios);
- return $horarios;
- }
- /**
- * Autentica un usuario
- * @param User $user
- * @param Response $response
- */
- protected function authenticateUser($user, Response $response)
- {
- try {
- $this->container->get('fos_user.security.login_manager')->loginUser(
- $this->container->getParameter('fos_user.firewall_name'),
- $user,
- $response);
- } catch (AccountStatusException $ex) {
- // We simply do not authenticate users which do not pass the user
- // checker (not enabled, expired, etc.).
- }
- }
- public function createShopFormAction(PersistenceManagerRegistry $doctrine)
- {
- $em = $doctrine->getManager();
- $pedido = new Pedido();
- $form = $this->createForm(new CartStep1Type($em), $pedido);
- return $this->render('default/FastShop.html.twig', array(
- 'form' => $form->createView(),
- ));
- }
- /**
- * Guarda en sesión los pasos del carro completados
- * @return mixed
- */
- private function StepControl(Request $request)
- {
- $sesion = $request->getSession();
- // $logeado = $this->authorizationChecker->isGranted('ROLE_USER');
- //No existe sesion de control
- if ($sesion->get('cartStep') == null) {
- $cartStep[1] = false;
- $cartStep[2] = false;
- $cartStep[3] = false;
- $cartStep[4] = false;
- $cartStep[5] = false;
- } //Existe sesion de control
- else {
- $cartStep = $sesion->get('cartStep');
- }
- //Si esta logueado se valida el paso 2
- // if ($logeado) {
- // $cartStep[2] = true;
- // }
- $sesion->set('cartStep', $cartStep);
- return $cartStep;
- }
- private function retomarSesion(Request $request, )
- {
- $cartStep = $this->StepControl($request);
- $carro = new Carro();
- return $cartStep;
- }
- /**
- * Guarda los datos del primer carro en sesión
- * @param $carro
- */
- private function setCart1(Request $request, $carro)
- {
- $sesion = $request->getSession();
- $cartStep = $sesion->get('cartStep');
- $cartStep[1] = true;
- $sesion->set('cartStep', $cartStep);
- $carroSesion = $sesion->get('carro');
- //Hay carro en sesion
- if (isset($carroSesion)) {
- //Actualizamos el carro
- $carroSesion->setPedidos($carro->getPedidos());
- $carroSesion->setReserva($carro->getReserva());
- $sesion->set('carro', $carroSesion);
- } else {
- //Metemos el carro nuevo
- $sesion->set('carro', $carro);
- }
- // dump($carro);die();
- }
- /**
- * @Route("/carro1", name="carro1error")
- */
- public function redirectCarro1()
- {
- return $this->redirectToRoute('index_es');
- }
- /**
- * @Route("/en/cart1", name="cart1error")
- */
- public function redirectCart1()
- {
- return $this->redirectToRoute('index_en');
- }
- #[Route(path: [
- 'es' => '/verCarro',
- 'en' => '/en/showBarrow'
- ], name: 'app_cart_1')]
- public function Cart1Action(Request $request, PersistenceManagerRegistry $doctrine, WebServiceTPV $wstpv)
- {
- $locale = $request->getLocale();
- $pedido = new Pedido();
- $carro = new Carro();
- $predefined = null;
- $em = $doctrine->getManager();
- //Si pasan valores por GET
- if ($request->query->get('dinamic_shop_cartStep1') || $request->query->get('divisaOrigen') || $request->query->get('divisaFinal')) {
- $predefined = $request->query->get('dinamic_shop_cartStep1');
- // dump($predefined);die();
- if (!$predefined) {
- $predefined['divisaOrigen'] = $request->query->get('divisaOrigen');
- $predefined['divisaFinal'] = $request->query->get('divisaFinal');
- $predefined['cantidadOrigen'] = $request->query->get('cantidadOrigen');
- $predefined['cantidadFinal'] = $request->query->get('cantidadFinal');
- $predefined['codigoPromo'] = $request->query->get('codigoPromo');
- $predefined['tipoPromo'] = $request->query->get('tipoPromo');
- }
- $predefined['cantidadOrigen'] = str_replace(',', '.', $predefined['cantidadOrigen']);
- $predefined['cantidadFinal'] = str_replace(',', '.', $predefined['cantidadFinal']);
- $pedido->setDivisaOrigen($em->getRepository('App\Entity\Divisa')->findOneById($predefined['divisaOrigen']));
- $pedido->setDivisaFinal($em->getRepository('App\Entity\Divisa')->findOneById($predefined['divisaFinal']));
- $pedido->setCantidadOrigen($predefined['cantidadOrigen']);
- $pedido->setCantidadFinal($predefined['cantidadFinal']);
- // $pedido->setCupon($predefined['codigoProm']);
- $carro->addPedido($pedido);
- $div_f_nombre = $pedido->getDivisaFinal()->getSimbolo();
- $div_o_nombre = $pedido->getDivisaOrigen()->getSimbolo();
- } //Si vuelve atrƔs
- else if ($this->getCart($request)) {
- $carro = $this->getCart($request);
- $carro->setOficina(NULL);
- $carro->setHoraEntrega(NULL);
- $carro->setFechaEntrega(NULL);
- $carro->setFreeShipping(0);
- //Reiniciamos la oficina por si ha elegido una en el paso 3
- //No todas las divisas estƔn disponibles en todas las oficinas
- $sesion = $request->getSession();
- $sesion->set('carro', $carro);
- $cartStep = $sesion->get('cartStep');
- $cartStep[3] = NULL;
- $sesion->set('cartStep', $cartStep);
- } //Si ponen la URL vacĆa en el navegador
- else {
- $predefined['divisaOrigen'] = 12;
- $predefined['divisaFinal'] = 10;
- $predefined['cantidadFinal'] = 100;
- $pedido->setDivisaOrigen($em->getRepository('App\Entity\Divisa')->findOneById(10));
- $pedido->setDivisaFinal($em->getRepository('App\Entity\Divisa')->findOneById(12));
- $pedido->setCantidadFinal(100);
- $carro->addPedido($pedido);
- }
- // die();
- $oficina = $em->getRepository("App\Entity\Oficina")->findAll();
- $formCarro = $this->createForm(CarroType::class, $carro, [
- 'tipo_value' => 0,
- 'em' => $em,
- 'locale' => $locale,
- 'csrf_protection' => false
- ]);
- if(isset($div_f_nombre) && isset($div_o_nombre)){
- }else{
- $div_f_nombre = $em->getRepository('App\Entity\Divisa')->findOneBy(['id' => 12]);
- $div_o_nombre = $em->getRepository('App\Entity\Divisa')->findOneBy(['id' => 10]);
- $div_f_nombre = $div_f_nombre->getSimbolo();
- $div_o_nombre = $div_o_nombre->getSimbolo();
- }
- //Procesar Datos
- if ($request->getMethod() == 'POST' ) {
- $formCarro->handleRequest($request);
- if ($formCarro->isValid()) {
- $codigoPromocional = $formCarro->get('codigoPromo')->getData();
- $carro->setCodigoPromo($codigoPromocional);
- $carro->setTipoPromo($formCarro->get('tipoPromo')->getData());
- // $carro->setTipoPromo($formCarro->get('tipoPromo')->getData());
- $this->setCart1($request, $carro);
- if($formCarro->get('tipo')->getData() == 0){
- $response = $this->redirect($this->generateUrl('app_cart_2'));
- }
- else{
- $response = $this->redirect($this->generateUrl('app_cart_1'));
- }
- $sesion = $request->getSession();
- $sesion->set('metodoEntrega', $formCarro->get('metodoEntrega')->getData());
- if ($formCarro->get('metodoEntrega')->getData() == 1) {
- $carro->setOficina((integer)($_COOKIE['cookieoficina']));
- }
- if ($carro->getTotalTransaccion()) {
- $this->deleteErpSale($carro,$wstpv);
- }
- return $response;
- }
- }
- $repository = $em->getRepository('App\Entity\Cotizaciones');
- $permiteCompra = 1;
- if(isset($_COOKIE['cookieoficina'])){
- $ofi = (integer)($_COOKIE['cookieoficina']);
- $rep = $em->getRepository('App\Entity\Oficina')->findOneById($ofi);
- if($rep){
- if($rep->permiteCompra() != 1){
- $permiteCompra = 0;
- }
- }
- $cotizaciones = $repository->getLastChangesOffice($ofi);
- if($ofi == 1){
- $cotizaciones = $repository->getLastChangesOffice($this->getParameter('oficina_por_defecto'));
- }
- $pedido->setOficina($ofi);
- }else{
- $ofi = $this->getParameter('oficina_por_defecto');
- $cotizaciones = $repository->getLastChanges($ofi);
- }
- $cartStep = $this->StepControl($request);
- $divisas = $em->getRepository('App\Entity\Divisa')->findBy(['visible' => 1]);
- $cotizacionesOnline = $repository->getLastChangesOffice($this->getParameter('oficina_por_defecto'));
- $cotizacionesOnlineJson = [];
- foreach($cotizacionesOnline as $n)
- $cotizacionesOnlineJson[$n['shortName']] = $n;
- $cotizacionesJson = [];
- foreach($cotizaciones as $c)
- $cotizacionesJson[$c['shortName']] = $c;
- // dump($divisas); die();
- $divisasJson = [];
- foreach($divisas as $d)
- $divisasJson[$d->getId()] = [
- 'shortName' => $d->getShortName(),
- 'redondeoMinimo' => $d->getRedondeoMinimo(),
- 'compraMinima' => $d->getCompraMinima(),
- ];
- // dump($formCarro->createView()); die();
- /****/
- $provincias = $em->getRepository('App\Entity\Provincia')->findAll();
- /****/
- return $this->render('default/carrito/carrito1.html.twig', array(
- 'cotizaciones' => $cotizaciones,
- 'cotizacionesJson' => json_encode($cotizacionesJson),
- 'cotizacionesOnlineJson' => json_encode($cotizacionesOnlineJson),
- 'stepBread' => $cartStep,
- 'carro' => $formCarro->createView(),
- 'currentStep' => 1,
- 'divisas' => $divisas,
- 'divisasJson' => json_encode($divisasJson),
- 'predefined' => $predefined,
- 'ofi_var' => $ofi,
- 'oficina' => $oficina,
- 'div_f_nombre' => $div_f_nombre,
- 'div_o_nombre' => $div_o_nombre,
- 'permiteCompra' => $permiteCompra,
- /****/
- 'provincias' => $provincias
- /****/
- ));
- }
- private function setCart2($request, $em)
- {
- $sesion = $request->getSession();
- $cartStep = $sesion->get('cartStep');
- $cartStep[2] = true;
- $sesion->set('cartStep', $cartStep);
- $carro = $sesion->get('carro');
- $oficina1 = $_COOKIE['cookieoficina'];
- if($oficina1 == 1){
- $oficina = $em->getRepository('App\Entity\Oficina')->findOneById($this->getParameter('oficina_por_defecto'));
- }else{
- $oficina = $em->getRepository('App\Entity\Oficina')->findOneById($oficina1);
- }
- $provincia = $oficina->getProvincia();
- $carro->setProvincia($provincia);
- $carro->setOficina($oficina);
- $carro->setUsuario($this->getUser());
- $sesion->set('carro', $carro);
- }
- private function setInvitado($request, $invitado)
- {
- $sesion = $request->getSession();
- $cartStep = $sesion->get('cartStep');
- $cartStep[2] = true;
- $sesion->set('cartStep', $cartStep);
- $carro = $sesion->get('carro');
- $carro->setInvitado($invitado);
- $sesion->set('carro', $carro);
- }
- private function createFormNoCorreo($options)
- {
- $formCorreo = $this->createFormBuilder()
- ->add('Dni_correo_sin', HiddenType::class, array()
- )
- ->add('email', TextType::class, array(
- 'label' => false,
- 'attr' => array(
- 'placeholder' => 'Email'
- )
- )
- )
- ->add('password1', TextType::class, array(
- 'label' => false,
- 'attr' => array(
- 'placeholder' => $options->getValue('cart2.password')
- )
- )
- )
- ->add('password2', TextType::class, array(
- 'label' => false,
- 'attr' => array(
- 'placeholder' => $options->getValue('cart2.repassword')
- )
- )
- )
- ->add('submitNoCorreo', SubmitType::class, array(
- 'label' => false,
- 'attr' => array(
- 'placeholder' => $options->getValue('cart2.repassword')
- )
- )
- )
- ->getForm();
- return $formCorreo;
- }
- private function createFormCorreo($options)
- {
- $formCorreo = $this->createFormBuilder()
- ->add('Dni_correo_con', HiddenType::class, array()
- )
- ->add('codigo_correo', TextType::class, array(
- 'label' => false,
- 'attr' => array(
- 'placeholder' => $options->getValue('cart2.code')
- )
- )
- )
- ->add('password1', PasswordType::class, array(
- 'label' => false,
- 'attr' => array(
- 'placeholder' => $options->getValue('cart2.password')
- )
- )
- )
- ->add('password2', PasswordType::class, array(
- 'label' => false,
- 'attr' => array(
- 'placeholder' => $options->getValue('cart2.repassword')
- )
- )
- )
- ->add('submitCorreo', SubmitType::class, array(
- 'label' => false,
- 'attr' => array(
- 'placeholder' => $options->getValue('cart2.repassword')
- )
- )
- )
- ->getForm();
- return $formCorreo;
- }
- private function createFormSinPago($options)
- {
- $formCorreo = $this->createFormBuilder()
- ->add('Dni_sin_pago', HiddenType::class, array()
- )
- ->add('email', TextType::class, array(
- 'label' => false,
- 'required' => true,
- 'attr' => array(
- 'placeholder' => 'Email'
- )
- )
- )
- ->add('nombre', TextType::class, array(
- 'label' => false,
- 'required' => true,
- 'attr' => array(
- 'placeholder' => $options->getValue('cart2.nombre.titular')
- )
- )
- )
- ->add('telefono', TextType::class, array(
- 'label' => false,
- 'required' => false,
- 'attr' => array(
- 'placeholder' => $options->getValue('cart2.telefono.titular')
- )
- )
- )
- ->add('submitSinPago', SubmitType::class, array(
- 'label' => $options->getValue('cart2.compraPaga')
- )
- )
- ->getForm();
- return $formCorreo;
- }
- private function getErrorMessages(\Symfony\Component\Form\Form $form) {
- $errors = array();
- foreach ($form->getErrors() as $key => $error) {
- if ($form->isRoot()) {
- $errors['#'][] = $error->getMessage();
- } else {
- $errors[] = $error->getMessage();
- }
- }
- foreach ($form->all() as $child) {
- if (!$child->isValid()) {
- $errors[$child->getName()] = $this->getErrorMessages($child);
- }
- }
- return $errors;
- }
- public function ComprobarStock($request, $doctrine, $carro)
- {
- $pedidos = $carro->getPedidos();
- // dump($carro);dump($pedidos);die();
- $em = $doctrine->getManager();
- foreach ($pedidos as $pedido) {
- // $oficina = $carro->getOficina();
- $oficina = $em->getRepository('App\Entity\Oficina')->findOneBy(array('id' => $carro->getOficina()->getId()));
- $divisa = $pedido->getDivisaFinal();
- $StockMax = $em->getRepository('App\Entity\Stock')->findOneBy(array('oficina' => $oficina, 'divisa' => $divisa));
- if ($StockMax) {
- } else {
- $this->addFlash(
- 'danger',
- 'La oficina ' . $oficina->getNombre() . ' no dispone de stock de la moneda ' . $divisa->getNombre()
- );
- return false;
- }
- }
- return true;
- }
- #[Route(path: [
- 'es' => '/carro2',
- 'en' => '/en/cart2'
- ], name: 'app_cart_2')]
- public function Cart2Action(Request $request,PersistenceManagerRegistry $doctrine, SettingsManager $sm, WebServiceUsuarios $wsu, WebServiceFunciones $wsf, Mailer $mailer)
- {
- $locale = $request->getLocale();
- $em = $doctrine->getManager();
- // dump($sesion = $request->getSession());die();
- if ($request->query->has('t')) {
- $t = $request->query->get('t');
- return $this->redirect($this->generateUrl('app_cart_3', ['t' => $t]));
- }
- if ($re = $this->CartRedirect($request, 2)) {
- return $re;
- }
- // $options = $this->container->get('dinamic_settings.manager');
- //Formulario de busqueda de cliente
- // $formShortReg = $this->createFormBuilder()
- // ->add('DNI', NumberType::class, array(
- // 'label' => false,
- // 'attr' => array(
- // 'placeholder' => $sm->getValue('cart2.idnumber')
- // )
- // )
- // )
- // ->getForm();
- //Formulario para usuarios venidos del ERP con correo
- // $formCorreo = $this->createFormCorreo($sm);
- //Formulario para usuarios venidos del ERP sin correo
- // $formNoCorreo = $this->createFormNoCorreo($sm);
- /****/
- $formSinPago = $this->createFormSinPago($sm);
- /****/
- try {
- $stepBread = $this->StepControl($request);
- // $request = $this->get('request');
- $local = $request->getLocale();
- $invitado = new Invitado();
- $options = ['settings' => $sm];
- $invitadoForm = $this->createForm(InvitadoType::class, $invitado, $options);
- /****/
- $nameLogeado = null;
- $emailLogeado = null;
- if ($this->getUser()) {
- // $this->setCart2($request, $em);
- // return $this->redirect($this->generateUrl('app_cart_3'));
- $nameLogeado = $this->getUser()->getName();
- $emailLogeado = $this->getUser()->getEmail();
- }
- /****/
- // $user = new User();
- // $loginForm = $this->createForm(LoginType::class, $user);
- //Usuario invitado
- $invitadoForm->handleRequest($request);
- if ($invitadoForm->isSubmitted()) {
- if ($invitadoForm->isValid()) {
- $this->setInvitado($request, $invitado);
- return $this->redirect($this->generateUrl('app_cart_3'));
- }
- }
- //Registro de usuarios desde el ERP sin email
- // $formNoCorreo->handleRequest($request);
- // if ($formNoCorreo->isSubmitted()) {
- // if ($formNoCorreo->isValid()) {
- // $data = $formNoCorreo->getData();
- // // $WSF = $this->container->get('web.service.funciones', $em);
- // $userERP = $wsf->getClienteporNumId($data['Dni_correo_sin']);
- // if ($userERP) {
- // $wsf->modificarEmail($userERP, $data['email']);
- // $user = new User();
- // $user->setIdCard($data['Dni_correo_sin']);
- // $user->setEmail($data['email']);
- // $user->setPassword($data['password1']);
- // $user->setPlainPassword($data['password1']);
- // $user->setErpId($userERP);
- // $user->setEnabled(1);
- // $user->setIdiomaPreferido($request->getLocale());
- // // $userManager = $this->container->get('fos_user.user_manager');
- // // $userManager->updatePassword($user);
- // $em->persist($user);
- // $em->flush();
- // $route = 'app_cart_3';
- // $url = $this->container->get('router')->generate($route);
- // $response = new RedirectResponse($url);
- // $this->authenticateUser($user, $response);
- // return $response;
- // }
- // }
- // }
- //
- // //Registro de usuarios desde el ERP con email
- // $formCorreo->handleRequest($request);
- // if ($formCorreo->isSubmitted()) {
- // if ($formCorreo->isValid()) {
- // $data = $formCorreo->getData();
- // if ($data['password1'] == $data['password2']) {
- // $user = $em->getRepository('App\Entity\User')->findOneByUsernameCanonical(strtolower($data['Dni_correo_con']));
- // if ($user && $user->getConfirmationToken() == $data['codigo_correo']) {
- // $user->setPlainPassword($data['password1']);
- // $user->setConfirmationToken(null);
- // $user->setPasswordRequestedAt(null);
- // $user->setIdiomaPreferido($request->getLocale());
- // $em->persist($user);
- // $em->flush();
- // $route = 'app_cart_3';
- // $url = $this->container->get('router')->generate($route);
- // $response = new RedirectResponse($url);
- // $this->authenticateUser($user, $response);
- // return $response;
- // }
- // }
- // }
- // }
- $carro = $this->getCart($request);
- // dump($carro);die();
- $reserva = $carro->getReserva();
- if(isset($_COOKIE['cookieoficina'])) {
- $ofi = (integer)($_COOKIE['cookieoficina']);
- if ($ofi == 1) {
- $ofi = $this->getParameter('oficina_por_defecto');
- }
- // if (!$this->ComprobarStock($request, $doctrine, $carro, $ofi))
- // return $this->redirect($this->generateUrl('app_cart_1'));
- } else {
- $ofi = $this->getParameter('oficina_por_defecto');
- }
- // dump($carro);die();
- /****/
- $sesion = $request->getSession();
- $metodoEntrega = $sesion->get('metodoEntrega');
- if ($metodoEntrega == 1) {
- $oficina = $em->getRepository('App\Entity\Oficina')->findOneBy(['id' => $carro->getOficina()]);
- if ($oficina->permiteCompra()) {
- $gastosEnv = 0;
- } else {
- $gastosEnv = $oficina->getProvincia()->getGastos();
- }
- $nomOfi = $oficina->getNombre();
- } else if ($metodoEntrega == 2) {
- $provDest = $em->getRepository('App\Entity\Provincia')->findOneBy(['id' => $carro->getProvincia()]);
- $gastosEnv = $provDest->getGastos();
- $nomOfi = null;
- }
- $totalPagar = 0;
- $vaAComprar = '';
- $listResumen = '';
- foreach ($carro->getPedidos() as $pedido) {
- // dump($pedido->getDivisaFinal()->getImagen()->getId());die();
- if ($totalPagar != 0) {
- $vaAComprar = $vaAComprar . ' + ' . $pedido->getCantidadFinal() . ' ' . $pedido->getDivisaFinal()->getNombre();
- } else {
- $vaAComprar = $pedido->getCantidadFinal() . ' ' . $pedido->getDivisaFinal()->getNombre();
- }
- $totalPagar = $totalPagar + $pedido->getCantidadOrigen();
- $imgDiv = $em->getRepository('App\Entity\Imagen')->findOneBy(['id' => $pedido->getDivisaFinal()->getImagen()->getId()]);
- $providerName = $imgDiv->getProviderReference();
- $listResumen = $listResumen . '<li><img src="/upload/media/divisa/0001/01/' . $providerName . '" width="30px"> <span>' . $pedido->getCantidadFinal() . '</span> ' . $pedido->getDivisaFinal()->getNombre() . '</li>';
- }
- if ($totalPagar >= 500) {
- $carro->setFreeShipping(1);
- $gastosEnv = 0;
- }
- // $codProm =
- $formSinPago->handleRequest($request);
- if ($formSinPago->isSubmitted()) {
- if ($formSinPago->isValid()) {
- $data = $formSinPago->getData();
- $transaccion = new Transaccion();
- $user = $em->getRepository('App\Entity\User')->findOneBy(['email' => $data['email']]);
- if ($user) {
- $carro->setUsuario($user);
- $sesion->set('carro', $carro);
- $transaccion->setUsuario($user);
- }
- $timestamp = (new \DateTime())->format('Y-m-d H:i:s');
- $base = $data['email'] . '||' . $timestamp;
- $random = bin2hex(random_bytes(16));
- $token = hash('sha256', $base . '||' . $random);
- $transaccion->setTokenEmail($token);
- $transaccion->setTitular($data['nombre']);
- $transaccion->setEmailTitular($data['email']);
- $transaccion->setTelefono($data['telefono']);
- if ($metodoEntrega == 1) {
- $oficina = $em->getRepository('App\Entity\Oficina')->findOneBy(['id' => $ofi]);
- $transaccion->setOficina($oficina);
- } else if ($metodoEntrega == 2) {
- $transaccion->setProvincia($provDest);
- }
- $transaccion->setCupon($carro->getCodigoPromo());
- $transaccion->setTipoPromo($carro->getTipoPromo());
- $transaccion->setEstado('En pasarela de pago');
- $transaccion->setTipoPago('TPV');
- foreach ($carro->getPedidos() as $pedido) {
- $transaccionLinea = new TransaccionLinea();
- $transaccionLinea->setDivisaDestino($em->getReference('App\Entity\Divisa', $pedido->getDivisaFinal()->getId()));
- $transaccionLinea->setCantidad($pedido->getCantidadFinal());
- $transaccionLinea->setErpCode($pedido->getErpCode());
- $transaccion->addLinea($transaccionLinea);
- }
- $transaccion->setTotalLineas($totalPagar);
- $transaccion->setGastosEnvio((float)$gastosEnv);
- $transaccion->setTotal($totalPagar + $gastosEnv);
- $transaccion->setIdioma(strtoupper($locale));
- // dump($transaccion->getTotal());die();
- $sesion->set('transaccion', $transaccion);
- $em->persist($transaccion);
- $em->flush();
- // dump($transaccion);die();
- $redsysData = $this->buildRedsys($request, $transaccion);
- $formTPV = $this->container->get('form.factory')->createNamedBuilder('', FormType::class, array(), array(
- 'action' => $this->getParameter('redsys_gateway'),
- 'method' => 'POST',
- 'csrf_protection' => false,
- 'attr' => array('name' => 'tpv', 'id' => 'formTPV'),
- ))
- ->add('Ds_SignatureVersion', HiddenType::class, ['data' => $this->getParameter('redsys_version')])
- ->add('Ds_MerchantParameters', HiddenType::class, ['data' => $redsysData['params']])
- ->add('Ds_Signature', HiddenType::class, ['data' => $redsysData['signature']])
- ->getForm();
- return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
- }
- }
- /****/
- // dump($gastosEnv + $totalPagar);die();
- $returnArray = array(
- // 'loginForm' => $loginForm->createView(),
- 'stepBread' => $stepBread,
- // 'formShortReg' => $formShortReg->createView(),
- // 'fullForm' => $fullForm->createView(),
- // 'formCorreo' => $formCorreo->createView(),
- // 'formNoCorreo' => $formNoCorreo->createView(),
- 'clienteInvitado' => $invitadoForm->createView(),
- 'sm' => $sm,
- 'reserva' => $reserva,
- 'currentStep' => 2,
- /****/
- 'formSinPago' => $formSinPago->createView(),
- 'metodoEntrega' => $metodoEntrega,
- 'gastosEnv' => $gastosEnv,
- 'totalPagar' => $totalPagar,
- 'vaAComprar' => $vaAComprar,
- 'codProm' => $carro->getCodigoPromo(),
- 'listResumen' => $listResumen,
- 'nameLogeado' => $nameLogeado,
- 'emailLogeado' => $emailLogeado,
- 'nomOfi' => $nomOfi
- /****/
- );
- return $this->render('default/carrito/carrito2.html.twig', $returnArray);
- } catch (\Exception $e) {
- if ($this->kernel->getEnvironment() == 'dev') throw $e;
- $this->resetCart($request);
- $catcher = $this->container->get('web.service.catchException');
- $log = new Log();
- $log->setLocation('carro2');
- $log->setUser($this->getUser());
- $log->setText(json_encode($e->getTrace()));
- $error = $e->getMessage();
- $catcher->saveException($log);
- return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $error, 'currentStep' => 5));
- }
- }
- /**
- * @return Carro
- */
- private function getCart($request)
- {
- $sesion = $request->getSession();
- return $sesion->get('carro');
- }
- public function CartRedirect(Request $request, $paso)
- {
- $local = $request->getLocale();
- $sesion = $request->getSession();
- $cartStep = $sesion->get('cartStep');
- // dump($cartStep);
- // dump($paso);
- // die();
- if ($logeado = $this->authorizationChecker->isGranted('ROLE_ADMIN')) {
- $this->addFlash(
- 'danger',
- 'Tu usuario no permite realizar compras (ADMIN)'
- );
- $response = $this->redirect($this->generateUrl('app_cart_1'));
- return $response;
- }
- if ($cartStep == null) {
- //No ha hecho nada
- $response = $this->redirect($this->generateUrl('app_cart_1'));
- return $response;
- } elseif ($paso > 1 and (!isset($cartStep[1]) or !$cartStep[1])) {
- //No ha completado el primer paso
- $response = $this->redirect($this->generateUrl('app_cart_1'));
- return $response;
- } elseif ($paso > 2 and (!isset($cartStep[2]) or !$cartStep[2])) {
- //No ha completado el segundo paso
- $response = $this->redirect($this->generateUrl('app_cart_2'));
- return $response;
- } elseif ($paso > 3 and (!isset($cartStep[3]) or !$cartStep[3])) {
- //No ha completado el tercer paso
- $response = $this->redirect($this->generateUrl('app_cart_3'));
- return $response;
- }
- $response = false;
- return $response;
- }
- private function SaveCartShop(Request $request, $carro3)
- {
- $sesion = $request->getSession();
- //Validamos el paso 3
- $cartStep = $sesion->get('cartStep');
- $cartStep[3] = true;
- $sesion->set('cartStep', $cartStep);
- //Guardamos los datos de la tienda
- $carro = $sesion->get('carro');
- $carro->setOficina($carro3->getOficina());
- $carro->setFechaEntrega($carro3->getFechaEntrega());
- $carro->setHoraEntrega($carro3->getHoraEntrega());
- $carro->setComentario($carro3->getComentario());
- //Reset del otro metodo de entrega
- $carro->setDireccion(NULL);
- $carro->setCodigoPostal(NULL);
- $carro->setCiudad(NULL);
- $carro->setProvincia(NULL);
- $carro->setPais(NULL);
- $carro->setTipoPago($carro3->getTipoPago());
- // dump($carro3);die();
- $carro->setTitular($carro3->getTitular());
- $sesion->set('carro', $carro);
- }
- private function SaveDeliver(Request $request, $carro3)
- {
- $sesion = $request->getSession();
- $cartStep = $sesion->get('cartStep');
- $cartStep[3] = true;
- $sesion->set('cartStep', $cartStep);
- //Guardamos la direccion de la tienda
- $carro = $sesion->get('carro');
- $carro->setDireccion($carro3->getDireccion());
- $carro->setCodigoPostal($carro3->getCodigoPostal());
- $carro->setCiudad($carro3->getCiudad());
- $carro->setProvincia($carro3->getProvincia());
- $carro->setPais($carro3->getPais());
- $carro->setComentario($carro3->getComentario());
- $carro->setNameSend($carro3->getNameSend());
- $carro->setCardSend($carro3->getCardSend());
- //Reset del otro metodo de entrega
- $carro->setOficina(NULL);
- $carro->setFechaEntrega(NULL);
- $carro->setHoraEntrega(NULL);
- $carro->setTipoPago($carro3->getTipoPago());
- $carro->setTitular($carro3->getTitular());
- $sesion->set('carro', $carro);
- }
- #[Route(path: [
- 'es' => '/carro3',
- 'en' => '/en/cart3'
- ], name: 'app_cart_3')]
- public function Cart3Action(Request $request, PersistenceManagerRegistry $doctrine, SettingsManager $sm, WebServiceTPV $wstpv, WebServiceFunciones $wsf)
- {
- try {
- if ($request->query->has('t')) {
- $em = $doctrine->getManager();
- $t = $request->query->get('t');
- $transaccion = $em->getRepository('App\Entity\Transaccion')->findOneBy(['tokenEmail' => $t]);
- } else {
- return $this->redirect($this->generateUrl('app_cart_1'));
- }
- if ($transaccion && $transaccion->getEstado() == 'En pasarela de pago') {
- $redsysData = $this->buildRedsys($request, $transaccion);
- $formTPV = $this->container->get('form.factory')->createNamedBuilder('', FormType::class, array(), array(
- 'action' => $this->getParameter('redsys_gateway'),
- 'method' => 'POST',
- 'csrf_protection' => false,
- 'attr' => array('name' => 'tpv', 'id' => 'formTPV'),
- ))
- ->add('Ds_SignatureVersion', HiddenType::class, ['data' => $this->getParameter('redsys_version')])
- ->add('Ds_MerchantParameters', HiddenType::class, ['data' => $redsysData['params']])
- ->add('Ds_Signature', HiddenType::class, ['data' => $redsysData['signature']])
- ->getForm();
- return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
- }
- //limpiamos el carro par no tenerlo ahĆ, ya que la transaccion estĆ” creada
- $this->resetCart($request);
- if ($transaccion && ($transaccion->getFechaRecogida() != null || $transaccion->getDireccionCompleta() != null)) {
- return $this->redirect($this->generateUrl('app_cart_5', ['t' => $transaccion->getTokenEmail()]));
- }
- // dump($transaccion);die();
- //Redirect is something failed
- // if ($re = $this->CartRedirect($request, 3)) {
- // return $re;//$this->CartRedirect($request, 3);
- // }
- // $carro = $this->getCart($request);
- $json = $this->getHorariosAction($request, $em);
- // $pedido = new Pedido();
- // $nCarro = new Carro();
- $formShortReg = $this->createFormBuilder()
- ->add('DNI', NumberType::class, array(
- 'label' => false,
- 'attr' => array(
- 'placeholder' => $sm->getValue('cart2.idnumber')
- )
- )
- )
- ->getForm();
- $user = new User();
- $loginForm = $this->createForm(LoginType::class, $user);
- if ($this->getUser()) {
- $userLog = true;
- } else {
- $userLog = false;
- }
- //HACKS para que la divisa pase la validación del carro
- // $pedido->setDivisaOrigen($em->getRepository('App\Entity\Divisa')->findOneByMaestro(1));
- // $nCarro->setReserva(1);
- // $formShop = $this->createForm(CartShop::class, $nCarro, array('carro' => $carro));
- // $formDeliver = $this->createForm(CartDeliver::class, $nCarro);
- $nTransaccion = new Transaccion();
- $formShop = $this->createForm(TransactionType::class, $nTransaccion);
- $formDeliver = $this->createForm(CartDeliver::class, $nTransaccion, array('transaccion' => $transaccion));
- // $stepBread = $this->StepControl($request);
- $local = $request->getLocale();
- $total = $transaccion->getTotalLineas();
- $ahora = new \DateTime('now');
- $domingo = false;
- if ($ahora->format('N') == 7) {
- $domingo = true;
- }
- $totalEntregar = 0;
- foreach ($transaccion->getLineas() as $linea) {
- $totalEntregar = $totalEntregar + $linea->getCantidad();
- }
- $listResumen = '';
- foreach ($transaccion->getLineas() as $linea) {
- $imgDiv = $em->getRepository('App\Entity\Imagen')->findOneBy(['id' => $linea->getDivisaDestino()->getImagen()->getId()]);
- $providerName = $imgDiv->getProviderReference();
- $listResumen = $listResumen . '<li><img src="/upload/media/divisa/0001/01/' . $providerName . '" width="30px"> <span>' . $linea->getCantidad() . '</span> ' . $linea->getDivisaDestino()->getNombre() . '</li>';
- }
- if($transaccion->getOficina() != null){
- $ofi = $transaccion->getOficina()->getId();
- $festivos = $em->getRepository("App\Entity\DayOff")->findBy(array('oficina' => $ofi));
- } else {
- $ofi = (integer)0;
- $festivos = $em->getRepository("App\Entity\DayOff")->findBy(array('oficina' => $ofi));
- }
- $oficina = $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => $ofi));
- if (!$oficina) {
- $oficina = $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => 20));
- }
- if ($request->getMethod() == 'POST') {
- //
- //Pasamos los datos del carro 1 a la validacion del formulario
- // $formShop->getData()->setPedidos($carro->getPedidos());
- // $formShop->getData()->setReserva($carro->getReserva());
- $formShop->handleRequest($request);
- $currentDateTime = new \DateTime('now');
- $currentTime = $currentDateTime->format('H:i');
- // Restricciones de recogida si son Libra o Dolar Estadounidense
- if ($currentTime < '14:00') {
- if ($currentDateTime->format('N') == 5) { // Si el pedido entra Viernes por la maƱana
- $currentDateTime->add(new \DateInterval('P3D'));
- } elseif ($currentDateTime->format('N') == 6){ // Si el pedido entra SƔbado por la maƱana
- $currentDateTime->add(new \DateInterval('P2D'));
- } else { // Si el pedido entra de Domingo a Jueves, por la maƱana
- $currentDateTime->add(new \DateInterval('P1D'));
- }
- } else {
- if ($currentDateTime->format('N') == 4) { // Si el pedido entra Jueves por la tarde
- $currentDateTime->add(new \DateInterval('P4D'));
- $currentDateTime->setTime(12, 0);
- } elseif ($currentDateTime->format('N') == 5){ // Si el pedido entra Viernes por la tarde
- $currentDateTime->add(new \DateInterval('P4D'));
- $currentDateTime->setTime(12, 0);
- } elseif ($currentDateTime->format('N') == 6){ // Si el pedido entra SƔbado por la tarde
- $currentDateTime->add(new \DateInterval('P3D'));
- $currentDateTime->setTime(12, 0);
- } else { // Si el pedido entra de Domingo a MiƩrcoles, por la tarde
- $currentDateTime->add(new \DateInterval('P2D'));
- $currentDateTime->setTime(12, 0);
- }
- }
- $restriccionDivisa = false;
- foreach ($transaccion->getLineas() as $linea) {
- if ($linea->getDivisaDestino()->getId() != 24 && $linea->getDivisaDestino()->getId() != 12) {
- $restriccionDivisa = true;
- }
- }
- // Restricciones de recogida si NO son ni Libra ni Dolar Estadounidense
- if ($restriccionDivisa) {
- $fechaRestriccion = new \DateTime('now');
- // $fechaRestriccion->add(new \DateInterval('P2D'));
- $currentTime = $fechaRestriccion->format('H:i');
- if ($currentTime < '14:00') {
- if ($fechaRestriccion->format('N') == 4) { // Si el pedido entra Jueves por la maƱana
- $fechaRestriccion->add(new \DateInterval('P4D'));
- } elseif ($fechaRestriccion->format('N') == 5) { // Si el pedido entra Viernes por la maƱana
- $fechaRestriccion->add(new \DateInterval('P4D'));
- } elseif ($fechaRestriccion->format('N') == 6){ // Si el pedido entra SƔbado por la maƱana
- $fechaRestriccion->add(new \DateInterval('P3D'));
- } else { // Si el pedido entra de Domingo a Miercoles, por la maƱana
- $fechaRestriccion->add(new \DateInterval('P2D'));
- }
- } else {
- if ($fechaRestriccion->format('N') == 3) { // Si el pedido entra MiƩrcoles por la tarde
- $fechaRestriccion->add(new \DateInterval('P5D'));
- $fechaRestriccion->setTime(12, 0);
- } elseif ($fechaRestriccion->format('N') == 4) { // Si el pedido entra Jueves por la tarde
- $fechaRestriccion->add(new \DateInterval('P5D'));
- $fechaRestriccion->setTime(12, 0);
- } elseif ($fechaRestriccion->format('N') == 5){ // Si el pedido entra Viernes por la tarde
- $fechaRestriccion->add(new \DateInterval('P5D'));
- $fechaRestriccion->setTime(12, 0);
- } elseif ($fechaRestriccion->format('N') == 6){ // Si el pedido entra SƔbado por la tarde
- $fechaRestriccion->add(new \DateInterval('P4D'));
- $fechaRestriccion->setTime(12, 0);
- } else { // Si el pedido entra de Domingo a Martes, por la tarde
- $fechaRestriccion->add(new \DateInterval('P3D'));
- $fechaRestriccion->setTime(12, 0);
- }
- }
- if ($fechaRestriccion > $currentDateTime) {
- $currentDateTime = $fechaRestriccion;
- }
- }
- // $carro->setFechaDisponible($currentDateTime);
- //Formulario de oficina
- if ($formShop->isSubmitted()) {
- if ($formShop->isValid()) {
- // $this->SaveCartShop($request, $nCarro);
- if($transaccion->getOficina() != null) {
- foreach($festivos as $fest) {
- if ($nTransaccion->getFechaRecogida()->format('d/m/y') == $fest->getDate()->format('d/m/y')) {
- $this->addFlash(
- 'danger',
- 'El dia seleccionado es festivo en esta oficina.'
- );
- return $this->redirect($this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()]));
- }
- }
- $fecha = $nTransaccion->getFechaRecogida()->format('Y-m-d');
- $hora = $nTransaccion->getHoraRecogida();
- $fechaHoraRecogida = new \DateTime("$fecha $hora", $nTransaccion->getFechaRecogida()->getTimezone());
- if ($totalEntregar >= 50 || !$transaccion->getOficina()->permiteCompra()) {
- if ($fechaHoraRecogida < $currentDateTime) {
- $this->addFlash(
- 'danger',
- '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")
- );
- return $this->redirect($this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()]));
- }
- } else if ($restriccionDivisa) {
- $this->addFlash(
- 'danger',
- '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")
- );
- return $this->redirect($this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()]));
- }
- }
- // dump('Ha pasado el flash');die();
- $transaccion->setUsuario($this->getUser());
- $transaccion->setFechaRecogida($nTransaccion->getFechaRecogida());
- $hora = \DateTime::createFromFormat('H:i', $nTransaccion->getHoraRecogida());
- $transaccion->setHoraRecogida($hora);
- $transaccion->setAnotacion($nTransaccion->getAnotacion());
- $transaccion->setEmailTitular($this->getUser()->getEmail());
- // dump($transaccion);die();
- $em->persist($transaccion);
- $em->flush();
- return $this->redirect($this->generateUrl('app_cart_5', ['t' => $transaccion->getTokenEmail()]));
- }
- }
- //Formulario de envio
- $formDeliver->handleRequest($request);
- if ($formDeliver->isSubmitted()) {
- if ($formDeliver->isValid()) {
- // $this->SaveDeliver($request, $nCarro);
- $transaccion->setUsuario($this->getUser());
- $transaccion->setDireccionCompleta($nTransaccion->getDireccionCompleta());
- $transaccion->setCodigoPostal($nTransaccion->getCodigoPostal());
- $transaccion->setCiudad($nTransaccion->getCiudad());
- $transaccion->setPais($nTransaccion->getPais());
- $transaccion->setAnotacion($nTransaccion->getAnotacion());
- $transaccion->setCardSend($nTransaccion->getCardSend());
- $transaccion->setNameSend($nTransaccion->getNameSend());
- $transaccion->setEmailTitular($this->getUser()->getEmail());
- // dump($transaccion);die();
- $em->persist($transaccion);
- $em->flush();
- $response = $this->redirect($this->generateUrl('app_cart_5', ['t' => $transaccion->getTokenEmail()]));
- return $response;
- }
- }
- }
- // foreach($oficina->getDayoffs() as $dayo) {
- // dump($dayo);
- // }
- // die();
- $provincias = $em->getRepository("App\Entity\Provincia")->findAll();
- $localidades = $em->getRepository("App\Entity\Localidad")->findAll();
- $metodosPago = $em->getRepository("App\Entity\MetodoPago")->findBy([], ['position' => 'ASC']);
- // $totalEntregar = 0;
- // foreach ($carro->getPedidos() as $pedido) {
- // $totalEntregar = $totalEntregar + $pedido->getCantidadFinal();
- // }
- // $metodosPagoJson = [];
- // foreach($metodosPago as $d)
- // $metodosPagoJson[$d->getId()] = [
- // 'activo' => $d->isActivo(),
- // 'nombre' => $d->getNombre(),
- // ];
- // dump($metodosPagoJson);die();
- return $this->render('default/carrito/carrito3.html.twig', array(
- // 'stepBread' => $stepBread,
- // 'carro' => $carro,
- 'formShop' => $formShop->createView(),
- 'formDeliver' => $formDeliver->createView(),
- 'json' => $json,
- 'localidades' => $localidades,
- 'provincias' => $provincias,
- 'ofi_var' => $ofi,
- 'sm' => $sm,
- 'currentStep' => 3,
- 'total' => $total,
- 'ofii' => $oficina,
- 'metodosPago' =>$metodosPago,
- 'festivos' => $festivos,
- 'totalEntregar' => $totalEntregar,
- 'domingo' => $domingo,
- 'loginForm' => $loginForm->createView(),
- 'formShortReg' => $formShortReg->createView(),
- 'userLog' => $userLog,
- 'transaccion' => $transaccion,
- 'listResumen' => $listResumen,
- ));
- } catch (\Exception $e) {
- if ($this->kernel->getEnvironment() == 'dev') throw $e;
- $this->resetCart($request);
- $this->deleteErpSale($carro,$wstpv);
- $catcher = $this->container->get('web.service.catchException');
- $log = new Log();
- $log->setLocation('carro3');
- $log->setUser($this->getUser());
- $log->setText(json_encode($e->getTrace()));
- $error = $e->getMessage();
- $catcher->saveException($log);
- return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $error, 'currentStep' => 5));
- }
- }
- public function obtenerDatosOficina($id, PersistenceManagerRegistry $doctrine, SettingsManager $sm, Request $request)
- {
- $em = $doctrine->getManager();
- $oficina = $em->getRepository("App\Entity\Oficina")->findOneBy(array('id' => $id));
- $festivos = $em->getRepository("App\Entity\DayOff")->findBy(array('oficina' => $id));
- $carro = $this->getCart($request);
- $totalEntregar = 0;
- foreach ($carro->getPedidos() as $pedido) {
- $totalEntregar = $totalEntregar + $pedido->getCantidadFinal();
- }
- $ahora = new \DateTime('now');
- $domingo = false;
- if ($ahora->format('N') == 7) {
- $domingo = true;
- }
- // dump($totalEntregar);die();
- return $this->render('default/carrito/horarioOficina.html.twig', array(
- 'ofii' => $oficina,
- 'festivos' => $festivos,
- 'sm' => $sm,
- 'totalEntregar' => $totalEntregar,
- 'domingo' => $domingo,
- ));
- }
- public function comprobarTitular(Request $request)
- {
- $igual = 'No igual';
- try{
- $user = $this->getUser();
- $titular = $request->request->get('titular');
- /*$palabrasTitutar = explode(' ', $titular);
- $palabrasUser = explode(' ', $user->getName());
- $nomTitular = strtolower($palabrasTitutar[0]);
- $nomUser = strtolower($palabrasUser[0]);*/
- $nomUser = mb_strtolower($user->getName());
- $nomTitular = mb_strtolower($titular);
- if ($nomUser == $nomTitular) {
- $igual = 'Igual';
- }
- } catch (\Exception $e) {
- return new JsonResponse(['error' => $e->getMessage()], 500);
- }
- return new Response($igual);
- }
- /**
- * Tras realizar la compra actualizamos el stock
- * de la tienda
- * @param $carro
- * @throws \Exception
- */
- public function ActualizarStock($doctrine, $carro)
- {
- $pedidos = $carro->getPedidos();
- $divisas = array();
- $em = $doctrine->getManager();
- $repo = $em->getRepository('App\Entity\Existencia');
- foreach ($pedidos as $pedido) {
- $Existencia = $repo->findOneBy(array('oficina' => $carro->getOficina(), 'dia' => $carro->getFechaEntrega(), 'divisa' => $pedido->getDivisaFinal()));
- //La validacion del stock se realiza en el carro 1 y 3
- //Una vez llegados aqui damos por senteado que no estĆ”
- //haciendo nada raro con el stock
- if ($Existencia) {
- //Si ya estĆ” en la tabla de stock se resta la cantidad actual
- $stock = $Existencia->getCantidad();
- $resta = $stock - $pedido->getCantidadFinal();
- $Existencia->setCantidad($resta);
- $em->persist($Existencia);
- $em->flush();
- } else {
- //Si no estĆ” en la tabla de stocks se crea una nueva fila y
- //se resta la cantidad final
- $Existencia = new Existencia();
- $oficina = $carro->getOficina();
- $divisa = $pedido->getDivisaFinal();
- $StockMax = $em->getRepository('App\Entity\Stock')->findOneBy(array('oficina' => $oficina, 'divisa' => $divisa));
- if ($StockMax) {
- $resta = $StockMax->getStockMaximo() - $pedido->getCantidadFinal();
- $Existencia->setDivisa($em->getReference('App\Entity\Oficina', $divisa->getId()));
- $Existencia->setOficina($em->getReference('App\Entity\Oficina', $carro->getOficina()->getId()));
- $Existencia->setCantidad($resta);
- $Existencia->setDia($carro->getFechaEntrega());
- if (!$em->isOpen()) {
- "NO Esta abierta";
- }
- $em->persist($Existencia);
- $em->flush();
- } else {
- // throw new \Exception('La oficina: [' . $oficina . '] no dispone de stock de la mondea:[' . $divisa->getNombre() . ']');
- }
- }
- }
- }
- /**
- * Saca la Reserva del carro, la persiste en el ERP y en local.
- * Y manda el correo de notificación al usuario
- * @param Carro $carro carro de compra
- * @return Reserva Estado de la operación
- * @throws \Exception Fallo en el ERP
- *
- */
- private function persistBooking(PersistenceManagerRegistry $doctrine, WebServiceUsuarios $wsu, WebServiceFunciones $wsf, Mailer $mailer, $carro)
- {
- $em = $doctrine->getManager();
- // $WSF = $this->container->get('web.service.funciones', $em);
- // $WSU = $this->container->get('web.service.usuarios', $em);
- // $mailer = $this->container->get('dinamic_shop.mailer');
- if ($this->getUser()) {
- $userERP = $this->getUser()->getErpId();
- } else {
- $userERP = 'INVITADO';
- }
- $Reserva = new Reserva();
- //PEDIDO DE USUARIO REGISTRADO
- if ($userERP != 'INVITADO') {
- $clienteERP = $wsu->findOne($userERP);
- $Reserva->setUsuario($em->getReference('App\Entity\User', $this->getUser()->getId()));
- $tipoC = 'USUARIO';
- } //PEDIDO DE USUARIO INVITADO
- else {
- $tipoC = 'INVITADO';
- $Reserva->setNombre($carro->getInvitado()->getNombre());
- $Reserva->setApellido($carro->getInvitado()->getApellidos());
- $Reserva->setTelefono($carro->getInvitado()->getTelefono());
- $Reserva->setEmail($carro->getInvitado()->getEmail());
- $clienteERP = $carro->getInvitado();
- }
- $oficina = $em->getRepository("App\Entity\Oficina")->findOneById($carro->getOficina()->getId());
- $Reserva->setOficina($em->getReference('App\Entity\Oficina', $oficina->getId()));
- $Reserva->setHoraRecogida($carro->getHoraEntrega());
- $Reserva->setCupon($carro->getCodigoPromo());
- $Reserva->setFechaRecogida($carro->getFechaEntrega());
- $Reserva->setEstado('ACEPTADA');
- $carro->setOficina($oficina);
- $cupon = $carro->getCodigoPromo();
- $rep_cup = $em->getRepository('App\Entity\Cupon')->findOneBy(['codigo'=>$cupon]);
- if($rep_cup){
- $aux = $rep_cup->getTotalUsos();
- $rep_cup->setTotalUsos($aux-1);
- $em->persist($rep_cup);
- }
- //Mandamos linea a linea la reserva y la guardamos en
- //la BBDD
- foreach ($carro->getPedidos() as $linea) {
- $respuesta = $wsf->RegistrarReserva($carro, $linea, $clienteERP, $tipoC);
- if ($respuesta) {
- $ReservaLinea = new ReservaLinea();
- $ReservaLinea->setErpCode($respuesta);
- $ReservaLinea->setDivisaOrigen($em->getReference('App\Entity\Divisa', $linea->getDivisaOrigen()->getId()));
- $ReservaLinea->setDivisaDestino($em->getReference('App\Entity\Divisa', $linea->getDivisaFinal()->getId()));
- $ReservaLinea->setCantidad($linea->getCantidadFinal());
- $Reserva->addLinea($ReservaLinea);
- $em->persist($ReservaLinea);
- } else {
- throw new \Exception("Fallo al registrar al reserva");
- }
- }
- $em->persist($Reserva);
- $em->flush($Reserva);
- if ($tipoC == 'INVITADO') {
- $mailer->successReserve(NULL, $Reserva);
- } else {
- $mailer->successReserve($this->getUser(), $Reserva);
- }
- return $Reserva;
- }
- /**
- * Actualiza la transacción en la base de datos
- * @param $request
- * @param $estado
- * @return Transaccion
- */
- private function persistTransaccion($doctrine, $request, $estado)
- {
- $em = $doctrine->getManager();
- $sesion = $request->getSession();
- /** @var Carro $carro */
- $carro = $sesion->get('carro');
- $Transaccion = new Transaccion();
- if ($carro->getOficina()) {
- $Transaccion->setOficina($em->getReference('App\Entity\Oficina', $carro->getOficina()->getId()));
- }
- $Transaccion->setUsuario($em->getReference('App\Entity\User', $carro->getUsuario()->getId()));
- $Transaccion->sethoraRecogida($carro->getHoraEntrega());
- $Transaccion->setFechaRecogida($carro->getFechaEntrega());
- $Transaccion->setTipoPago($carro->getTipoPago());
- $Transaccion->setCupon($carro->getCodigoPromo());
- $Transaccion->setTipoPromo($carro->getTipoPromo());
- $Transaccion->setDireccionCompleta($carro->getDireccion());
- $Transaccion->setCodigoPostal($carro->getCodigoPostal());
- $Transaccion->setCiudad($carro->getCiudad());
- $Transaccion->setEstado($estado);
- $Transaccion->setPais($carro->getPais());
- $Transaccion->setAnotacion($carro->getComentario());
- $Transaccion->setTiempoEnvio($carro->getFechaEntrega());
- //si el descuento es de tipo divisa descontar usos
- if ($carro->getTipoPromo() == Carro::TIPO_PROMO_DIVISA) {
- $cupon = $carro->getCodigoPromo();
- $rep_cup = $em->getRepository('App\Entity\Cupon')->findOneBy(['codigo'=>$cupon]);
- if($rep_cup){
- $aux = $rep_cup->getTotalUsos();
- $rep_cup->setTotalUsos($aux-1);
- $em->persist($rep_cup);
- }
- }
- if ($carro->getProvincia() && !$carro->getFreeShipping()) {
- $Transaccion->setProvincia($em->getReference('App\Entity\Provincia', $carro->getProvincia()->getId()));
- }
- if ($carro->getCardSend() != null) {
- $Transaccion->setCardSend($carro->getCardSend());
- $Transaccion->setNameSend($carro->getNameSend());
- $Transaccion->setTitular($carro->getTitular());
- }
- if ($carro->getTipoPago() == "TPV") {
- $Transaccion->setTitular($carro->getTitular());
- }
- foreach ($carro->getPedidos() as $pedido) {
- $TransaccionLinea = new TransaccionLinea();
- $TransaccionLinea->setDivisaDestino($em->getReference('App\Entity\Divisa', $pedido->getDivisaFinal()->getId()));
- $TransaccionLinea->setCantidad($pedido->getCantidadFinal());
- $TransaccionLinea->setErpCode($pedido->getErpCode());
- $Transaccion->addLinea($TransaccionLinea);
- }
- $Transaccion->setTotalLineas($carro->getTotalTransaccion()-$carro->getGastosEnvio());
- $Transaccion->setGastosEnvio($carro->getGastosEnvio());
- // dump($Transaccion);die();
- $valor_trans = $Transaccion->getId();
- if(isset($_COOKIE['afcodigo'])){
- // $numero = substr($_COOKIE['afcodigo'], 0);
- $numero = Utils::decode_afcode($_COOKIE['afcodigo']);
- // var_dump($numero);die();
- //No se puede asignar la transaccion al afiliado
- if ($numero and $carro->getUsuario()->getId() != (int)$numero) {
- $numero = $em->getRepository('App\Entity\User')->findOneById($numero);
- $Transaccion->setUsuarioAfiliado($numero);
- }
- }else{
- }
- //Guardamos en sesion y base de datos
- $sesion->set('transaccion', $Transaccion);
- $em->persist($Transaccion);
- $em->flush();
- return $Transaccion;
- }
- /**
- * Parche para cargar las traducciones ya que las entidades
- * se persisten con las relaciones por referencia.
- * @return array
- */
- protected function loadDivisaTraducciones(PersistenceManagerRegistry $doctrine, Request $request)
- {
- $em = $doctrine->getManager();
- $repo = $em->getRepository('App\Entity\DivisaTranslation');
- $sesion = $request->getSession();
- $carro = $sesion->get('carro');
- // $idioma = $request->getLocale();
- // $idioma = $em->getRepository('App\Entity\Idioma')->findOneByUrl($idioma);
- $pedidos = $carro->getPedidos();
- foreach ($pedidos as $key => $pedido) {
- $origenes[$key] = $repo->findOneBy(['translatable' => $pedido->getDivisaOrigen()/*, 'idioma' => $idioma*/]);
- $destinos[$key] = $repo->findOneBy(['translatable' => $pedido->getDivisaFinal()/*, 'idioma' => $idioma*/]);
- }
- return ['origenes' => $origenes, 'destinos' => $destinos];
- }
- /**
- * Borras las ventas del ERP.
- * Se llama a esta función cuando el usuario va para atrÔs,
- * hay una excepción o algún fallo en el ERP.
- * @param Carro $cart
- * @return bool Estado de la operación
- */
- protected function deleteErpSale($cart, WebServiceTPV $wstpv)
- {
- // $WSTPV = $this->container->get('web.service.tpv', $em);
- $success = 1;
- foreach ($cart->getPedidos() as $pedido) {
- $success *= $wstpv->BorrarVenta($pedido->getErpCode());
- $pedido->setErpCode(NULL);
- }
- $cart->setTotalTransaccion(NULL);
- return $success;
- }
- private function buildRedsys($request, $transaccion)
- {
- $local = $request->getLocale();
- $redsys = new ApiRedsys();
- // Valores de entrada
- $terminal = "001";
- $moneda = "978";
- $trans = "1";
- //PASARELA DE PAGO
- $url = $this->generateUrl('app_cart_notification', [], UrlGeneratorInterface::ABSOLUTE_URL);
- // $urlOK = $this->generateUrl('app_cart_5', ['t' => $transaccion->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
- $urlOK = $this->generateUrl('app_cart_3', ['t' => $transaccion->getTokenEmail()], UrlGeneratorInterface::ABSOLUTE_URL);
- $urlKO = $this->generateUrl('app_cart_critical', ['t' => $transaccion->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
- $id = str_pad($transaccion->getId(), 4, "0", STR_PAD_LEFT);
- // $amount = money_format($transaccion->getTotal() * 100, 2);
- $amount = number_format($transaccion->getTotal(),2,"","");
- // Se Rellenan los campos
- $redsys->setParameter("DS_MERCHANT_AMOUNT", $amount);
- $redsys->setParameter("DS_MERCHANT_ORDER", strval($id));
- $redsys->setParameter("DS_MERCHANT_MERCHANTCODE", $this->getParameter('redsys_fuc'));
- $redsys->setParameter("DS_MERCHANT_CURRENCY", $moneda);
- $redsys->setParameter("DS_MERCHANT_TRANSACTIONTYPE", $trans);
- $redsys->setParameter("DS_MERCHANT_TERMINAL", $terminal);
- $redsys->setParameter("DS_MERCHANT_MERCHANTURL", $url);
- $redsys->setParameter("DS_MERCHANT_URLOK", $urlOK);
- $redsys->setParameter("DS_MERCHANT_URLKO", $urlKO);
- $redsys->setParameter("Ds_Merchant_MerchantData", $transaccion->getTitular());
- $return['params'] = $redsys->createMerchantParameters();
- $return['signature'] = $redsys->createMerchantSignature($this->getParameter('redsys_key'));
- return $return;
- }
- #[Route(path: [
- 'es' => '/carro4',
- 'en' => '/en/cart4'
- ], name: 'app_cart_4')]
- public function Cart4Action(Request $request,PersistenceManagerRegistry $doctrine, SettingsManager $sm, WebServiceTPV $wstpv, Mailer $mailer, WebServiceFunciones $wsf)
- {
- $fullCart = $this->getCart($request);
- // dump($fullCart);die();
- $ped = $fullCart->getPedidos();
- // dump($fullCart);
- try {
- if ($re = $this->CartRedirect($request, 4)) {
- return $re;
- }
- $gastosEnv = 0;
- $now = new \DateTime();
- $day = date('l', strtotime($now->format("Y-m-d H:i:s")));
- $time = date("H:i", strtotime($now->format("Y-m-d H:i:s")));
- $em = $doctrine->getManager();
- // $options = $this->container->get('dinamic_settings.manager');
- $fullCart = $this->getCart($request);
- // Comprobar stock en tienda
- if ($fullCart->getOficina() != null) {
- // if (!$this->ComprobarStock($request, $doctrine, $fullCart))
- // return $this->redirect($this->generateUrl('app_cart_3'));
- $fest = $em->getRepository('App\Entity\DayOff')->findBy(['oficina'=>$fullCart->getOficina()->getId()]);
- for ($i = 0; $i < count($fest); $i++) {
- $fechFest = $fest[$i]->getDate()->format("d/m/y");
- $fechRec = $fullCart->getFechaEntrega()->format("d/m/y");
- if($fechFest == $fechRec) {
- $this->addFlash(
- 'danger',
- 'Seleccione otro dĆa de recogida. El que ha seleccionado es festivo en esta oficina.'
- );
- return $this->redirect($this->generateUrl('app_cart_3'));
- }
- }
- if ($fullCart->getReserva() == 1) {
- $fullCart->setTotalEstimado(0);
- for ($i = 0; $i < count($ped); $i++) {
- $short = $ped[$i]->getDivisaFinal()->getId();
- $maxDia = $em->getRepository('App\Entity\Cotizaciones')->getMaxDia($fullCart->getOficina()->getId());
- $fechaMax = new \DateTime($maxDia);
- $nuevaCotizacion = $em->getRepository('App\Entity\Cotizaciones')->findBy(['oficina'=>$fullCart->getOficina()->getId(), 'shortName'=>$short, 'dia'=>$fechaMax]);
- $nCant = $nuevaCotizacion[0]->getPrecioVenta() * $ped[$i]->getCantidadFinal();
- $ped[$i]->setCantidadOrigen($nCant);
- $tot = $fullCart->getTotalEstimado() + $nCant;
- $fullCart->setTotalEstimado($tot);
- }
- } else {
- $fullCart->setTotalEstimado(0);
- for ($i = 0; $i < count($ped); $i++) {
- $short = $ped[$i]->getDivisaFinal()->getId();
- $maxDia = $em->getRepository('App\Entity\Cotizaciones')->getMaxDia($fullCart->getOficina()->getId());
- $fechaMax = new \DateTime($maxDia);
- $nuevaCotizacion = $em->getRepository('App\Entity\Cotizaciones')->findBy(['oficina'=>$this->getParameter('oficina_por_defecto'), 'shortName'=>$short, 'dia'=>$fechaMax]);
- $nCant = $nuevaCotizacion[0]->getPrecioVenta() * $ped[$i]->getCantidadFinal();
- $ped[$i]->setCantidadOrigen($nCant);
- $tot = $fullCart->getTotalEstimado() + $nCant;
- $fullCart->setTotalEstimado($tot);
- }
- }
- // $fullCart->getOficina()
- }
- $local = $request->getLocale();
- $total = 0;
- $formCard = $this->createFormBuilder()
- ->add('save40', SubmitType::class,
- array('label' => $sm->getValue('cart4.pay'),
- 'attr' => array('class' => 'pagar bcol1')))
- ->getForm();
- $formTrans = $this->createFormBuilder()
- ->add('save41', SubmitType::class,
- array('label' => $sm->getValue('cart4.pushOrder'),
- 'attr' => array('class' => 'pagar bcol1')))
- ->getForm();
- $formReserv = $this->createFormBuilder()
- ->add('save42', SubmitType::class,
- array('label' => $sm->getValue('cart4.book'),
- 'attr' => array('class' => 'pagar bcol1')))
- ->getForm();
- $repository = $em->getRepository('App\Entity\Oficina');
- if(isset($_COOKIE['cookieoficina']) ){
- $ofi = (integer)($_COOKIE['cookieoficina']);
- $cotizaciones = json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local, $ofi));
- if($ofi == 1){
- $ofi = $this->getParameter('oficina_por_defecto');
- $cotizaciones = json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local, $this->getParameter('oficina_por_defecto')));
- }
- } else {
- $ofi = (integer)0;
- $cotizaciones = json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChanges($local));
- }
- // $oficina = $repository->findOneBy(['id' => $ofi]);
- // $fullCart->setOficina($oficina);
- //Si no es una reserva y no se ha guardado antes (por si refrescan la vista)
- if (!$fullCart->getReserva() && !$fullCart->getTotalTransaccion()) {
- // $WSTPV = $this->container->get('web.service.tpv', $em);
- $gastosEnvio = 0;
- if (( $ofi == 0 && !$fullCart->getFreeShipping()) || (!$fullCart->getOficina() && !$fullCart->getFreeShipping())) {
- $gastosEnvio = $fullCart->getProvincia()->getGastos();
- }
- // var_dump($gastosEnvio); die();
- $pedidos = $fullCart->getPedidos();
- //Persistir en ERP REMOTO
- $fail = false;
- $total = 0;
- if($fullCart->getOficina() != null){
- $ofC = $em->getRepository('App\Entity\Oficina')->findOneById($fullCart->getOficina()->getId());
- if ($ofC->permiteCompra()) {
- $gastosEnv = 0;
- $fullCart->setGastosEnvio(0);
- } else {
- $gastosEnv = $ofC->getProvincia()->getGastos();
- $fullCart->setGastosEnvio($gastosEnv);
- }
- }else{
- $gastosEnv = $fullCart->getProvincia()->getGastos();
- }
- $cupon = $fullCart->getCodigoPromo();
- if($fullCart->getFreeShipping()){
- $gastosEnv = 0;
- }
- for ($i = 0; $i < count($pedidos); $i++) {
- $extra = ($i == 0) ? $gastosEnv : 0;
- if($gastosEnv == 0){
- $extra = 0;
- }
- // var_dump($extra);die();
- if($cupon) {
- if ($fullCart->getTipoPromo() == Carro::TIPO_PROMO_DIVISA AND $this->comprobarCupon($request, $doctrine, $cupon)) {
- // dump('a'); die();
- $rep_cup = $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $cupon ]);
- $respuesta = $wstpv->CrearVentaV2($fullCart, $pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra, $rep_cup->getCodigoTPV(), Carro::TIPO_PROMO_DIVISA);
- } elseif ($fullCart->getTipoPromo() == Carro::TIPO_PROMO_CUPON) {
- $resultado_cupon = $this->comprobarCuponCodigo($cupon, $fullCart->getTotalEstimado(),$wsf);
- if ($resultado_cupon === true) {
- $respuesta = $wstpv->CrearVentaV2($fullCart, $pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra, $cupon, Carro::TIPO_PROMO_CUPON);
- }
- else {
- $this->addFlash(
- 'danger',
- $sm->getValue($resultado_cupon['error'])
- );
- return $this->redirect($this->generateUrl('app_cart_1'));
- }
- }
- else {
- // dump($fullCart->getTipoPromo()); die();
- $respuesta = false;
- }
- }
- else {
- $respuesta = $wstpv->CrearVenta($fullCart, $pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra);
- }
- if (!$respuesta) {
- throw new \Exception('Una de las lļæ½neas ha fallado en el ERP');
- } else {
- $descuento = 0;
- if (isset($respuesta['DescuentoTicket']) and $respuesta['DescuentoTicket'] > 0) {
- $descuento = $respuesta['DescuentoTicket'];
- $fullCart->setDescuentoPromo($descuento);
- }
- //En local pillmamos el estimado porque Navision nos devolveria el importe de otro carrito
- if ($this->kernel->getEnvironment() == 'dev')
- $total = $fullCart->getTotalEstimado()+$gastosEnv-$descuento ;
- else
- $total += $respuesta['importe'];
- $pedidos[$i]->setErpCode($respuesta['erpCode']);
- // dump($respuesta); die();
- }
- }
- $fullCart->setTotalTransaccion($total);
- $fullCart->setGastosEnvio($gastosEnv);
- // dump($hhh->getProvincia()->getGastos());die();
- //Si hay un problema en el ERP con alguna lļæ½nea
- //reiniciamos el proceso
- if ($fail) {
- throw new \Exception('Una de las lļæ½neas ha fallado en el ERP');
- }
- }
- $reducido = null;
- if ($fullCart->getReserva()) {
- // $dayoffs = $em->getRepository("App\Entity\HorarioReducido")->findOficinaDate($fullCart->getOficina(), $fullCart->getFechaEntrega());
- // $dayoffs = $em->getRepository("App\Entity\DayOff")->findBy(array('id' => $ofi));
- // $now = $fullCart->getFechaEntrega();
- //
- // if ($dayoffs) {
- //
- // if ($request->getLocale() == "es") {
- // $reducido = "Horario reducido de " . $dayoffs->getHoraInicio()->format("H:i") . " a " . $dayoffs->getHoraFin()->format("H:i");
- // } else {
- // $reducido = "Reduced hours of " . $dayoffs->getHoraInicio()->format("H:i") . " to " . $dayoffs->getHoraFin()->format("H:i");
- // }
- // }
- } else {
- if ($fullCart->getTipoPago() == "TPV") {
- $em = $doctrine->getManager();
- $repository = $em->getRepository('App\Entity\Oficina');
- if(isset($_COOKIE['cookieoficina']) ){
- $ofi = (integer)($_COOKIE['cookieoficina']);
- $cotizaciones = json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local, $ofi));
- if($ofi == 1){
- $cotizaciones = json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local, $this->getParameter('oficina_por_defecto')));
- }
- } else {
- $ofi = (integer)0;
- $cotizaciones = json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local, $this->getParameter('oficina_por_defecto')));
- }
- // $oficina = $repository->findOneBy(['id' => $ofi]);
- // $fullCart->setOficina($oficina);
- //comprobamos stock
- foreach ($fullCart->getPedidos() as $linea) {
- if ($fullCart->getOficina()) { //Compromas los tiempos para recogida con tarjeta
- foreach ($fullCart->getOficina()->getStocks() as $stock) {
- if (!$stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //con stock con tarjeta
- if ($time < "15:00" and $day == "Friday") { //viernes antes del as 3
- $now->modify('+3 days');
- } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
- $now->modify('+4 days');
- } elseif ($day == "Saturday") { //sabado
- $now->modify('+3 days');
- } elseif ($day == "Sunday") {//domingo
- $now->modify('+2 days');
- } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
- $now->modify('+4 days');
- } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday" || $day == "Wednesday")) { //Lunes, martes o miercoles despues de las 3
- $now->modify('+2 days');
- } else {
- $now->modify('+1 days');
- }
- } elseif ($stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //sin stock
- if ($time < "15:00" and $day == "Friday") { //viernes antes del as 3
- $now->modify('+3 days');
- } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
- $now->modify('+4 days');
- } elseif ($day == "Saturday") { //sabado
- $now->modify('+3 days');
- } elseif ($day == "Sunday") {//domingo
- $now->modify('+2 days');
- } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
- $now->modify('+4 days');
- } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday" || $day == "Wednesday")) { //Lunes, martes o miercoles despues de las 3
- $now->modify('+2 days');
- } else {
- $now->modify('+1 days');
- }
- }
- }
- $now = $this->comprobarFecha($now, $fullCart->getOficina(), $em);
- // $dayoffs = $em->getRepository("App\Entity\HorarioReducido")->findOficinaDate($fullCart->getOficina(), $now);
- //
- // if ($dayoffs) {
- //
- // if ($request->getLocale() == "es") {
- // $reducido = "Horario reducido de " . $dayoffs->getHoraInicio()->format("H:i") . " a " . $dayoffs->getHoraFin()->format("H:i");
- //
- // } else {
- // $reducido = "Reduced hours of " . $dayoffs->getHoraInicio()->format("H:i") . " to " . $dayoffs->getHoraFin()->format("H:i");
- // }
- // }
- } else { //sino es a domicilio
- //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);
- $oficina = $em->getRepository("App\Entity\Oficina")->findOneById($this->getParameter('oficina_por_defecto'));
- $now = $this->comprobarFecha($now, $oficina, $em);
- $day = date('l', strtotime($now->format("Y-m-d H:i:s")));
- if ($linea->getDivisaFinal()->getCompraMinima() == 0) { //con stock con tarjeta
- if ($time < "15:00" and $day == "Friday") { //viernes antes del as 3
- $now->modify('+3 days');
- } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
- $now->modify('+4 days');
- } elseif ($day == "Saturday") { //sabado
- $now->modify('+3 days');
- } elseif ($day == "Sunday") {//domingo
- $now->modify('+2 days');
- } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
- $now->modify('+4 days');
- } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday" || $day == "Wednesday")) { //Lunes, martes o miercoles despues de las 3
- $now->modify('+2 days');
- } else {
- $now->modify('+1 days');
- }
- } elseif ($linea->getDivisaFinal()->getCompraMinima() != 0) { //sin stock
- if ($time < "15:00" and $day == "Friday") { //viernes antes del as 3
- $now->modify('+4 days');
- } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
- $now->modify('+5 days');
- } elseif ($day == "Saturday") { //sabado
- $now->modify('+4 days');
- } elseif ($day == "Sunday") {//domingo
- $now->modify('+3 days');
- } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
- $now->modify('+6 days');
- } elseif ($time >= "15:00" and $day == "Wednesday") { //jueves despues de las 3
- $now->modify('+5 days');
- } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
- $now->modify('+3 days');
- } else {
- $now->modify('+2 days');
- }
- }
- if ($day == "Sunday") { //sunday
- $now = $this->comprobarFecha($now->modify('+1 days'), $oficina, $em);
- }
- }
- }
- } else if ($fullCart->getTipoPago() == "TRANSFERENCIA") { //tranferencia
- $em = $doctrine->getManager();
- $repository = $em->getRepository('App\Entity\Oficina');
- if(isset($_COOKIE['cookieoficina']) ){
- $ofi = (integer)($_COOKIE['cookieoficina']);
- $cotizaciones = json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local, $ofi));
- if($ofi == 1){
- $cotizaciones = json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local, $this->getParameter('oficina_por_defecto')));
- }
- } else {
- $ofi = (integer)0;
- $cotizaciones = json_encode($em->getRepository('App\Entity\Cotizaciones')->getLastChangesOffice($local, $this->getParameter('oficina_por_defecto')));
- }
- // $oficina = $repository->findOneBy(['id' => $ofi]);
- // $fullCart->setOficina($oficina);
- //comprobamos stock
- foreach ($fullCart->getPedidos() as $linea) {
- if ($fullCart->getOficina()) { //Compromas los tiempos para recogida con tarjeta
- foreach ($fullCart->getOficina()->getStocks() as $stock) {
- if (!$stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //con stock con transferencia
- if ($time < "15:00" and $day == "Friday") { //viernes antes del as 3
- $now->modify('+4 days');
- } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
- $now->modify('+4 days');
- } elseif ($day == "Saturday") { //sabado
- $now->modify('+4 days');
- } elseif ($day == "Sunday") {//domingo
- $now->modify('+3 days');
- } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
- $now->modify('+5 days');
- } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
- $now->modify('+5 days');
- } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
- $now->modify('+3 days');
- } else {
- $now->modify('+2 days');
- }
- } elseif ($stock->getCompraProveedor() and $stock->getDivisa()->getId() == $linea->getDivisaFinal()->getId()) { //sin stock
- if ($time < "15:00" and $day == "Friday") { //viernes antes del as 3
- $now->modify('+4 days');
- } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
- $now->modify('+5 days');
- } elseif ($day == "Saturday") { //sabado
- $now->modify('+4 days');
- } elseif ($day == "Sunday") {//domingo
- $now->modify('+3 days');
- } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
- $now->modify('+5 days');
- } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
- $now->modify('+5 days');
- } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
- $now->modify('+3 days');
- } else {
- $now->modify('+2 days');
- }
- }
- }
- $now = $this->comprobarFecha($now, $fullCart->getOficina(), $em);
- } else { //sino es a domicilio
- //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 = $em->getRepository("App\Entity\Oficina")->findOneById($this->getParameter('oficina_por_defecto'));
- $dateBefore = $now;
- $now = $this->comprobarFecha($now, $oficina, $em);
- $dateAfter = $now;
- $day = date('l', strtotime($now->format("Y-m-d H:i:s")));
- if ($linea->getDivisaFinal()->getCompraMinima() == 0) { //con stock con transferencia
- if ($dateBefore->diff($dateAfter)->format('%R%a') == "+1" and $day == "Friday") { //viernes cerrado el jueves
- $now->modify('+3 days');
- } elseif ($time < "15:00" and $day == "Friday") { //viernes antes del as 3
- $now->modify('+4 days');
- } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
- $now->modify('+4 days');
- } elseif ($day == "Saturday") { //sabado
- $now->modify('+4 days');
- } elseif ($day == "Sunday") {//domingo
- $now->modify('+3 days');
- } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
- $now->modify('+5 days');
- } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
- $now->modify('+5 days');
- } elseif ($time >= "15:00" and ($day == "Monday" || $day == "Tuesday")) { //Lunes, martes o miercoles despues de las 3
- $now->modify('+3 days');
- } else {
- $now->modify('+2 days');
- }
- } elseif ($linea->getDivisaFinal()->getCompraMinima() != 0) { //sin stock
- if ($time < "15:00" and $day == "Friday") { //viernes antes del as 3
- $now->modify('+5 days');
- } elseif ($time >= "15:00" and $day == "Friday") { //viernes antes despues de las 3
- $now->modify('+6 days');
- } elseif ($day == "Saturday") { //sabado
- $now->modify('+5 days');
- } elseif ($day == "Sunday") {//domingo
- $now->modify('+4 days');
- } elseif ($time >= "15:00" and $day == "Wednesday") { //miercoles despues de las 3
- $now->modify('+6 days');
- } elseif ($time >= "15:00" and $day == "Thursday") { //jueves despues de las 3
- $now->modify('+6 days');
- } elseif ($time >= "15:00" and $day == "Tuesday") { //martes despues de las 3
- $now->modify('+6 days');
- } elseif ($time >= "15:00" and $day == "Monday") { //Lunes despues de las 3
- $now->modify('+4 days');
- } else {
- $now->modify('+3 days');
- }
- }
- if ($day == "Sunday") { //sunday
- $now = $this->comprobarFecha($now->modify('+1 days'), $oficina, $em);
- }
- }
- }
- } else if ($fullCart->getTipoPago() == "PAYPAL") {
- } else if ($fullCart->getTipoPago() == "BIZUM") {
- }
- }
- // $fullCart->setFechaEntrega($now);
- $totalEntregar = 0;
- foreach ($fullCart->getPedidos() as $pedido) {
- $totalEntregar = $totalEntregar + $pedido->getCantidadFinal();
- }
- $nuevaFechaDisponible = new \DateTime('now');
- $domingo = false;
- if ($nuevaFechaDisponible->format('N') == 7) {
- $domingo = true;
- }
- if($fullCart->getOficina() != null) {
- $oficinaE = $em->getRepository('App\Entity\Oficina')->findOneById($fullCart->getOficina()->getId());
- if ($totalEntregar >= 50 || !$oficinaE->permiteCompra()) {
- if ($fullCart->getFechaEntrega() < $fullCart->getFechaDisponible() || $fullCart->getFechaEntrega() == $fullCart->getFechaDisponible() && $fullCart->getHoraEntrega()->format("H:i") < $fullCart->getFechaDisponible()->format("H:i")) {
- $this->addFlash(
- 'danger',
- '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")
- );
- return $this->redirect($this->generateUrl('app_cart_3'));
- }
- } else if ($domingo == true) {
- $nuevaFechaDisponible->add(new \DateInterval('PT10H'));
- $fullCart->setFechaDisponible($nuevaFechaDisponible);
- } else {
- $fullCart->setFechaDisponible($nuevaFechaDisponible);
- }
- }
- // dump($fullCart);die();
- // $dayoffs = $em->getRepository('App\Entity\HorarioReducido')->findOficinaDate($fullCart->getOficina(), $now);
- //
- // if ($dayoffs) {
- //
- // if ($request->getLocale() == "es") {
- // $reducido = "Horario reducido de " . $dayoffs->getHoraInicio()->format("H:i") . " a " . $dayoffs->getHoraFin()->format("H:i");
- //
- // } else {
- // $reducido = "Reduced hours of " . $dayoffs->getHoraInicio()->format("H:i") . " to " . $dayoffs->getHoraFin()->format("H:i");
- // }
- // }
- //Pago con tarjeta
- $formCard->handleRequest($request);
- if ($formCard->isSubmitted() and $formCard->isValid()) {
- //PERSISTIR EN BASE DE DATOS LOCAL
- $transaccion = $this->persistTransaccion($doctrine, $request, 'En pasarela de pago');
- // Creamos un formulario oculto para enviar la informaciļæ½n mediante POST a los servidores del TPV
- $redsysData = $this->buildRedsys($request, $transaccion);
- $formTPV = $this->container->get('form.factory')->createNamedBuilder('', FormType::class, array(), array(
- 'action' => $this->getParameter('redsys_gateway'),
- 'method' => 'POST',
- 'csrf_protection' => false,
- 'attr' => array('name' => 'tpv', 'id' => 'formTPV'),
- ))
- ->add('Ds_SignatureVersion', HiddenType::class, ['data' => $this->getParameter('redsys_version')])
- ->add('Ds_MerchantParameters', HiddenType::class, ['data' => $redsysData['params']])
- ->add('Ds_Signature', HiddenType::class, ['data' => $redsysData['signature']])
- ->getForm();
- return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
- }
- //Pago con transferencia
- $formTrans->handleRequest($request);
- if ($formTrans->isSubmitted() and $formTrans->isValid()) {
- $transaccion = $this->persistTransaccion($doctrine, $request, 'Pendiente de pago');
- $response = $this->redirect($this->generateUrl('app_cart_5'));
- $transaccion = $em->getRepository("App\Entity\Transaccion")->findOneById($transaccion->getId());
- // $WSTPV = $this->container->get('web.service.tpv', $em);
- foreach ($transaccion->getLineas() as $linea) {
- $upLinea = $em->getRepository("App\Entity\TransaccionLinea")->findOneById($linea->getId());
- // ACTIVAR EN PRODUCCION
- // $respuesta = $wstpv->RegistrarVenta($upLinea);
- // $upLinea = $upLinea->setTicket($respuesta);
- // $upLinea->setTicket($respuesta);
- //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- $em->merge($upLinea);
- $em->flush();
- }
- // ACTIVAR EN PRODUCCION
- $mailer->pendingTransaction($this->getUser(), $transaccion);
- return $response;
- //Proceso de pago con transferencia
- }
- //RESERVA
- $formReserv->handleRequest($request);
- if ($formReserv->isSubmitted() and $formReserv->isValid()) {
- $this->ActualizarStock($doctrine, $fullCart);
- $response = $this->redirect($this->generateUrl('app_cart_5'));
- return $response;
- }
- $stepBread = $this->StepControl($request);
- $user = $this->getUser();
- $invitado = $fullCart->getInvitado();
- $traducciones = $this->loadDivisaTraducciones($doctrine, $request);
- $idPago = $fullCart->getTipoPago();
- $metodoPago = $em->getRepository("App\Entity\MetodoPago")->findOneBy(array('id' => $idPago));
- return $this->render('default/carrito/carrito4.html.twig', array(
- // 'reducido' => $reducido,
- 'formReserva' => $formReserv->createView(),
- 'stepBread' => $stepBread,
- 'carro' => $fullCart,
- 'usuario' => $user,
- 'invitado' => $invitado,
- 'formCard' => $formCard->createView(),
- 'formTrans' => $formTrans->createView(),
- 'currentStep' => 4,
- 'total' => $fullCart->getTotalTransaccion(),
- 'descuentoPromo' => $fullCart->getDescuentoPromo(),
- 'gastosEnvio' => $gastosEnv,
- 'sm' => $sm,
- 'traducciones' => $traducciones,
- 'tiempoenvio' => $fullCart->getFechaDisponible(),
- 'tiemporecogida' => $fullCart->getFechaEntrega(),
- 'metodoPago' => $metodoPago
- ));
- } catch
- (\Exception $e) {
- if ($this->kernel->getEnvironment() == 'dev') throw $e;
- $this->resetCart($request);
- $catcher = $this->container->get('web.service.catchException');
- $log = new Log();
- $this->deleteErpSale($fullCart,$wstpv);
- $log->setLocation('carro4');
- $log->setUser($this->getUser());
- $log->setText(json_encode($e->getTrace()));
- $error = $e->getMessage();
- $catcher->saveException($log);
- return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $error, 'currentStep' => 5));
- }
- }
- public function resetCart($request)
- {
- $sesion = $request->getSession();
- $sesion->set('cartStep', null);
- $sesion->set('carro', null);
- $sesion->set('transferencia', null);
- }
- #[Route(path: [
- 'es' => '/carro5',
- 'en' => '/en/cart5'
- ], name: 'app_cart_5')]
- public function Cart5Action(Request $request,PersistenceManagerRegistry $doctrine, WebServiceUsuarios $wsu, WebServiceFunciones $wsf, LoggerInterface $logger, Mailer $mailer, EventDispatcherInterface $EventDispatcher, WebServiceTPV $wstpv)
- {
- try {
- if ($request->query->has('t')) {
- $em = $doctrine->getManager();
- $t = $request->query->get('t');
- $transaccion = $em->getRepository('App\Entity\Transaccion')->findOneBy(['tokenEmail' => $t]);
- } else {
- return $this->redirect($this->generateUrl('app_cart_1'));
- }
- if ($transaccion && $transaccion->getEstado() == 'En pasarela de pago') {
- $redsysData = $this->buildRedsys($request, $transaccion);
- $formTPV = $this->container->get('form.factory')->createNamedBuilder('', FormType::class, array(), array(
- 'action' => $this->getParameter('redsys_gateway'),
- 'method' => 'POST',
- 'csrf_protection' => false,
- 'attr' => array('name' => 'tpv', 'id' => 'formTPV'),
- ))
- ->add('Ds_SignatureVersion', HiddenType::class, ['data' => $this->getParameter('redsys_version')])
- ->add('Ds_MerchantParameters', HiddenType::class, ['data' => $redsysData['params']])
- ->add('Ds_Signature', HiddenType::class, ['data' => $redsysData['signature']])
- ->getForm();
- return $this->render('default/carrito/to_tpv.html.twig', ['form' => $formTPV->createView()]);
- }
- // $EventDispatcher->dispatch(new OrderCompleteEvent($transaccion,$request), OrderCompleteEvent::NAME);
- // $respuesta = $wstpv->CrearVentaV2($fullCart, $pedidos[$i], $this->getUser(), $fullCart->getTipoPago(), $extra, $cupon, Carro::TIPO_PROMO_CUPON);
- $cupon = $transaccion->getCupon();
- foreach ($transaccion->getLineas() as $linea) {
- if ($linea->getErpCode() == null) {
- if($cupon) {
- if ($transaccion->getTipoPromo() == Carro::TIPO_PROMO_DIVISA) {
- $rep_cup = $em->getRepository('App\Entity\Cupon')->findOneBy([ 'codigo' => $cupon ]);
- $respuesta = $wstpv->CrearVentaV2($transaccion, $linea, $this->getUser(), $transaccion->getTipoPago(), $transaccion->getGastosEnvio(), $rep_cup->getCodigoTPV(), Carro::TIPO_PROMO_DIVISA);
- } elseif ($transaccion->getTipoPromo() == Carro::TIPO_PROMO_CUPON) {
- $respuesta = $wstpv->CrearVentaV2($transaccion, $linea, $this->getUser(), $transaccion->getTipoPago(), $transaccion->getGastosEnvio(), $cupon, Carro::TIPO_PROMO_CUPON);
- } else {
- $respuesta = false;
- }
- } else {
- $respuesta = $wstpv->CrearVenta($transaccion, $linea, $this->getUser(), $transaccion->getTipoPago(), $transaccion->getGastosEnvio());
- }
- if (!$respuesta) {
- throw new \Exception('Una de las lĆneas ha fallado en el ERP al crearse');
- }
- $linea->setErpCode($respuesta['erpCode']);
- $em->persist($linea);
- $em->flush();
- $respuesta = $wstpv->RegistrarVenta($linea);
- if (!$respuesta) {
- throw new \Exception('Una de las lĆneas ha fallado en el ERP al registrarse');
- }
- $linea->setTicket($respuesta);
- $em->persist($linea);
- $em->flush();
- }
- }
- $mailer->succcessBought($transaccion->getUsuario(), $transaccion);
- // $mailer->transactionNotification($transaccion);
- $returnArray = array(
- 'currentStep' => 5,
- 'transaccion' => $transaccion,
- );
- return $this->render('default/carrito/carrito5.html.twig', $returnArray);
- // if ($this->getCart($request)) {
- // $Reserva = $transaccion = NULL;
- // if ($re = $this->CartRedirect($request, 5)) {
- // return $re;
- // }
- // $carro = $this->getCart($request);
- //
- // //Es una COMPRA SIN cerrar
- // if (!$carro->getReserva()) {
- // $sesion = $request->getSession();
- // $transaccion = $sesion->get('transaccion');
- // //AVISAMOS AL ERP DE QUE LA COMPRA FUE BIEN
- // $transaccion = $em->getRepository("App\Entity\Transaccion")->findOneById($transaccion->getId());
- //
- // //SI ES UNA COMPRA RECOGIDA EN OFICINA ACTUALIZAMOS EL STOCK
- // if ($carro->getOficina()) {
- // $this->ActualizarStock($doctrine, $carro);
- // }
- //
- // $EventDispatcher->dispatch(new OrderCompleteEvent($transaccion,$request), OrderCompleteEvent::NAME);
- // }
- // //Es una RESERVA
- // else if ($carro->getReserva()) {
- // $Reserva = $this->persistBooking($doctrine, $wsu, $wsf, $mailer, $carro);
- // $EventDispatcher->dispatch(new BookingCompleteEvent($Reserva,$request), BookingCompleteEvent::NAME);
- // }
- // $stepBread = $this->StepControl($request);
- //
- // $returnArray = array(
- // 'stepBread' => $stepBread,
- // 'reserva' => $Reserva,
- // 'currentStep' => 5,
- // 'transaccion' => $transaccion,
- // );
- //
- // /**
- // * Para depurar el carro sin que saque del paso 5
- // * comenta esta linea
- // */
- // // $this->resetCart($request);
- //
- // // return $returnArray;
- //
- // return $this->render('default/carrito/carrito5.html.twig', $returnArray);
- // } else {
- // $response = $this->redirect($this->generateUrl('index'));
- // return $response;
- // }
- } catch (\Exception $e)
- {
- $logger->error($e->getMessage(). ' | '.$e->getTraceAsString());
- if($this->getParameter('kernel.debug')) {
- throw $e;
- }
- return $this->render('default/carrito/Cart5ERP.html.twig', array('exception' => $e->getMessage(), 'currentStep' => 5));
- }
- }
- #[Route(path: [
- 'es' => '/notificacion',
- 'en' => 'en/notification'
- ], name: 'app_cart_notification')]
- public function notificationAction(Request $request, PersistenceManagerRegistry $doctrine, SettingsManager $sm, WebServiceTPV $wstpv, Mailer $mailer, LoggerInterface $redsysLogger)
- {
- // $logger = $this->get('monolog.logger.redsys');
- try {
- $em = $doctrine->getManager();
- // $options = $this->container->get('dinamic_settings.manager');
- // $WSTPV = $this->container->get('web.service.tpv', $em);
- // $wstpv2 = $this->container->get('App\Services\WebServiceTPV');
- $sesion = $request->getSession();
- $transaccion = $sesion->get('transaccion');
- // Se crea Objeto
- $redsys = new ApiRedsys();
- $redsysLogger->info('[NTFA] Empezamos la notificacion.');
- $version = $request->get("Ds_SignatureVersion");
- $redsysLogger->info('[NTFA] Versión: ' . $version);
- $datos = $request->get("Ds_MerchantParameters");
- // dump($datos);die();
- $redsysLogger->info('[NTFA] Datos: ' . $datos);
- $signatureRecibida = $request->get("Ds_Signature");
- $redsysLogger->info('[NTFA] Firma: ' . $signatureRecibida);
- $decodec = $redsys->decodeMerchantParameters($datos);
- $response = json_decode($decodec, true);
- $firma = $redsys->createMerchantSignatureNotif($this->getParameter('redsys_key'), $datos);
- $dsResponse = intval($response['Ds_Response']);
- if ($firma === $signatureRecibida && ($dsResponse <= 99 || $dsResponse == 900 || $dsResponse == 400)) {
- //PERSISTIR EN ERP
- $firmado = "FIRMA OK";
- $transaccionId = ltrim($redsys->getParameter('Ds_Order'), '0');
- $em = $doctrine->getManager();
- $transaccion = $em->getRepository('App\Entity\Transaccion')->findOneById($transaccionId);
- if ($transaccion) {
- $redsysLogger->info('Poniendo pagado a: ' . $transaccion->getId());
- // $mailer = $this->container->get('dinamic_shop.mailer');
- $transaccion->setEstado('Pagado');
- $pago = new \DateTime();
- $transaccion->setFechaPagado($pago);
- $em->persist($transaccion);
- $em->flush();
- foreach ($transaccion->getLineas() as $linea) {
- $upLinea = $em->getRepository("App\Entity\TransaccionLinea")->findOneById($linea->getId());
- // ACTIVAR EN PRODUCCION
- // dump($wstpv); die();
- // $respuesta = $wstpv->RegistrarVenta($upLinea);
- // $upLinea = $upLinea->setTicket($respuesta);
- // $upLinea->setTicket($respuesta);
- //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- $em->merge($upLinea);
- $em->flush();
- }
- $mailer->completeTransation($transaccion->getEmailTitular(), $transaccion);
- // $mailer->pendingTransaction($this->getUser(), $transaccion);
- // dump($mailer);die();
- } else {
- $redsysLogger->info('[NTFA] La transaccion ' . $transaccionId . ' NO ha sido encontrada.');
- }
- $redsysLogger->info('[NTFA] Final de Firma ok');
- } else {
- $redsysLogger->info('[NTFA] Error en la pasarela');
- $transaccion->setEstado('ERROR EN PASARELA');
- $em->persist($transaccion);
- $em->flush();
- $firmado = "FIRMA KO";
- }
- return new Response($firmado);
- } catch (\Exception $e) {
- $redsysLogger->critical('[NTFA][1/2][CRITICAL]' . $e->getMessage());
- $redsysLogger->critical('[NTFA][2/2][CRITICAL]' . $e->getTraceAsString());
- return new Response("ERROR");
- }
- }
- #[Route(path: [
- 'es' => '/error-carro',
- 'en' => 'en/cart-error'
- ], name: 'app_cart_critical')]
- public function pasarelaCritical(Request $request)
- {
- $this->resetCart($request);
- $response = $request->request->get("Ds_Response");
- //print_r($response);
- $version = $request->request->get("Ds_SignatureVersion");
- //print_r($version);
- return $this->render('default/carrito/errorcart.html.twig');
- }
- public function comprobarFecha($now, Oficina $oficina, $em)
- {
- $dayoffs = $em->getRepository("App\Entity\DayOff")->findBy(array('id' => $oficina));
- $validDate = clone $now;
- foreach ($dayoffs as $dayoff) {
- $formatted = $validDate->format("Y-m-d");
- if (!in_array($formatted, $dayoffs) and $this->isOpenOffice($validDate, $oficina)) {
- return $validDate;
- }
- $validDate->modify('+1 days');
- }
- return $validDate;
- }
- public function isOpenOffice($date, Oficina $oficina)
- {
- $fechaValida = false;
- $date = $date->format('D');
- $franjas = $oficina->getFranjas();
- for ($i = 0; $i < count($franjas) && !$fechaValida; $i++) {
- switch ($date) {
- case 'Mon':
- if ($franjas[$i]->getLunes()) $fechaValida = true;
- break;
- case 'Tue':
- if ($franjas[$i]->getMartes()) $fechaValida = true;
- break;
- case 'Wed':
- if ($franjas[$i]->getMiercoles()) $fechaValida = true;
- break;
- case 'Thu':
- if ($franjas[$i]->getJueves()) $fechaValida = true;
- break;
- case 'Fri':
- if ($franjas[$i]->getViernes()) $fechaValida = true;
- break;
- case 'Sat':
- if ($franjas[$i]->getSabado()) $fechaValida = true;
- break;
- case 'Sun':
- if ($franjas[$i]->getDomingo()) $fechaValida = true;
- break;
- default:
- break;
- }
- }
- return $fechaValida;
- }
- }