src/Controller/ProductsController.php line 60

Open in your IDE?
  1. <?php
  2. /*
  3.  * To change this license header, choose License Headers in Project Properties.
  4.  * To change this template file, choose Tools | Templates
  5.  * and open the template in the editor.
  6.  */
  7. namespace App\Controller;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\HttpFoundation\Session\Session;
  10. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  13. use Symfony\Component\HttpFoundation\File\UploadedFile;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Knp\Component\Pager\PaginatorInterface;
  17. use App\Entity\Products;
  18. use App\Entity\Attributes;
  19. use App\Form\AttributosType;
  20. use App\Entity\ProductAttributes;
  21. use App\Controller\WCController;
  22. use App\Entity\Categorias;
  23. use App\Entity\Marcas;
  24. use App\Entity\Proveedores;
  25. use App\Form\ProveedoresType;
  26. use App\Entity\Albaranes;
  27. use App\Entity\ProductMarca;
  28. use App\Entity\ProductUploads;
  29. use App\Entity\ProveedorOrder;
  30. use CodeItNow\BarcodeBundle\Utils\BarcodeGenerator;
  31. use Symfony\Component\Serializer\Serializer;
  32. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  33. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  34. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  35. use Symfony\Component\Serializer\Encoder\CsvEncoder;
  36. use App\Form\CategoriasType;
  37. /**
  38.  * Description of ProductsController
  39.  *
  40.  * @author joseangelparra
  41.  */
  42. class ProductsController extends AbstractController {
  43.     private $params;
  44.     private $api;
  45.     public function __construct(ParameterBagInterface $params) {
  46.         $this->session = new Session();
  47.         $this->params $params;
  48.         $this->api = new WCController();
  49.     }
  50.     public function index(Request $requestPaginatorInterface $paginator) {
  51.         if (!$this->getUser() || !is_object($this->getUser())) {
  52.             return $this->redirectToRoute('logout');
  53.         }
  54.         $em $this->getDoctrine()->getManager();
  55.         $s = ($request->get("s") ) ? $request->get("s") : "";
  56.         $s_str "";
  57.         if ($s) {
  58.             $s_str " AND p.name LIKE '%" $s "%' OR p.ean LIKE '%" $s "%' OR p.sku LIKE '%" $s "%'";
  59.         }
  60.         $orden = ($request->get("orden")) ? $request->get("orden") : 'DESC';
  61.         $filter = ($request->get("filter")) ? $request->get("filter") : 'id';
  62.         $prods $em->createQueryBuilder()->select("p")
  63.                         ->from("App\Entity\Products""p")
  64.                         ->where("p.id <> '' and p.status > 0 and p.parent= 0" $s_str)
  65.                         ->orderBy("p." $filter$orden)
  66.                         ->getQuery()->getResult();
  67.         $productos $paginator->paginate(
  68.                 $prods$request->query->getInt('page'1), 20);
  69.         return $this->render('products/list.html.twig', array(
  70.                     'productos' => $productos,
  71.                     's' => $s,
  72.                     'orden' => $orden
  73.         ));
  74.     }
  75.     public function addProduct(Request $request) {
  76.         $page $request->get("page");
  77.         $em $this->getDoctrine()->getManager();
  78.         $parent_products $em->createQueryBuilder()->select('p')
  79.                 ->from("App\Entity\Products""p")
  80.                 ->where("(p.parent=0 ) and p.status=1")
  81.                 ->orderBy("p.name""ASC")
  82.                 ->getQuery()
  83.                 ->getResult();
  84.         $attr $em->getRepository(Attributes::class)->findAll();
  85.         $cats $em->getRepository(Categorias::class)->findAll();
  86.         $marcas =  $em->createQueryBuilder()->select('p')
  87.                 ->from("App\Entity\Marcas""p")
  88.                 ->where("p.status=1")
  89.                 ->getQuery()
  90.                 ->getResult();
  91.         
  92.         return $this->render('products/add.html.twig', array(
  93.                     'parents' => $parent_products,
  94.                     'attr' => $attr,
  95.                     'cats' => $cats,
  96.                     'page' => $page,
  97.                     'marcas'=>$marcas
  98.         ));
  99.     }
  100.     public function getAttributesConfig(Request $request) {
  101.         $id $request->get("id");
  102.         $em $this->getDoctrine()->getManager();
  103.         $attr $em->getRepository(Attributes::class)->find($id);
  104.         return $this->render('products/_parts/attrConfig.html.twig', array(
  105.                     'attr' => $attr
  106.         ));
  107.     }
  108.     public function storeProduct(Request $request) {
  109.         
  110.         $page $request->get("page");
  111.         $em $this->getDoctrine()->getManager();
  112.         
  113.         $info $request->request->all();
  114.         //dd($info);
  115.         if (isset($info["id"]) && $info["id"] != "") {
  116.             $product $em->getRepository(Products::class)->find($info["id"]);
  117.             $prod_image $product->getImage();
  118.         } else {
  119.             $product = new Products();
  120.             $product->setDateCreated(new \DateTime());
  121.             $prod_image "";
  122.         }
  123.         //seteamos
  124.         $product->setName($info["name"]);
  125.         $product->setSku($info["sku"]);
  126.         $product->setEan($info["ean"]);
  127.         $product->setDescription($info["description"]);
  128.         $product->setPrice(floatval($info["price"]));
  129.         $product->setIva(floatval($info["iva"]));
  130.         $product->setCostPrice($info["cost_price"]);
  131.         $product->setStoreStock($info["store_stock"]);
  132.         $product->setWpStock($info["wp_stock"]);
  133.         if ($info["discount_from"] != "") {
  134.             $disc_from = \DateTime::createFromFormat('d/m/Y'$info["discount_from"]);
  135.             $product->setDiscountFrom($disc_from);
  136.         } else {
  137.             $product->setDiscountFrom(null);
  138.         }
  139.         if ($info["discount_to"] != "") {
  140.             $disc_to = \DateTime::createFromFormat('d/m/Y'$info["discount_to"]);
  141.             $product->setDiscountTo($disc_to);
  142.         } else {
  143.             $product->setDiscountTo(null);
  144.         }
  145.         $product->setStoreDiscount(($info["store_discount"] != "") ? $info["store_discount"] : );
  146.         $product->setWebDiscount(($info["web_discount"] != "") ? $info["web_discount"] : 0);
  147.         $product->setDateModify(new \DateTime());
  148.         $product->setGlobalStock(floatval($info["store_stock"]) + floatval($info["wp_stock"]));
  149.         $product->setStatus(1);
  150.         $product->setParent((isset($info["parent"]) ? $info["parent"] : 0));
  151.         //imagen
  152.         $image $request->files->get("image");
  153.         if ($image) { //subimos la imagen
  154.             $originalFilename pathinfo($image[0]->getClientOriginalName(), PATHINFO_FILENAME);
  155.             $safeFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()'$originalFilename);
  156.             $newFileName $safeFilename "-product" uniqid() . "." $image[0]->guessExtension();
  157.             try {
  158.                 $image[0]->move(
  159.                         'assets/images/products/',
  160.                         $newFileName
  161.                 );
  162.             } catch (FileException $e) {
  163.                 var_dump($e);
  164.                 die();
  165.             }
  166.             $product->setImage($newFileName);
  167.             if (count($image) > 0) {
  168.                 $gal = [];
  169.                 for ($i 1$i count($image); $i++) {
  170.                     $originalFilename pathinfo($image[$i]->getClientOriginalName(), PATHINFO_FILENAME);
  171.                     $safeFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()'$originalFilename);
  172.                     $newFileName $safeFilename "-product" uniqid() . "." $image[$i]->guessExtension();
  173.                     try {
  174.                         $image[$i]->move(
  175.                                 'assets/images/products/',
  176.                                 $newFileName
  177.                         );
  178.                     } catch (FileException $e) {
  179.                         var_dump($e);
  180.                         die();
  181.                     }
  182.                     $gal[] = $newFileName;
  183.                 }
  184.                 $product->setGallery(json_encode($gal));
  185.             }
  186.         } else {
  187.             $product->setImage($prod_image);
  188.         }
  189.         
  190.         //guardamos en local
  191.         $em->persist($product);
  192.         $f $em->flush();
  193.         if ($f == null) {
  194.             //atributos
  195.             if (isset($info["attr"]) && $info["attr"] != "") {
  196.                 //borramos los atributos actuales
  197.                 $p_attr $em->getRepository(ProductAttributes::class)->findBy(array("productId" => $product->getId()));
  198.                 foreach ($p_attr as $p_at) {
  199.                     $em->remove($p_at);
  200.                     $em->flush();
  201.                 }
  202.                 foreach ($info["attr"] as $attr_id) {
  203.                     $value $info["attrib_" $attr_id "_value"];
  204.                     $prod_attr = new ProductAttributes();
  205.                     $prod_attr->setAttributeId($attr_id);
  206.                     $prod_attr->setProductId($product->getId());
  207.                     $prod_attr->setValue($value);
  208.                     $em->persist($prod_attr);
  209.                     $em->flush();
  210.                 }
  211.             }
  212.             //categorías
  213.             if (isset($info["categoria"]) && count($info["categoria"])>0) {
  214.                 
  215.                 foreach($categoria as $cat){
  216.                   $prod_cat = new \App\Entity\ProductCats();
  217.                   $prod_cat->setCatId($cat);
  218.                   $prod_cat->setProductId($product->getId());
  219.                   $prod_cat->setDateCreated(new \DateTime());
  220.                 
  221.                   $em->persist($prod_cat);
  222.                   $em->flush();
  223.                 }
  224.             }
  225.             
  226.             //marca
  227.             if(isset($info["marca"]) && $info["marca"] !=""){
  228.                 $marc = new ProductMarca();
  229.                 $marc->setProductId($product->getId());
  230.                 $marc->setMarcaId($info["marca"]);
  231.                 
  232.                 $em->persist($marc);
  233.                 $em->flush();
  234.             }
  235.             //web
  236.             if (isset($info["web"]) && $info["web"] == "on") {
  237.                 //lo enviamos a WP
  238.                 $addedwp $this->api->addProductToWP($product$em);
  239.             }
  240.             $type 1;
  241.             $status "Producto guardado correctamente";
  242.         } else {
  243.             $type 0;
  244.             $status "Error al guardar el producto";
  245.         }
  246.         $this->session->getFlashBag()->add('type'$type);
  247.         $this->session->getFlashBag()->add('status'$status);
  248.         return $this->redirectToRoute('productos', ['page' => $page]);
  249.     }
  250.     public function deleteProduct(Request $request) {
  251.         
  252.         if (!$this->getUser() || !is_object($this->getUser())) {
  253.             return $this->redirectToRoute('logout');
  254.         }
  255.         $em $this->getDoctrine()->getManager();
  256.         $pid $request->get("id");
  257.         $page $request->get("page");
  258.         $prod $em->getRepository(Products::class)->find($pid);
  259.         if ($prod) {
  260.             $prod->setStatus(0);
  261.             $em->persist($prod);
  262.             $f $em->flush();
  263.             if ($f == null) {
  264.                 if ($prod->getWpId() != null) {
  265.                     $delete_wp $this->api->deleteProductToWP($prod$em);
  266.                 }
  267.                 $type 1;
  268.                 $status "Producto eliminado correctamente";
  269.             } else {
  270.                 $type 0;
  271.                 $status "Error al eliminar el producto";
  272.             }
  273.         } else {
  274.             $type 0;
  275.             $status "Producto no encontrado";
  276.         }
  277.         $this->session->getFlashBag()->add('type'$type);
  278.         $this->session->getFlashBag()->add('status'$status);
  279.         return $this->redirectToRoute('productos', ['page' => $page]);
  280.     }
  281.     public function generateAutoSku() {
  282.         $em $this->getDoctrine()->getManager();
  283.         $l_prod $em->createQueryBuilder()->select('p')
  284.                 ->from("App\Entity\Products""p")
  285.                 ->where("p.id<>''")
  286.                 ->orderBy("p.id""DESC")
  287.                 ->setMaxResults(1)
  288.                 ->getQuery()
  289.                 ->getResult();
  290.         if ($l_prod) {
  291.             $last_num $l_prod[0]->getSku();
  292.             $last_num++;
  293.         } else {
  294.             $last_num date("Y") . "00001";
  295.         }
  296.         return new JsonResponse(array('sku' => $last_num));
  297.     }
  298.     public function editProduct(Request $request) {
  299.         $em $this->getDoctrine()->getManager();
  300.         $id $request->get("id");
  301.         $page $request->get("page");
  302.         $prod $em->getRepository(Products::class)->find($id);
  303.         $parent_products $em->createQueryBuilder()->select('p')
  304.                 ->from("App\Entity\Products""p")
  305.                 ->where("(p.parent=0 ) and p.status=1")
  306.                 ->orderBy("p.name""ASC")
  307.                 ->getQuery()
  308.                 ->getResult();
  309.         $product_attr $em->getRepository(ProductAttributes::class)->findBy(array("productId" => $id));
  310.         $atrib = array();
  311.         foreach ($product_attr as $pa) {
  312.             $atrib[] = $pa->getAttributeId();
  313.         }
  314.         $attr $em->getRepository(Attributes::class)->findAll();
  315.         $cats $em->getRepository(Categorias::class)->findAll();
  316.         $product_cats $em->getRepository(\App\Entity\ProductCats::class)->findBy(array("productId" => $id));
  317.         $c_cats = array();
  318.         foreach ($product_cats as $c) {
  319.             $c_cats[] = $c->getCatId();
  320.         }
  321.         
  322.         $marcas $marcas =  $em->createQueryBuilder()->select('p')
  323.                 ->from("App\Entity\Marcas""p")
  324.                 ->where("p.status=1")
  325.                 ->getQuery()
  326.                 ->getResult();
  327.                 
  328.         $product_marcas $em->getRepository(ProductMarca::class)->findBy(array("productId"=>$id));
  329.         $c_marc = array();
  330.         foreach($product_marcas as $m){
  331.           $c_marc[] = $m->getMarcaId();
  332.         }
  333.         
  334.         return $this->render('products/edit.html.twig', array(
  335.                     "prod" => $prod,
  336.                     'parents' => $parent_products,
  337.                     'attr' => $attr,
  338.                     'c_attr' => $product_attr,
  339.                     'atrib' => $atrib,
  340.                     'cats' => $cats,
  341.                     'c_cats' => $c_cats,
  342.                     'page' => $page,
  343.                     'marcas'=>$marcas,
  344.                     'c_marc'=>$c_marc
  345.         ));
  346.     }
  347.     public function updateProduct(Request $request) {
  348.         $em $this->getDoctrine()->getManager();
  349.         $page $request->get("page");
  350.         $info $request->request->all();
  351.         //dd($info);
  352.         if (isset($info["id"]) && $info["id"] != "") {
  353.             $product $em->getRepository(Products::class)->find($info["id"]);
  354.             $prod_image $product->getImage();
  355.         } else {
  356.             return false;
  357.         }
  358.         //seteamos
  359.         $product->setName($info["name"]);
  360.         $product->setSku($info["sku"]);
  361.         $product->setEan($info["ean"]);
  362.         $product->setDescription($info["description"]);
  363.         $product->setPrice(floatval($info["price"]));
  364.         $product->setIva(floatval($info["iva"]));
  365.         $product->setCostPrice($info["cost_price"]);
  366.         $product->setStoreStock($info["store_stock"]);
  367.         $product->setWpStock($info["wp_stock"]);
  368.         if ($info["discount_from"] != "") {
  369.             $disc_from = \DateTime::createFromFormat('d/m/Y'$info["discount_from"]);
  370.             $product->setDiscountFrom($disc_from);
  371.         }
  372.         if ($info["discount_to"] != "") {
  373.             $disc_to = \DateTime::createFromFormat('d/m/Y'$info["discount_to"]);
  374.             $product->setDiscountTo($disc_to);
  375.         }
  376.         $product->setStoreDiscount(($info["store_discount"] != "") ? $info["store_discount"] : );
  377.         $product->setWebDiscount(($info["web_discount"] != "") ? $info["web_discount"] : 0);
  378.         $product->setDateModify(new \DateTime());
  379.         $product->setGlobalStock(floatval($info["store_stock"]) + floatval($info["wp_stock"]));
  380.         $product->setParent((isset($info["parent"]) ? $info["parent"] : 0));
  381.         //imagen
  382.         $image $request->files->get("image");
  383.         if ($image) { //subimos la imagen
  384.             $originalFilename pathinfo($image[0]->getClientOriginalName(), PATHINFO_FILENAME);
  385.             $safeFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()'$originalFilename);
  386.             $newFileName $safeFilename "-product" uniqid() . "." $image[0]->guessExtension();
  387.             try {
  388.                 $image[0]->move(
  389.                         'assets/images/products/',
  390.                         $newFileName
  391.                 );
  392.             } catch (FileException $e) {
  393.                 var_dump($e);
  394.                 die();
  395.             }
  396.             $product->setImage($newFileName);
  397.             if (count($image) > 0) {
  398.                 $gal = [];
  399.                 for ($i 1$i count($image); $i++) {
  400.                     $originalFilename pathinfo($image[$i]->getClientOriginalName(), PATHINFO_FILENAME);
  401.                     $safeFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()'$originalFilename);
  402.                     $newFileName $safeFilename "-product" uniqid() . "." $image[$i]->guessExtension();
  403.                     try {
  404.                         $image[$i]->move(
  405.                                 'assets/images/products/',
  406.                                 $newFileName
  407.                         );
  408.                     } catch (FileException $e) {
  409.                         var_dump($e);
  410.                         die();
  411.                     }
  412.                     $gal[] = $newFileName;
  413.                 }
  414.                 $product->setGallery(json_encode($gal));
  415.             }
  416.         } else {
  417.             $product->setImage($prod_image);
  418.         }
  419.         //guardamos en local
  420.         $em->persist($product);
  421.         $f $em->flush();
  422.         if ($f == null) {
  423.             //atributos
  424.             if (isset($info["attr"]) && $info["attr"] != "") {
  425.                 //borramos los atributos actuales
  426.                 $p_attr $em->getRepository(ProductAttributes::class)->findBy(array("productId" => $product->getId()));
  427.                 foreach ($p_attr as $p_at) {
  428.                     $em->remove($p_at);
  429.                     $em->flush();
  430.                 }
  431.                 foreach ($info["attr"] as $attr_id) {
  432.                     $value $info["attrib_" $attr_id "_value"];
  433.                     $prod_attr = new ProductAttributes();
  434.                     $prod_attr->setAttributeId($attr_id);
  435.                     $prod_attr->setProductId($product->getId());
  436.                     $prod_attr->setValue($value);
  437.                     $em->persist($prod_attr);
  438.                     $em->flush();
  439.                 }
  440.             }
  441.             //categorías
  442.             
  443.             if (isset($info["categoria"]) && count($info["categoria"])>0) {
  444.                 //borramos la actual
  445.                 $p_cats $em->getRepository(\App\Entity\ProductCats::class)->findBy(array('productId' => $product->getId()));
  446.                 foreach ($p_cats as $pc) {
  447.                     $em->remove($pc);
  448.                     $em->flush();
  449.                 }
  450.                 foreach($categoria as $cat){
  451.                   $prod_cat = new \App\Entity\ProductCats();
  452.                   $prod_cat->setCatId($cat);
  453.                   $prod_cat->setProductId($product->getId());
  454.                   $prod_cat->setDateCreated(new \DateTime());
  455.                 
  456.                   $em->persist($prod_cat);
  457.                   $em->flush();
  458.                 }
  459.                 
  460.             }
  461.             
  462.             if(isset($info["marca"]) && $info["marca"] !=""){
  463.               //borramos la actual
  464.                 $p_cats $em->getRepository(\App\Entity\ProductMarca::class)->findBy(array('productId' => $product->getId()));
  465.                 foreach ($p_cats as $pc) {
  466.                     $em->remove($pc);
  467.                     $em->flush();
  468.                 }
  469.                 $marc = new ProductMarca();
  470.                 $marc->setProductId($product->getId());
  471.                 $marc->setMarcaId($info["marca"]);
  472.                 
  473.                 $em->persist($marc);
  474.                 $em->flush();
  475.             }
  476.             //web
  477.             if (isset($info["web"]) && $info["web"] == "on") {
  478.                 if ($product->getWpId()) {
  479.                     //update
  480.                     $updatedwp $this->api->updateProductToWP($product$em);
  481.                 } else {
  482.                     //create
  483.                     $addedwp $this->api->addProductToWP($product$em);
  484.                 }
  485.             } else {
  486.                 if ($product->getWpId()) {
  487.                     $deleteWp $this->api->deleteProductToWP($product$em);
  488.                 }
  489.             }
  490.             $type 1;
  491.             $status "Producto guardado correctamente";
  492.         } else {
  493.             $type 0;
  494.             $status "Error al guardar el producto";
  495.         }
  496.         $this->session->getFlashBag()->add('type'$type);
  497.         $this->session->getFlashBag()->add('status'$status);
  498.         return $this->redirectToRoute('productos', ['page' => $page]);
  499.     }
  500.     public function addProductVariation(Request $request) {
  501.         $em $this->getDoctrine()->getManager();
  502.         $id $request->get("id");
  503.         $prod $em->getRepository(Products::class)->find($id);
  504.         $parent_products $em->createQueryBuilder()->select('p')
  505.                 ->from("App\Entity\Products""p")
  506.                 ->where("(p.parent=0 ) and p.status=1")
  507.                 ->orderBy("p.name""ASC")
  508.                 ->getQuery()
  509.                 ->getResult();
  510.         $product_attr $em->getRepository(ProductAttributes::class)->findBy(array("productId" => $id));
  511.         $atrib = array();
  512.         foreach ($product_attr as $pa) {
  513.             $atrib[] = $pa->getAttributeId();
  514.         }
  515.         $attr $em->getRepository(Attributes::class)->findAll();
  516.         $cats $em->getRepository(Categorias::class)->findAll();
  517.         $product_cats $em->getRepository(\App\Entity\ProductCats::class)->findBy(array("productId" => $id));
  518.         $c_cats = array();
  519.         foreach ($product_cats as $c) {
  520.             $c_cats[] = $c->getCatId();
  521.         }
  522.         
  523.         $marcas =  $em->createQueryBuilder()->select('p')
  524.                 ->from("App\Entity\Marcas""p")
  525.                 ->where("p.status=1")
  526.                 ->getQuery()
  527.                 ->getResult();
  528.         $product_marcas $em->getRepository(\App\Entity\ProductMarca::class)->findBy(array("productId" => $id));
  529.         $c_marc = array();
  530.         foreach($product_marcas as $m){
  531.           $c_marc[] = $m->getMarcaId();
  532.         }
  533.         
  534.         return $this->render('products/addProdVariation.html.twig', array(
  535.                     "prod" => $prod,
  536.                     'parents' => $parent_products,
  537.                     'attr' => $attr,
  538.                     'c_attr' => $product_attr,
  539.                     'atrib' => $atrib,
  540.                     'cats' => $cats,
  541.                     'c_cats' => $c_cats,
  542.                     'marcas'=>$marcas,
  543.                     'c_marc'=>$c_marc
  544.         ));
  545.     }
  546.     public function viewProductVariations(Request $requestPaginatorInterface $paginator) {
  547.         $em $this->getDoctrine()->getManager();
  548.         $id $request->get("id");
  549.         $prod_parent $em->getRepository(Products::class)->find($id);
  550.         $prods $em->createQueryBuilder()->select("p")
  551.                         ->from("App\Entity\Products""p")
  552.                         ->where("p.id <> '' and p.status > 0 and p.parent=" $id)
  553.                         ->getQuery()->getResult();
  554.         $productos $paginator->paginate(
  555.                 $prods$request->query->getInt('page'1), 20);
  556.         return $this->render('products/listVariations.html.twig', array(
  557.                     'productos' => $productos,
  558.                     'prod' => $prod_parent
  559.         ));
  560.     }
  561.     /*
  562.      * Attributes functions
  563.      */
  564.     public function indexAtributes(Request $requestPaginatorInterface $paginator) {
  565.         $em $this->getDoctrine()->getManager();
  566.         $attr_new = new Attributes();
  567.         $form $this->createForm(AttributosType::class, $attr_new, ['save_lbl' => "Guardar"]);
  568.         $form->handleRequest($request);
  569.         if ($form->isSubmitted()) {
  570.             $attr_new->setDatecreated(new \DateTime());
  571.             $em->persist($attr_new);
  572.             $f $em->flush();
  573.             if ($f == null) {
  574.                 $type 1;
  575.                 $status "Atributo guardado correctamente";
  576.             } else {
  577.                 $type 0;
  578.                 $status "Error al guardar el atributo";
  579.             }
  580.             $this->session->getFlashBag()->add('type'$type);
  581.             $this->session->getFlashBag()->add('status'$status);
  582.             return $this->redirectToRoute('atributos');
  583.         }
  584.         $orden = ($request->get("orden")) ? $request->get("orden") : 'DESC';
  585.         $filter = ($request->get("filter")) ? $request->get("filter") : 'id';
  586.         $attrs $em->createQueryBuilder()->select("a")
  587.                         ->from("App\Entity\Attributes""a")
  588.                         ->where("a.id <> ''")
  589.                         ->orderBy("a." $filter$orden)
  590.                         ->getQuery()->getResult();
  591.         $atributos $paginator->paginate(
  592.                 $attrs$request->query->getInt('page'1), 20);
  593.         return $this->render('products/attributes/list.html.twig', array(
  594.                     'atributos' => $atributos,
  595.                     'orden' => $orden,
  596.                     'form' => $form->createView()
  597.         ));
  598.     }
  599.     public function addAtributeValues(Request $request) {
  600.         $em $this->getdoctrine()->getManager();
  601.         $values $request->request->get("valores");
  602.         $id $request->request->get('id_attr');
  603.         if ($values != "") {
  604.             $valores json_encode(explode(","$values));
  605.             $atr $em->getRepository(Attributes::class)->find($id);
  606.             $atr->setValue($valores);
  607.             $em->persist($atr);
  608.             $f $em->flush();
  609.             if ($f == null) {
  610.                 $type 1;
  611.                 $status "Atributos guardados correctamente";
  612.             } else {
  613.                 $type 0;
  614.                 $status "Error al guardar atributos";
  615.             }
  616.             $this->session->getFlashBag()->add('type'$type);
  617.             $this->session->getFlashBag()->add('status'$status);
  618.             return $this->redirectToRoute('atributos');
  619.         }
  620.     }
  621.     /*
  622.      * Categorias functions
  623.      */
  624.     public function indexCategorias(Request $requestPaginatorInterface $paginator) {
  625.         $em $this->getDoctrine()->getManager();
  626.         $orden = ($request->get("orden")) ? $request->get("orden") : 'DESC';
  627.         //$cats = $em->getRepository(\App\Entity\Categorias::class)->findAll();
  628.         
  629.         $cats $em->createQueryBuilder()->select("c")
  630.             ->from("App\Entity\Categorias""c")
  631.             ->where("c.id <> '' and c.status > 0")
  632.             ->getQuery()->getResult();
  633.         
  634.         $pagination $paginator->paginate(
  635.                 $cats$request->query->getInt('page'1), 20);
  636.                 
  637.         $cat_new = new Categorias();
  638.         $p_cats $em->getRepository(Categorias::class)->findBy(array('parent'=>0));
  639.         $parents = ["Ninguna"=>0];
  640.         foreach($p_cats as $cat){
  641.             if ($cat->getStatus() != '0')
  642.             $parents[$cat->getNombre()]=$cat->getId();
  643.         }
  644.         
  645.         $form $this->createForm(CategoriasType::class,$cat_new, [
  646.             'save_lbl'=>"Guardar",
  647.             'parents'=>$parents
  648.         ]);
  649.         
  650.         $form->handleRequest($request);
  651.         
  652.         if($form->isSubmitted()){
  653.             $cat_new->setIdWp('');
  654.             $cat_new->setParentWp('');
  655.             $cat_new->setStatus('1');
  656.             
  657.             $em->persist($cat_new);
  658.             $f $em->flush();
  659.             if($f == null){
  660.                 $type 1;
  661.                 $status "Categoría guardada correctamente";
  662.             }else{
  663.                 $type 0;
  664.                 $status "Error al guardar categoría";
  665.             }
  666.             $this->session->getFlashBag()->add('type'$type);
  667.             $this->session->getFlashBag()->add('status'$status);
  668.             return $this->redirectToRoute('categorias');
  669.         }
  670.         
  671.         return $this->render('products/categories/list.html.twig', array(
  672.                     "cats" => $pagination,
  673.                     'orden' => $orden,
  674.                     'form'=>$form->createView()
  675.         ));
  676.     }
  677.     
  678.     public function categoryEditForm(Request $request) {
  679.         
  680.         $em $this->getDoctrine()->getManager();
  681.         
  682.         $id $request->request->get('id');
  683.         
  684.         $cat $em->getRepository(Categorias::class)->findBy(['id' => $id]);
  685.         $cats $em->createQueryBuilder()->select("c")
  686.             ->from("App\Entity\Categorias""c")
  687.             ->where("c.id <> '' and c.status > 0")
  688.             ->getQuery()->getResult();
  689.         
  690.         
  691.         
  692.         return $this->render('products/categories/editForm.html.twig', array(
  693.                     "id" => $id,
  694.                     "cat" => $cat[0],
  695.                     "cats" => $cats,
  696.         ));
  697.     }
  698.     
  699.     public function categoryEdit(Request $request) {
  700.         
  701.         //dd($request->request);
  702.         $em $this->getDoctrine()->getManager();
  703.         $data $request->request->all();
  704.         
  705.         $cat $em->getRepository(Categorias::class)->find($data['id']);
  706.         
  707.         if($data && $cat && $data['nombre']){
  708.             
  709.             $cat->setNombre($data['nombre']); 
  710.             $cat->setParent($data['padre']);
  711.             
  712.             $em->persist($cat);
  713.             $f $em->flush();
  714.             
  715.             if($f == null){
  716.                 $type 1;
  717.                 $status "Categoría editada correctamente";
  718.             }else{
  719.                 $type 0;
  720.                 $status "Error al editar la categoría";
  721.             } 
  722.         } else {
  723.             $type 0;
  724.             $status "Datos incorrectos o no se encontro la categoría";
  725.         }
  726.         $this->session->getFlashBag()->add('type'$type);
  727.         $this->session->getFlashBag()->add('status'$status);
  728.         
  729.         return $this->redirectToRoute('categorias');
  730.     }
  731.     
  732.     public function categoryDelete(Request $request) {
  733.         
  734.         if (!$this->getUser() || !is_object($this->getUser())) {
  735.             return $this->redirectToRoute('logout');
  736.         }
  737.         
  738.         $em $this->getDoctrine()->getManager();
  739.         $id $request->query->get('id');
  740.         
  741.         $cat $em->getRepository(Categorias::class)->find($id);
  742.         
  743.         if($id && $cat){
  744.             $cat->setStatus(0);
  745.             $em->persist($cat);
  746.             $f $em->flush();
  747.             if($f == null){
  748.                 $type 1;
  749.                 $status "Categoría eliminada correctamente";
  750.             }else{
  751.                 $type 0;
  752.                 $status "Error al eliminar la categoría";
  753.             }
  754.         } else {
  755.             $type 0;
  756.             $status "Datos incorrectos o no se encontro la categoría";
  757.         }
  758.         $this->session->getFlashBag()->add('type'$type);
  759.         $this->session->getFlashBag()->add('status'$status);
  760.         
  761.         return $this->redirectToRoute('categorias');
  762.     }
  763.     public function SyncCatsWP(Request $request) {
  764.         $em $this->getDoctrine()->getManager();
  765.         $api = new WCController();
  766.         $return $request->get("return");
  767.         $cats $api->getProductCats();
  768.         foreach ($cats as $cat) {
  769.             if (!is_object($cat)) {
  770.                 dd($cat);
  771.             }
  772.             $cate $em->getRepository(Categorias::class)->findOneBy(array('idWp' => $cat->id));
  773.             if (!$cate) {
  774.                 $cate = new Categorias();
  775.             }
  776.             $cate->setIdWp($cat->id);
  777.             $cate->setNombre($cat->name);
  778.             if ($cat->parent == 0) {
  779.                 $cate->setParent($cat->parent);
  780.             } else {
  781.                 $parent_cat $em->getRepository(Categorias::class)->findOneBy(array('idWp' => $cat->parent));
  782.                 if ($parent_cat) {
  783.                     $cate->setParent($parent_cat->getId());
  784.                 } else {
  785.                     $cate->setParent(0);
  786.                 }
  787.             }
  788.             $cate->setParentWp($cat->parent);
  789.             $em->persist($cate);
  790.             $em->flush();
  791.         }
  792.         if ($return == 1) {
  793.             $this->session->getFlashBag()->add('type'1);
  794.             $this->session->getFlashBag()->add('status'"Categorías sincronizadas");
  795.             return $this->redirectToRoute('categorias');
  796.         } else {
  797.             dd($cats);
  798.         }
  799.     }
  800.     public function SyncBrandsWP(Request $request) {
  801.         $api = new WCController();
  802.         $brands $api->getProductBrands();
  803.         dd($brands);
  804.     }
  805.     /*
  806.      * Proveedores functions
  807.      */
  808.     public function proveedoresIndex(Request $requestPaginatorInterface $paginator) {
  809.         if (!$this->getUser() || !is_object($this->getUser())) {
  810.             return $this->redirectToRoute('logout');
  811.         }
  812.         $s = ($request->get("s") ) ? $request->get("s") : "";
  813.         $s_str "";
  814.         if ($s) {
  815.             $s_str " AND p.name LIKE '%" $s "%' OR p.email LIKE '%" $s "%'";
  816.         }
  817.         $orden = ($request->get("orden")) ? $request->get("orden") : 'DESC';
  818.         $filter = ($request->get("filter")) ? $request->get("filter") : 'id';
  819.         $em $this->getDoctrine()->getManager();
  820.         $proveedores $em->createQueryBuilder()->select("p")
  821.                 ->from("App\Entity\Proveedores""p")
  822.                 ->where("p.id <> ''")
  823.                 ->orderBy("p." $filter$orden)
  824.                 ->getQuery()
  825.                 ->getResult();
  826.         $provs $paginator->paginate(
  827.                 $proveedores$request->query->getInt('page'1), 20);
  828.         $new_p = new Proveedores();
  829.         $form $this->createForm(ProveedoresType::class, $new_p, [
  830.             'save_lbl' => "Guardar"
  831.         ]);
  832.         $form->handleRequest($request);
  833.         if ($form->isSubmitted()) {
  834.             $new_p->setDatecreated(new \DateTime());
  835.             $em->persist($new_p);
  836.             $f $em->flush();
  837.             if ($f == null) {
  838.                 $type 1;
  839.                 $status "Proveedor guardado correctamente";
  840.             } else {
  841.                 $type 0;
  842.                 $status "Error al guardar el proveedor";
  843.             }
  844.             $this->session->getFlashBag()->add('type'$type);
  845.             $this->session->getFlashBag()->add('status'$status);
  846.             return $this->redirectToRoute('proveedores');
  847.         }
  848.         return $this->render('products/proveedores/index.html.twig', array(
  849.                     "s" => $s,
  850.                     "proveedores" => $provs,
  851.                     'orden' => $orden,
  852.                     'form' => $form->createView()
  853.         ));
  854.     }
  855.     public function deleteProveedor(Request $request) {
  856.         $id $request->get("id");
  857.         $em $this->getDoctrine()->getManager();
  858.         $provee $em->getRepository(Proveedores::class)->find($id);
  859.         if ($provee) {
  860.             $em->remove($provee);
  861.             $f $em->flush();
  862.             if ($f == null) {
  863.                 $type 1;
  864.                 $status "Proveedor eliminado correctamente";
  865.             } else {
  866.                 $type 0;
  867.                 $status "Error al eliminar el proveedor";
  868.             }
  869.             $this->session->getFlashBag()->add('type'$type);
  870.             $this->session->getFlashBag()->add('status'$status);
  871.             return $this->redirectToRoute('proveedores');
  872.         }
  873.     }
  874.     public function editProveedor(Request $request) {
  875.         $id $request->get("id");
  876.         $em $this->getDoctrine()->getManager();
  877.         $prove $em->getRepository(Proveedores::class)->find($id);
  878.         $form $this->createForm(ProveedoresType::class, $prove, [
  879.             'save_lbl' => "Guardar"
  880.         ]);
  881.         $form->handleRequest($request);
  882.         if ($form->isSubmitted()) {
  883.             $em->persist($prove);
  884.             $f $em->flush();
  885.             if ($f == null) {
  886.                 $type 1;
  887.                 $status "Proveedor editado correctamente";
  888.             } else {
  889.                 $type 0;
  890.                 $status "Error al editar el proveedor";
  891.             }
  892.             $this->session->getFlashBag()->add('type'$type);
  893.             $this->session->getFlashBag()->add('status'$status);
  894.             return $this->redirectToRoute('proveedores');
  895.         }
  896.         return $this->render('products/proveedores/edit.html.twig', array(
  897.                     'id' => $id,
  898.                     'form' => $form->createView()
  899.         ));
  900.     }
  901.     public function proveedorAlbaranes(Request $requestPaginatorInterface $paginator) {
  902.         if (!$this->getUser() || !is_object($this->getUser())) {
  903.             return $this->redirectToRoute('logout');
  904.         }
  905.         $s = ($request->get("s") ) ? $request->get("s") : "";
  906.         $s_str "";
  907.         if ($s) {
  908.             $s_str " AND a.num_albaran LIKE '%" $s "%'";
  909.         }
  910.         $orden = ($request->get("orden")) ? $request->get("orden") : 'DESC';
  911.         $filter = ($request->get("filter")) ? $request->get("filter") : 'id';
  912.         $em $this->getDoctrine()->getManager();
  913.         $id $request->get("id");
  914.         $proveedor $em->getRepository(Proveedores::class)->find($id);
  915.         $albaranes $em->createQueryBuilder()->select("a")
  916.                 ->from("App\Entity\Albaranes""a")
  917.                 ->where("a.id_provider = " $id " " $s_str)
  918.                 ->orderBy("a." $filter$orden)
  919.                 ->getQuery()
  920.                 ->getResult();
  921.         $provs $paginator->paginate(
  922.                 $albaranes$request->query->getInt('page'1), 20);
  923.                 
  924.         $uploads $em->createQueryBuilder()->select("p")
  925.                 ->from("App\Entity\ProductUploads""p")
  926.                 ->where("p.proveedorId = " $id " " $s_str)
  927.                 ->getQuery()
  928.                 ->getResult();
  929.         return $this->render('products/proveedores/albaranes.html.twig', array(
  930.                     'id' => $id,
  931.                     'albaranes' => $provs,
  932.                     'proveedor' => $proveedor,
  933.                     "s" => $s,
  934.                     'orden' => $orden,
  935.                     'uploads' => $uploads,
  936.                         //'form'=>$form->createView()
  937.         ));
  938.     }
  939.     public function addAlbaran(Request $request) {
  940.         if (!$this->getUser() || !is_object($this->getUser())) {
  941.             return $this->redirectToRoute('logout');
  942.         }
  943.         $em $this->getDoctrine()->getManager();
  944.         $id $request->get("id");
  945.         $proveedor $em->getRepository(Proveedores::class)->find($id);
  946.         return $this->render('products/proveedores/add_albaran.html.twig', array(
  947.                     'id' => $id,
  948.                     'proveedor' => $proveedor,
  949.         ));
  950.     }
  951.     public function printLabel(Request $request) {
  952.         $em $this->getDoctrine()->getManager();
  953.         $id $request->request->get("id");
  954.         $prod $em->getRepository(Products::class)->find($id);
  955.         $barcode = new BarcodeGenerator();
  956.         $barcode->setText($prod->getSku());
  957.         $barcode->setType(BarcodeGenerator::Code128);
  958.         $barcode->setScale(2);
  959.         $barcode->setThickness(25);
  960.         $barcode->setFontSize(10);
  961.         $code $barcode->generate();
  962.         return $this->render('products/label.html.twig', array(
  963.                     'id' => $id,
  964.                     'prod' => $prod,
  965.                     'code' => $code
  966.         ));
  967.     }
  968.     public function addNewProductAjax(Request $request) {
  969.         $em $this->getDoctrine()->getManager();
  970.         $data $request->request->get("form");
  971.         $prod = new Products();
  972.         $prod->setCostPrice(0);
  973.         $prod->setDateCreated(new \DateTime());
  974.         $prod->setDescription("");
  975.         $prod->setDateModify(new \DateTime());
  976.         $prod->setDiscount(0);
  977.         $prod->setDiscountFrom(null);
  978.         $prod->setDiscountTo(null);
  979.         $prod->setEan("");
  980.         $prod->setGlobalStock($data[3]["value"]);
  981.         $prod->setImage("");
  982.         $prod->setName($data[0]["value"]);
  983.         $prod->setParent(0);
  984.         $prod->setPrice($data[2]["value"]);
  985.         $prod->setSku($data[1]["value"]);
  986.         $prod->setStatus(1);
  987.         $prod->setStoreDiscount(0);
  988.         $prod->setStoreStock($data[3]["value"]);
  989.         $prod->setWebDiscount(0);
  990.         $prod->setWpId(null);
  991.         $prod->setWpStock(0);
  992.         $prod->setIva(21);
  993.         $em->persist($prod);
  994.         $f $em->flush();
  995.         if ($f == null) {
  996.             return new JsonResponse(array("ok" => true"sku" => $prod->getSku()));
  997.         } else {
  998.             return new JsonResponse(array("ok" => false));
  999.         }
  1000.     }
  1001.     public function getAlbaranesLine(Request $request) {
  1002.         $em $this->getDoctrine()->getManager();
  1003.         $id $request->request->get("id");
  1004.         $prod $em->getRepository(Products::class)->find($id);
  1005.         return $this->render('products/proveedores/albaranLineTable.html.twig', array(
  1006.                     'prod' => $prod,
  1007.         ));
  1008.     }
  1009.     public function UpdateAllProductsToWp(Request $request) {
  1010.         $em $this->getDoctrine()->getManager();
  1011.         $products $em->createQueryBuilder()->select("p")
  1012.                 ->from(Products::class, "p")
  1013.                 ->where("p.wpId IS NOT NULL AND p.wpId <> '' and p.sku > 3627")
  1014.                 ->getQuery()
  1015.                 ->getResult();
  1016.                 //dd($products);
  1017.             //creem tots els productes
  1018.             foreach ($products as $product) {
  1019.                 $product->setWpId(null);
  1020.                 
  1021.                 $this->api->addProductToWP($product$em);
  1022.                 //die();
  1023.                 
  1024.             }
  1025.         return new JsonResponse(array("ok" => true));
  1026.     }
  1027.     
  1028.     public function choice(Request $request) {
  1029.         
  1030.         if (!$this->getUser() || !is_object($this->getUser())) {
  1031.             return $this->redirectToRoute('logout');
  1032.         }
  1033.         $em $this->getDoctrine()->getManager();
  1034.         $id $request->get("id");
  1035.         $proveedor $em->getRepository(Proveedores::class)->find($id);
  1036.         
  1037.         return $this->render('products/proveedores/choice.html.twig', array(
  1038.                     'id' => $id,
  1039.                     'proveedor' => $proveedor,
  1040.         ));
  1041.     }
  1042.     
  1043.     public function volcar(Request $request) {
  1044.         
  1045.         if (!$this->getUser() || !is_object($this->getUser())) {
  1046.             return $this->redirectToRoute('logout');
  1047.         }
  1048.         $em $this->getDoctrine()->getManager();
  1049.         $id $request->get("id");
  1050.         $proveedor $em->getRepository(Proveedores::class)->find($id);
  1051.         
  1052.         return $this->render('products/proveedores/volcar.html.twig', array(
  1053.                     'id' => $id,
  1054.                     'proveedor' => $proveedor,
  1055.         ));
  1056.     }
  1057.     
  1058.     public function saveFiles(Request $request): response {
  1059.         
  1060.         if (!$this->getUser() || !is_object($this->getUser())) {
  1061.             return $this->redirectToRoute('logout');
  1062.         }
  1063.         $em $this->getDoctrine()->getManager();
  1064.         $id $request->get("proveedor_id");
  1065.         
  1066.         $images $request->files->get("imgs");
  1067.         $file $request->files->get("file");
  1068.         
  1069.         // UPLOAD IMAGES
  1070.         $newImagesFileName NULL;
  1071.         if ($images) {
  1072.             if ($images->guessExtension() == "zip") {
  1073.                 $originalImagesFilename pathinfo($images->getClientOriginalName(), PATHINFO_FILENAME);
  1074.                 $safeImagesFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()'$originalImagesFilename);
  1075.                 $newImagesFileName $safeImagesFilename "-product" uniqid() . "." $images->guessExtension();
  1076.                 try {
  1077.                     $images->move(
  1078.                         'assets/images/products/',
  1079.                         $newImagesFileName
  1080.                     );
  1081.                 } catch (FileException $e) {
  1082.                     var_dump($e);
  1083.                     die();
  1084.                 }
  1085.             } else {
  1086.                 $type 0;
  1087.                 $status "Formato de imágenes incorrecto. Asegúrese de subir un archivo comprimido .zip";
  1088.                 $this->session->getFlashBag()->add('type'$type);
  1089.                 $this->session->getFlashBag()->add('status'$status);
  1090.                 return $this->redirectToRoute('proveedor_volcar', [ 'id' => $id ]);
  1091.             }
  1092.         }
  1093.         
  1094.         //UPLOAD FILE
  1095.         $extension "";
  1096.         if ($file != null) { $extension '.'.$file->getClientOriginalExtension();}
  1097.         if ($file && $extension == ".csv") {
  1098.             
  1099.             $originalFilename pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  1100.             $safeFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()'$originalFilename);
  1101.             $newFileName $safeFilename "-product" uniqid() . $extension;
  1102.             
  1103.             try {
  1104.                 $file->move(
  1105.                     'assets/files/products/',
  1106.                     $newFileName
  1107.                 );
  1108.             } catch (FileException $e) {
  1109.                 var_dump($e);
  1110.                 die();
  1111.             }
  1112.             
  1113.         } else {
  1114.             
  1115.             $type 0;
  1116.             $status "Archivo .csv no seleccionado o formato incorrecto";
  1117.             
  1118.             $this->session->getFlashBag()->add('type'$type);
  1119.             $this->session->getFlashBag()->add('status'$status);
  1120.             
  1121.             return $this->redirectToRoute('proveedor_volcar', [ 'id' => $id ]);
  1122.             
  1123.         } 
  1124.         
  1125.         $productUploads = new ProductUploads();
  1126.         
  1127.         $productUploads->setProveedorId($request->get("proveedor_id"));
  1128.         $productUploads->setFile($newFileName);
  1129.         if ($newImagesFileName != NULL) {
  1130.         $productUploads->setImages($newImagesFileName);
  1131.         } else {
  1132.             $productUploads->setImages("null");
  1133.         }
  1134.         
  1135.         $em->persist($productUploads);
  1136.         $em->flush();
  1137.         
  1138.         $prodUploadsId $productUploads->getId();
  1139.         
  1140.         return $this->redirectToRoute('proveedor_selectRows', [ 'id' => $prodUploadsId ]);
  1141.     }
  1142.     
  1143.     public function selectRows(Request $request){
  1144.         
  1145.         if (!$this->getUser() || !is_object($this->getUser())) {
  1146.             return $this->redirectToRoute('logout');
  1147.         }
  1148.         
  1149.         $em $this->getDoctrine()->getManager();
  1150.         $id $request->get("id");
  1151.         $prodUploads $em->getRepository(ProductUploads::class)->find($id);
  1152.         $proveedorId $prodUploads->getProveedorId();
  1153.         $proveedor $em->getRepository(Proveedores::class)->find($proveedorId);
  1154.         
  1155.         $order $em->createQueryBuilder()->select("o.rowsOrder")
  1156.                 ->from(ProveedorOrder::class, "o")
  1157.                 ->where("o.proveedorId = '$proveedorId'")
  1158.                 ->orderBy("o.id""DESC"// Ordena por ID en orden descendente
  1159.                 ->setMaxResults(1)
  1160.                 ->getQuery()
  1161.                 ->getOneOrNullResult();
  1162.         
  1163.         $arrayOrder = (array) null;
  1164.         if ($order) {
  1165.             
  1166.             $arrayOrder json_decode($order['rowsOrder']);
  1167.           
  1168.         }
  1169.         
  1170.         
  1171.         $file $prodUploads->getFile();
  1172.         $filePath 'assets/files/products/' $file;
  1173.         
  1174.         // CSV Decoder
  1175.         $csvEncoder = new CsvEncoder();
  1176.         $values $csvEncoder->decode(file_get_contents($filePath), 'csv',[CsvEncoder::DELIMITER_KEY => ';']);
  1177.         //dd(count($values[0]));
  1178.         if (count($values[0]) == 1) {
  1179.             $values $csvEncoder->decode(file_get_contents($filePath), 'csv',[CsvEncoder::DELIMITER_KEY => ',']);
  1180.         }
  1181.         
  1182.         // Save only array keys (first colum)
  1183.         $columnNames array_keys($values[0]);
  1184.         
  1185.         return $this->render('products/proveedores/selectRows.html.twig', array(
  1186.             'rows' => $columnNames,
  1187.             'proveedor' => $proveedor,
  1188.             'prod_uploads_id' => $id,
  1189.             'order' => $arrayOrder,
  1190.         ));
  1191.     }
  1192.     
  1193.     public function saveOrder(Request $request) {
  1194.         
  1195.         if (!$this->getUser() || !is_object($this->getUser())) {
  1196.             return $this->redirectToRoute('logout');
  1197.         }
  1198.         
  1199.         $em $this->getDoctrine()->getManager();
  1200.         $proveedorId $request->get("proveedor_id");
  1201.         $prodUploadsId $request->get("prod_uploads_id");
  1202.         $rows $request->get("product");
  1203.         
  1204.         //Si mantenen el valor per defecte del formulari ho cambia a null
  1205.         for ($i 0$i <= 21$i++) {
  1206.             if ($rows[$i] == "Seleccionar columna") {
  1207.                 $rows[$i] = "null";
  1208.             }
  1209.         }
  1210.         
  1211.         $stringRows json_encode($rows);
  1212.         
  1213.         $proveedorOrder = new ProveedorOrder();
  1214.         $proveedorOrder->setProveedorId($proveedorId);
  1215.         $proveedorOrder->setRowsOrder($stringRows);
  1216.         $proveedorOrder->setProductUploadId($prodUploadsId);
  1217.         $em->persist($proveedorOrder);
  1218.         $em->flush();
  1219.         
  1220.         //MUNTAR PRODUCTES
  1221.         
  1222.         //CARREGAR EL FILE I IMAGES
  1223.         $prodUploads $em->getRepository(ProductUploads::class)->find($prodUploadsId);
  1224.         $file $prodUploads->getFile();
  1225.         $images $prodUploads->getImages();
  1226.         
  1227.         $filePath 'assets/files/products/' $file;
  1228.         $imagePath 'assets/images/products/' $images;
  1229.         $savePath 'assets/images/products/';
  1230.         
  1231.         // CSV Decoder
  1232.         $csvEncoder = new CsvEncoder();
  1233.         $values $csvEncoder->decode(file_get_contents($filePath), 'csv',[CsvEncoder::DELIMITER_KEY => ';']); //posar el ';'
  1234.         if (count($values[0]) == 1) {
  1235.             $values $csvEncoder->decode(file_get_contents($filePath), 'csv',[CsvEncoder::DELIMITER_KEY => ',']);
  1236.         }
  1237.         //DESCOMPRIMIR LES IMATGES I BORRAR EL ZIP
  1238.         
  1239.         $zip = new \ZipArchive();
  1240.         if ($zip->open($imagePath) === TRUE) {
  1241.             $zip->extractTo($savePath);
  1242.             $zip->close();
  1243.         }
  1244.         
  1245.         foreach ($values as $key => $value) {
  1246.                 
  1247.             //$orderedValue = array_merge(array_flip($rows), $value);
  1248.             $index = [];
  1249.             foreach ($rows as $clave) {
  1250.                 $index[] = isset($value[$clave]) ? $value[$clave] : null;
  1251.             }
  1252.             $sku = array("sku" => "$index[2]");
  1253.             $product $em->getRepository(Products::class)->findOneBy($sku);
  1254.             
  1255.             if (isset($index[0]) && $index[0] !== "") {
  1256.                 
  1257.                 if (!isset($product) && $product == "") {
  1258.                     $product = new Products();
  1259.                     $product->setDateCreated(new \DateTime());
  1260.                 }
  1261.                 //convert parent id into int
  1262.                 $parentIdInt = (int)$index[7];
  1263.                 //Setters
  1264.                 $product->setName(($index[0])?$index[0] : '');
  1265.                 $product->setEan(($index[1])?$index[1] : '');
  1266.                 if ($index[2] != null || $index[2] != "") {
  1267.                     $product->setSku($index[2]);
  1268.                 } else {
  1269.                     //Generate sku
  1270.                     $genSkuJson $this->generateAutoSku();
  1271.                     $content $genSkuJson->getContent();
  1272.                     $data json_decode($contenttrue);
  1273.                     if ($sku["sku"] == null || $sku["sku"] == "") {
  1274.                         $product->setSku($data["sku"]);
  1275.                         } else {
  1276.                             $product->setSku($index[2]);
  1277.                     }
  1278.                 }
  1279.                 $product->setDescription(($index[3])?$index[3] : '');
  1280.                 $product->setPrice(($index[4])?floatval(str_replace(",",".",$index[4])) : 0);
  1281.                 $product->setIva(($index[5])?floatval($index[5]) : 0);
  1282.                 //$product->setDateCreated(new \DateTime());
  1283.                 $product->setParent((isset($parentIdInt) ? $parentIdInt 0));
  1284.                 //wpId = $index[8]
  1285.                 $images explode(",",$index[9]);
  1286.                 if($images){
  1287.                     $product->setImage($images[0]);
  1288.                 }
  1289.                 $product->setCostPrice((isset($index[10]) ? floatval($index[10]) : 0));
  1290.                 $product->setDateModify(new \DateTime());
  1291.                 //globalStock = $index[12]
  1292.                 $product->setWpStock((isset($index[13]) ? floatval($index[13]) : 0));
  1293.                 $product->setStoreStock((isset($index[14]) ? floatval($index[14]) : 0));
  1294.                 ////discount = $index[15]
  1295.                 if ($index[16] != "") {
  1296.                     $disc_from = \DateTime::createFromFormat('d/m/Y'$index[16]);
  1297.                     $product->setDiscountFrom($disc_from);
  1298.                 } else {
  1299.                     $product->setDiscountFrom(null);
  1300.                 }
  1301.                 if ($index[17] != "") {
  1302.                     $disc_to = \DateTime::createFromFormat('d/m/Y'$index[17]);
  1303.                     $product->setDiscountTo($disc_to);
  1304.                 } else {
  1305.                     $product->setDiscountTo(null);
  1306.                 }
  1307.                 $product->setStoreDiscount(($index[18] != "") ? $index[18] : );
  1308.                 $product->setWebDiscount(($index[19] != "") ? $index[19] : 0);
  1309.                 //$product->setGlobalStock(floatval($index[14]) + floatval($index[13]));
  1310.                 $product->setGlobalStock((isset($index[14]) ? floatval($index[14]) : 0));
  1311.                 $product->setStatus(1);
  1312.                 $em->persist($product);
  1313.                 $f $em->flush();
  1314.             }
  1315.         }
  1316.         
  1317.         if ($f == null) {
  1318.             $type 1;
  1319.             $status "Albaran subido correctamente";
  1320.         } else {
  1321.             $type 0;
  1322.             $status "Error al guardar el Albaran";
  1323.         }
  1324.         $this->session->getFlashBag()->add('type'$type);
  1325.         $this->session->getFlashBag()->add('status'$status);
  1326.         
  1327.         return $this->redirectToRoute('proveedor_albaranes', [ 'id' => $proveedorId ]);
  1328.     }
  1329. }