src/Controller/Frontend/WebsiteController.php line 373

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