<?php
namespace App\Controller;
use App\Entity\Lot;
use App\Entity\Product;
use App\Form\ProductType;
use App\Repository\ConfigurationRepository;
use App\Repository\LotRepository;
use App\Repository\PieceLineRepository;
use App\Repository\ProductRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Knp\Component\Pager\PaginatorInterface;
use App\Form\ProductSearchType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Spipu\Html2Pdf\Html2Pdf;
use Aspera\Spreadsheet\XLSX\Reader;
/**
* @Route("/product")
*/
class ProductController extends AbstractController
{
/**
* @Route("/", name="product_index", methods={"GET|POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function index(ProductRepository $productRepository, Request $request, PaginatorInterface $paginator): Response
{
$form = $this->createForm(ProductSearchType::class);
$form->handleRequest($request);
if ($form->isSubmitted()) {
$url = $this->buildSearchUrl($request->request->all());
if (!empty($url)) {
return $this->redirectToRoute('product_index', $url);
}
}
$products = $paginator->paginate(
$productRepository->MyFindAll($request->query->all()), /* query NOT result */
$request->query->getInt('page', 1)/* page number */, 20/* limit per page */
);
return $this->render('product/index.html.twig', [
'products' => $products,
'form' => $form->createView(),
'data' => $request->query->all()
]);
}
/**
* @Route("/recup_stock_lot", name="recup_stock_lot", methods={"GET|POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function recupStockLot(ProductRepository $productRepository, LotRepository $lotRepository): Response
{
$products = $productRepository->findAll();
foreach ($products as $product) {
$lot = new Lot();
$lot->setProduct($product);
$lot->setStock($product->getStock());
$lot->setDateExpiration($product->getDateExpiration());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($lot);
$entityManager->flush();
}
return new Response('ok');
}
/**
* @Route("/recup_lot_ligne_vente", name="recup_lot_ligne_vente", methods={"GET|POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function recupLotLigneVente(ProductRepository $productRepository, LotRepository $lotRepository, PieceLineRepository $pieceLineRepository): Response
{
$pieceLines = $pieceLineRepository->findAll();
foreach ($pieceLines as $pieceLine) {
$pieceLine->setLot($pieceLine->getProduct()->getLots()[0]);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($pieceLine);
$entityManager->flush();
}
return new Response('ok');
}
/**
* @Route("/imprimer_produit", name="product_print_search", methods={"GET|POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function productPrintSearch(ProductRepository $productRepository, ConfigurationRepository $configurationRepository, Request $request): Response
{
$products = $productRepository->MyFindAllPrint($request->query->all());
$configuration = $configurationRepository->find(1);
$html = $this->renderView('product/imprimer_search.html.twig', [
'products' => $products,
'data' => $request->query->all(),
'config' => $configuration,
'server' => 'https://' . $_SERVER['HTTP_HOST'],
]);
$html2pdf = new Html2Pdf('L', 'A4', 'fr');
$html2pdf->writeHTML($html);
$html2pdf->Output();
}
/**
* @Route("/new", name="product_new", methods={"GET","POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function new(Request $request): Response
{
$product = new Product();
$lot = new Lot();
if (count($product->getLots()) === 0) {
$product->addLot($lot);
}
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($product);
$entityManager->flush();
$this->addFlash("success", "Produit Ajouté avec succès");
return $this->redirectToRoute('product_index');
}
return $this->render('product/new.html.twig', [
'product' => $product,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}/delete-confirmation", name="product_delete_confirmation", methods={"GET"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function deleteConfirmation(Product $product): Response
{
return $this->render('product/_delete_confirmation.html.twig', [
'product' => $product,
]);
}
/**
* @Route("/delete-validation", name="product_delete_validation", methods={"GET"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function deleteValidation(): Response
{
return $this->render('product/_delete_validation.html.twig', [
]);
}
/**
* @Route("/{id}", name="product_show", methods={"GET"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function show(Product $product): Response
{
return $this->render('product/show.html.twig', [
'product' => $product,
]);
}
public function read($csv)
{
$file = fopen($csv, 'r');
while (!feof($file)) {
$line[] = fgetcsv($file, 1024);
}
fclose($file);
return $line;
}
/**
* @Route("/importation-produit-csv", name="product_import1", methods={"GET|POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN') or is_granted('ROLE_DIRECTEUR') or is_granted('ROLE_RESPONSABLE_REGIONAL') or is_granted('ROLE_ASSISTANTE')")
*/
public function productImportCsv(): Response
{
$hex="\x49\x73\x6f\x50\x72\x69\x6d\x65\xae\x20\x43\x46\x4d\x20\x35\x30\x30\x67\x20\x44\x4f\x59\x50\x41\x43\x4b\x20";
//echo utf8_decode($hex);exit();
$target_dir = $this->getParameter('app.path.excel') . "/";
$target_file = $target_dir . $this->getUser()->getId() . '.csv';
if (!empty($_FILES)) {
move_uploaded_file($_FILES["file_excel"]["tmp_name"], $target_file);
}
if (($target_file != '' && file_exists($target_file))) {
$csv = $this->read($target_file);
foreach ($csv as $key => $ligne_csv) {
if (!empty($ligne_csv) && $key != 0) {
$l_csv = explode(';', $ligne_csv[0]);
echo "<pre>".print_r($l_csv,1)."</pre>";
if ($l_csv[4] != '') {
$product = new Product();
$product->setCode($l_csv[0]);
$product->setMarque($l_csv[1]);
$product->setName(utf8_decode($l_csv[2]));
//$product->setName(chr($l_csv[2]));
$product->setTaillePoids($l_csv[3]);
if ($l_csv[4] == '') {
$buy_ht = 0;
} else {
$t_buy_ht = explode(' CHF', $l_csv[4]);
$buy_ht = str_replace(',', '.', $t_buy_ht[0]);
}
$product->setBuyHT($buy_ht);
if ($l_csv[6] == '') {
$sell_ht = 0;
} else {
$t_sell_ht = explode(' CHF', $l_csv[6]);
$sell_ht = str_replace(',', '.', $t_sell_ht[0]);
}
$product->setSellHT($sell_ht);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($product);
$entityManager->flush();
$lot = new Lot();
$lot->setProduct($product);
if (isset($l_csv[7]) && $l_csv[7] != '') {
$t_date_expiration = explode('.', $l_csv[7]);
$date_expiration = $t_date_expiration[2] . '-' . $t_date_expiration[1] . '-' . $t_date_expiration[0];
$lot->setDateExpiration(new \DateTime($date_expiration));
} else {
$lot->setDateExpiration(null);
}
if ($l_csv[6] != '') {
$stock = $l_csv[6];
} else {
$stock = 0;
}
$lot->setStock(floatval($stock));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($lot);
$entityManager->flush();
}
}
}
$this->addFlash("success", "Importation des produits réussite avec sucèss!");
} else {
$this->addFlash("danger", "Erreur importation fichier excel!");
}
exit();
return $this->redirectToRoute('product_index');
}
/**
* @Route("/importation-produit-excel", name="product_import", methods={"GET|POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN') or is_granted('ROLE_DIRECTEUR') or is_granted('ROLE_RESPONSABLE_REGIONAL') or is_granted('ROLE_ASSISTANTE')")
*/
public function productImportExcel(): Response
{
$target_dir = $this->getParameter('app.path.excel') . "/";
$target_file = $target_dir . $this->getUser()->getId() . '.xlsx';
if (!empty($_FILES)) {
move_uploaded_file($_FILES["file_excel"]["tmp_name"], $target_file);
}
if (($target_file != '' && file_exists($target_file))) {
$tab_element = $this->recupInfoExcel();
//dump($tab_element);exit();
foreach ($tab_element as $element) {
if ($element[4] != '') {
$product = new Product();
$product->setCode($element[0]);
$product->setMarque($element[1]);
$product->setName($element[2]);
$product->setTaillePoids($element[3]);
if ($element[4] == '') {
$buy_ht = 0;
} else {
$t_buy_ht = explode(' CHF', $element[4]);
$buy_ht = str_replace(',', '.', $t_buy_ht[0]);
}
$product->setBuyHT($buy_ht);
if ($element[6] == '') {
$sell_ht = 0;
} else {
$t_sell_ht = explode(' CHF', $element[6]);
$sell_ht = str_replace(',', '.', $t_sell_ht[0]);
}
$product->setSellHT($sell_ht);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($product);
$entityManager->flush();
$lot = new Lot();
$lot->setProduct($product);
if (isset($element[7]) && $element[7] != '') {
$t_date_expiration = explode('.', $element[7]);
$date_expiration = $t_date_expiration[2] . '-' . $t_date_expiration[1] . '-' . $t_date_expiration[0];
$lot->setDateExpiration(new \DateTime($date_expiration));
} else {
$lot->setDateExpiration(null);
}
if ($element[5] != '') {
$stock = $element[5];
} else {
$stock = 0;
}
$lot->setStock(floatval($stock));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($lot);
$entityManager->flush();
}
}
$this->addFlash("success", "Importation des produits réussite avec sucèss!");
} else {
$this->addFlash("danger", "Erreur importation fichier excel!");
}
return $this->redirectToRoute('product_index');
}
/**
* @Route("/importation-code-barre-produit-excel", name="product_barecode_import", methods={"GET|POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN') or is_granted('ROLE_DIRECTEUR') or is_granted('ROLE_RESPONSABLE_REGIONAL') or is_granted('ROLE_ASSISTANTE')")
*/
public function productBareCode(ProductRepository $productRepository): Response
{
$target_dir = $this->getParameter('app.path.excel') . "/";
$target_file = $target_dir . $this->getUser()->getId() . '.xlsx';
if (!empty($_FILES)) {
move_uploaded_file($_FILES["file_excel"]["tmp_name"], $target_file);
}
if (($target_file != '' && file_exists($target_file))) {
$tab_element = $this->recupInfoExcel();
$entityManager = $this->getDoctrine()->getManager();
foreach ($tab_element as $element) {
if ($element[2] != '') {
$product = $productRepository->findOneBy(['code'=>$element[0]]);
if($product){
$product->setBarecode($element[2]);
$entityManager->flush();
}
}
}
$this->addFlash("success", "Importation des codes à barre réussite avec sucèss!");
} else {
$this->addFlash("danger", "Erreur importation fichier excel!");
}
return $this->redirectToRoute('product_index');
}
private function recupInfoExcel()
{
$file_name = $this->getUser()->getId() . '.xlsx';
$folder = $this->getParameter('app.path.excel') . '/';
$file = $folder . $file_name;
if (!file_exists($file)) {
return false;
}
$reader = new Reader();
$reader->open($file);
$reader->changeSheet(0);
$tab = [];
foreach ($reader as $ligne => $row) {
if ($ligne > 1) {
$tab[$ligne - 1] = $row;
}
}
return $tab;
}
/**
* @Route("/recup_info_product", name="recup_info_product", methods={"GET|POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function recupInfoProduct(Request $request, ProductRepository $productRepository, LotRepository $lotRepository): Response
{
$id = $request->request->get('id');
$product = $productRepository->find($id);
$lots = $lotRepository->findLot($product);
$nb_lot = count($lots);
$tab_product = [
'priceHT' => $product->getSellHT(),
'priceBuyHT' => $product->getBuyHT(),
'nb_lot' => $nb_lot
];
if ($nb_lot == 1) {
$lot = $lots[0];
$tab_product['lot'] = $lot->getId();
}
return new Response(json_encode($tab_product));
}
/**
* @Route("/selectionner_lot/{id}", name="selectionner_lot", methods={"GET|POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function selectionnerLot(Lot $lot, Request $request): Response
{
$id = $request->request->get('id');
$product = $lot->getProduct();
$tab_product = [
'priceHT' => $product->getSellHT(),
'priceBuyHT' => $product->getBuyHT(),
'lot' => $lot->getId()
];
return new Response(json_encode($tab_product));
}
/**
* @Route("/recup_lot_product", name="recup_lot_product", methods={"GET|POST"})
* @Security("is_granted('ROLE_USER')")
*/
public function recupLotProduct(Request $request, ProductRepository $productRepository, LotRepository $lotRepository): Response
{
$id = $request->request->get('id');
$index = $request->request->get('index');
$product = $productRepository->find($id);
$lots = $lotRepository->findLot($product);
return $this->render('product/lot_product.html.twig', [
'lots' => $lots,
'index' => $index,
]);
}
/**
* @Route("/{id}/edit", name="product_edit", methods={"GET","POST"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function edit(Request $request, Product $product): Response
{
$form = $this->createForm(ProductType::class, $product);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
$this->addFlash("success", "Produit modifié avec succès");
return $this->redirectToRoute('product_index');
}
return $this->render('product/edit.html.twig', [
'product' => $product,
'form' => $form->createView(),
]);
}
/**
* @Route("/{id}/delete", name="product_delete", methods={"DELETE"})
* @Security("is_granted('ROLE_SUPER_ADMIN')")
*/
public function delete(Request $request, Product $product): Response
{
if ($this->isCsrfTokenValid('delete' . $product->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($product);
$entityManager->flush();
}
return $this->redirectToRoute('product_delete_validation');
}
private function buildSearchUrl($data)
{
$url = [];
foreach ($data as $k => $v) {
if (isset($data['product_search']['marque']) && !empty($data['product_search']['marque'])) {
$url['marque'] = $data['product_search']['marque'];
}
if (isset($data['product_search']['produit']) && !empty($data['product_search']['produit'])) {
$url['produit'] = $data['product_search']['produit'];
}
if (isset($data['product_search']['code']) && !empty($data['product_search']['code'])) {
$url['code'] = $data['product_search']['code'];
}
if (isset($data['product_search']['barecode']) && !empty($data['product_search']['barecode'])) {
$url['barecode'] = $data['product_search']['barecode'];
}
if (isset($data['product_search']['achatMin']) && !empty($data['product_search']['achatMin'])) {
$url['achatMin'] = floatval($data['product_search']['achatMin']);
}
if (isset($data['product_search']['achatMax']) && !empty($data['product_search']['achatMax'])) {
$url['achatMax'] = floatval($data['product_search']['achatMax']);
}
if (isset($data['product_search']['venteMin']) && !empty($data['product_search']['venteMin'])) {
$url['venteMin'] = floatval($data['product_search']['venteMin']);
}
if (isset($data['product_search']['venteMax']) && !empty($data['product_search']['venteMax'])) {
$url['venteMax'] = floatval($data['product_search']['venteMax']);
}
if (isset($data['product_search']['stockMin']) && !empty($data['product_search']['stockMin'])) {
$url['stockMin'] = $data['product_search']['stockMin'];
}
if (isset($data['product_search']['stockMax']) && !empty($data['product_search']['stockMax'])) {
$url['stockMax'] = $data['product_search']['stockMax'];
}
if (isset($data['product_search']['dateExpDu']) && !empty($data['product_search']['dateExpDu'])) {
$url['dateExpDu'] = $data['product_search']['dateExpDu'];
}
if (isset($data['product_search']['dateExpAu']) && !empty($data['product_search']['dateExpAu'])) {
$url['dateExpAu'] = $data['product_search']['dateExpAu'];
}
}
return $url;
}
}