<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Knp\Component\Pager\PaginatorInterface;
use App\Entity\Products;
use App\Entity\Attributes;
use App\Form\AttributosType;
use App\Entity\ProductAttributes;
use App\Controller\WCController;
use App\Entity\Categorias;
use App\Entity\Marcas;
use App\Entity\Proveedores;
use App\Form\ProveedoresType;
use App\Entity\Albaranes;
use App\Entity\ProductMarca;
use App\Entity\ProductUploads;
use App\Entity\ProveedorOrder;
use CodeItNow\BarcodeBundle\Utils\BarcodeGenerator;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use App\Form\CategoriasType;
/**
* Description of ProductsController
*
* @author joseangelparra
*/
class ProductsController extends AbstractController {
private $params;
private $api;
public function __construct(ParameterBagInterface $params) {
$this->session = new Session();
$this->params = $params;
$this->api = new WCController();
}
public function index(Request $request, PaginatorInterface $paginator) {
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$em = $this->getDoctrine()->getManager();
$s = ($request->get("s") ) ? $request->get("s") : "";
$s_str = "";
if ($s) {
$s_str = " AND p.name LIKE '%" . $s . "%' OR p.ean LIKE '%" . $s . "%' OR p.sku LIKE '%" . $s . "%'";
}
$orden = ($request->get("orden")) ? $request->get("orden") : 'DESC';
$filter = ($request->get("filter")) ? $request->get("filter") : 'id';
$prods = $em->createQueryBuilder()->select("p")
->from("App\Entity\Products", "p")
->where("p.id <> '' and p.status > 0 and p.parent= 0" . $s_str)
->orderBy("p." . $filter, $orden)
->getQuery()->getResult();
$productos = $paginator->paginate(
$prods, ($request->query->getInt('page')>0) ? $request->query->getInt('page', 1) : 1, 20);
/*$productos = $paginator->paginate(
$prods, $request->query->getInt('page', 1), 20);
*/
return $this->render('products/list.html.twig', array(
'productos' => $productos,
's' => $s,
'orden' => $orden
));
}
public function addProduct(Request $request) {
$page = $request->get("page");
$em = $this->getDoctrine()->getManager();
$parent_products = $em->createQueryBuilder()->select('p')
->from("App\Entity\Products", "p")
->where("(p.parent=0 ) and p.status=1")
->orderBy("p.name", "ASC")
->getQuery()
->getResult();
$attr = $em->getRepository(Attributes::class)->findAll();
$cats = $em->getRepository(Categorias::class)->findAll();
$marcas = $em->createQueryBuilder()->select('p')
->from("App\Entity\Marcas", "p")
->where("p.status=1")
->getQuery()
->getResult();
return $this->render('products/add.html.twig', array(
'parents' => $parent_products,
'attr' => $attr,
'cats' => $cats,
'page' => $page,
'marcas'=>$marcas
));
}
public function getAttributesConfig(Request $request) {
$id = $request->get("id");
$em = $this->getDoctrine()->getManager();
$attr = $em->getRepository(Attributes::class)->find($id);
return $this->render('products/_parts/attrConfig.html.twig', array(
'attr' => $attr
));
}
public function storeProduct(Request $request) {
$page = $request->get("page");
$em = $this->getDoctrine()->getManager();
$info = $request->request->all();
//dd($info);
if (isset($info["id"]) && $info["id"] != "") {
$product = $em->getRepository(Products::class)->find($info["id"]);
$prod_image = $product->getImage();
} else {
$product = new Products();
$product->setDateCreated(new \DateTime());
$prod_image = "";
}
//seteamos
$product->setName($info["name"]);
$product->setSku($info["sku"]);
$product->setEan($info["ean"]);
$product->setDescription($info["description"]);
$product->setPrice(floatval($info["price"]));
$product->setIva(floatval($info["iva"]));
$product->setCostPrice($info["cost_price"]);
$product->setStoreStock($info["store_stock"]);
$product->setWpStock($info["wp_stock"]);
if ($info["discount_from"] != "") {
$disc_from = \DateTime::createFromFormat('d/m/Y', $info["discount_from"]);
$product->setDiscountFrom($disc_from);
} else {
$product->setDiscountFrom(null);
}
if ($info["discount_to"] != "") {
$disc_to = \DateTime::createFromFormat('d/m/Y', $info["discount_to"]);
$product->setDiscountTo($disc_to);
} else {
$product->setDiscountTo(null);
}
$product->setStoreDiscount(($info["store_discount"] != "") ? $info["store_discount"] : 0 );
$product->setWebDiscount(($info["web_discount"] != "") ? $info["web_discount"] : 0);
$product->setDateModify(new \DateTime());
$product->setGlobalStock(floatval($info["store_stock"]) + floatval($info["wp_stock"]));
$product->setStatus(1);
$product->setParent((isset($info["parent"]) ? $info["parent"] : 0));
//imagen
$image = $request->files->get("image");
if ($image) { //subimos la imagen
$originalFilename = pathinfo($image[0]->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFileName = $safeFilename . "-product" . uniqid() . "." . $image[0]->guessExtension();
try {
$image[0]->move(
'assets/images/products/',
$newFileName
);
} catch (FileException $e) {
var_dump($e);
die();
}
$product->setImage($newFileName);
if (count($image) > 0) {
$gal = [];
for ($i = 1; $i < count($image); $i++) {
$originalFilename = pathinfo($image[$i]->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFileName = $safeFilename . "-product" . uniqid() . "." . $image[$i]->guessExtension();
try {
$image[$i]->move(
'assets/images/products/',
$newFileName
);
} catch (FileException $e) {
var_dump($e);
die();
}
$gal[] = $newFileName;
}
$product->setGallery(json_encode($gal));
}
} else {
$product->setImage($prod_image);
}
//guardamos en local
$em->persist($product);
$f = $em->flush();
if ($f == null) {
//atributos
if (isset($info["attr"]) && $info["attr"] != "") {
//borramos los atributos actuales
$p_attr = $em->getRepository(ProductAttributes::class)->findBy(array("productId" => $product->getId()));
foreach ($p_attr as $p_at) {
$em->remove($p_at);
$em->flush();
}
foreach ($info["attr"] as $attr_id) {
$value = $info["attrib_" . $attr_id . "_value"];
$prod_attr = new ProductAttributes();
$prod_attr->setAttributeId($attr_id);
$prod_attr->setProductId($product->getId());
$prod_attr->setValue($value);
$em->persist($prod_attr);
$em->flush();
}
}
//categorÃas
if (isset($info["categoria"]) && count($info["categoria"])>0) {
foreach($info["categoria"] as $cat){
$prod_cat = new \App\Entity\ProductCats();
$prod_cat->setCatId($cat);
$prod_cat->setProductId($product->getId());
$prod_cat->setDateCreated(new \DateTime());
$em->persist($prod_cat);
$em->flush();
}
}
//marca
if(isset($info["marca"]) && $info["marca"] !=""){
$marc = new ProductMarca();
$marc->setProductId($product->getId());
$marc->setMarcaId($info["marca"]);
$em->persist($marc);
$em->flush();
}
//web
if (isset($info["web"]) && $info["web"] == "on") {
//lo enviamos a WP
$addedwp = $this->api->addProductToWP($product, $em);
}
$type = 1;
$status = "Producto guardado correctamente";
} else {
$type = 0;
$status = "Error al guardar el producto";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('productos', ['page' => $page]);
}
public function deleteProduct(Request $request) {
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$em = $this->getDoctrine()->getManager();
$pid = $request->get("id");
$page = $request->get("page");
$prod = $em->getRepository(Products::class)->find($pid);
if ($prod) {
if ($prod->getWpId() != null) {
$delete_wp = $this->api->deleteProductToWP($prod, $em);
}
//$prod->remove(0);
$em->remove($prod);
$f = $em->flush();
if ($f == null) {
$type = 1;
$status = "Producto eliminado correctamente";
} else {
$type = 0;
$status = "Error al eliminar el producto";
}
} else {
$type = 0;
$status = "Producto no encontrado";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('productos', ['page' => $page]);
}
public function generateAutoSku() {
$em = $this->getDoctrine()->getManager();
$l_prod = $em->createQueryBuilder()->select('p')
->from("App\Entity\Products", "p")
->where("p.id<>''")
->orderBy("p.id", "DESC")
->setMaxResults(1)
->getQuery()
->getResult();
if ($l_prod) {
$last_num = $l_prod[0]->getSku();
$last_num++;
} else {
$last_num = date("Y") . "00001";
}
return new JsonResponse(array('sku' => $last_num));
}
public function editProduct(Request $request) {
$em = $this->getDoctrine()->getManager();
$id = $request->get("id");
$page = $request->get("page");
$prod = $em->getRepository(Products::class)->find($id);
$parent_products = $em->createQueryBuilder()->select('p')
->from("App\Entity\Products", "p")
->where("(p.parent=0 ) and p.status=1")
->orderBy("p.name", "ASC")
->getQuery()
->getResult();
$product_attr = $em->getRepository(ProductAttributes::class)->findBy(array("productId" => $id));
$atrib = array();
foreach ($product_attr as $pa) {
$atrib[] = $pa->getAttributeId();
}
$attr = $em->getRepository(Attributes::class)->findAll();
$cats = $em->getRepository(Categorias::class)->findAll();
$product_cats = $em->getRepository(\App\Entity\ProductCats::class)->findBy(array("productId" => $id));
$c_cats = array();
foreach ($product_cats as $c) {
$c_cats[] = $c->getCatId();
}
$marcas = $marcas = $em->createQueryBuilder()->select('p')
->from("App\Entity\Marcas", "p")
->where("p.status=1")
->getQuery()
->getResult();
$product_marcas = $em->getRepository(ProductMarca::class)->findBy(array("productId"=>$id));
$c_marc = array();
foreach($product_marcas as $m){
$c_marc[] = $m->getMarcaId();
}
return $this->render('products/edit.html.twig', array(
"prod" => $prod,
'parents' => $parent_products,
'attr' => $attr,
'c_attr' => $product_attr,
'atrib' => $atrib,
'cats' => $cats,
'c_cats' => $c_cats,
'page' => $page,
'marcas'=>$marcas,
'c_marc'=>$c_marc
));
}
public function updateProduct(Request $request) {
$em = $this->getDoctrine()->getManager();
$page = $request->request->get("page");
$info = $request->request->all();
//dd($info);
if (isset($info["id"]) && $info["id"] != "") {
$product = $em->getRepository(Products::class)->find($info["id"]);
$prod_image = $product->getImage();
} else {
return false;
}
//seteamos
$product->setName($info["name"]);
$product->setSku($info["sku"]);
$product->setEan($info["ean"]);
$product->setDescription($info["description"]);
$product->setPrice(floatval($info["price"]));
$product->setIva(floatval($info["iva"]));
$product->setCostPrice($info["cost_price"]);
$product->setStoreStock($info["store_stock"]);
$product->setWpStock($info["wp_stock"]);
if ($info["discount_from"] != "") {
$disc_from = \DateTime::createFromFormat('d/m/Y', $info["discount_from"]);
$product->setDiscountFrom($disc_from);
}
if ($info["discount_to"] != "") {
$disc_to = \DateTime::createFromFormat('d/m/Y', $info["discount_to"]);
$product->setDiscountTo($disc_to);
}
$product->setStoreDiscount(($info["store_discount"] != "") ? $info["store_discount"] : 0 );
$product->setWebDiscount(($info["web_discount"] != "") ? $info["web_discount"] : 0);
$product->setDateModify(new \DateTime());
$product->setGlobalStock(floatval($info["store_stock"]) + floatval($info["wp_stock"]));
$product->setParent((isset($info["parent"]) ? $info["parent"] : 0));
//imagen
$image = $request->files->get("image");
if ($image) { //subimos la imagen
$originalFilename = pathinfo($image[0]->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFileName = $safeFilename . "-product" . uniqid() . "." . $image[0]->guessExtension();
try {
$image[0]->move(
'assets/images/products/',
$newFileName
);
} catch (FileException $e) {
var_dump($e);
die();
}
$product->setImage($newFileName);
if (count($image) > 0) {
$gal = [];
for ($i = 1; $i < count($image); $i++) {
$originalFilename = pathinfo($image[$i]->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFileName = $safeFilename . "-product" . uniqid() . "." . $image[$i]->guessExtension();
try {
$image[$i]->move(
'assets/images/products/',
$newFileName
);
} catch (FileException $e) {
var_dump($e);
die();
}
$gal[] = $newFileName;
}
$product->setGallery(json_encode($gal));
}
} else {
$product->setImage($prod_image);
}
//guardamos en local
$em->persist($product);
$f = $em->flush();
if ($f == null) {
//atributos
if (isset($info["attr"]) && $info["attr"] != "") {
//borramos los atributos actuales
$p_attr = $em->getRepository(ProductAttributes::class)->findBy(array("productId" => $product->getId()));
foreach ($p_attr as $p_at) {
$em->remove($p_at);
$em->flush();
}
foreach ($info["attr"] as $attr_id) {
$value = $info["attrib_" . $attr_id . "_value"];
$prod_attr = new ProductAttributes();
$prod_attr->setAttributeId($attr_id);
$prod_attr->setProductId($product->getId());
$prod_attr->setValue($value);
$em->persist($prod_attr);
$em->flush();
}
}
//categorÃas
$p_cats = $em->getRepository(\App\Entity\ProductCats::class)->findBy(array('productId' => $product->getId()));
foreach ($p_cats as $pc) {
$em->remove($pc);
$em->flush();
}
if (isset($info["categoria"]) && count($info["categoria"])>0) {
//borramos la actual
foreach($info["categoria"] as $cat){
$prod_cat = new \App\Entity\ProductCats();
$prod_cat->setCatId($cat);
$prod_cat->setProductId($product->getId());
$prod_cat->setDateCreated(new \DateTime());
$em->persist($prod_cat);
$em->flush();
}
}
if(isset($info["marca"]) && $info["marca"] !=""){
//borramos la actual
$p_cats = $em->getRepository(\App\Entity\ProductMarca::class)->findBy(array('productId' => $product->getId()));
foreach ($p_cats as $pc) {
$em->remove($pc);
$em->flush();
}
$marc = new ProductMarca();
$marc->setProductId($product->getId());
$marc->setMarcaId($info["marca"]);
$em->persist($marc);
$em->flush();
}
//web
if (isset($info["web"]) && $info["web"] == "on") {
if ($product->getWpId()) {
//update
$updatedwp = $this->api->updateProductToWP($product, $em);
} else {
//create
$addedwp = $this->api->addProductToWP($product, $em);
//dd($addedwp);
}
} else {
if ($product->getWpId()) {
$deleteWp = $this->api->deleteProductToWP($product, $em);
}
}
$type = 1;
$status = "Producto guardado correctamente";
} else {
$type = 0;
$status = "Error al guardar el producto";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('productos', ['page' => $page]);
}
public function addProductVariation(Request $request) {
$em = $this->getDoctrine()->getManager();
$id = $request->get("id");
$prod = $em->getRepository(Products::class)->find($id);
$parent_products = $em->createQueryBuilder()->select('p')
->from("App\Entity\Products", "p")
->where("(p.parent=0 ) and p.status=1")
->orderBy("p.name", "ASC")
->getQuery()
->getResult();
$product_attr = $em->getRepository(ProductAttributes::class)->findBy(array("productId" => $id));
$atrib = array();
foreach ($product_attr as $pa) {
$atrib[] = $pa->getAttributeId();
}
$attr = $em->getRepository(Attributes::class)->findAll();
$cats = $em->getRepository(Categorias::class)->findAll();
$product_cats = $em->getRepository(\App\Entity\ProductCats::class)->findBy(array("productId" => $id));
$c_cats = array();
foreach ($product_cats as $c) {
$c_cats[] = $c->getCatId();
}
$marcas = $em->createQueryBuilder()->select('p')
->from("App\Entity\Marcas", "p")
->where("p.status=1")
->getQuery()
->getResult();
$product_marcas = $em->getRepository(\App\Entity\ProductMarca::class)->findBy(array("productId" => $id));
$c_marc = array();
foreach($product_marcas as $m){
$c_marc[] = $m->getMarcaId();
}
return $this->render('products/addProdVariation.html.twig', array(
"prod" => $prod,
'parents' => $parent_products,
'attr' => $attr,
'c_attr' => $product_attr,
'atrib' => $atrib,
'cats' => $cats,
'c_cats' => $c_cats,
'marcas'=>$marcas,
'c_marc'=>$c_marc
));
}
public function viewProductVariations(Request $request, PaginatorInterface $paginator) {
$em = $this->getDoctrine()->getManager();
$id = $request->get("id");
$prod_parent = $em->getRepository(Products::class)->find($id);
$prods = $em->createQueryBuilder()->select("p")
->from("App\Entity\Products", "p")
->where("p.id <> '' and p.status > 0 and p.parent=" . $id)
->getQuery()->getResult();
$productos = $paginator->paginate(
$prods, $request->query->getInt('page', 1), 20);
return $this->render('products/listVariations.html.twig', array(
'productos' => $productos,
'prod' => $prod_parent
));
}
/*
* Attributes functions
*/
public function indexAtributes(Request $request, PaginatorInterface $paginator) {
$em = $this->getDoctrine()->getManager();
$attr_new = new Attributes();
$form = $this->createForm(AttributosType::class, $attr_new, ['save_lbl' => "Guardar"]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$attr_new->setDatecreated(new \DateTime());
$em->persist($attr_new);
$f = $em->flush();
if ($f == null) {
$type = 1;
$status = "Atributo guardado correctamente";
} else {
$type = 0;
$status = "Error al guardar el atributo";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('atributos');
}
$orden = ($request->get("orden")) ? $request->get("orden") : 'DESC';
$filter = ($request->get("filter")) ? $request->get("filter") : 'id';
$attrs = $em->createQueryBuilder()->select("a")
->from("App\Entity\Attributes", "a")
->where("a.id <> ''")
->orderBy("a." . $filter, $orden)
->getQuery()->getResult();
$atributos = $paginator->paginate(
$attrs, $request->query->getInt('page', 1), 20);
return $this->render('products/attributes/list.html.twig', array(
'atributos' => $atributos,
'orden' => $orden,
'form' => $form->createView()
));
}
public function addAtributeValues(Request $request) {
$em = $this->getdoctrine()->getManager();
$values = $request->request->get("valores");
$id = $request->request->get('id_attr');
if ($values != "") {
$valores = json_encode(explode(",", $values));
$atr = $em->getRepository(Attributes::class)->find($id);
$atr->setValue($valores);
$em->persist($atr);
$f = $em->flush();
if ($f == null) {
$type = 1;
$status = "Atributos guardados correctamente";
} else {
$type = 0;
$status = "Error al guardar atributos";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('atributos');
}
}
/*
* Categorias functions
*/
public function indexCategorias(Request $request, PaginatorInterface $paginator) {
$em = $this->getDoctrine()->getManager();
$orden = ($request->get("orden")) ? $request->get("orden") : 'DESC';
//$cats = $em->getRepository(\App\Entity\Categorias::class)->findAll();
$cats = $em->createQueryBuilder()->select("c")
->from("App\Entity\Categorias", "c")
->where("c.id <> '' and c.status > 0")
->getQuery()->getResult();
$pagination = $paginator->paginate(
$cats, $request->query->getInt('page', 1), 20);
$cat_new = new Categorias();
$p_cats = $em->getRepository(Categorias::class)->findBy(array('parent'=>0));
$parents = ["Ninguna"=>0];
foreach($p_cats as $cat){
if ($cat->getStatus() != '0')
$parents[$cat->getNombre()]=$cat->getId();
}
$form = $this->createForm(CategoriasType::class,$cat_new, [
'save_lbl'=>"Guardar",
'parents'=>$parents
]);
$form->handleRequest($request);
if($form->isSubmitted()){
$cat_new->setStatus('1');
//crear categoria a wp
$wc = new WCController();
$parent_cat_wp = 0;
if($cat_new->getParent()){
$par_cat = $em->getRepository(Categorias::class)->find($cat_new->getParent());
$parent_cat_wp = $par_cat->getIdWp();
}
$wp_cat = $wc->createCat($cat_new->getNombre(), str_replace(" ", "-", strtolower($cat_new->getNombre())), $parent_cat_wp);
//dd($wp_cat);
$cat_new->setIdWp($wp_cat->id);
$cat_new->setParentWp($wp_cat->parent);
$em->persist($cat_new);
$f = $em->flush();
if($f == null){
$type = 1;
$status = "CategorÃa guardada correctamente";
}else{
$type = 0;
$status = "Error al guardar categorÃa";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('categorias');
}
return $this->render('products/categories/list.html.twig', array(
"cats" => $pagination,
'orden' => $orden,
'form'=>$form->createView()
));
}
public function categoryEditForm(Request $request) {
$em = $this->getDoctrine()->getManager();
$id = $request->request->get('id');
$cat = $em->getRepository(Categorias::class)->findBy(['id' => $id]);
$cats = $em->createQueryBuilder()->select("c")
->from("App\Entity\Categorias", "c")
->where("c.id <> '' and c.status > 0")
->getQuery()->getResult();
return $this->render('products/categories/editForm.html.twig', array(
"id" => $id,
"cat" => $cat[0],
"cats" => $cats,
));
}
public function categoryEdit(Request $request) {
//dd($request->request);
$em = $this->getDoctrine()->getManager();
$data = $request->request->all();
$cat = $em->getRepository(Categorias::class)->find($data['id']);
if($data && $cat && $data['nombre']){
$cat->setNombre($data['nombre']);
$cat->setParent($data['padre']);
$wc = new WCController();
if($cat->getIdWp()==""){
$parent_cat_wp = 0;
if($cat->getParent()){
$par_cat = $em->getRepository(Categorias::class)->find($cat->getParent());
$parent_cat_wp = $par_cat->getIdWp();
}
$wp_cat = $wc->createCat($cat->getNombre(), str_replace(" ", "-", strtolower($cat->getNombre())), $parent_cat_wp);
$cat->setIdWp($wp_cat->id);
$cat->setParentWp($wp_cat->parent);
}else{
$parent_cat_wp = 0;
$wp_cat = $wc->updateCat($cat->getNombre(), str_replace(" ", "-", strtolower($cat->getNombre())), $cat->getParentWp(), $cat->getIdWp());
}
$em->persist($cat);
$f = $em->flush();
if($f == null){
$type = 1;
$status = "CategorÃa editada correctamente";
}else{
$type = 0;
$status = "Error al editar la categorÃa";
}
} else {
$type = 0;
$status = "Datos incorrectos o no se encontro la categorÃa";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('categorias');
}
public function categoryDelete(Request $request) {
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$em = $this->getDoctrine()->getManager();
$id = $request->query->get('id');
$cat = $em->getRepository(Categorias::class)->find($id);
if($id && $cat){
$cat->setStatus(0);
if($cat->getIdWP()!=""){
$wc = new WCController();
$del = $wc->deleteCat($cat->getIdWp());
$cat->setIdWp("");
$cat->setParentWp("");
}
$em->persist($cat);
$f = $em->flush();
if($f == null){
$type = 1;
$status = "CategorÃa eliminada correctamente";
}else{
$type = 0;
$status = "Error al eliminar la categorÃa";
}
} else {
$type = 0;
$status = "Datos incorrectos o no se encontro la categorÃa";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('categorias');
}
public function SyncCatsWP(Request $request) {
$em = $this->getDoctrine()->getManager();
$api = new WCController();
$return = $request->get("return");
$cats = $api->getProductCats();
foreach ($cats as $cat) {
if (!is_object($cat)) {
dd($cat);
}
$cate = $em->getRepository(Categorias::class)->findOneBy(array('idWp' => $cat->id));
if (!$cate) {
$cate = new Categorias();
$cate->setStatus(1);
}
$cate->setIdWp($cat->id);
$cate->setNombre($cat->name);
if ($cat->parent == 0) {
$cate->setParent($cat->parent);
} else {
$parent_cat = $em->getRepository(Categorias::class)->findOneBy(array('idWp' => $cat->parent));
if ($parent_cat) {
$cate->setParent($parent_cat->getId());
} else {
$cate->setParent(0);
}
}
$cate->setParentWp($cat->parent);
$em->persist($cate);
$em->flush();
}
if ($return == 1) {
$this->session->getFlashBag()->add('type', 1);
$this->session->getFlashBag()->add('status', "CategorÃas sincronizadas");
return $this->redirectToRoute('categorias');
} else {
dd($cats);
}
}
public function SyncBrandsWP(Request $request) {
$api = new WCController();
$brands = $api->getProductBrands();
dd($brands);
}
/*
* Proveedores functions
*/
public function proveedoresIndex(Request $request, PaginatorInterface $paginator) {
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$s = ($request->get("s") ) ? $request->get("s") : "";
$s_str = "";
if ($s) {
$s_str = " AND p.name LIKE '%" . $s . "%' OR p.email LIKE '%" . $s . "%'";
}
$orden = ($request->get("orden")) ? $request->get("orden") : 'DESC';
$filter = ($request->get("filter")) ? $request->get("filter") : 'id';
$em = $this->getDoctrine()->getManager();
$proveedores = $em->createQueryBuilder()->select("p")
->from("App\Entity\Proveedores", "p")
->where("p.id <> ''")
->orderBy("p." . $filter, $orden)
->getQuery()
->getResult();
$provs = $paginator->paginate(
$proveedores, $request->query->getInt('page', 1), 20);
$new_p = new Proveedores();
$form = $this->createForm(ProveedoresType::class, $new_p, [
'save_lbl' => "Guardar"
]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$new_p->setDatecreated(new \DateTime());
$em->persist($new_p);
$f = $em->flush();
if ($f == null) {
$type = 1;
$status = "Proveedor guardado correctamente";
} else {
$type = 0;
$status = "Error al guardar el proveedor";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('proveedores');
}
return $this->render('products/proveedores/index.html.twig', array(
"s" => $s,
"proveedores" => $provs,
'orden' => $orden,
'form' => $form->createView()
));
}
public function deleteProveedor(Request $request) {
$id = $request->get("id");
$em = $this->getDoctrine()->getManager();
$provee = $em->getRepository(Proveedores::class)->find($id);
if ($provee) {
$em->remove($provee);
$f = $em->flush();
if ($f == null) {
$type = 1;
$status = "Proveedor eliminado correctamente";
} else {
$type = 0;
$status = "Error al eliminar el proveedor";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('proveedores');
}
}
public function editProveedor(Request $request) {
$id = $request->get("id");
$em = $this->getDoctrine()->getManager();
$prove = $em->getRepository(Proveedores::class)->find($id);
$form = $this->createForm(ProveedoresType::class, $prove, [
'save_lbl' => "Guardar"
]);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$em->persist($prove);
$f = $em->flush();
if ($f == null) {
$type = 1;
$status = "Proveedor editado correctamente";
} else {
$type = 0;
$status = "Error al editar el proveedor";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('proveedores');
}
return $this->render('products/proveedores/edit.html.twig', array(
'id' => $id,
'form' => $form->createView()
));
}
public function proveedorAlbaranes(Request $request, PaginatorInterface $paginator) {
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$s = ($request->get("s") ) ? $request->get("s") : "";
$s_str = "";
if ($s) {
$s_str = " AND a.num_albaran LIKE '%" . $s . "%'";
}
$orden = ($request->get("orden")) ? $request->get("orden") : 'DESC';
$filter = ($request->get("filter")) ? $request->get("filter") : 'id';
$em = $this->getDoctrine()->getManager();
$id = $request->get("id");
$proveedor = $em->getRepository(Proveedores::class)->find($id);
$albaranes = $em->createQueryBuilder()->select("a")
->from("App\Entity\Albaranes", "a")
->where("a.id_provider = " . $id . " " . $s_str)
->orderBy("a." . $filter, $orden)
->getQuery()
->getResult();
$provs = $paginator->paginate(
$albaranes, $request->query->getInt('page', 1), 20);
$uploads = $em->createQueryBuilder()->select("p")
->from("App\Entity\ProductUploads", "p")
->where("p.proveedorId = " . $id . " " . $s_str)
->getQuery()
->getResult();
return $this->render('products/proveedores/albaranes.html.twig', array(
'id' => $id,
'albaranes' => $provs,
'proveedor' => $proveedor,
"s" => $s,
'orden' => $orden,
'uploads' => $uploads,
//'form'=>$form->createView()
));
}
public function addAlbaran(Request $request) {
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$em = $this->getDoctrine()->getManager();
$id = $request->get("id");
$proveedor = $em->getRepository(Proveedores::class)->find($id);
return $this->render('products/proveedores/add_albaran.html.twig', array(
'id' => $id,
'proveedor' => $proveedor,
));
}
public function printLabel(Request $request) {
$em = $this->getDoctrine()->getManager();
$id = $request->request->get("id");
$prod = $em->getRepository(Products::class)->find($id);
$barcode = new BarcodeGenerator();
$barcode->setText($prod->getSku());
$barcode->setType(BarcodeGenerator::Code128);
$barcode->setScale(2);
$barcode->setThickness(25);
$barcode->setFontSize(10);
$code = $barcode->generate();
return $this->render('products/label.html.twig', array(
'id' => $id,
'prod' => $prod,
'code' => $code
));
}
public function addNewProductAjax(Request $request) {
$em = $this->getDoctrine()->getManager();
$data = $request->request->get("form");
$prod = new Products();
$prod->setCostPrice(0);
$prod->setDateCreated(new \DateTime());
$prod->setDescription("");
$prod->setDateModify(new \DateTime());
$prod->setDiscount(0);
$prod->setDiscountFrom(null);
$prod->setDiscountTo(null);
$prod->setEan("");
$prod->setGlobalStock($data[3]["value"]);
$prod->setImage("");
$prod->setName($data[0]["value"]);
$prod->setParent(0);
$prod->setPrice($data[2]["value"]);
$prod->setSku($data[1]["value"]);
$prod->setStatus(1);
$prod->setStoreDiscount(0);
$prod->setStoreStock($data[3]["value"]);
$prod->setWebDiscount(0);
$prod->setWpId(null);
$prod->setWpStock(0);
$prod->setIva(21);
$em->persist($prod);
$f = $em->flush();
if ($f == null) {
return new JsonResponse(array("ok" => true, "sku" => $prod->getSku()));
} else {
return new JsonResponse(array("ok" => false));
}
}
public function getAlbaranesLine(Request $request) {
$em = $this->getDoctrine()->getManager();
$id = $request->request->get("id");
$prod = $em->getRepository(Products::class)->find($id);
return $this->render('products/proveedores/albaranLineTable.html.twig', array(
'prod' => $prod,
));
}
public function UpdateAllProductsToWp(Request $request) {
$em = $this->getDoctrine()->getManager();
$products = $em->createQueryBuilder()->select("p")
->from(Products::class, "p")
->where("p.wpId IS NOT NULL AND p.wpId <> '' and p.sku > 3627")
->getQuery()
->getResult();
//dd($products);
//creem tots els productes
foreach ($products as $product) {
$product->setWpId(null);
$this->api->addProductToWP($product, $em);
//die();
}
return new JsonResponse(array("ok" => true));
}
public function choice(Request $request) {
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$em = $this->getDoctrine()->getManager();
$id = $request->get("id");
$proveedor = $em->getRepository(Proveedores::class)->find($id);
return $this->render('products/proveedores/choice.html.twig', array(
'id' => $id,
'proveedor' => $proveedor,
));
}
public function volcar(Request $request) {
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$em = $this->getDoctrine()->getManager();
$id = $request->get("id");
$proveedor = $em->getRepository(Proveedores::class)->find($id);
return $this->render('products/proveedores/volcar.html.twig', array(
'id' => $id,
'proveedor' => $proveedor,
));
}
public function saveFiles(Request $request): response {
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$em = $this->getDoctrine()->getManager();
$id = $request->get("proveedor_id");
$images = $request->files->get("imgs");
$file = $request->files->get("file");
// UPLOAD IMAGES
$newImagesFileName = NULL;
if ($images) {
if ($images->guessExtension() == "zip") {
$originalImagesFilename = pathinfo($images->getClientOriginalName(), PATHINFO_FILENAME);
$safeImagesFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalImagesFilename);
$newImagesFileName = $safeImagesFilename . "-product" . uniqid() . "." . $images->guessExtension();
try {
$images->move(
'assets/images/products/',
$newImagesFileName
);
} catch (FileException $e) {
var_dump($e);
die();
}
} else {
$type = 0;
$status = "Formato de imágenes incorrecto. Asegúrese de subir un archivo comprimido .zip";
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('proveedor_volcar', [ 'id' => $id ]);
}
}
//UPLOAD FILE
$extension = "";
if ($file != null) { $extension = '.'.$file->getClientOriginalExtension();}
if ($file && $extension == ".csv") {
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = \transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFileName = $safeFilename . "-product" . uniqid() . $extension;
try {
$file->move(
'assets/files/products/',
$newFileName
);
} catch (FileException $e) {
var_dump($e);
die();
}
} else {
$type = 0;
$status = "Archivo .csv no seleccionado o formato incorrecto";
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('proveedor_volcar', [ 'id' => $id ]);
}
$productUploads = new ProductUploads();
$productUploads->setProveedorId($request->get("proveedor_id"));
$productUploads->setFile($newFileName);
if ($newImagesFileName != NULL) {
$productUploads->setImages($newImagesFileName);
} else {
$productUploads->setImages("null");
}
$em->persist($productUploads);
$em->flush();
$prodUploadsId = $productUploads->getId();
return $this->redirectToRoute('proveedor_selectRows', [ 'id' => $prodUploadsId ]);
}
public function selectRows(Request $request){
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$em = $this->getDoctrine()->getManager();
$id = $request->get("id");
$prodUploads = $em->getRepository(ProductUploads::class)->find($id);
$proveedorId = $prodUploads->getProveedorId();
$proveedor = $em->getRepository(Proveedores::class)->find($proveedorId);
$order = $em->createQueryBuilder()->select("o.rowsOrder")
->from(ProveedorOrder::class, "o")
->where("o.proveedorId = '$proveedorId'")
->orderBy("o.id", "DESC") // Ordena por ID en orden descendente
->setMaxResults(1)
->getQuery()
->getOneOrNullResult();
$arrayOrder = (array) null;
if ($order) {
$arrayOrder = json_decode($order['rowsOrder']);
}
$file = $prodUploads->getFile();
$filePath = 'assets/files/products/' . $file;
// CSV Decoder
$csvEncoder = new CsvEncoder();
$values = $csvEncoder->decode(file_get_contents($filePath), 'csv',[CsvEncoder::DELIMITER_KEY => ';']);
//dd(count($values[0]));
if (count($values[0]) == 1) {
$values = $csvEncoder->decode(file_get_contents($filePath), 'csv',[CsvEncoder::DELIMITER_KEY => ',']);
}
// Save only array keys (first colum)
$columnNames = array_keys($values[0]);
return $this->render('products/proveedores/selectRows.html.twig', array(
'rows' => $columnNames,
'proveedor' => $proveedor,
'prod_uploads_id' => $id,
'order' => $arrayOrder,
));
}
public function saveOrder(Request $request) {
if (!$this->getUser() || !is_object($this->getUser())) {
return $this->redirectToRoute('logout');
}
$em = $this->getDoctrine()->getManager();
$proveedorId = $request->get("proveedor_id");
$prodUploadsId = $request->get("prod_uploads_id");
$rows = $request->get("product");
//Si mantenen el valor per defecte del formulari ho cambia a null
for ($i = 0; $i <= 21; $i++) {
if ($rows[$i] == "Seleccionar columna") {
$rows[$i] = "null";
}
}
$stringRows = json_encode($rows);
$proveedorOrder = new ProveedorOrder();
$proveedorOrder->setProveedorId($proveedorId);
$proveedorOrder->setRowsOrder($stringRows);
$proveedorOrder->setProductUploadId($prodUploadsId);
$em->persist($proveedorOrder);
$em->flush();
//MUNTAR PRODUCTES
//CARREGAR EL FILE I IMAGES
$prodUploads = $em->getRepository(ProductUploads::class)->find($prodUploadsId);
$file = $prodUploads->getFile();
$images = $prodUploads->getImages();
$filePath = 'assets/files/products/' . $file;
$imagePath = 'assets/images/products/' . $images;
$savePath = 'assets/images/products/';
// CSV Decoder
$csvEncoder = new CsvEncoder();
$values = $csvEncoder->decode(file_get_contents($filePath), 'csv',[CsvEncoder::DELIMITER_KEY => ';']); //posar el ';'
if (count($values[0]) == 1) {
$values = $csvEncoder->decode(file_get_contents($filePath), 'csv',[CsvEncoder::DELIMITER_KEY => ',']);
}
//DESCOMPRIMIR LES IMATGES I BORRAR EL ZIP
$zip = new \ZipArchive();
if ($zip->open($imagePath) === TRUE) {
$zip->extractTo($savePath);
$zip->close();
}
foreach ($values as $key => $value) {
//$orderedValue = array_merge(array_flip($rows), $value);
$index = [];
foreach ($rows as $clave) {
$index[] = isset($value[$clave]) ? $value[$clave] : null;
}
$sku = array("sku" => "$index[2]");
$product = $em->getRepository(Products::class)->findOneBy($sku);
if (isset($index[0]) && $index[0] !== "") {
if (!isset($product) && $product == "") {
$product = new Products();
$product->setDateCreated(new \DateTime());
}
//convert parent id into int
$parentIdInt = (int)$index[7];
//Setters
$product->setName(($index[0])?$index[0] : '');
$product->setEan(($index[1])?$index[1] : '');
if ($index[2] != null || $index[2] != "") {
$product->setSku($index[2]);
} else {
//Generate sku
$genSkuJson = $this->generateAutoSku();
$content = $genSkuJson->getContent();
$data = json_decode($content, true);
if ($sku["sku"] == null || $sku["sku"] == "") {
$product->setSku($data["sku"]);
} else {
$product->setSku($index[2]);
}
}
$product->setDescription(($index[3])?$index[3] : '');
$product->setPrice(($index[4])?floatval(str_replace(",",".",$index[4])) : 0);
$product->setIva(($index[5])?floatval($index[5]) : 0);
//$product->setDateCreated(new \DateTime());
$product->setParent((isset($parentIdInt) ? $parentIdInt : 0));
//wpId = $index[8]
$images = explode(",",$index[9]);
if($images){
$product->setImage($images[0]);
}
$product->setCostPrice((isset($index[10]) ? floatval($index[10]) : 0));
$product->setDateModify(new \DateTime());
//globalStock = $index[12]
$product->setWpStock((isset($index[13]) ? floatval($index[13]) : 0));
$product->setStoreStock((isset($index[14]) ? floatval($index[14]) : 0));
////discount = $index[15]
if ($index[16] != "") {
$disc_from = \DateTime::createFromFormat('d/m/Y', $index[16]);
$product->setDiscountFrom($disc_from);
} else {
$product->setDiscountFrom(null);
}
if ($index[17] != "") {
$disc_to = \DateTime::createFromFormat('d/m/Y', $index[17]);
$product->setDiscountTo($disc_to);
} else {
$product->setDiscountTo(null);
}
$product->setStoreDiscount(($index[18] != "") ? $index[18] : 0 );
$product->setWebDiscount(($index[19] != "") ? $index[19] : 0);
//$product->setGlobalStock(floatval($index[14]) + floatval($index[13]));
$product->setGlobalStock((isset($index[14]) ? floatval($index[14]) : 0));
$product->setStatus(1);
$em->persist($product);
$f = $em->flush();
}
}
if ($f == null) {
$type = 1;
$status = "Albaran subido correctamente";
} else {
$type = 0;
$status = "Error al guardar el Albaran";
}
$this->session->getFlashBag()->add('type', $type);
$this->session->getFlashBag()->add('status', $status);
return $this->redirectToRoute('proveedor_albaranes', [ 'id' => $proveedorId ]);
}
public function syncStocksWeb(Request $request){
$em = $this->getDoctrine()->getManager();
if($request->get("page")){
$paged = 20 * (intval($request->get("page"))-1);
}else{
$paged = 0;
}
$products = $em->createQueryBuilder()->select("p")
->from(Products::class, "p")
->where("p.wpId <> 'NULL'")
->orderBy("p.id", "DESC") // Ordena por ID en orden descendente
->setFirstResult($paged)
->setMaxResults(20)
->getQuery()
->getResult();
//dd(count($products));
$wc = new WCController();
foreach($products as $prod){
$wc->updateProductToWP($prod, $em);
}
dd($products);
}
public function exportProductsStocks(Request $request){
$entityManager = $this->getDoctrine()->getManager();
$products = $entityManager->getRepository(Products::class)->findAll();
$response = new StreamedResponse(function() use ($products) {
$output = fopen('php://output', 'w');
// Write headers
fputcsv($output, [
'ID', 'Name', 'EAN', 'SKU', 'Description', 'Price', 'IVA', 'Date Created',
'Parent', 'WP ID', 'Image', 'Cost Price', 'Date Modified', 'Global Stock',
'Store Stock', 'Discount', 'Discount From', 'Discount To',
'Store Discount', 'Web Discount', 'Status', 'Gallery'
],";");
// Write data
foreach ($products as $product) {
fputcsv($output, [
$product->getId(),
$product->getName(),
$product->getEan(),
$product->getSku(),
$product->getDescription(),
number_format($product->getPrice(),2,",",""),
$product->getIva(),
$product->getDateCreated()->format('Y-m-d H:i:s'),
$product->getParent(),
$product->getWpId(),
$product->getImage(),
$product->getCostPrice(),
$product->getDateModify()->format('Y-m-d H:i:s'),
$product->getGlobalStock(),
$product->getStoreStock(),
$product->getDiscount(),
$product->getDiscountFrom() ? $product->getDiscountFrom()->format('Y-m-d H:i:s') : '',
$product->getDiscountTo() ? $product->getDiscountTo()->format('Y-m-d H:i:s') : '',
$product->getStoreDiscount(),
$product->getWebDiscount(),
$product->getStatus(),
$product->getGallery()
],";");
}
fclose($output);
});
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment; filename="products_export.csv"');
return $response;
}
}