src/Controller/Frontend/WebsiteController.php line 2471

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Frontend;
  3. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  4. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use App\Entity\Orders;
  8. use App\Entity\OrderDetail;
  9. use App\Entity\OrderField;
  10. use App\Entity\ProductInventoryLog;
  11. use App\Entity\AlertPurchase;
  12. use App\Entity\Setting;
  13. use App\Entity\WebSlide;
  14. use App\Entity\WebSetting;
  15. use App\Entity\Brand;
  16. use App\Entity\Payment;
  17. use App\Entity\Category;
  18. use App\Entity\Subcategory;
  19. use App\Entity\Blog;
  20. use App\Entity\Customer;
  21. use App\Entity\Client;
  22. use App\Entity\CustomerLocation;
  23. use App\Service\PaymentQPayProHelper;
  24. //use AppBundle\Helper\MailHelper;
  25. use App\Service\DistanceHelper;
  26. //use App\Helper\PaymentQPayProHelper;
  27. use Nzo\UrlEncryptorBundle\Annotations\ParamDecryptor;
  28. use Nzo\UrlEncryptorBundle\Annotations\ParamEncryptor;
  29. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  30. use Symfony\Component\Security\Core\Security;
  31. use App\Service\HelperService;
  32. use App\Service\MailHelper;
  33. use Symfony\Component\String\Slugger\SluggerInterface;
  34. use Nzo\UrlEncryptorBundle\Encryptor\Encryptor;
  35. class WebsiteController extends AbstractController {
  36.     private $encryptor;
  37.     public function __constructEncryptor $encryptor)
  38.     {
  39.         $this->encryptor $encryptor;    
  40.     }
  41.     
  42.     /**
  43.      *
  44.      * @Route("{slug}/store-product", name="frontend_store_product")
  45.      */
  46.     public function storeAction(Request $request$slug)
  47.     {
  48.         $em          $this->getDoctrine()->getManager();
  49.         $userData    $this->get("session")->get("userData");       
  50.         $currentCart json_decode($this->get("session")->get("cart"));
  51.         
  52.         /*
  53.         $newCart = array();
  54.         $this->get("session")->set("cart", json_encode($newCart));
  55.         $currentCart = json_decode($this->get("session")->get("cart"));
  56.         exit;
  57.         */
  58.         
  59.         if($currentCart)
  60.         {
  61.             if(count($currentCart) == 0)
  62.             {
  63.                 $currentCart = array();
  64.             }
  65.         } else {
  66.             $currentCart = array();
  67.         }
  68.         //print_r($currentCart);exit;
  69.         if($request->get('remove'))
  70.         {
  71.             $key $request->get('key');
  72.             $newCart = array();
  73.             foreach($currentCart as $thisKey => $cart)
  74.             {
  75.                 if($thisKey == $key)
  76.                 {
  77.                     
  78.                 } else {
  79.                     $newCart[] = $cart;
  80.                 }
  81.             }
  82.             $this->get("session")->set("cart"json_encode($newCart));
  83.             $currentCart json_decode($this->get("session")->get("cart"));
  84.         }
  85.         if($request->get('clean'))
  86.         {
  87.             $newCart = array();
  88.             $this->get("session")->set("cart"json_encode($newCart));
  89.             $currentCart json_decode($this->get("session")->get("cart"));
  90.         }
  91.         if($request->get('cart'))
  92.         {
  93.             $pid $request->get('pid');
  94.             $quantity $request->get('quantity');
  95.             $clientId 1;
  96.             $offerId  $request->get('oid','n');
  97.             $checkOffer $em->getRepository(\App\Entity\Product::class)->findOffer($offerId);
  98.             
  99.             $product $em->getRepository(\App\Entity\Product::class)->findOneBy(array(
  100.                 'productId' => $pid
  101.             ));
  102.             
  103.             $newCart = array();
  104.             $currentCart json_decode($this->get("session")->get("cart"));
  105.             
  106.             //print_r($currentCart);exit;
  107.             if (!$this->get("session")->get("cart") || $this->get("session")->get("cart") == "[]")
  108.             {
  109.                 //print_r($currentCart);exit;
  110.                 $price  $product->getMainPrice();
  111.                 $o_name "";
  112.                 
  113.                 if($offerId)
  114.                 {                                    
  115.                     if($checkOffer)
  116.                     {     
  117.                         if($checkOffer['product_id'] != "" )
  118.                         {
  119.                             $o_name $checkOffer['offer_name'];                              
  120.                             $price $checkOffer['new_price'];     
  121.                         } else {                                         
  122.                             $discount = ($checkOffer['percent_discount']/100);
  123.                             $pricePercentage $product->getMainPrice()*$discount;                        
  124.                             $o_name $checkOffer['offer_name'];                              
  125.                             $price number_format($product->getMainPrice()-$pricePercentage2'.''');
  126.                         }
  127.                     }                    
  128.                 }                
  129.                 
  130.                 $newItem = array(
  131.                     'name'     => $product->getName(),
  132.                     'quantity' => $quantity,
  133.                     'price' => $price,
  134.                     'pid'   => $pid,
  135.                     'oid'   => $offerId,
  136.                     'o_name'=> $o_name,                       
  137.                     'img'   => $product->getMainPicture()
  138.                 );
  139.                 array_push($newCart$newItem);
  140.                 
  141.             } else {
  142.                 $foundPid = -1;
  143.                 foreach ($currentCart as $key => $cart)
  144.                 {
  145.                     if ($cart->pid == $pid) {
  146.                         //En que KEY esta el PID en cuestion?                    
  147.                         $foundPid $key;
  148.                     }
  149.                     
  150.                     $productObj $em->getRepository(\App\Entity\Product::class)->findOneBy(array(
  151.                         'productId' => $cart->pid
  152.                     ));                    
  153.                     
  154.                     $price  $cart->price;
  155.                     $o_name $cart->o_name;
  156.                     if($cart->oid)
  157.                     {            
  158.                         $checkOffer $em->getRepository(\App\Entity\Product::class)->findOffer($cart->oid);
  159.                         if($checkOffer)
  160.                         {     
  161.                             if($checkOffer['brand_id'] != "" || $checkOffer['category_id'] != "" || $checkOffer['subcategory_id'] != "" )
  162.                             {
  163.                                 $discount = ($checkOffer['percent_discount']/100);
  164.                                 $pricePercentage $productObj->getMainPrice()*$discount;
  165.                                 $o_name $checkOffer['offer_name'];
  166.                                 $price number_format($productObj->getMainPrice()-$pricePercentage2'.''');  
  167.                             } else {                             
  168.             
  169.                                 $o_name $checkOffer['offer_name'];
  170.                                 $price $checkOffer['new_price'];
  171.                 
  172.                             }    
  173.                                        
  174.                         }
  175.                     }
  176.                    
  177.                     $newItem = array(
  178.                         'name'     => $cart->name,
  179.                         'quantity' => $cart->quantity,
  180.                         'price' => $price,
  181.                         'pid'   => $cart->pid,
  182.                         'oid'   => $cart->oid,    
  183.                         'o_name'=> $o_name,   
  184.                         'img'   => $cart->img
  185.                     );
  186.                     
  187.                     array_push($newCart$newItem);
  188.                     
  189.                 }
  190.                 
  191.                 if ($foundPid == -1)
  192.                 {
  193.                     $price $product->getMainPrice();
  194.                     $o_name "";
  195.                     $checkOffer $em->getRepository(\App\Entity\Product::class)->findOffer($offerId);
  196.                     if($checkOffer)
  197.                     {     
  198.                         if($checkOffer['product_id'] != "")
  199.                         {                            
  200.                             $o_name $checkOffer['offer_name'];
  201.                             $price $checkOffer['new_price'];
  202.                         } else {    
  203.                         
  204.                             $discount = ($checkOffer['percent_discount']/100);
  205.                             $pricePercentage $product->getMainPrice()*$discount;
  206.                             $o_name $checkOffer['offer_name'];
  207.                             $price number_format($product->getMainPrice()-$pricePercentage2'.''');  
  208.                         } 
  209.                     }
  210.                     $newItem = array(
  211.                         'name' => $product->getName(),
  212.                         'quantity' => $quantity,
  213.                         'price' => $price,
  214.                         'pid' => $pid,
  215.                         'oid' => $offerId,
  216.                         'o_name'=> $o_name,   
  217.                         'img' => $product->getMainPicture()
  218.                     );
  219.                     array_push($newCart$newItem);
  220.                     
  221.                 } else {
  222.                     
  223.                     if ($quantity 0)
  224.                     {
  225.                         $newCart[$foundPid]['quantity'] = $quantity;
  226.                     } else {
  227.                         unset($newCart[$foundPid]);
  228.                     }
  229.                     
  230.                 }
  231.                 
  232.             }
  233.            
  234.             
  235.             $this->get("session")->set("cart"json_encode($newCart));
  236.             $currentCart $this->get("session")->get("cart");
  237.         }
  238.         $val 0;
  239.         $priceVal 0;
  240.         if (is_array($currentCart)) {
  241.             $currentCarts $currentCart;
  242.         } else {
  243.             $currentCarts json_decode($currentCart);
  244.         }
  245.         /*echo "<pre>";
  246.         print_r($currentCarts);
  247.         echo "</pre>";*/
  248.         $quitCoupon =false;    
  249.         foreach ($currentCarts as $cartTemp)
  250.         {
  251.             $val += $cartTemp->quantity;
  252.             $priceVal += $cartTemp->price $cartTemp->quantity;
  253.             //$val++;
  254.             if($cartTemp->oid != ''){
  255.                 $quitCoupon true;
  256.             }
  257.         }
  258.         //Verificamos configuración de cupones si hay productos con ofertas
  259.         
  260.         /*$client_id = $this->getParameter('client_id');
  261.         $client  = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  262.             "clientId" => $client_id
  263.         ));*/
  264.         
  265.         $client  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  266.             "slug" => $slug
  267.         ));
  268.         $client_id $client->getClientId();
  269.         
  270.         $setting  $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  271.             "Client" => $client
  272.         ));
  273.                    
  274.         if($quitCoupon && $setting->getCartAllowCouponWhithOffers() == '0'){
  275.              $this->get("session")->set("coupon",'');
  276.         }
  277.         $html "";
  278.         
  279.                 
  280.         if (is_array($currentCart)) {
  281.             $checkCart $currentCart;
  282.         } else {
  283.             $checkCart json_decode($currentCart);
  284.         }
  285.         if(count($checkCart) > 0)
  286.         {
  287.             
  288.             if ($priceVal 0) {
  289.                 $total 0;
  290.                 $grandTotal $priceVal;
  291.                 if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != ''){
  292.                     $coupon_id $this->get("session")->get("coupon");
  293.                     $couponObj $this->getDoctrine()->getRepository('AppBundle:Coupon')->findOneBy(array(
  294.                         "couponId" => $coupon_id
  295.                     ));
  296.                     $discount = ($priceVal $couponObj->getDiscountPercent())/100;
  297.                     $total $priceVal $discount;
  298.                     $grandTotal $total;
  299.                 }
  300.                 $finalPrice number_format($grandTotal2'.'',');
  301.             } else {
  302.                 $finalPrice '';
  303.             }
  304.             
  305.             //Aplicamos cupón
  306.             //$client_id = $this->getParameter('client_id');
  307.             $url $this->generateUrl('frontend_checkout', ['slug' => $slug]);
  308.             $information  $client;        
  309.             //Obtenemos simbolo de moneda a utilizar
  310.             $symbol $information->getCurrency()->getCurrencySymbol();
  311.             $html "<div id='cart_main' rel='popover' class='icon-header-item cl2 hov-cl1 trans-04 p-l-22 p-r-11 icon-header-noti js-show-cart' onclick='window.location.href=\"$url\"' data-notify='$val'>
  312.                 <i class='zmdi zmdi-shopping-cart'></i> $symbol$finalPrice
  313.                 <small class='cart_bottom_legend'>Clic aquí para terminar</small>
  314.             </div>";
  315.             
  316.         };
  317.         return new JsonResponse(array(
  318.             'slug'     => $slug,
  319.             'quantity' => $val,
  320.             'price'    => $priceVal,
  321.             'cart'     => $currentCarts,
  322.             'html'     => $html
  323.         ));
  324.     }
  325.     /**     
  326.      * @Route("{slug}/products", name="frontend_product")
  327.      */
  328.     public function productAction(Request $request$slug)
  329.     {
  330.         $em        $this->getDoctrine()->getManager();
  331.         $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  332.             "slug" => $slug
  333.         ));
  334.         $client_id $client->getClientId();
  335.         
  336.         $productCategory "";
  337.         $pager_limit     12;
  338.         $globalSearch    "";
  339.         $token           '';
  340.         $token2          '';
  341.         $brand           '';
  342.         $category        '';
  343.         $type            $request->get('type');
  344.         
  345.         if($request->get("token"))
  346.         {
  347.             $token $request->get('token');
  348.         }
  349.         if($request->get("token2"))
  350.         {
  351.             $token2 $request->get('token2');
  352.         }
  353.         if($request->get('search'))
  354.         {
  355.             $globalSearch $request->get('search');
  356.         }
  357.         if ($request->get('brand'))
  358.         {
  359.             $brand $request->get('brand');
  360.             $type 3;
  361.         }
  362.         
  363.         if($request->get('category'))
  364.         {
  365.             $category $request->get('category');
  366.             $type 3;
  367.         }
  368.         $filters = [
  369.             'token'     => $token,
  370.             'token2'    => $token2,
  371.             'type'      => $type,
  372.             'search'    => $globalSearch,
  373.             'brand'     => $brand,
  374.             'category'  => $category
  375.         ];
  376.         
  377.         //Obtenemos configuraciones para mostrar o ocultar productos sin stock
  378.         $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  379.             "clientId" => $client_id
  380.         ));
  381.         $settings $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  382.             "Client" => $client
  383.         ));
  384.         $query $em->getRepository(\App\Entity\Product::class)->getProducts($filters$client_id$settings->getCartHideEmptyStock());
  385.        
  386.         $subcategories $em->getRepository(\App\Entity\Subcategory::class)->findBy(array('is_active' => 1));
  387.         $categories $em->getRepository(\App\Entity\Category::class)->getCategories($client_id);
  388.         $total $em->getRepository(\App\Entity\Product::class)->getTotalCount();
  389.         
  390.         $webSetting $this->getDoctrine()->getRepository(\App\Entity\WebSetting::class)->findOneBy(array("Client" => $client_id));        
  391.         
  392.         // replace this example code with whatever you need
  393.         return $this->render('Frontend/Product/index.html.twig', array(
  394.             'list' => $query,
  395.             'pager_limit'     => $pager_limit,
  396.             'subcategories'   => $subcategories,
  397.             'categories'      => $categories,
  398.             'productCategory' => $productCategory,
  399.             'globalSearch'    => $globalSearch,
  400.             'webSetting'      => $webSetting,
  401.             'brand'           => $brand,
  402.             'category'        => $category,
  403.             'slug'              => $slug
  404.         ));
  405.     }
  406.     
  407.     
  408.     /* @Route("/product/direct/{id}", name="frontend_product_direct")*/
  409.     /**
  410.     * @Route("{slug}/product/direct/{productId}", name="frontend_product_index")
  411.     * @ParamDecryptor({"productId"})
  412.     */
  413.     public function productDirectAction(Request $requestProduct $product) {
  414.         $em $this->getDoctrine()->getManager();
  415.         $client_id $this->getParameter('client_id');
  416.         
  417.         //$productObj = $em->getRepository(Product)->findProductByMd5Id($id);
  418.         //if($productObj)
  419.         //{
  420.             
  421.     
  422.             //$product = $em->getRepository('AppBundle:Product')->findOneBy(array('productId' => $productObj['product_id']));    
  423.             $serverName $_SERVER['SERVER_NAME'];    
  424.             $product_id $product->getProductId();
  425.             return $this->render('Frontend/Product/product_direct.html.twig', array(
  426.                 'product_id' => $product_id,
  427.                 'product'    => $product,
  428.                 'brand'      => '',
  429.                     'category'   => '',
  430.                     'productCategory' => '',
  431.                     'pager_limit'     => 12,
  432.                     'globalSearch'    => '',
  433.                     'serverName'      => $serverName
  434.             ));
  435.             
  436.         //} else {
  437.             //return $this->redirectToRoute("frontend_index");
  438.         //}
  439.         
  440.     }
  441.     
  442.     
  443.         
  444.     
  445.     /**
  446.      *
  447.      * @Route("{slug}/product-modal-load", name="frontend_product_modal_load")
  448.      */
  449.     public function productModalLoadAction(Request $request$slug)
  450.     {
  451.         $em $this->getDoctrine()->getManager();
  452.         
  453.         $information $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy([
  454.             "slug" => $slug
  455.         ]);
  456.         $client_id $information->getClientId();
  457.         //Obtenemos configuraciones para mostrar o ocultar productos sin stock
  458.         $setting $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy([
  459.             "Client" => $information
  460.         ]);
  461.         $query $em->getRepository(\App\Entity\Product::class)->getOneProduct($request->get('id'),$setting->getCartHideEmptyStock());
  462.         
  463.         
  464.         //VERIFICAMOS HORARIOS
  465.         $store_status 'open';               
  466.         $day_number date('N');
  467.         $hoursToday $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->verifyHoursForToday($day_number$client_id);        
  468.         if($hoursToday['is_open'] == '0')
  469.         {
  470.            $store_status    'closed';                  
  471.         }
  472.         $customerData '';
  473.         if($this->get("session")->get("userData"))
  474.         {
  475.             $customerData $this->get("session")->get("userData");
  476.         }    
  477.         // replace this example code with whatever you need
  478.         return $this->render('Frontend/_modal_content_product.html.twig', array(
  479.             'item'           => $query
  480.             'setting'        => $setting,
  481.             'information'    => $information,
  482.             'store_status'   => $store_status,
  483.             'customerData'   => $customerData,
  484.             'slug'           => $slug
  485.         ));
  486.     }
  487.     /**
  488.      *
  489.      * @Route("{slug}/get-product", name="frontend_get_product")
  490.      */
  491.     public function getProductAction(Request $request$slug)
  492.     {
  493.         $em $this->getDoctrine()->getManager();
  494.         
  495.         //$client_id = $this->getParameter('client_id');
  496.         $client    $this->getDoctrine()->getRepository(Client::class)->findOneBy(["slug" => $slug]);
  497.         $client_id $client->getClientId();
  498.         $pager_limit  12;
  499.         $globalSearch "";
  500.         $token '';
  501.         if($request->get("token"))
  502.         {
  503.             $token $request->get('token');
  504.         }
  505.         
  506.         $token2 '';
  507.         if($request->get("token2"))
  508.         {
  509.             $token2 $request->get('token2');
  510.         }
  511.         if($request->get('search'))
  512.         {
  513.             $globalSearch $request->get('search');
  514.         }
  515.         $filters = [
  516.             'token'  => $token,
  517.             'token2' => $token2,
  518.             'type'   => $request->get('type'),
  519.             'search' => $globalSearch,
  520.             'limit'  => $request->get('limit')
  521.         ];
  522.         
  523.         //Obtenemos configuraciones para mostrar o ocultar productos sin stock
  524.         $setting $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(["Client" => $client]);        
  525.         $query   $em->getRepository(\App\Entity\Product::class)->getProducts($filters,$client_id,$setting->getCartHideEmptyStock());
  526.         
  527.         $subcategories $em->getRepository(\App\Entity\Subcategory::class)->findBy(['is_active' => 1]);
  528.         $categories    $em->getRepository(\App\Entity\Category::class)->getCategories($client_id);
  529.         $total         $em->getRepository(\App\Entity\Product::class)->getProducts($filters,$client_id,$setting->getCartHideEmptyStock(),true);
  530.         
  531.        
  532.         
  533.         // replace this example code with whatever you need
  534.         return $this->render('Frontend/product_items.html.twig', array(
  535.             'list' => $query,
  536.             'pager_limit'   => $pager_limit,
  537.             'subcategories' => $subcategories,
  538.             'categories'    => $categories,
  539.             'product_count' => count($total),
  540.             'globalSearch'  => $globalSearch,
  541.             'isMore'        => $request->get('isMore'),
  542.             'setting'       => $setting,
  543.             'slug'          => $slug,
  544.             'information'   => $client
  545.                 
  546.         ));
  547.     }
  548.     /**
  549.      *
  550.      * @Route("/start/token={id}", name="frontend_start")
  551.      */
  552.     public function startAction(Request $request) {
  553.         if($request->get('id') == 'c4ca4238a0b923820dcc509a6f75849b')
  554.         {
  555.             $valor "25";
  556.         } elseif ($request->get('id') == 'c81e728d9d4c2f636f067f89cc14862c')
  557.         {
  558.             $valor "58";
  559.         } elseif ($request->get('id') == 'eccbc87e4b5ce2fe28308fd9f2a7baf3')
  560.         {
  561.             $valor "39";
  562.         }
  563.         return $this->render('Frontend/Index/start.html.twig', array(
  564.             "valor" => $valor
  565.         ));
  566.     }
  567.     /**
  568.      * @Route("{slug}/blogs", name="frontend_blog")
  569.      */
  570.     public function blogAction(Request $request$slug)
  571.     {
  572.         
  573.         // replace this example code with whatever you need
  574.         $categories $this->getDoctrine()->getRepository(\App\Entity\Blog::class)->getCategoriesBlog($slug);
  575.         return $this->render('Frontend/Blog/blog.html.twig', array(
  576.             'categories'      => $categories,
  577.             'slug'            => $slug,
  578.             'productCategory' => '',
  579.             'pager_limit'     => 12,
  580.             'globalSearch'    => '',
  581.             'brand'           => '',
  582.             'category'        => ''
  583.         ));
  584.     }
  585.     /**     
  586.      * @Route("{slug}/blog/load-items", name="frontend_blog_items")
  587.      */
  588.     public function blogLoadAction(Request $request$slug)
  589.     {   
  590.         $em        $this->getDoctrine()->getManager();
  591.         $desde     $request->get('desde');
  592.         $hasta     $request->get('hasta');
  593.         $categoria $request->get('categoria');
  594.         
  595.         //$client_id = $this->getParameter('client_id');
  596.         $client    $this->getDoctrine()->getRepository(Client::class)->findOneBy(array("slug" => $slug));
  597.         $client_id $client->getClientId();
  598.         
  599.         $blogs $em->getRepository(\App\Entity\Blog::class)->listBlog($desde$hasta$categoriafalse$client_id);
  600.         $blogs_total $em->getRepository(\App\Entity\Blog::class)->listBlog($desde$hasta$categoriatrue$client_id);
  601.         $blogs_count $em->getRepository(\App\Entity\Blog::class)->listBlog(0,($desde+$hasta), $categoriafalse$client_id);
  602.         return $this->render('Frontend/Blog/load_items_blog.html.twig',array(
  603.             "list"  => $blogs,
  604.             "slug"  => $slug,
  605.             "count" => count($blogs_count),
  606.             "total" => count($blogs_total)
  607.         ));
  608.     }
  609.     /**     
  610.      * @Route("{slug}/blog/detail/{blogId}", name="frontend_blog_detail")
  611.      * @ParamDecryptor({"blogId"})
  612.      */
  613.     public function blogDetailAction(Request $requestBlog $blog$slug)
  614.     {   
  615.         
  616.         //$category = $this->getDoctrine()->getRepository('AppBundle:BlogCategory')->findBy(array("isActive" => '1'));
  617.         return $this->render('Frontend/Blog/blog_detail.html.twig',array(
  618.             "blog"              => $blog,
  619.             "slug"              => $slug,
  620.             'productCategory'   => '',
  621.             'pager_limit'       => 12,
  622.             'globalSearch'      => '',
  623.             'brand'             => '',
  624.             'category'          => ''
  625.         ));
  626.     }
  627.  
  628.    
  629.     /**
  630.      * @Route("/check", name="frontend_check" )
  631.      */
  632.     public function checkAction(Request $request) {
  633.         return new JsonResponse(array(
  634.             'status' => 'success'
  635.         ));
  636.     }
  637.     /**
  638.      * @Route("/process", name="frontend_process" )
  639.      */
  640.     public function processAction(Request $request) {
  641.         var_dump($request);
  642.         die;
  643.         return new JsonResponse(array(
  644.             'status' => 'success'
  645.         ));
  646.     }
  647.     /**
  648.      *
  649.      * @Route("{slug}/checkout", name="frontend_checkout")
  650.      */
  651.     public function checkoutAction(Request $request$slug)
  652.     {
  653.         $lastUsername $request->getSession()->get(Security::LAST_USERNAME);
  654.         
  655.         $information $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy([
  656.             "slug" => $slug
  657.         ]);
  658.         $client_id   $information->getClientId();
  659.         if(!$information)
  660.         {
  661.             return $this->redirectToRoute("homepage_website", ['slug' => $slug]);
  662.         }
  663.         $currentCart $this->get("session")->get("cart");
  664.         if($currentCart)
  665.         {
  666.             
  667.         } else {
  668.             return $this->redirectToRoute("frontend_index", ['slug' => $slug]);
  669.         }
  670.         $settings $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy([
  671.             "Client" => $information
  672.         ]);
  673.         
  674.         $customerData '';                
  675.         if($lastUsername)
  676.         {
  677.             $customerData $request->getSession()->get($lastUsername);
  678.         }    
  679.         
  680.         $coupon '';
  681.         if($this->get("session")->get("coupon"))
  682.         {
  683.             $coupon $this->get("session")->get("coupon");
  684.         }
  685.         
  686.                 
  687.         $day_number   date('N');
  688.         $store_status "open";
  689.         
  690.         $client         $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(["clientId" => $client_id]);
  691.         $hoursToday     $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->verifyHoursForToday($day_number$client_id);
  692.         $paymentMethods $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findBy([
  693.             'Client'     => $client,
  694.             'is_display' => 1,
  695.             'is_active'  => 1
  696.         ]);        
  697.         $paymentCardObj $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy([
  698.             'Client'    => $client,
  699.             'is_active' => 1,
  700.             'is_cash'   => 0
  701.         ]); 
  702.                 
  703.         if($hoursToday['is_open'] == '0')
  704.         {
  705.             $store_status "closed";
  706.         }
  707.         
  708.         $session_uniq_id uniqid();
  709.         
  710.         $org_id       "";
  711.         $random_value "";
  712.         if($paymentCardObj->getPaymentMethodGateway())
  713.         {
  714.             //QPAYPRO es gateway 1
  715.             if($paymentCardObj->getPaymentMethodGateway()->getPaymentMethodGatewayId() == 1)
  716.             {
  717.                 $org_id       "1snn5n9w";
  718.                 $random_value "visanet_qpay"."1618";
  719.                 
  720.                 //Esta bandera es para definir si es PROD o no
  721.                 //Get Field Token Tertiary es igual al public Key
  722.                 if($paymentCardObj->getIsProd())
  723.                 {            
  724.                     $org_id       "k8vif92e";
  725.                     $random_value $paymentCardObj->getFieldTokenTertiary()."1618";
  726.                 }
  727.             }    
  728.         }        
  729.         
  730.         $storedCards = [];
  731.         if($customerData)
  732.         {
  733.             $storedCards $this->getDoctrine()->getRepository(\App\Entity\CustomerToken::class)->findBy([
  734.                 'Customer'  => $customerData['customer_id'],
  735.                 'is_active' => 1                
  736.             ]); 
  737.         }
  738.         
  739.         return $this->render('Frontend/Checkout/checkout.html.twig', [
  740.             'productCategory' => '',
  741.             'pager_limit'     => 12,
  742.             'globalSearch'    => '',
  743.             'slug'            => $slug,
  744.             'settings'        => $settings,
  745.             'information'     => $information,
  746.             'coupon'          => $coupon,
  747.             'customerData'    => $customerData,
  748.             'brand'           => '',
  749.             'category'        => '',
  750.             'store_stataus'   => $store_status,
  751.             'client_id'       => $client_id,
  752.             'payment_methods' => $paymentMethods,
  753.             'session_uniq_id' => $session_uniq_id,
  754.             'random_value'    => $random_value,
  755.             'org_id'          => $org_id,
  756.             'storedCards'     => $storedCards
  757.         ]);
  758.     }
  759.     /**
  760.      * @Route("{slug}/email_test", name="frontend_checkout_emailtest")
  761.      */
  762.     public function emailTest(Request $requestMailHelper $MailHelper)
  763.     {
  764.         exit;
  765.         $textMessage str_replace('_TABLA_PEDIDOS_''<br>PEDIDOS PEDIDOS PEDIDOS',"Hola hola hola");
  766.         $myMessage $this->render 'MailTemplate/template_email_orders.html.twig', array (
  767.             'emailTitle'    =>  "Prueba Email",
  768.             'logoPath'      =>  "https://dev.aguilalibreweb.com/2308/ecommerce_aguila/public/uploads/12/web/30724402820250820002840.png",
  769.             'message'       =>  $textMessage,
  770.             'footer1'       =>  "footer",       
  771.             'user'          =>  '',
  772.             'rootWebUrl'    =>  "rootURL"
  773.         ) )->getContent();
  774.         $debug $MailHelper->sendEmail("Nombre de Tienda","servicio@aguilalibreweb.com""Prueba Email"$myMessage"");
  775.         return new JsonResponse(array(
  776.             'status'  => 'success',
  777.             'orderId' => $debug
  778.         ));
  779.         
  780.     }
  781.     
  782.     
  783.     /**
  784.      *
  785.      * @Route("/checkout/execute", name="frontend_checkout_execute")
  786.      */
  787.     public function checkoutExecuteAction(Request $requestMailHelper $MailHelper)
  788.     {
  789.         
  790.         $lastUsername $request->getSession()->get(Security::LAST_USERNAME);
  791.         $userData false;
  792.         if($lastUsername)
  793.         {
  794.             $userData $request->getSession()->get($lastUsername);        
  795.         }
  796.         $em $this->getDoctrine ()->getManager ();
  797.         $client_id $this->getParameter('client_id');
  798.         
  799.         $data           $request->get('query');
  800.         $payment_method $request->get('payment_method');
  801.         $dummy_order_id $request->get('auth');
  802.         /*echo "<pre>";
  803.         print_r($data);
  804.         echo "</pre>";        
  805.         exit;*/
  806.         $userData $this->get("session")->get("userData");
  807.         $information  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  808.             "clientId" => $client_id
  809.         ));        
  810.         $webSetting  $this->getDoctrine()->getRepository(\App\Entity\WebSetting::class)->findOneBy(array(
  811.             "Client" => $information
  812.         ));        
  813.         
  814.         //Obtenemos simbolo de moneda a utilizar
  815.         $symbol $information->getCurrency()->getCurrencySymbol();
  816.         
  817.         $payment  $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy(array(
  818.             "paymentMethodId" => $payment_method
  819.         ));        
  820.         $orderStatus  $this->getDoctrine()->getRepository(\App\Entity\OrderStatus::class)->findOneBy(array(
  821.             "orderStatusId" => 1
  822.         ));                
  823.         $deliveryCharge "";
  824.         if($request->get("delivery_price"))
  825.         {
  826.             $deliveryCharge $request->get("delivery_price");            
  827.         }
  828.         $orders = new Orders();
  829.         $orders->setOrderType('cart');
  830.         $orders->setDeliveryCharge($deliveryCharge);
  831.         $orders->setPaymentMethod($payment);
  832.         $orders->setServiceFee($information->getServiceFee());
  833.         
  834.         if($userData)
  835.         {
  836.             $customerObj $this->getDoctrine()->getRepository(\App\Entity\Customer::class)->findOneBy(array(
  837.                 "customerId" => $userData['customer_id']
  838.             ));
  839.             $orders->setCustomer($customerObj);
  840.         }
  841.         
  842.         $orders->setIsActive(1);
  843.         $orders->setClient($information);
  844.         $orders->setOrderStatus($orderStatus);
  845.         $orders->setCreatedAt(new \DateTime());
  846.         $em->persist($orders);
  847.         $em->flush();     
  848.         if($orders)
  849.         {
  850.             $currentCart  $this->get("session")->get("cart");
  851.             $cartList     json_decode($currentCart);                    
  852.             $orderDetailMail ="<table style='width:100%;text-align: left!important;'>
  853.                                 <tr style='border-bottom:1px solid #ccc'>
  854.                                 <th>Productos</th><th></th>
  855.                                 </tr>";
  856.             $totalOrder 0;
  857.             if(count($cartList) > 0)
  858.             {        
  859.                 foreach($cartList as $cart)
  860.                 {
  861.                     $productObj $this->getDoctrine()->getRepository(\App\Entity\Product::class)->findOneBy(array(
  862.                         "productId" => $cart->pid
  863.                     ));
  864.                     $offerObj $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
  865.                         "offerId" => $cart->oid
  866.                     ));                                
  867.                 
  868.                     $orderDetail = new OrderDetail();
  869.                     $orderDetail->setOrder($orders);
  870.                     $orderDetail->setProduct($productObj);
  871.                     $orderDetail->setQuantity($cart->quantity);
  872.                     $orderDetail->setPriceGiven($cart->price);
  873.                     $orderDetail->setOriginalPrice($productObj->getMainPrice());                                        
  874.                     $orderDetail->setCreatedAt(new \DateTime());
  875.                     
  876.                     $totalPrice $cart->quantity*$cart->price;
  877.                     $totalOrder $totalOrder $totalPrice;
  878.                     $orderDetailMail .= "<tr style='border-bottom:1px solid #ccc;text-align: left!important;'>                          
  879.                         <td style='padding:10px;text-align: left!important;'>
  880.                             <img style='height:80px' src='".$productObj->getMainPicture()."' >
  881.                         </td>
  882.                             <td style='padding:10px;text-align: left!important;'>
  883.                                 ".$productObj->getName()."<br>
  884.                                 $symbol.$cart->price x $cart->quantity = <b>$symbol.".number_format($totalPrice2'.''')."</b><br>                                         
  885.                             
  886.                         ";
  887.                     
  888.                     if($cart->oid)
  889.                     {
  890.                         $offerObj $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
  891.                             "offerId" => $cart->oid
  892.                         ));            
  893.                         $orderDetailMail.="<p style='color:tomato;'>".$offerObj->getOfferName()."</p>";
  894.                         $orderDetail->setOffer($offerObj);
  895.                     }
  896.                     $orderDetailMail.="</td></tr>";
  897.                     $em->persist($orderDetail);
  898.                     $em->flush();            
  899.                     
  900.                     //RESTAMOS DE INVENTARIO
  901.                     $is_not_stock $productObj->getIsNotStock();
  902.                     if($is_not_stock != '1')
  903.                     {
  904.                         $productInventory $this->getDoctrine()->getRepository(\App\Entity\ProductInventory::class)->findOneBy(array(
  905.                             "Product" => $productObj
  906.                         ));                                                
  907.                         if($productInventory)
  908.                         {
  909.                             $oldStock $productInventory->getAvailable();
  910.                             $stock $oldStock $cart->quantity;
  911.                             $productInventory->setAvailable($stock);
  912.                             $em->persist($productInventory);
  913.                             $em->flush();    
  914.                             $productInventoryLog = new ProductInventoryLog();
  915.                             $productInventoryLog->setProduct($productObj);
  916.                             $productInventoryLog->setCreatedAt(new \DateTime());
  917.                             $productInventoryLog->setOrderDetail($orderDetail);
  918.                             $productInventoryLog->setSelledQuantity($cart->quantity);
  919.                             $em->persist($productInventoryLog);
  920.                             $em->flush();
  921.                         }
  922.                     }
  923.                 }
  924.             }
  925.             $orderDetailMail.="</table>";   
  926.             $grandTotal $totalOrder;
  927.             $orders->setTotalOriginal($grandTotal);
  928.             if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != '')
  929.             {
  930.                 $coupon_id $this->get("session")->get("coupon");
  931.                 $couponObj $this->getDoctrine()->getRepository('AppBundle:Coupon')->findOneBy(array(
  932.                     "couponId" => $coupon_id
  933.                 ));
  934.                 $discount = ($totalOrder $couponObj->getDiscountPercent())/100;
  935.                 $total $totalOrder $discount;
  936.                                 
  937.                 $grandTotal $total;
  938.                 $orders->setTotal(number_format($total2'.'','));
  939.                 $orders->setCoupon($couponObj);
  940.                 $this->get("session")->set("coupon"'');
  941.                 $orderDetailMail.="<center><table>
  942.                     <tr><td style='width:150px;text-align: left!important;'><b style='color:#ccc'>Cupón aplicado: </b></td><td style='text-align: left!important;' >".$couponObj->getCouponCode()."</td></tr>
  943.                     <tr><td style='text-align: left!important;'><b style='color:#ccc'>Subtotal: </b></td><td style='text-align: left!important;'> $symbol.".$total."</td></tr>
  944.                     <tr><td style='text-align: left!important;'><b style='color:#ccc'>Descuento: </b></td><td style='text-align: left!important;'> $symbol.".number_format($discount2'.'',')." <b>-".$couponObj->getDiscountPercent()."%</b></td></tr></table></center>";                 
  945.             
  946.             } else {
  947.                 $orders->setTotal(number_format($totalOrder2'.'','));
  948.             }
  949.         
  950.             $em->persist($orders);
  951.             $em->flush();   
  952.                     
  953.             if($deliveryCharge == 'N')
  954.             {
  955.                 $orderDetailMail.="<p  style='color:tomato'>No se pudo calcular el cargo por la entrega automáticamente.Cargos de entrega podrían aplicar posterior a la confirmación de su pedido.</p>";
  956.             } else if($deliveryCharge == 'FREE')
  957.             {
  958.                 $orderDetailMail.="<p  style='color:tomato'>¡Envío Gratis!</p>";
  959.             } else if($deliveryCharge != "")
  960.             {
  961.                 $orderDetailMail.="<p style='color:tomato'>+Cargo de envío: <b>$symbol.".number_format($deliveryCharge2'.'',')."</b></p>";
  962.             }
  963.             //Se agrega el service fee
  964.             if($information->getServiceFee() > 0)
  965.             {                
  966.                 $grandTotal $grandTotal $information->getServiceFee();
  967.             }            
  968.             $orderDetailMail.="<h3><b>Total: $symbol.</b>".number_format($grandTotal2'.'',')." </h3>";
  969.             
  970.             $purchaserValue "";
  971.             $emailAnonymous="";
  972.         
  973.             foreach($data['purchaser'] as $purchaser)
  974.             {
  975.                     
  976.                 if($purchaser['is_email'] == true){
  977.                     $emailAnonymous $purchaser['value']; 
  978.                 }
  979.             
  980.                 $fieldClientObj $this->getDoctrine()->getRepository(\App\Entity\FieldClient::class)->findOneBy(array(
  981.                     "fieldClientId" => $purchaser['field_client_id']
  982.                 ));    
  983.                 $fieldTypeObj $this->getDoctrine()->getRepository(\App\Entity\FieldType::class)->findOneBy(array(
  984.                     "fieldTypeId" => $purchaser['field_type_id']
  985.                 ));                                
  986.                 $orderField = new OrderField();
  987.                 $orderField->setOrder($orders);
  988.                 $orderField->setFieldClient($fieldClientObj);
  989.                 $orderField->setFieldType($fieldTypeObj);
  990.                 $orderField->setName($purchaser['name']);
  991.                 if($purchaser['field_type_id'] == 3)
  992.                 {
  993.                     $fieldValueObj $this->getDoctrine()->getRepository(\App\Entity\FieldValue::class)->findOneBy(array(
  994.                         "fieldValueId" => $purchaser['value']
  995.                     ));    
  996.                     if($fieldValueObj)
  997.                     {
  998.                         $orderField->setFieldValue($fieldValueObj);                    
  999.                     }
  1000.                 } else if($purchaser['field_type_id'] == 4)
  1001.                 {
  1002.                         $lat $purchaser['value']['lat'];
  1003.                         $lng $purchaser['value']['lng'];                    
  1004.                         $orderField->setValueText("$lat,$lng");                    
  1005.                 } else {
  1006.                         $orderField->setValueText($purchaser['value']);                    
  1007.                 }
  1008.                 $orderField->setCreatedAt(new \DateTime());                
  1009.                 $em->persist($orderField);
  1010.                 $em->flush();                
  1011.             }        
  1012.             //ENVÍO DE EMAIL
  1013.             
  1014.             $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1015.                 "clientId" => $client_id
  1016.             ));
  1017.             $setting $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  1018.                 "Client" => $client
  1019.             ));        
  1020.             $MailHelper = new MailHelper();   
  1021.             $rootWebUrl =  $MailHelper->getRootWebAppURL("0");
  1022.             $subject 'Nuevo pedido registrado #'.$orders->getOrderId();
  1023.             $textMessage $setting->getTemplateConfirmationOrders();
  1024.             $array_cc = array();
  1025.             $mails_sent "";
  1026.             if($userData)
  1027.             {
  1028.                 $mailTo =  $customerObj->getEmail();  
  1029.                 $mailCopy $setting->getEmailNotificationOrder();
  1030.                 $mails_sent=$mailTo.",".$mailCopy;
  1031.             } else {
  1032.                 if($emailAnonymous != '')
  1033.                 {
  1034.                     $mailTo $emailAnonymous;
  1035.                     $mailCopy $setting->getEmailNotificationOrder();
  1036.                     $mails_sent=$mailTo.",".$mailCopy;
  1037.                 } else {
  1038.                     $mailTo $setting->getEmailNotificationOrder();
  1039.                     $mails_sent=$mailTo;
  1040.                     $mailCopy null;
  1041.                 }
  1042.             }
  1043.             
  1044.             
  1045.             $footer1 =  null;
  1046.             
  1047.             $textMessage str_replace('_TABLA_PEDIDOS_''<br>'.$orderDetailMail$textMessage);
  1048.             $myMessage $this->render 'MailTemplate/template_email_orders.html.twig', array (
  1049.                 'emailTitle'    =>  $subject,
  1050.                 'logoPath'      =>  $webSetting->getLogoPath(),
  1051.                 'message'       =>  $textMessage,
  1052.                 'footer1'       =>  $footer1,                   
  1053.                 'user'          =>  '',
  1054.                 'rootWebUrl'    =>  $rootWebUrl
  1055.             ) )->getContent();
  1056.             $MailHelper->sendEmail($client->getName(),$mailTo$subject$myMessage$mailCopy );
  1057.             
  1058.             
  1059.             //Guardamos log de envío de alerta
  1060.             $alertPurchase = new AlertPurchase();
  1061.             $alertPurchase->setClient($client);
  1062.             $alertPurchase->setCreatedAt(new \DateTime());
  1063.             $alertPurchase->setEmailSent($mails_sent);
  1064.             $alertPurchase->setIsActive(1);
  1065.             $alertPurchase->setOrder($orders);
  1066.             $em->persist($alertPurchase);
  1067.             $em->flush();    
  1068.             
  1069.             //Si la compra se proceso correctamente entonces guardamos el id de la orden en la tabla payment
  1070.             if($payment->getIsCash() != '1' && $dummy_order_id != '0')
  1071.             {
  1072.                 $paymentRegister $this->getDoctrine()->getRepository(\App\Entity\Payment::class)->findOneBy(array(
  1073.                     "custom_auth_code" => $dummy_order_id
  1074.                 ));                
  1075.                 $paymentRegister->setOrder($orders);
  1076.                 $em->persist($paymentRegister);
  1077.                 $em->flush();
  1078.             }
  1079.             
  1080.             $orderIdEncoded $this->encryptor->encrypt($orders->getOrderId());
  1081.             
  1082.             return new JsonResponse(array(
  1083.                 'status'  => 'success',
  1084.                 'orderId' => $orderIdEncoded
  1085.             ));
  1086.             
  1087.         } else {
  1088.             
  1089.             return new JsonResponse(array(
  1090.                 'status'  => 'error',
  1091.                 'orderId' => ''
  1092.             ));            
  1093.             
  1094.         }
  1095.         
  1096.         
  1097.         
  1098.     }
  1099.     /**
  1100.      *
  1101.      * @Route("/checkout/direct-execute", name="frontend_checkout_direct_execute")
  1102.      */
  1103.     public function checkoutDirectExecuteAction(Request $request)
  1104.     {
  1105.         
  1106.                 $em $this->getDoctrine ()->getManager ();
  1107.                 $client_id  $this->getParameter('client_id');
  1108.                 $product_id $request->get('product_id');
  1109.                 $offer_id   $request->get('offer_id');
  1110.                 $price      $request->get('price');
  1111.                 $data       $request->get('query');
  1112.                 $userData $this->get("session")->get("userData");
  1113.                 $information  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1114.                     "clientId" => $client_id
  1115.                 ));        
  1116.                 //Obtenemos simbolo de moneda a utilizar
  1117.                 $symbol $information->getCurrency()->getCurrencySymbol();
  1118.                 $payment  $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy(array(
  1119.                     "paymentMethodId" => 1
  1120.                 ));        
  1121.                 $orderStatus  $this->getDoctrine()->getRepository(\App\Entity\OrderStatus::class)->findOneBy(array(
  1122.                     "orderStatusId" => 1
  1123.                 ));
  1124.                 $orders = new Orders();
  1125.                 $orders->setOrderType('direct');
  1126.                 $orders->setPaymentMethod($payment);
  1127.                 if($userData)
  1128.                 {
  1129.                         $customerObj $this->getDoctrine()->getRepository(\App\Entity\Customer::class)->findOneBy(array(
  1130.                             "customerId" => $userData['customer_id']
  1131.                         ));
  1132.                         $orders->setCustomer($customerObj);
  1133.                 }
  1134.                 $orders->setIsActive(1);
  1135.                 $orders->setOrderStatus($orderStatus);
  1136.                 $orders->setCreatedAt(new \DateTime());
  1137.                 $em->persist($orders);
  1138.                 $em->flush();     
  1139.                 if($orders)
  1140.                 {
  1141.                 $orderDetailMail ="<table style='width:100%;text-align: left!important;'>
  1142.                 <tr style='border-bottom:1px solid #ccc'>
  1143.                   <th>Producto</th><th></th>
  1144.                 </tr>";              
  1145.                 $productObj $this->getDoctrine()->getRepository(\App\Entity\Product::class)->findOneBy(array(
  1146.                     "productId" => $product_id
  1147.                  ));
  1148.                 $offerObj $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
  1149.                     "offerId" => $offer_id
  1150.                 ));                                
  1151.                 $orderDetail = new OrderDetail();
  1152.                 $orderDetail->setOrder($orders);
  1153.                 $orderDetail->setProduct($productObj);
  1154.                 $orderDetail->setQuantity(1);
  1155.                 $orderDetail->setPriceGiven($price);
  1156.                 $orderDetail->setOriginalPrice($productObj->getMainPrice());                    
  1157.                 $orderDetail->setCreatedAt(new \DateTime());
  1158.                 $orderDetailMail .= "<tr style='border-bottom:1px solid #ccc;text-align: left!important;'>                          
  1159.                     <td style='padding:10px;text-align: left!important;'>
  1160.                         <img style='height:80px' src='".$productObj->getMainPicture()."' >
  1161.                     </td>
  1162.                       <td style='padding:10px;text-align: left!important;'>
  1163.                           ".$productObj->getName()."<br>
  1164.                           $symbol.$price x 1 = <b>$symbol.".number_format($price2'.''')."</b><br>                                         
  1165.                   ";
  1166.                 if($offer_id && $offer_id != '')
  1167.                 {
  1168.                     $offerObj $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
  1169.                         "offerId" => $offer_id
  1170.                     ));            
  1171.                     $orderDetailMail.="<p style='color:tomato;'>".$offerObj->getOfferName()."</p>";
  1172.                     $orderDetail->setOffer($offerObj);
  1173.                 }
  1174.                 $orderDetailMail.="</td></tr>";
  1175.                 $em->persist($orderDetail);
  1176.                 $em->flush();            
  1177.                 //RESTAMOS DE INVENTARIO
  1178.                 $is_not_stock $productObj->getIsNotStock();
  1179.                 if($is_not_stock != '1'){
  1180.                     $productInventory $this->getDoctrine()->getRepository(\App\Entity\ProductInventory::class)->findOneBy(array(
  1181.                         "product" => $productObj
  1182.                     ));                                                
  1183.                     if($productInventory){
  1184.                         $oldStock $productInventory->getAvailable();
  1185.                         $stock $oldStock 1;
  1186.                         $productInventory->setAvailable($stock);
  1187.                         $em->persist($productInventory);
  1188.                         $em->flush();    
  1189.                         $productInventoryLog = new ProductInventoryLog();
  1190.                         $productInventoryLog->setProduct($productObj);
  1191.                         $productInventoryLog->setCreatedAt(new \DateTime());
  1192.                         $productInventoryLog->setOrderDetail($orderDetail);
  1193.                         $productInventoryLog->setSelledQuantityy(1);
  1194.                         $em->persist($productInventoryLog);
  1195.                         $em->flush();
  1196.                     }
  1197.                 }
  1198.                 $orderDetailMail.="</table>";   
  1199.                 $grandTotal $price;
  1200.                 $orders->setTotalOriginal($grandTotal);
  1201.                 $orders->setTotal(number_format($grandTotal2'.'','));
  1202.                 $orderDetailMail.="<h3><b>Total: $symbol.</b>".number_format($grandTotal2'.'',')." </h3>";
  1203.                 $em->persist($orders);
  1204.                 $em->flush();   
  1205.                 $purchaserValue "";
  1206.                 $emailAnonymous="";
  1207.                 foreach($data as $purchaser)
  1208.                 {
  1209.                         if($purchaser['is_email'] == true){
  1210.                             $emailAnonymous $purchaser['value']; 
  1211.                         }
  1212.                         $fieldClientObj $this->getDoctrine()->getRepository(\App\Entity\FieldClient::class)->findOneBy(array(
  1213.                             "fieldClientId" => $purchaser['field_client_id']
  1214.                         ));    
  1215.                         $fieldTypeObj $this->getDoctrine()->getRepository(\App\Entity\FieldType::class)->findOneBy(array(
  1216.                             "fieldTypeId" => $purchaser['field_type_id']
  1217.                         ));                                
  1218.                         $orderField = new OrderField();
  1219.                         $orderField->setOrder($orders);
  1220.                         $orderField->setFieldClient($fieldClientObj);
  1221.                         $orderField->setFieldType($fieldTypeObj);
  1222.                         $orderField->setName($purchaser['name']);
  1223.                         if($purchaser['field_type_id'] == 3)
  1224.                         {
  1225.                             $fieldValueObj $this->getDoctrine()->getRepository(\App\Entity\FieldValue::class)->findOneBy(array(
  1226.                                 "fieldValueId" => $purchaser['value']
  1227.                             ));    
  1228.                                 if($fieldValueObj)
  1229.                                 {
  1230.                                     $orderField->setFieldValue($fieldValueObj);                    
  1231.                                 }
  1232.                         } else if($purchaser['field_type_id'] == 4)
  1233.                         {
  1234.                                 $lat $purchaser['value']['lat'];
  1235.                                 $lng $purchaser['value']['lng'];                    
  1236.                                 $orderField->setValueText("$lat,$lng");                    
  1237.                         } else {
  1238.                                 $orderField->setValueText($purchaser['value']);                    
  1239.                         }
  1240.                         $orderField->setCreatedAt(new \DateTime());                
  1241.                         $em->persist($orderField);
  1242.                         $em->flush();                
  1243.                 }        
  1244.                 //ENVÍO DE EMAIL
  1245.                 $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1246.                     "clientId" => $client_id
  1247.                 ));
  1248.                 $setting $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  1249.                     "client" => $client
  1250.                 ));        
  1251.                 $MailHelper = new MailHelper();   
  1252.                 $rootWebUrl =  $MailHelper->getRootWebAppURL("0");
  1253.                 $subject 'Nuevo pedido registrado #'.$orders->getOrderId();
  1254.                 $textMessage $setting->getDirectTemplateConfirmationOrders();
  1255.                 $array_cc = array();
  1256.                 $mails_sent "";
  1257.                 if($userData){
  1258.                     $mailTo =  $customerObj->getEmail();  
  1259.                     $mailCopy $setting->getDirectEmailNotificationOrder();
  1260.                     $mails_sent=$mailTo.",".$mailCopy;
  1261.                 }else{
  1262.                     if($emailAnonymous != ''){
  1263.                         $mailTo $emailAnonymous;
  1264.                         $mailCopy $setting->getDirectEmailNotificationOrder();
  1265.                         $mails_sent=$mailTo.",".$mailCopy;
  1266.                     }else{
  1267.                         $mailTo $setting->getDirectEmailNotificationOrder();
  1268.                         $mails_sent=$mailTo;
  1269.                         $mailCopy null;
  1270.                     }
  1271.                 }
  1272.                 
  1273.                 $footer1 =  null;
  1274.                 $textMessage str_replace('_TABLA_PEDIDOS_''<br>'.$orderDetailMail$textMessage);
  1275.                 $myMessage $this->render 'MailTemplate/template_email_orders.html.twig', array (
  1276.                     'emailTitle'    =>  $subject,
  1277.                     'message'       =>  $textMessage,
  1278.                     'footer1'       =>  $footer1,                   
  1279.                     'user'          =>  '',
  1280.                     'rootWebUrl'    =>  $rootWebUrl
  1281.                 ) )->getContent();
  1282.                 $MailHelper->sendEmail($client->getName(),$mailTo$subject$myMessage$mailCopy );
  1283.                 //Guardamos log de envío de alerta
  1284.                 $alertPurchase = new AlertPurchase();
  1285.                 $alertPurchase->setClient($client);
  1286.                 $alertPurchase->setCreatedAt(new \DateTime());
  1287.                 $alertPurchase->setEmailSent($mails_sent);
  1288.                 $alertPurchase->setIsActive(1);
  1289.                 $alertPurchase->setOrder($orders);
  1290.                 $em->persist($alertPurchase);
  1291.                 $em->flush();    
  1292.                 return new JsonResponse(array(
  1293.                     'status'  => 'success',
  1294.                     'orderId' => $orders->getOrderId() 
  1295.                 ));
  1296.             
  1297.         } else {
  1298.             
  1299.             return new JsonResponse(array(
  1300.                 'status'  => 'error',
  1301.                 'orderId' => ''
  1302.             ));            
  1303.             
  1304.         }
  1305.         
  1306.         
  1307.         
  1308.     }
  1309.     
  1310.     /**     
  1311.      * @Route("{slug}/checkout/validate-cart", name="frontend_checkout_validate_cart")
  1312.      */
  1313.     public function checkoutValidateCartAction(Request $request$slug)
  1314.     {
  1315.         $currentCart  $this->get("session")->get("cart");
  1316.         $cartList     json_decode($currentCart);
  1317.         if(count($cartList) > 0)
  1318.         {        
  1319.             $validate true;
  1320.             foreach($cartList as $cart)
  1321.             {
  1322.                 $product_stock $this->getDoctrine()->getRepository(\App\Entity\Product::class)->getInventoryProduct($cart->pid);
  1323.                 $stock 0;
  1324.                 if($product_stock){
  1325.                     if($product_stock['available'] != ''){
  1326.                         $stock $product_stock['available'];
  1327.                     }
  1328.                     
  1329.                     if($product_stock['is_not_stock'] == '1'){
  1330.                         $stock 'not_stock';
  1331.                     }
  1332.                 }
  1333.                 if($stock != 'not_stock'){
  1334.                     if($cart->quantity $stock){
  1335.                         $validate false;
  1336.                         break;
  1337.                     }
  1338.                 }
  1339.             }
  1340.             
  1341.         }
  1342.         
  1343.         return new JsonResponse(array(
  1344.             'validate'  => $validate
  1345.         ));    
  1346.                 
  1347.     }
  1348.     
  1349.     /**    
  1350.      * @Route("{slug}/checkout/validate-stock", name="frontend_checkout_validate_stock")
  1351.      */
  1352.     public function checkoutValidateStockAction(Request $request$slug)
  1353.     {
  1354.         $id $request->get('id');
  1355.         if($id != '')
  1356.         {        
  1357.             $validate true;
  1358.          
  1359.             $product_stock $this->getDoctrine()->getRepository(\App\Entity\Product::class)->getInventoryProduct($id);
  1360.             $stock 0;
  1361.             if($product_stock){
  1362.                 if($product_stock['available'] != ''){
  1363.                     $stock $product_stock['available'];
  1364.                 }
  1365.                 if($product_stock['is_not_stock'] == '1'){
  1366.                     $stock 'not_stock';
  1367.                 }
  1368.             }
  1369.             if($stock != 'not_stock'){
  1370.                 if($stock 1){
  1371.                     $validate false;
  1372.                 }
  1373.             }
  1374.             
  1375.             
  1376.         }
  1377.         
  1378.         return new JsonResponse(array(
  1379.             'validate'  => $validate
  1380.         ));    
  1381.         
  1382.         
  1383.     }
  1384.     
  1385.             
  1386.     /**
  1387.      *
  1388.      * @Route("{slug}/checkout/thanks", name="frontend_checkout_thanks")
  1389.      */
  1390.     public function checkOutThanksAction(Request $request$slug)
  1391.     {
  1392.         
  1393.         // replace this example code with whatever you need
  1394.         //$client_id = $this->getParameter('client_id');
  1395.         $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1396.             "slug" => $slug
  1397.         ));
  1398.         if(!$client)
  1399.         {
  1400.             //Si no se encuentra debe indicar algún error
  1401.         }
  1402.         $orderNumberRaw $request->get('orderNumber','');       
  1403.         $orderNumber    $this->encryptor->decrypt($orderNumberRaw);
  1404.         $order          $this->getDoctrine()->getRepository(\App\Entity\Orders::class)->findOneBy(array("orderId"=> $orderNumber));        
  1405.         
  1406.         if(!$order)
  1407.         {            
  1408.             return $this->redirectToRoute("frontend_index", ['slug' => $slug]);
  1409.         }
  1410.         
  1411.         //$categories   = $this->getDoctrine()->getRepository(\App\Entity\Blog::class)->getCategoriesBlog($slug);        
  1412.         $settings       $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  1413.             "Client" => $client
  1414.         ));
  1415.     
  1416.         return $this->render('Frontend/Checkout/thanks.html.twig', array(
  1417.             'productCategory' => '',
  1418.             'pager_limit'     => 12,
  1419.             'globalSearch'    => '',
  1420.             'settings'        => $settings,
  1421.             'orderNumber'     => $orderNumber,
  1422.             'brand'           => '',
  1423.             'category'        => '',
  1424.             'slug'            => $slug,
  1425.             'type'            => $order->getOrderType()
  1426.         ));
  1427.     }    
  1428.     
  1429.  
  1430.     
  1431.    /**
  1432.      * @Route("{slug}/checkout/payment", name="frontend_checkout_payment")
  1433.      */
  1434.     public function checkoutPaymentAction(Request $request$slug)
  1435.     {
  1436.         $purchaser    $request->get('query');
  1437.         $purchaserObj $purchaser;
  1438.         
  1439.         $currentCart  $this->get("session")->get("cart");
  1440.         $response     $currentCart;
  1441.        
  1442.         return new JsonResponse(array('status' => 'success''data' => $purchaserObj));
  1443.         
  1444.     } 
  1445.     
  1446.     /**
  1447.      * @Route("/checkout/test_payment", name="frontend_checkout_test")
  1448.      */
  1449.     public function checkoutTestPayment(Request $requestPaymentQPayProHelper $paymentQPayProHelper)
  1450.     {
  1451.         $em $this->getDoctrine()->getManager();
  1452.         $parameters = array(
  1453.             "x_amount"        => 1.00,
  1454.             "x_currency_code" => "GTQ",
  1455.             "x_product_id"    => "1618",
  1456.             "x_freight"       => 0,
  1457.             "x_audit_number"  => "123",
  1458.             "x_line_item"     => "T-shirt Live Dreams<|>w01<|><|>1<|>1000.00<|>N",
  1459.             "x_email"         => "servicio@aguilalibreweb.com",
  1460.             "x_fp_sequence"   => "123",
  1461.             "x_fp_timestamp"  => time(),
  1462.             "x_invoice_num"   => "123",
  1463.             "x_first_name"    => "Customer",
  1464.             "x_last_name"     => "Name",
  1465.             "x_company"        => "C/F",
  1466.             "x_address"       => "Guatemala",
  1467.             "x_city"             => "Guatemala",
  1468.             "x_state"         => "Guatemala",
  1469.             "x_country"       => "Guatemala",
  1470.             "x_zip"           => "01056",                 
  1471.             "cc_number"       => "4111111111111111",
  1472.             "cc_exp"          => "01/26",
  1473.             "cc_cvv2"         => "4567",
  1474.             "cc_name"         => "Josue Prueba Dos",                        
  1475.             'finger'          => "",
  1476.             "device_fingerprint_id" => ""
  1477.         );
  1478.         
  1479.         $QPayPro   = new PaymentQPayProHelper();                                                           
  1480.         $response  $QPayPro->executePaymentOld($em$parameters);
  1481.         return new JsonResponse(array('status' => 'success','msg' => $response));
  1482.     }
  1483.     
  1484.     
  1485.    /**
  1486.      * @Route("{slug}/checkout/payment_no_cash", name="frontend_checkout_no_cash")
  1487.      */
  1488.     public function checkoutPaymentNoCashAction(Request $requestPaymentQPayProHelper $paymentQPayProHelper$slug)
  1489.     {
  1490.         $lastUsername $request->getSession()->get(Security::LAST_USERNAME);
  1491.         $userData false;
  1492.         if($lastUsername)
  1493.         {
  1494.             $userData $request->getSession()->get($lastUsername);        
  1495.         }
  1496.         
  1497.         $ccData        $request->get('ccData');
  1498.         $purchasers    $request->get('query');
  1499.         $paymentId     $request->get('pmid');
  1500.         $deliveryPrice $request->get('deliveryPrice');
  1501.         $finger        $request->get('finger');
  1502.         $device_fingerprint_id $request->get('device_fingerprint_id');
  1503.         $em $this->getDoctrine()->getManager();
  1504.         //$client_id = $this->getParameter('client_id');
  1505.         $session_uniq_id uniqid();
  1506.                         
  1507.         //Información de la tarjeta
  1508.         $dummyOrderId  date("Ymdhis").rand(1,999);
  1509.         $expDate       $ccData['ccmonth']."/".$ccData['ccyear'];
  1510.         $cleanNumber   str_replace(" """$ccData['ccn']);
  1511.         //Si viene desde la selección de un Token, entonces usaremos el nombre de sesión
  1512.         //Que seguramente debería tener su sesión iniciada para usar la función de tokens
  1513.         if($request->get('paymentMode') == 'token')
  1514.         {
  1515.             $customer_name explode(' ',$userData['name']);
  1516.         } else {
  1517.             $customer_name explode(' ',$ccData['name']);                    
  1518.         }
  1519.         if(count($customer_name) == || !is_array($customer_name))
  1520.         {
  1521.             return new JsonResponse(array(
  1522.                 'status' => 'error',
  1523.                 'msg'    => 'Por favor, escriba su nombre como aparece en la tarjeta de crédito'
  1524.             ));
  1525.         }
  1526.         if($paymentId 0)
  1527.         {
  1528.             
  1529.             $clientObj $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array('slug' => $slug));            
  1530.             if(!$clientObj)
  1531.             {
  1532.                 //Si no encuentra el cliente, entonces da error
  1533.                 return new JsonResponse(array(
  1534.                     'status' => 'error',
  1535.                     'msg'    => 'No se puede realizar la transacción en este momento. Por favor, informar de este error a soporte técnico (A34)'
  1536.                 ));
  1537.             }
  1538.             //Si el customer no esta registrado y no hay un campo configurado para email entonces envia el email al cliente
  1539.             $emailCustomer $clientObj->getEmail();
  1540.             if($userData)
  1541.             {
  1542.                 $customerObj $this->getDoctrine()->getRepository(\App\Entity\Customer::class)->findOneBy(array('customerId' => $userData['customer_id']));    
  1543.                 $emailCustomer $customerObj->getEmail();                        
  1544.             } else {
  1545.                 foreach($purchasers['purchaser'] as $purchaser)
  1546.                 {                        
  1547.                     if($purchaser['is_email'] == true)
  1548.                     {
  1549.                         $emailCustomer $purchaser['value']; 
  1550.                     }
  1551.                 }
  1552.             }
  1553.                     
  1554.             $paymentMethod $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy(array(
  1555.                 'paymentMethodId' => $paymentId
  1556.                 'Client' => $clientObj
  1557.             ));
  1558.             if($paymentMethod)
  1559.             {
  1560.                 //QPAY PRO
  1561.                 if($paymentMethod->getPaymentMethodGateway() && $paymentMethod->getPaymentMethodGateway()->getPaymentMethodGatewayId() == '1')
  1562.                 {
  1563.                             
  1564.                     //Calculo de Total incluyendo cargos dPre envio
  1565.                     $cartInfo   $this->refreshCart($slug);
  1566.                     $grandTotal 0;
  1567.                     if($deliveryPrice == 'N')
  1568.                     {
  1569.                         $grandTotal $cartInfo['price'];                        
  1570.                     } else if($deliveryPrice == "FREE")
  1571.                     {
  1572.                         $grandTotal $cartInfo['price'];    
  1573.                     } else {
  1574.                         if($deliveryPrice 0)
  1575.                         {
  1576.                             $grandTotal = ($cartInfo['price']+$deliveryPrice);                      
  1577.                         } else {
  1578.                             $grandTotal $cartInfo['price'];                      
  1579.                         }
  1580.                     }
  1581.                     //Agregando el servife fee
  1582.                     if($clientObj->getServiceFee() > 0)
  1583.                     {
  1584.                         $withServiceFee $grandTotal $clientObj->getServiceFee();                        
  1585.                         $grandTotal     number_format($withServiceFee2'.''');                        
  1586.                     }
  1587.                 
  1588.                     
  1589.                     $order    false;                    
  1590.                     $QPayPro  = new PaymentQPayProHelper();        
  1591.                     
  1592.                     //Si se usa el metodo para llenar los datos de tarjeta de crédito
  1593.                     if($request->get('paymentMode') == 'card')
  1594.                     {
  1595.                         $parameters = array(
  1596.                             "x_amount"        => $grandTotal,
  1597.                             "x_currency_code" => $clientObj->getCurrency()->getCurrencyIso(),
  1598.                             "x_product_id"    => "1618",
  1599.                             "x_freight"       => 0,
  1600.                             "x_audit_number"  => $dummyOrderId,
  1601.                             "x_line_item"     => $cartInfo['qpay_pro'],
  1602.                             "x_email"         => $emailCustomer,
  1603.     
  1604.                             "x_fp_sequence"   => $dummyOrderId,
  1605.                             "x_fp_timestamp"  => time(),
  1606.                             "x_invoice_num"   => $dummyOrderId,
  1607.                             "x_first_name"    => $customer_name[0],
  1608.                             "x_last_name"     => $customer_name[1],
  1609.                             "x_company"        => "C/F"// Company o C/F
  1610.                             "x_address"       => "Guatemala",
  1611.                             "x_city"             => "Guatemala",
  1612.                             "x_state"         => "Guatemala",
  1613.                             "x_country"       => "Guatemala",
  1614.                             "x_zip"           => "01056",     
  1615.                             
  1616.                             "cc_number"       => $cleanNumber,
  1617.                             "cc_exp"          => $expDate,
  1618.                             "cc_cvv2"         => $ccData['ccv'],
  1619.                             "cc_name"         => $ccData['name'],                        
  1620.     
  1621.                             'finger'          => $finger,
  1622.                             "device_fingerprint_id" => $device_fingerprint_id                                                                                                        
  1623.                         );
  1624.                         $response $QPayPro->executePayment($em$parameters$clientObj$paymentId);
  1625.                     //Si se usa el metodo de pago TOKEN (Solo para usuarios que esten registrados)
  1626.                     } else if($request->get('paymentMode') == 'token')
  1627.                     {
  1628.                         $parameters = array(
  1629.                             "x_amount"   => $grandTotal,
  1630.                             "x_currency" => $clientObj->getCurrency()->getCurrencyIso()
  1631.                         );
  1632.                         $customerTokenDecrypted $this->encryptor->decrypt($request->get('customerToken'));
  1633.                         $tokenObj $this->getDoctrine()->getRepository(\App\Entity\CustomerToken::class)->findOneBy(array(
  1634.                             'customerTokenId' => $customerTokenDecrypted,
  1635.                             'is_active' => 1                            
  1636.                         ));
  1637.                         if($tokenObj)
  1638.                         {                            
  1639.                             
  1640.                             $response $QPayPro->useToken($em$parameters$clientObj$paymentId$tokenObj->getToken());
  1641.                         } else {
  1642.                             return new JsonResponse(array(
  1643.                                 'status' => 'error',
  1644.                                 'msg'    => 'No es posible utilizar esta tarjeta guardada en este momento. Por favor intente de nuevo y si el problema persiste Comuníquese con servicio al cliente.'
  1645.                             ));    
  1646.                         }
  1647.                     } else {
  1648.                         return new JsonResponse(array(
  1649.                             'status' => 'error',
  1650.                             'msg'    => 'No es posible realizar la transacción en este momento. Por favor intente de nuevo y si el problema persiste Comuníquese con servicio al cliente.'
  1651.                         ));    
  1652.                     }
  1653.                     
  1654.                     
  1655.                     if(isset($response->responseCode))
  1656.                     {
  1657.                                                 
  1658.                         if(strlen($response->responseText[0]) == 1)
  1659.                         {                                            
  1660.                             $text $response->responseText;                                                
  1661.                         } else {                                            
  1662.                             $text $response->responseText[0];                                                                        
  1663.                         }                                                         
  1664.                         $paymentObj = new Payment();
  1665.                         $paymentObj->setLast4Tdc(substr($cleanNumber,13,16));
  1666.                         $paymentObj->setResult($response->result);
  1667.                         $paymentObj->setTitle($response->title);
  1668.                         $paymentObj->setCustomAuthCode($dummyOrderId);
  1669.                         $paymentObj->setResponseCode($response->responseCode);
  1670.                         $paymentObj->setResponseText($response->responseText);
  1671.                         $paymentObj->setResponseObject(json_encode($response));
  1672.                         
  1673.                         if($request->get('paymentMode') == 'token')
  1674.                         {
  1675.                             $paymentObj->setResponseAuthorization($response->responseAutorization);
  1676.                             $paymentObj->setIdTransaction($response->transactionId);
  1677.                         } else {
  1678.                             $paymentObj->setResponseAuthorization($response->responseAuthorization);
  1679.                             $paymentObj->setIdTransaction($response->idTransaction);
  1680.                         }
  1681.                                                 
  1682.                         $paymentObj->setAmount($grandTotal);
  1683.                         $paymentObj->setRequest(json_encode($parameters));
  1684.                         $paymentObj->setCreatedAt(new \DateTime());
  1685.                         $paymentObj->setClient($clientObj);
  1686.                         $em->persist($paymentObj);
  1687.                         $em->flush(); 
  1688.                         
  1689.                         if($response->responseCode == '100')
  1690.                         {        
  1691.                             return new JsonResponse(array(
  1692.                                 'status' => 'success',
  1693.                                 'data'   => $response,
  1694.                                 'dummyOrderId' => $dummyOrderId,
  1695.                                 'msg' => 'Pago recibido correctamente, estamos procesando en este momento la orden'
  1696.                             ));                                                        
  1697.                         } else {                                                 
  1698.                             return new JsonResponse(array(
  1699.                                 'status' => 'error',
  1700.                                 'data'   => $response,
  1701.                                 'dummyOrderId' => $dummyOrderId,
  1702.                                 'msg' => $text
  1703.                             ));                                    
  1704.                         }    
  1705.                         
  1706.                     }        
  1707.                 //Termina qpay_pro
  1708.                 }
  1709.                         
  1710.                         
  1711.                         
  1712.             }
  1713.             
  1714.         }
  1715.        
  1716.         return new JsonResponse(array(
  1717.             'status' => 'error',
  1718.             'msg'    => 'No fue posible comunicarse con la pasarela de Pago. Por favor utilice otro método de pago para continuar'
  1719.         ));
  1720.         
  1721.     }        
  1722.    
  1723.         
  1724.     
  1725.     
  1726.     /**
  1727.      *
  1728.      * @Route("{slug}/checkout_fields", name="frontend_checkout_fields")
  1729.      */
  1730.     public function checkoutFieldsAction(Request $request$slug)
  1731.     {
  1732.         $clientIdNum $this->getParameter('client_id');
  1733.                 
  1734.         $lastUsername $request->getSession()->get(Security::LAST_USERNAME);
  1735.         $userData false;
  1736.         if($lastUsername)
  1737.         {
  1738.             $userData $request->getSession()->get($lastUsername);        
  1739.         }
  1740.         $client $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1741.             "clientId" => $clientIdNum
  1742.         ));
  1743.         
  1744.         $settings $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  1745.             "Client" => $client
  1746.         ));
  1747.         
  1748.         //VERIFICAMOS HORARIOS
  1749.         $store_status   'open';                
  1750.         $message_closed "";
  1751.         $day_number     date('N');
  1752.         
  1753.         $hoursToday $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->verifyHoursForToday($day_number$clientIdNum);
  1754.         if($hoursToday['is_open'] == '0')
  1755.         {
  1756.             $store_status    'closed';                    
  1757.             $information $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1758.                 "clientId" => $clientIdNum
  1759.             ));
  1760.             $message_closed  $information->getClosedNotice();
  1761.         }
  1762.         
  1763.         $type "";
  1764.         
  1765.         if($request->get('direct_field_id'))
  1766.         {
  1767.             # REEMPLAZO DE TIENDA CERRADA
  1768.             //Si tiene un horario configurado para este dia, entonces se reemplaza
  1769.             if($store_status == 'open')
  1770.             {
  1771.                 $cartField    $request->get('direct_field_id');
  1772.             }else{
  1773.                 $cartField       $settings->getClosedDirectFieldList()->getFieldListId();
  1774.             }
  1775.             $type"direct";
  1776.         } else {
  1777.             # REEMPLAZO DE TIENDA CERRADA
  1778.             //Si tiene un horario configurado para este dia, entonces se reemplaza
  1779.             //obtenemos el día actual
  1780.             if($store_status == 'open')
  1781.             {
  1782.                 $cartField $settings->getCartFieldList()->getFieldListId();
  1783.             } else {
  1784.                 $cartField $settings->getClosedCartFieldList()->getFieldListId();                            
  1785.             }
  1786.             $type="cart";
  1787.         }                
  1788.                 
  1789.         if(true)
  1790.         {
  1791.                 $array $this->getDoctrine()->getRepository(\App\Entity\FieldList::class)->getFieldsById($cartField,$clientIdNum);
  1792.         } else {
  1793.                 //Si no tiene campos el formulario que deberia de ser, mandamos el formulario por defecto.
  1794.                 $array $this->getDoctrine()->getRepository(\App\Entity\FieldList::class)->getFieldsById(0,$clientIdNum);
  1795.         }
  1796.         
  1797.         $finalArray = array();
  1798.         
  1799.         
  1800.         foreach($array as $item)
  1801.         {
  1802.                         
  1803.             $merged $item;                        
  1804.             
  1805.             if($item['field_type_id'] == 4)
  1806.             {
  1807.                 $polygons $this->getDoctrine()->getRepository(\App\Entity\FieldList::class)->getPolygonsForFieldClient($item['field_client_id']);
  1808.                 if($polygons)
  1809.                 {
  1810.                     $polArray = array();
  1811.                     foreach($polygons as $pols)
  1812.                     {
  1813.                         $polArray[] = $pols;
  1814.                     }
  1815.                     $merged array_merge($item, array('polygons'=>$polArray));
  1816.                 
  1817.                 }
  1818.             }
  1819.             
  1820.             $finalArray[] = $merged;            
  1821.             
  1822.         }
  1823.                
  1824.         /*echo "<pre>";
  1825.           print_r($merged);
  1826.         echo "</pre>";    */    
  1827.         
  1828.         /*return new JsonResponse(array(
  1829.             'status'   => 'success',
  1830.             'result'   => $array,
  1831.             'store_status'  => $store_status
  1832.         ));*/
  1833.         $customerLocation '';
  1834.         if($userData)
  1835.         {
  1836.             if($userData['customer_id'])
  1837.             {
  1838.                 $customerLocation $this->getDoctrine()->getRepository(\App\Entity\CustomerLocation::class)->findOneBy([
  1839.                     "Customer" => $userData['customer_id']
  1840.                 ]);
  1841.             }
  1842.         }
  1843.         return $this->render('Frontend/Checkout/checkout_fields.html.twig', array(
  1844.             'status'                => 'success',
  1845.             'result'                => $finalArray,
  1846.             'slug'                  => $slug,
  1847.             'userData'              => $userData,
  1848.             'store_status'          => $store_status,
  1849.             'message_closed'        => $message_closed,
  1850.             'customerLocation'      => $customerLocation,
  1851.             'type'                  => $type
  1852.         ));               
  1853.        
  1854.        
  1855.     }    
  1856.     
  1857.     
  1858.     /**
  1859.      *
  1860.      * @Route("{slug}/checkout_table", name="frontend_checkout_table")
  1861.      */
  1862.     public function checkoutTableAction(Request $request$slug)
  1863.     {
  1864.         
  1865.         $cart       json_decode($this->get("session")->get("cart"));
  1866.         $cartArray  = array();
  1867.         $grandTotal 0;
  1868.                 
  1869.         $information  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy([
  1870.             "slug" => $slug
  1871.         ]);                
  1872.         $client_id $information->getClientId();
  1873.         //Obtenemos simbolo de moneda a utilizar
  1874.         $symbol $information->getCurrency()->getCurrencySymbol();
  1875.         if(count($cart) > 0)
  1876.         {
  1877.             foreach($cart as $item)
  1878.             {
  1879.                 
  1880.                 $productObj $this->getDoctrine()->getRepository(\App\Entity\Product::class)->findOneBy(array(
  1881.                     'productId' => $item->pid
  1882.                 ));            
  1883.                 
  1884.                 $productInventory $this->getDoctrine()->getRepository(\App\Entity\Product::class)->getInventoryProduct($item->pid);
  1885.                 $stock 0;
  1886.                 if($productInventory){
  1887.                     if($productInventory['available'] != ''){
  1888.                         $stock $productInventory['available'];
  1889.                     }
  1890.                     
  1891.                     if($productInventory['is_not_stock'] == '1'){
  1892.                         $stock 'not_stock';
  1893.                     }
  1894.                     
  1895.                 }
  1896.                 $cleanPrice preg_replace("/[^0-9.]/","",$item->price);                                
  1897.                 $cleanPrice ltrim($cleanPrice,".");
  1898.                 $cleanPrice sprintf('%0.2f',$cleanPrice); 
  1899.                 
  1900.                 $subtotal = ($item->quantity $cleanPrice);
  1901.                 
  1902.                 
  1903.                 $itemArray = [
  1904.                     'product' => [
  1905.                         "name"        => $item->name,
  1906.                         "product_id"  => $item->pid,
  1907.                         "offer_name"  => $item->o_name,
  1908.                         "offer_id"    => $item->oid,
  1909.                         "clean_price" => $cleanPrice,    
  1910.                         "stock"       => $stock,
  1911.                         'subtotal'    => number_format($subtotal2'.'','),
  1912.                         'image'       => $productObj->getMainPicture(),        
  1913.                     ],
  1914.                     "quantity"    => $item->quantity,
  1915.                     "symbol"      => $symbol,
  1916.                     'service_fee' => $information->getServiceFee()
  1917.                 ];
  1918.                 
  1919.                 $grandTotal += $subtotal;                
  1920.                 $cartArray[] = $itemArray;
  1921.                                 
  1922.             }
  1923.         }
  1924.         
  1925.         
  1926.                 
  1927.         $coupon '';
  1928.         $grandTotalFinal $grandTotal;
  1929.         $discount 0;
  1930.         if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != '')
  1931.         {
  1932.             $coupon_id $this->get("session")->get("coupon");
  1933.             $coupon $this->getDoctrine()->getRepository(\App\Entity\Coupon::class)->findOneBy(array(
  1934.                 'couponId' => $coupon_id
  1935.             ));    
  1936.             
  1937.             $discount_percent $coupon->getDiscountPercent();
  1938.             $discount         = ($grandTotal*$discount_percent)/100;
  1939.             $grandTotalFinal  $grandTotal $discount;
  1940.         }
  1941.         //SE APLICA EL SERVICE FEE
  1942.         if($information->getServiceFee() && $information->getServiceFee() > 0)
  1943.         {            
  1944.             $grandTotalFinal $grandTotalFinal $information->getServiceFee();
  1945.         }
  1946.         return $this->render('Frontend/Checkout/checkout_table.html.twig', array(
  1947.             'productCategory' => '',
  1948.             'pager_limit'     => 12,
  1949.             'globalSearch'    => '',
  1950.             'slug'            => $slug,
  1951.             'cart'            => $cartArray,
  1952.             'coupon'          => $coupon,
  1953.             'subTotal'        => number_format($grandTotal2'.'','),
  1954.             'discount'        => number_format($discount2'.'','),
  1955.             'grandTotal'      => number_format($grandTotalFinal2'.'','),
  1956.             'symbol'          => $symbol,
  1957.             'service_fee'     => $information->getServiceFee()
  1958.         ));
  1959.     }    
  1960.     /**     
  1961.      * @Route("{slug}/checkout_refresh_cart", name="frontend_checkout_refresh_cart")
  1962.      */
  1963.     public function checkoutRefreshCartAction(Request $request$slug) {
  1964.            
  1965.            
  1966.             $response $this->refreshCart($slug);
  1967.             return new JsonResponse($response);
  1968.     }   
  1969.     
  1970.     
  1971.     public function refreshCart($slug)
  1972.     {
  1973.             
  1974.             $information  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  1975.                 "slug" => $slug
  1976.             ));        
  1977.             if(!$information)
  1978.             {
  1979.                 //@TODO hacer algo si no se detecta
  1980.             }
  1981.             $client_id $information->getClientId();
  1982.             //Obtenemos simbolo de moneda a utilizar
  1983.             $symbol $information->getCurrency()->getCurrencySymbol();
  1984.             $currentCart json_decode($this->get("session")->get("cart"));
  1985.             if(is_array($currentCart))
  1986.             {
  1987.                 if (count($currentCart) == 0) {
  1988.                     $currentCart = array();
  1989.                 }
  1990.             }
  1991.             
  1992.             $val 0;
  1993.             $priceVal 0;
  1994.             if (is_array($currentCart)) {
  1995.                 $currentCarts $currentCart;
  1996.             } else {
  1997.                 $currentCarts json_decode($currentCart);
  1998.             }
  1999.             //Cadena para gateway de pago
  2000.             $QPayPro "";
  2001.             
  2002.             
  2003.             //-------------------------
  2004.             
  2005.             if(is_array($currentCarts))
  2006.             {
  2007.                 foreach($currentCarts as $cartTemp)
  2008.                 {
  2009.                     $val += $cartTemp->quantity;
  2010.                     $priceVal += $cartTemp->price $cartTemp->quantity;
  2011.                     
  2012.                     //Cadenas para gateway de pago
  2013.                     $QPayPro .= $cartTemp->name."<|>".$cartTemp->pid."<|>".$cartTemp->quantity."<|>".$cartTemp->price."<|>N";
  2014.                 }
  2015.             }
  2016.             
  2017.             $coupon '';
  2018.             $grandTotalFinal $priceVal;
  2019.             $discount 0;
  2020.             if($grandTotalFinal ){
  2021.                 if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != ''){
  2022.                     $coupon_id $this->get("session")->get("coupon");
  2023.                     $coupon $this->getDoctrine()->getRepository(\App\Entity\Coupon::class)->findOneBy(array(
  2024.                             'couponId' => $coupon_id
  2025.                     ));    
  2026.                     $discount_percent $coupon->getDiscountPercent();
  2027.                     $discount = ($priceVal*$discount_percent)/100;
  2028.                     $grandTotalFinal $priceVal $discount;
  2029.                     $grandTotalFinalnumber_format($grandTotalFinal2'.'',');
  2030.                 }
  2031.             }else{
  2032.                 $grandTotalFinal '';
  2033.             }
  2034.             
  2035.             $url $this->generateUrl('frontend_checkout', ['slug' => $slug]);
  2036.             $html "<div id='cart_main' rel='popover' class='icon-header-item cl2 hov-cl1 trans-04 p-l-22 p-r-11 icon-header-noti js-show-cart' onclick='window.location.href=\"$url\"' data-notify='$val'>
  2037.                 <i class='zmdi zmdi-shopping-cart'></i>$symbol$grandTotalFinal
  2038.                 <small class='cart_bottom_legend'>Clic aquí para terminar</small>
  2039.             </div>";
  2040.             $response = array(
  2041.                 'quantity' => $val,
  2042.                 'price'    => $grandTotalFinal,
  2043.                 'cart'     => $currentCarts,
  2044.                 'html'     => $html,
  2045.                 'qpay_pro' => $QPayPro
  2046.             );    
  2047.             
  2048.             return $response;    
  2049.     }
  2050.     
  2051.     
  2052.     
  2053.     /**
  2054.      * @Route("{slug}/checkout/verify-coupon", name="frontend_checkout_verify_coupon")
  2055.      */
  2056.     public function checkoutVerifyCouponAction(Request $request$slug)
  2057.     {
  2058.         $userData $this->get("session")->get("userData");
  2059.         
  2060.         $client  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  2061.             "slug" => $slug
  2062.         ));    
  2063.         $client_id $client->getClientId();
  2064.         if(!$client)
  2065.         {
  2066.             return new JsonResponse(array(
  2067.                 'status'    =>  'error',
  2068.                 'isValid'   =>  0,
  2069.                 'msg'       =>  "No se puede validar el cupón en este momento",
  2070.                 'coupon'    =>  ""
  2071.             ));
  2072.         }
  2073.         $setting  $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
  2074.             "Client" => $client
  2075.         ));        
  2076.         $customerId '';
  2077.         if($userData)
  2078.         {
  2079.             $customerId $userData['customer_id'];
  2080.         }
  2081.         $coupon    $request->get('coupon');        
  2082.         
  2083.         //VERIFICAMOS EXISTENCIA DEL CUPÓN
  2084.         $couponExist $this->getDoctrine()->getRepository(\App\Entity\Coupon::class)->verifyCoupon($coupon,$customerId$client_id);
  2085.         $isValid false;        
  2086.         $msg     "El cupón no es valido";
  2087.         $this->get("session")->set("coupon"'');
  2088.         if($couponExist)
  2089.         {
  2090.             if($userData)
  2091.             {
  2092.                  if($couponExist['customer_id'] != '' && $couponExist['customer_id'] != $userData['customer_id'])
  2093.                  {
  2094.                     $isValid false;
  2095.                     $msg     "El cupón ingresado no es válido";
  2096.                  }else{                  
  2097.                     $isValid true;
  2098.                  }
  2099.                      
  2100.             }else{
  2101.                 if($couponExist['customer_id'] == '')
  2102.                 {                    
  2103.                     $isValid true;                    
  2104.                 }
  2105.             }
  2106.             
  2107.             //Verificamos productos ofertados 
  2108.             if($isValid && $setting->getCartAllowCouponWhithOffers() == '0')
  2109.             {
  2110.                 $currentCart  $this->get("session")->get("cart");
  2111.                 $cartList     json_decode($currentCart);
  2112.                 if(count($cartList) > 0)
  2113.                 {        
  2114.                    
  2115.                     foreach($cartList as $cart)
  2116.                     {
  2117.                        if($cart->oid != ''){
  2118.                            $isValid false;
  2119.                            $msg     "No es posible utilizar el cúpon con productos ofertados";
  2120.                            break;
  2121.                        }
  2122.                     }
  2123.                 }
  2124.                 
  2125.             }
  2126.             
  2127.             if($isValid){
  2128.                 $this->get("session")->set("coupon"$couponExist['coupon_id']);
  2129.             }
  2130.         }
  2131.         
  2132.         return new JsonResponse(array(
  2133.             'status'    =>  'success',
  2134.             'isValid'   =>  $isValid,
  2135.             'msg'       =>  $msg,
  2136.             'coupon'    =>  $this->get("session")->get("coupon")
  2137.         ));
  2138.         
  2139.     }  
  2140.     
  2141.     
  2142.     /**
  2143.      * @Route("{slug}/checkout/distance-info", name="frontend_checkout_distance_info")
  2144.      */
  2145.     public function distanceInfoAction(Request $requestDistanceHelper $distanceHelper$slug)
  2146.     {
  2147.         
  2148.         $client  $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
  2149.             "slug" => $slug
  2150.         ));        
  2151.         $client_id $client->getClientId();
  2152.         $variable  $this->getDoctrine()->getRepository(\App\Entity\DeliveryVariable::class)->findOneBy(array(
  2153.             "Client" => $client_id
  2154.         ));        
  2155.         
  2156.          $response "";
  2157.          if($variable)
  2158.          {       
  2159.              
  2160.             $latTo $request->get('latTo');
  2161.             $lngTo $request->get('lngTo');             
  2162.             if($latTo != "" && $lngTo != "")
  2163.             {
  2164.                 $dummyLat $variable->getOriginLat();
  2165.                 $dummyLng $variable->getOriginLng();
  2166.                 $distanceHelper = new DistanceHelper();            
  2167.                 $response $distanceHelper->getDistanceInfo($dummyLat$dummyLng$latTo$lngTo$variable->getUseGoogle(), $variable->getApiKey());        
  2168.                 if($response)
  2169.                 {
  2170.                     if(strlen($response['distance']) > 0)
  2171.                     {
  2172.                         $rangeFound  $this->getDoctrine()->getRepository(\App\Entity\DeliveryRange::class)->findRangePrice($response['distance'], $client_id);
  2173.                         if($rangeFound)
  2174.                         {
  2175.                             
  2176.                             if($rangeFound['is_free'] == 1)
  2177.                             {
  2178.                                 $finalPrice 'FREE';        
  2179.                             } else {
  2180.                                 $finalPrice $rangeFound['price'];                        
  2181.                             }
  2182.                             
  2183.                             return new JsonResponse(array(
  2184.                                 'status'         => 'success',
  2185.                                 'delivery_price' => $finalPrice,
  2186.                                 'data'           => $response
  2187.                             ));
  2188.         
  2189.                         }
  2190.                     }
  2191.                 
  2192.                 }
  2193.                 return new JsonResponse(array(
  2194.                     'status'         => 'error',
  2195.                     'delivery_price' => '',
  2196.                     'data'           => $response
  2197.                 ));
  2198.             }
  2199.             
  2200.         } 
  2201.         
  2202.         
  2203.         return new JsonResponse(array(
  2204.             'status'         => 'success',
  2205.             'delivery_price' => '',
  2206.             'data'           => ''
  2207.         ));
  2208.             
  2209.         
  2210.     }  
  2211.     
  2212.         
  2213.       
  2214.     /**
  2215.      * @Route("/checkout/quit-coupon", name="frontend_checkout_quit_coupon")
  2216.      */
  2217.     public function checkoutQuitCouponAction(Request $request)
  2218.     {
  2219.         $this->get("session")->set("coupon",'');
  2220.         return new JsonResponse(array(
  2221.             'status'    => 'success'
  2222.         ));
  2223.         
  2224.     }  
  2225.     
  2226.       
  2227.     /**
  2228.      * @Route("/{slug}", name="frontend_index", requirements={"slug"="^(?!(login|backend|logout)(/|$)).*"}))
  2229.      */
  2230.     public function indexAction(Request $request$slug)
  2231.     {
  2232.         
  2233.         $em        $this->getDoctrine()->getManager();
  2234.         //$client_id = $this->getParameter('client_id');
  2235.         
  2236.         $productCategory "";
  2237.         $pager_limit     12;
  2238.         $globalSearch    "";
  2239.         //$client = $this->getDoctrine()->getRepository(Client::class)->findBy(array("clientId" => $client_id));
  2240.         $client    $this->getDoctrine()->getRepository(Client::class)->findOneBy(array("slug" => $slug));
  2241.         if(!$client)
  2242.         {
  2243.             return $this->redirectToRoute("homepage_website");
  2244.         }
  2245.         $client_id $client->getClientId();
  2246.         $slides $this->getDoctrine()->getRepository(WebSlide::class)->findBy(array("Client" => $client"is_active" => 1));
  2247.         $webSetting $this->getDoctrine()->getRepository(WebSetting::class)->findOneBy(array("Client" => $client));        
  2248.         
  2249.         $brands        $em->getRepository(Brand::class)->getBrands($client_id);
  2250.         $categories    $em->getRepository(Category::class)->getCategories($client_id);
  2251.         $subcategories $em->getRepository(Subcategory::class)->findBy(array('is_active' => 1'Client'=> $client));
  2252.         $blogs $em->getRepository(Blog::class)->findBy(array('is_active' => 1'is_published' => 1'featured'=> 1'Client' => $client));
  2253.         // replace this example code with whatever you need
  2254.         return $this->render('Frontend/Index/index.html.twig', array(
  2255.             'productCategory' => $productCategory,
  2256.             'pager_limit'     => $pager_limit,
  2257.             'globalSearch'    => $globalSearch,
  2258.             'slides'          => $slides,
  2259.             'categories'      => $categories,
  2260.             'brands'          => $brands,
  2261.             'blogs'           => $blogs,
  2262.             'slug'            => $slug,
  2263.             'subcategories'   => $subcategories,
  2264.             'webSetting'      => $webSetting,
  2265.             'brand'           => '',
  2266.             'category'        => ''
  2267.         ));
  2268.         
  2269.     }    
  2270.          
  2271. }