src/Controller/ProductController.php line 863

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\CompanyAssociation;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpFoundation\JsonResponse;
  9. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  10. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  11. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  14. use Symfony\Component\HttpFoundation\RedirectResponse;
  15. use Doctrine\Common\Collections\ArrayCollection;
  16. use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
  17. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  18. use Knp\Component\Pager\PaginatorInterface;
  19. use App\Entity\Category;
  20. use App\Entity\Cart;
  21. use App\Entity\Certification;
  22. use App\Entity\Company;
  23. use App\Entity\Conservation;
  24. use App\Entity\DeliveryMethod;
  25. use App\Entity\Ingredient;
  26. use App\Entity\Pricing;
  27. use App\Entity\Product;
  28. use App\Entity\ProductSponsored;
  29. use App\Entity\ProductSponsoredCategory;
  30. use App\Entity\ProductReplenishment;
  31. use App\Entity\Region;
  32. use App\Entity\Storage;
  33. use App\Entity\Tag;
  34. use App\Entity\UserSearch;
  35. use App\Entity\User;
  36. use App\Entity\ProductInBox;
  37. use App\Service\DistributorService;
  38. use App\Service\PaymentService;
  39. use App\Service\ProductService;
  40. use App\Service\UserService;
  41. use App\Service\ImageService;
  42. use App\Service\CompanyService;
  43. use App\Form\ProductType;
  44. use App\Form\ProductReplenishmentType;
  45. use App\Form\StorageType;
  46. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  47. class ProductController extends AbstractController
  48. {
  49.     private $entityMana;
  50.     private $productServ;
  51.     private $userServ;
  52.     private $companyServ;
  53.     private $request;
  54.     public function __construct(ProductService $prodServEntityManagerInterface $emUserService $userCompanyService $companyServ){
  55.         $this->entityMana $em;
  56.         $this->productServ $prodServ;
  57.         $this->userServ $user;
  58.         $this->companyServ $companyServ;
  59.     }
  60.     /**
  61.      * @route("/core/convert/productBoxes",
  62.      *      name="convertBoxesOfProduct")
  63.      */
  64.     public function convertCart(EntityManagerInterface $em){
  65.         return new Response('Disabled');
  66.         $products $em->getRepository(Product::class)->findProductsWithOldBundles();
  67.         foreach($products as $box){
  68.             $box->setIsBoxOfProducts(true);
  69.             foreach($box->getProductsInBundle() as $p){
  70.                 $pb = new ProductInBox();
  71.                 $pb->setProductRepresentingBox($box);
  72.                 $pb->setProduct($p->getProduct());
  73.                 $pb->setQuantity(1);
  74.                 $pb->setPriceToCompany($p->getPriceToCompany());
  75.                 $em->persist($pb);
  76.                 $box->addProductInBox($pb);
  77.             }
  78.             $em->persist($box);
  79.         }
  80.         $em->flush();
  81.         return new Response();
  82.     }
  83.     /**
  84.      * @route({
  85.      *          "fr": "/soldes",
  86.      *          "en": "/sponsored/{url}"
  87.      *      },
  88.      *      options = { "expose" = true },
  89.      *      name="viewOnSalesProduct")
  90.      * @Template("frontend/category.html.twig")
  91.      */
  92.     public function viewOnSaleProducts(Request $request){
  93.         $twigData = array();
  94.         $twigData['link'] = $request->getPathInfo();
  95.         $twigData['category'] =  new Category();
  96.         $twigData['category']->setTitle('En solde');
  97.         $twigData['noLoader'] = true;
  98.         $twigData['noPagination'] = true;
  99.         $twigData['forcedBanner'] = '/assets/frontend/images/Banner-02-2021-commealaferme.png';
  100.         $order 'Desc';
  101.         if ($request->get("order")) {
  102.           $order $request->get("order");
  103.         }
  104.         $twigData['order']= $order;
  105.         $sorting "date";
  106.         // $sorting = null;
  107.         if ($request->get("sorting")) {
  108.           $sorting $request->get("sorting");
  109.         }
  110.         $twigData['sorting']= $sorting;
  111.         $sales $this->entityMana->getRepository(Pricing::class)->findOnSale($sorting,$order);
  112.         // dd($sales);
  113.         $twigData['products'] = array();
  114.         foreach( $sales as $s ){
  115.         if($s->getDiscountProduct()->isSalable())
  116.             $twigData['products'][]= $s->getDiscountProduct();
  117.         }
  118.         $twigData['productsAmount'] = count($twigData['products']);
  119.         //$twigData['products']['getTotalItemCount'] = $category->getProductsSponsored()->count();
  120.         $twigData['regions'] = $this->entityMana->getRepository(Region::class)->findBy(['province'=>'Qc']);
  121.         $twigData['conservations'] = $this->entityMana->getRepository(Conservation::class)->findAll();
  122.         return $twigData;
  123.     }
  124.     /**
  125.      * @route({
  126.      *          "fr": "/vedette/{url}",
  127.      *          "en": "/sponsored/{url}"
  128.      *      },
  129.      *      defaults={
  130.      *          "url" = false
  131.      *      },
  132.      *      options = { "expose" = true },
  133.      *      name="viewSponsoredCategory")
  134.      * @Template("frontend/category.html.twig")
  135.      */
  136.     public function viewSponsoredCategory(ProductSponsoredCategory $category=nullRequest $request){
  137.         $twigData = array();
  138.         if(empty($category) || $category->getUrl() == 'soldes'){
  139.             return $this->redirectToRoute('viewOnSalesProduct');
  140.         }
  141.         if($category->getCategory()){
  142.             $fullUrl $category->getCategory()->getFullUrlPath();
  143.             return new RedirectResponse('/categorie'.$fullUrl);
  144.         }
  145.         $order "desc";
  146.         if ($request->get("order")) {
  147.           $order $request->get("order");
  148.         }
  149.         $twigData['order']= $order;
  150.         $sorting "date";
  151.         if ($request->get("sorting")) {
  152.           $sorting $request->get("sorting");
  153.         }
  154.         $twigData['sorting']= $sorting;
  155.         $twigData['category'] =  new Category();
  156.         $twigData['category']->setTitle($category->getTitle());
  157.         $twigData['noLoader'] = true;
  158.         $twigData['noPagination'] = true;
  159.         $twigData['forcedBanner'] = '/assets/frontend/images/Banner-02-2021-commealaferme.png';
  160.         $twigData['selected'] = array(
  161.             'main' => $twigData['category']->getId(),
  162.             'sub1' => false,
  163.             'sub2' => false,
  164.             'sub3' => false
  165.         );
  166.         $Products $this->entityMana->getRepository(Product::class)->getProductsSponsored($category$sorting$order);
  167.         $twigData['products'] = $Products;
  168.         // $now = new \DateTime('now');
  169.         // foreach( $Products as $p ) {
  170.         //   if (
  171.         //     $now >= $p->getFromDate() &&
  172.         //     $now <= $p->getToDate() &&
  173.         //     $p->getActive()
  174.         //   ) {
  175.         //     $twigData['products'][]= $p->getProduct();
  176.         //   }
  177.         // }
  178.         $twigData['productsAmount'] = count($twigData['products']);
  179.         //$twigData['products']['getTotalItemCount'] = $category->getProductsSponsored()->count();
  180.         $twigData['regions'] = $this->entityMana->getRepository(Region::class)->findBy(['province'=>'Qc']);
  181.         $twigData['conservations'] = $this->entityMana->getRepository(Conservation::class)->findAll();
  182.         return $twigData;
  183.     }
  184.     /**
  185.      * @route({
  186.      *          "fr": "/solex/{id}",
  187.      *          "en": "/solex/{id}"
  188.      *      },
  189.      *      options = { "expose" = true },
  190.      *      name="testing")
  191.      */
  192.     public function testing(DistributorService $dUser $user){
  193.         //$form = $this->createForm(ProductReplenishmentType::class, $replenishment);
  194.         $twig $this->get('twig')->render('emails/welcomeNewAccount.html.twig', [
  195.             'user' => $user,
  196.         ]);
  197.         var_dump($twig);
  198.         die();
  199.     }
  200.     /**
  201.      * @route({
  202.      *          "fr": "/vendeur/inventaire/{id}",
  203.      *          "en": "/seller/inventory/{id}"
  204.      *      },
  205.      *      defaults={
  206.      *          "id" = false
  207.      *      },
  208.      *      name="replenishment")
  209.      * @Security("has_role('ROLE_ADMIN')")
  210.      * @Template("admin/product/replenishmentCalendar.html.twig")
  211.      */
  212.     public function replenishmentCompany $company=nullDistributorService $distributor,Request $requestUserService $userServ){
  213.         if(empty($company)){
  214.             $user $userServ->getUser();
  215.             $companies $user->getCompanies();
  216.             if(count($companies) > 1){
  217.                 $this->addFlash('error'"Vous avez plusieur boutiques, pour accéder a l'inventaire via le menu");
  218.                 return $this->redirectToRoute('dashboard');
  219.             }else{
  220.                 $company $companies->get(0);
  221.             }
  222.         }
  223.         //@SECuritY
  224.         if(!$this->companyServ->allowedToModify($company) || empty($company)){
  225.             $this->addFlash('error'"Vous n'avez pas d'accès Ã  cette boutique, veuillez utiliser le menu");
  226.             return $this->redirectToRoute('dashboard');
  227.         }
  228.         if($_ENV['APP_ENV'] != 'dev'){
  229.             if(!$company->hasPayment()){
  230.                 $this->addFlash('error'"Avant de planifier votre mise en inventaire, SVP veuillez compléter votre mode de paiement. Ce mode de paiement servira Ã  payer vos frais mensuels tel l’abonnement de votre boutique et l’entreposage de vos produits.");
  231.                 return $this->redirectToRoute('companyPayment');
  232.             }
  233.         }
  234.         if(empty($company->getProducts()) || count($company->getProducts()) < 1){
  235.             $this->addFlash('error'"Vous devez avoir des produits pour prendre un rendez-vous.");
  236.             return $this->redirectToRoute('adminNewProduct', array('id' => $company->getId()));
  237.         }
  238.         $twigData = array();
  239.         $twigData['company'] = $company;
  240.         return $twigData;
  241.     }
  242.     /**
  243.      * @route({
  244.      *          "fr": "/vendeur/inventaire/dimensions/{id}",
  245.      *          "en": "/vendeur/inventory/dimensions/{id}"
  246.      *      },
  247.      *      options = { "expose" = true },
  248.      *      name="replenishmentDimensionsForm")
  249.      * @Security("has_role('ROLE_ADMIN')")
  250.      */
  251.     public function confirmDimensionStorage(Product $productProductService $productServRequest $request){
  252.         if(!$productServ->allowedToModify($product)){
  253.             $this->addFlash('error'"Vous n'avez pas d'accès Ã  ce produit.");
  254.             return $this->redirectToRoute('dashboard');
  255.         }
  256.         $response = new JsonResponse();
  257.         $twigData = array();
  258.         $twigData['product'] = $product;
  259.         $form $this->createFormBuilder($product)
  260.             ->add('storages'CollectionType::class, array(
  261.                 'entry_type' => StorageType::class,
  262.                 'allow_delete' => false,
  263.                 'data' => $product->getStorages()
  264.             ))
  265.             ->add('confirm'CheckboxType::class, array(
  266.                 'label' => 'Je confirme les informations et la mise-en-inventaire de ce produit.',
  267.                 'required' => true,
  268.                 'mapped' => false,
  269.                 'attr' => array(
  270.                     'class' => 'checkbox-only confirm-checkbox'
  271.                 )
  272.             ))
  273.             ->getForm();
  274.             ;
  275.         $twigData['form'] = $form->createView();
  276.         $form->handleRequest($request);
  277.         if($request->isXmlHttpRequest() && $request->get('form') !== null ){
  278.             $minimum $request->get('minimum');
  279.             if(!empty($minimum) && is_numeric($minimum))
  280.                 $product->setMinimumInStorage($minimum);
  281.             $em $this->getDoctrine()->getManager();
  282.             $em->persist($product);
  283.             $em->flush();
  284.             $response->setData(array('success' => true));
  285.             return $response;
  286.         }else{
  287.             $response->setData(array(
  288.                 'html' => $this->get('twig')->render('admin/product/replenishmentConfirmDimensions.html.twig'$twigData),
  289.                 'minimum' => $product->getMinimumInStorage()
  290.             ));
  291.             return $response;
  292.         }
  293.     }
  294.     /**
  295.      * @route({
  296.      *          "fr": "/vendeur/inventaire/rendezvous/{replenishment}/{sendEmail}",
  297.      *          "en": "/seller/inventory/appointment/{replenishment}/{sendEmail}"
  298.      *      },
  299.      *      options = { "expose" = true },
  300.      *      defaults={
  301.      *          "sendEmail" = 1,
  302.      *      },
  303.      *      name="editReplenishmentAppointment")
  304.      * @Security("has_role('ROLE_ADMIN')")
  305.      * @Template("admin/product/replenishmentSchedule.html.twig")
  306.      */
  307.     public function editReplenishmentAppointment(ProductReplenishment $replenishmentRequest $requestCompanyService $companyServDistributorService $distributorUserService $userServ$sendEmail=true){
  308.         $company $replenishment->getCompany();
  309.         if(!$companyServ->allowedToModify($company)){
  310.             $this->addFlash('error'"Vous n'avez pas d'accès Ã  cette boutique.");
  311.             return $this->redirectToRoute('dashboard');
  312.         }
  313.         $twigData = array();
  314.         $twigData['company'] = $company;
  315.         $twigData['editing'] = true;
  316.         $twigData['scheduleDate'] = $replenishment->getAppointmentDate();
  317.         $twigData['replenishment'] = $replenishment;
  318.         $form $this->createForm(ProductReplenishmentType::class, $replenishment);
  319.         $form
  320.             ->add('erase'SubmitType::Class,
  321.                 array(
  322.                     'label' => 'Annuler le rendez-vous',
  323.                     'attr' => array(
  324.                         'class' => 'btn btn-warning'
  325.                     )
  326.                 )
  327.             );
  328.         $form->handleRequest($request);
  329.         if($form->isSubmitted() && $form->isValid()){
  330.             $em $this->getDoctrine()->getManager();
  331.             //We erase
  332.             if($form->get('submit')->isClicked()){
  333.                 //We edit only
  334.                 $em->persist($replenishment);
  335.                 $em->flush();
  336.                 if($distributor->setStockingSchedule($replenishment)){
  337.                    $this->addFlash('success'"Votre rendez-vous Ã  Ã©té modifié.");
  338.                    if($sendEmail){
  339.                         $email =  $this->get('twig')->render('emails/confirmReplenishment.html.twig', array('replenishment' => $replenishment'user' => $userServ->getUser()));
  340.                        //For now we send a email to some people to warn them
  341.                        if($replenishment->hasProductsNeedingRefrigeration()){
  342.                             $userServ->sendEmail('Maturin: Un rdv pour produits réfrigéré le '.$replenishment->getAppointmentDate()->format('d-m-Y').' Ã  Ã©té pris'$emailfalse'support@maturin.ca');
  343.                             $userServ->sendEmail('Maturin: Un rdv pour produits réfrigéré le '.$replenishment->getAppointmentDate()->format('d-m-Y').' Ã  Ã©té pris'$emailfalse'philippe.vandelac@solexdocument.com');
  344.                        }
  345.                        $userServ->sendEmail(' Confirmation de votre rendez-vous chez Maturin le '.$replenishment->getAppointmentDate()->format('d-m-Y'), $emailfalse$userServ->getUser()->getEmail());
  346.                     }
  347.                 }else{
  348.                     $this->addFlash('error'"Nous n'avons pas réussi a confirmer votre rendez-vous.");
  349.                     $replenishment->setIsValid(false);
  350.                     $em->persist($replenishment);
  351.                     $em->flush();
  352.                 }
  353.             }else{
  354.                 if($distributor->cancelStockingSchedule($replenishment)){
  355.                     $this->addFlash('success'"Votre rendez-vous Ã  Ã©té annulé.");
  356.                     $replenishment->setIsValid(false);
  357.                     //$em->remove($replenishment);
  358.                     $em->persist($replenishment);
  359.                 }
  360.             }
  361.             $em->flush();
  362.             return $this->redirectToRoute('replenishment', array('id' => $company->getId()));
  363.         }
  364.         $twigData['form'] = $form->createView();
  365.         return $twigData;
  366.     }
  367.     /**
  368.      * @route({
  369.      *          "fr": "/vendeur/inventaire/rendezvous/{year}/{month}/{day}/{hour}/{min}/{company}",
  370.      *          "en": "/seller/inventory/appointment/{year}/{month}/{day}/{hour}/{min}/{company}"
  371.      *      },
  372.      *      options = { "expose" = true },
  373.      *      name="replenishmentAppointment")
  374.      * @Security("has_role('ROLE_ADMIN')")
  375.      * @Template("admin/product/replenishmentSchedule.html.twig")
  376.      */
  377.     public function replenishementAppointment(Company $company=null$year=null$month=null$day=null$hour=null$min=nullCompanyService $companyServRequest $requestDistributorService $distributorUserService $userServ){
  378.         if(!$companyServ->allowedToModify($company)){
  379.             $this->addFlash('error'"Vous n'avez pas d'accès Ã  cette boutique.");
  380.             return $this->redirectToRoute('dashboard');
  381.         }
  382.         $twigData = array();
  383.         $twigData['scheduleDate'] = \DateTime::createFromFormat('d-m-Y H:i'$day.'-'.$month.'-'.$year.' '.$hour.':'.$min);
  384.         $twigData['company'] = $company;
  385.         $twigData['loader'] = true;
  386.         //If they already have a appointment at that time, let's edit that one instead of creating a new one
  387.         if($test $company->hasReplenishmentOn($twigData['scheduleDate'])){
  388.             $this->addFlash('error''Utiliser le bouton "Ajouter un produit" pour ajouter un produit a votre commande');
  389.             $this->redirectToRoute('editReplenishmentAppointment', array('replenishment' => $test->getId()));
  390.         }
  391.         $replenishment = new ProductReplenishment();
  392.         $replenishment->setAppointmentDate($twigData['scheduleDate']);
  393.         $replenishment->setCompany($company);
  394.         $twigData['editing'] = false;
  395.         $twigData['replenishment'] = $replenishment;
  396.         $form $this->createForm(ProductReplenishmentType::class, $replenishment);
  397.         $form->handleRequest($request);
  398.         if($form->isSubmitted() && $form->isValid()){
  399.             try {
  400.                 $em $this->getDoctrine()->getManager();
  401.                 $em->persist($replenishment);
  402.                 $em->flush();
  403.                 if($distributor->setStockingSchedule($replenishment)){
  404.                    $email =  $this->get('twig')->render('emails/confirmReplenishment.html.twig', array('replenishment' => $replenishment'user' => $userServ->getUser()));
  405.                    $userServ->sendEmail(' Confirmation de votre rendez-vous chez Maturin le '.$replenishment->getAppointmentDate()->format('d-m-Y'), $emailfalse$userServ->getUser()->getEmail());
  406.                     $this->addFlash('success''Votre rendez-vous Ã©té confirmé.');
  407.                    //For now we send a email to some people to warn them
  408.                    if($replenishment->hasProductsNeedingRefrigeration()){
  409.                         $userServ->sendEmail('Maturin: Un rdv pour produits réfrigéré le '.$replenishment->getAppointmentDate()->format('d-m-Y').' Ã  Ã©té pris'$emailfalse'support@maturin.ca');
  410.                         $userServ->sendEmail('Maturin: Un rdv pour produits réfrigéré le '.$replenishment->getAppointmentDate()->format('d-m-Y').' Ã  Ã©té pris'$emailfalse'philippe.vandelac@solexdocument.com');
  411.                    }
  412.                 }else{
  413.                     $this->addFlash('error'"Nous n'avons pas réussi a confirmer votre rendez-vous.");
  414.                     $replenishment->setIsValid(false);
  415.                     $em->persist($replenishment);
  416.                     $em->flush();
  417.                 }
  418.             } catch (\Exception $e ){
  419.                 $this->addFlash('error''Une erreur est survenu, veuillez contacter notre support.');
  420.                 $this->addFlash('error'$e);
  421.                 $em->remove($replenishment);
  422.                 $em->flush();
  423.                 return $this->redirectToRoute('replenishment', array('id' => $company->getId()));
  424.             }
  425.             return $this->redirectToRoute('replenishment', array('id' => $company->getId()));
  426.         }
  427.         $twigData['form'] = $form->createView();
  428.         return $twigData;
  429.     }
  430.     /**
  431.      * @route({
  432.      *          "fr": "/admin/inventaire/horraire/{id}/{action}",
  433.      *          "en": "/admin/inventory/schedule/{id}/{action}"
  434.      *      },
  435.      *      options = { "expose" = true },
  436.      *      name="replenishmentGetSchedule")
  437.      * @Security("has_role('ROLE_ADMIN')")
  438.      */
  439.     public function replenishmentGetSchedule(DistributorService $distributorCompany $company$action){
  440.         $response = new JsonResponse();
  441.         $dateFrom = new \DateTime(urldecode($_GET['start']));
  442.         $dateTo = new \DateTime(urldecode($_GET['end']));
  443.         $data = array();
  444.         $now = new \DateTime();
  445.         foreach($company->getProductReplenishments() as $r){
  446.             $tmpDateFrom $r->getAppointmentDate();
  447.             if($tmpDateFrom $now){
  448.                 $data[]=array(
  449.                     'id' => $r->getId(),
  450.                     'title' => 'Votre rendez-vous',
  451.                     'allDay' => 'false',
  452.                     'className' => 'calendar-mine',
  453.                     'editable' => false,
  454.                     'start' => $tmpDateFrom->format('c'),
  455.                     'end' => $tmpDateFrom->modify('+59 minutes 60 seconds')->format('c')
  456.                 );
  457.             }
  458.         }
  459.         $minSchedule = new \DateTime();
  460.         $minSchedule->add(new \DateInterval('P1D'));
  461.         /*
  462.         if($minSchedule > $dateFrom){
  463.             $dateFrom = $minSchedule;
  464.         }
  465.          */
  466.         $schedules $distributor->getStockingSchedule($dateFrom->format('c'), $dateTo->format('c'));
  467.         $cmtp 0;
  468.         foreach($schedules as $s){
  469.             $dateFrom = new \DateTime($s->startTime);
  470.             $dateTo = new \DateTime($s->endTime);
  471.             $nbSpot $s->nbSpotsLeft;
  472.             if($nbSpot && $dateFrom->format('Ymd') >= $minSchedule->format('Ymd') ){
  473.                 $data[]=array(
  474.                     'id' => $cmtp,
  475.                     'title' => '',
  476.                     'allDay' => 'false',
  477.                     'className' => 'calendar-available',
  478.                     'editable' => false,
  479.                     'start' => $dateFrom->format('c'),
  480.                     'end' => $dateTo->format('c')
  481.                 );
  482.                 $cmtp++;
  483.             }
  484.         }
  485.         $response->setData($data);
  486.         return $response;
  487.     }
  488.     /**
  489.      * @route({
  490.      *          "fr": "/groupe/{groupUrlName}/produit/{producerUrl}/{productName}/{id}/",
  491.      *          "en": "/groupe/{groupUrlName}/product/{producerUrl}/{productName}/{id}/"
  492.      *      },
  493.      *      options = { "expose" = true },
  494.      *      name="viewProductInAssociation")
  495.      * @Template("frontend/product.html.twig")
  496.      */
  497.     public function viewProductInAssociation$groupUrlName$producerUrl$productName$id,    UserService $UserServiceProductService $ProductServiceEntityManagerInterface $emRequest $requestPaginatorInterface $paginatorUrlGeneratorInterface $router){
  498.         $product $em->getRepository(Product::class)->find((int)$id);
  499.         $assocation=$em->getRepository(CompanyAssociation::class)
  500.             ->findOneBy([
  501.                 'urlName' => $groupUrlName
  502.             ]);
  503.         if ($assocation && $assocation != $UserService->getAssociationUserIsBrowsing()){
  504.             $UserService->setAssociationUserIsBrowsing($assocation->getId());
  505.         }
  506.         return $this->viewProduct($UserService$ProductService$em$product$request$paginator$router);
  507.     }
  508.     /**
  509.      * @route({
  510.      *          "fr": "/produit/{producerUrl}/{productName}/{id}/",
  511.      *          "en": "/product/{producerUrl}/{productName}/{id}/"
  512.      *      },
  513.      *      options = { "expose" = true },
  514.      *      name="viewProduct")
  515.      * @Template("frontend/product.html.twig")
  516.      */
  517.     public function viewProduct(UserService $UserServiceProductService $ProductServiceEntityManagerInterface $emProduct $productRequest $requestPaginatorInterface $paginatorUrlGeneratorInterface $router){
  518.         $twigData = array();
  519.         $UserService->addViewedProduct($product);
  520.         if ($this->userServ->getAssociationUserIsBrowsing()){
  521.             if ($request->get('_route') == 'viewProduct'){
  522.                 return $this->redirectToRoute('viewProductInAssociation', [
  523.                     'groupUrlName' => $this->userServ->getAssociationUserIsBrowsing()->getUrlName(),
  524.                     'producerUrl' => $product->getCompany()->getUrlName(),
  525.                     'productName' => $product->getUrlName(),
  526.                     'id' => $product->getId(),
  527.                 ]);
  528.             }
  529.             $userAllowed false;
  530.             foreach($product->getCompany()->getAssociations() as $assocation){
  531.                 if ($assocation->getId() == $this->userServ->getAssociationUserIsBrowsing()->getId()){
  532.                     $userAllowed  =true;
  533.                 }
  534.             }
  535.             if (!$userAllowed){
  536.                 $this->addFlash('error''The product you tried to see is not allowed in '.$this->userServ->getAssociationUserIsBrowsing()->getName());
  537.                 $referer $request->headers->get('referer');
  538.                 return $this->redirect($referer != null $referer '/'307);
  539.             }
  540.         } else if ($product->getIsDisplayedInAssociationOnly() || !$product->getCompany()->getShowPublicly()
  541.             || !$product->getIsConsumer()){
  542.             $this->addFlash('error''The product you tried to see is not available.');
  543.             $referer $request->headers->get('referer');
  544.             return $this->redirect($referer != null $referer '/'307);
  545.         }
  546.         $referer $request->headers->get('referer');
  547.         if(stripos($referer'maturin.ca') !== false){
  548.             $baseUrl $request->getSchemeAndHttpHost();
  549.             $lastPath current(explode('?'substr($refererstrpos($referer$baseUrl) + strlen($baseUrl))));
  550.             $params $this->get('router')->getMatcher()->match($lastPath);
  551.             if(empty($params['sub1'])){
  552.                 $params['sub1']= false;
  553.                 $params['sub2']= false;
  554.                 $params['sub3']= false;
  555.             }
  556.             if($params['_route'] != 'allCategory' && strpos($referer'page') !== false){
  557.                 $raw explode('?'$referer);
  558.                 $page str_replace('page='''end($raw));
  559.                 if(is_numeric($page)){
  560.                     $request->attributes->set('page'$page);
  561.                 }
  562.             }
  563.         }else{
  564.             $params['sub1']= false;
  565.             $params['sub2']= false;
  566.             $params['sub3']= false;
  567.         }
  568.         /*
  569.          * Depending of how much results there is in this sub-Category
  570.          * We are either displaying the sub-Category if results are > 12 (Filling a least 3 rows in the Desktop UI)
  571.          */
  572.         if($product->getSubCategory() && $product->getSubCategory()->getProducts()->count() > )
  573.             $categoryToUse $product->getSubCategory();
  574.         else
  575.             $categoryToUse $product->getCategory();
  576.         $twigData $this->viewCategory($categoryToUse$params['sub1'], $params['sub2'], $params['sub3'], $paginator$requesttrue);
  577.         $twigData['categoryToUse'] = $categoryToUse;
  578.         $twigData['product'] = $product;
  579.         $twigData['showProductsRightAway']= true;
  580.         $twigData['productsToBuyToo'] = $ProductService->getSimilarProduct($product);
  581.         //Suggestion Algo Products 
  582.         $twigData['productsUserMayLike'] = false;
  583.         $produtSuggestion $product->getComplementedByGroups();
  584.         if(count($produtSuggestion) > 0){
  585.             $twigData['productsUserMayLike'] = $product->getAllComplementaryProducts();
  586.             if(count($product->getAllComplementaryProducts())< 4){
  587.                 //return an array of 4 elements for suggestion
  588.                 $suggestedProductsLength=(4count($product->getAllComplementaryProducts()));
  589.                 $suggestionArray $ProductService->getProductsSuggestion($suggestedProductsLength,$product);
  590.                 foreach ($product->getAllComplementaryProducts()as $p) {
  591.                    array_push($suggestionArray,$p);
  592.                 }
  593.                 $twigData['productsUserMayLike'] = $suggestionArray;
  594.             }
  595.         }else{
  596.                 $suggestedProductsLength=4;
  597.                 $suggestionArray $ProductService->getProductsSuggestion($suggestedProductsLength,$product);
  598.                 $twigData['productsUserMayLike'] = $suggestionArray;
  599.         }
  600.         // remove independante delivery for cartes-cadeauxCarte-cadeau
  601.         $twigData['independentDelivery'] = true;
  602.         if($categoryToUse->getId()== 341 && strpos($product->getName(), 'Carte-cadeau') !== false){
  603.             $twigData['independentDelivery'] = false;
  604.         };
  605.         return $twigData;
  606.     }
  607.     /**
  608.      * @route({
  609.      *          "fr": "/categorie",
  610.      *          "en": "/category"
  611.      *      },
  612.      *      options = { "expose" = true },
  613.      *      name="allCategory")
  614.      * @Template("frontend/category.html.twig")
  615.      */
  616.     public function allCategory(ProductService $ProductServiceEntityManagerInterface $emPaginatorInterface $paginatorRequest $request){
  617.         $twigData = array();
  618.         $order "desc";
  619.         if ($request->get("order")) {
  620.           $order $request->get("order");
  621.         }
  622.         $twigData['order']= $order;
  623.         $sorting "popularity";
  624.         if ($request->get("sorting")) {
  625.           $sorting $request->get("sorting");
  626.         }
  627.         $twigData['sorting']= $sorting;
  628.         $productsQuery  $this->entityMana->getRepository(Product::class)->getProductsForAllCategory($sorting$order);
  629.         $page 1;
  630.         if(!empty($request->get('page')))
  631.             $page $request->get('page');
  632.         // Paginate the results of the query
  633.         $twigData['products'] = $paginator->paginate(
  634.             $productsQuery,
  635.             $request->query->getInt('page'$page),
  636.             24
  637.         );
  638.         $twigData['productsAmount'] = count($productsQuery);
  639.         $twigData['regions'] = $this->entityMana->getRepository(Region::class)->findBy(['province'=>'Qc']);
  640.         $twigData['conservations'] = $this->entityMana->getRepository(Conservation::class)->findAll();
  641.         $twigData['category'] = new Category();
  642.         $twigData['category']->setTitle('NOTRE RICHESSE…');
  643.         $twigData['forcedBanner'] = '/assets/frontend/images/categorie-banner.png';
  644.         $twigData['noLoader'] = true;
  645.         $twigData['filters']= array();
  646.         $twigData['selected'] = array(
  647.             'main' => false,
  648.             'sub1' => false,
  649.             'sub2' => false,
  650.             'sub3' => false
  651.         );
  652.         return $twigData;
  653.     }
  654.     /**
  655.      * @route({
  656.      *          "fr": "/produits/recherche/{token}",
  657.      *          "en": "/products/search/{token}}"
  658.      *      },
  659.      *      options = { "expose" = true },
  660.      *      name="searchProducts")
  661.      * @Template("frontend/category.html.twig")
  662.      */
  663.     public function searchProducts($tokenRequest $requestProductService $productServPaginatorInterface $paginatorUserService $userServ$forcedValues false){
  664.         $twigData = array();
  665.         $search $this->entityMana->getRepository(UserSearch::class)->findOneBy(['token' => $token]);
  666.         $page 1;
  667.         if(!empty($request->get('page')))
  668.             $page $request->query->getInt('page');
  669.         $forcedValues = array(
  670.             'filters' => $search->getRawFilters(),
  671.             'token' => $token,
  672.             'page' => $page,
  673.         );
  674.         $products $this->getProductByActionFromAPI($search->getSearch(), $request$productServ$paginator$userServ$forcedValuesfalse);
  675.         //Template values
  676.         // Paginate the results of the query
  677.         $twigData['products'] = $paginator->paginate(
  678.             $products,
  679.             $page,
  680.             24
  681.         );
  682.         $rawFilters json_decode($search->getRawFilters());
  683.         $filters = array();
  684.         foreach( $rawFilters as $f){
  685.             $filters[$f->type][] = $f->id;
  686.         }
  687.         if(!empty($filters['category'])){
  688.             $category $this->entityMana->getRepository(Category::class)->findOneById(current($filters['category']));
  689.             $twigData['category'] = $category;
  690.             $twigData['selected'] = array(
  691.                 'main' => $category->getId(),
  692.                 'sub1' => false,
  693.                 'sub2' => false,
  694.                 'sub3' => false
  695.             );
  696.         }else{
  697.             $twigData['category'] = new Category();
  698.             $twigData['selected'] = array(
  699.                 'main' => false,
  700.                 'sub1' => false,
  701.                 'sub2' => false,
  702.                 'sub3' => false
  703.             );
  704.         }
  705.         $twigData['filters'] = $filters;
  706.         $twigData['productsAmount'] = $twigData['products']->getTotalItemCount();
  707.         $twigData['regions'] = $this->entityMana->getRepository(Region::class)->findBy(['province'=>'Qc']);
  708.         $twigData['conservations'] = $this->entityMana->getRepository(Conservation::class)->findAll();
  709.         return $twigData;
  710.     }
  711.     /**
  712.      * @route({
  713.      *          "fr": "/categorie/{name}/{sub1}/{sub2}/{sub3}",
  714.      *          "en": "/category/{name}/{sub1}/{sub2}/{sub3}"
  715.      *      },
  716.      *      options = { "expose" = true },
  717.      *      defaults={
  718.      *          "sub1" = false,
  719.      *          "sub2" = false,
  720.      *          "sub3" = false
  721.      *      },
  722.      *      name="viewCategory")
  723.      * @Entity("category", expr="repository.findByUrl(name)")
  724.      * @Template("frontend/category.html.twig")
  725.      */
  726.     public function viewCategory(Category $category$sub1$sub2$sub3PaginatorInterface $paginatorRequest $request$forceRoute=false){
  727.         $twigData = array();
  728.         $twigData['link'] = $request->getPathInfo();
  729.         // $order = "desc";
  730.         $order null;
  731.         if ($request->get("order")) {
  732.           $order $request->get("order");
  733.         }
  734.         $twigData['order']= $order;
  735.         // $sorting = "popularity";
  736.         $sorting null;
  737.         if ($request->get("sorting")) {
  738.           $sorting $request->get("sorting");
  739.         }
  740.         $twigData['sorting']= $sorting;
  741.         $twigData['selected'] = array(
  742.             'main' => $category->getId(),
  743.             'sub1' => $sub1,
  744.             'sub2' => $sub2,
  745.             'sub3' => $sub3
  746.         );
  747.         $twigData['noLoader'] = true;
  748.         $findCategory false;
  749.         //Let's find the final category the product should be in
  750.         //We go 4 levels here
  751.         if($sub1){
  752.             foreach($category->getCategories() as $cat){
  753.                 if(strtolower($cat->getUrlName()) == strtolower(urldecode($sub1))){
  754.                     $twigData['selected']['sub1'] = $cat->getId();
  755.                     if($sub2){
  756.                         foreach($cat->getCategories() as $subCat){
  757.                             if(strtolower($subCat->getUrlName()) == strtolower(urldecode($sub2))){
  758.                                 $twigData['selected']['sub2'] = $subCat->getId();
  759.                                 if($sub3){
  760.                                     foreach($subCat->getCategories() as $subSubCat){
  761.                                         if(strtolower($subSubCat->getUrlName()) == strtolower(urldecode($sub3))){
  762.                                             $twigData['selected']['sub3'] = $subSubCat->getId();
  763.                                             $findCategory $subSubCat;
  764.                                             break;
  765.                                         }
  766.                                     }
  767.                                 }else{
  768.                                     $findCategory $subCat;
  769.                                     break;
  770.                                 }
  771.                             }
  772.                         }
  773.                     }else{
  774.                         $findCategory $cat;
  775.                         break;
  776.                     }
  777.                 }
  778.             }
  779.         }
  780.         $filter null;
  781.         if ($request->get('filter')){
  782.             $filter $request->get('filter');
  783.         }
  784.        
  785.         //If all else fail let's go back to original cat
  786.         if(!$findCategory)
  787.             $findCategory $category;
  788.        
  789.         $categoryPlacementQuery $this->entityMana->getRepository(Category::class)->getMyCategoryforplacemnt($findCategory);
  790.         $productsQuery=[];
  791.         $allproductsSubSubcategories = [];
  792.         if (!$filter){
  793.         if ($sorting == null){
  794.             if (count($categoryPlacementQuery) > 0){
  795.                 $resproductsQueryultat = array();
  796.                     foreach ($categoryPlacementQuery as $orderPlacement) {
  797.                         $categories $this->entityMana->getRepository(Category::class)->find($orderPlacement['cateId']);
  798.                         $findsubCategories $categories->getSubCategory();
  799.                             $QueryTimeTwo $this->entityMana->getRepository(Category::class)->getMyCategoryforplacemnt($categories);
  800.                             if(count($QueryTimeTwo) > 0){
  801.                                     foreach ($QueryTimeTwo as $findproduct) {
  802.                                         $catefindproduct $this->entityMana->getRepository(Category::class)->find($findproduct['cateId']);
  803.                                         $prods $this->entityMana->getRepository(Product::class)->getcategoriesByPlacement($catefindproduct$sorting$order);
  804.                                                 if(count($prods) > 0){
  805.                                                     foreach ($prods as $prod) {
  806.                                                         array_push($productsQuery$prod);  
  807.                                                     }
  808.                                                 }else{
  809.                                                     $findsubsubCategories $catefindproduct->getSubCategory();
  810.                                                     $allproductsSubSubcategories $this->entityMana->getRepository(Product::class)->getcategoriesByPlacement($findsubsubCategories$sorting$order);
  811.                                                 }
  812.                                     }
  813.                             }
  814.                             // else{
  815.                             //     $allProductsifNoSubCategories = $this->entityMana->getRepository(Product::class)->getcategoriesByPlacement($findsubCategories, $sorting, $order);
  816.                                 // if($allProductsifNoSubCategories){
  817.                                 //     foreach ($allProductsifNoSubCategories as $allProductsifNoSubCategory) {
  818.                                 //         if (!in_array($allProductsifNoSubCategory,$productsQuery)){
  819.                                 //             array_push($productsQuery, $allProductsifNoSubCategory);
  820.                                 //         }   
  821.                                 //     }    
  822.                                 // }
  823.                             // }
  824.                             if($allproductsSubSubcategories){
  825.                                 foreach ($allproductsSubSubcategories as $allproductsSubSubcategory) {
  826.                                     
  827.                                     if (!in_array($allproductsSubSubcategory,$productsQuery)){
  828.                                         array_push($productsQuery$allproductsSubSubcategory);
  829.                                     }   
  830.                                 }    
  831.                             }
  832.                     }
  833.             }else{
  834.                 $testcategories $this->entityMana->getRepository(Product::class)->getcategoriesByPlacement($findCategory$sorting$order);
  835.                
  836.                 if($testcategories){
  837.                     foreach ($testcategories as $testcategorie) {
  838.                         array_push($productsQuery$testcategorie);  
  839.                     }
  840.                 }
  841.             }
  842.             $categoryforPages $this->entityMana->getRepository(Product::class)->getcategoriesByPlacement($findCategory$sorting$order);
  843.             if($categoryforPages){
  844.                 foreach ($categoryforPages as $categoryforPage) {
  845.                     
  846.                     if (!in_array($categoryforPage,$productsQuery)){
  847.                         array_push($productsQuery$categoryforPage);
  848.                     }   
  849.                 }    
  850.             }
  851.         }else{
  852.             $productsQuery $this->entityMana->getRepository(Product::class)->getcategoriesByPlacement($findCategory$sorting$order);
  853.         }
  854.     }else{
  855.         // $productsQuery = $this->entityMana->getRepository(Product::class)->getcategoriesByPlacement($findCategory, $sorting, $order);
  856.         
  857.             $region explode('region_',$filter);
  858.             if (count($region) > 1){
  859.                 $regionName$region[1];
  860.                 $region $this->entityMana->getRepository(Region::class)->findOneBy([ 'name' => $regionName ])->getId();
  861.             }
  862.             $productsQuery $this->entityMana->getRepository(Product::class)->getcategoriesByPlacementWithFilter($findCategory$sorting$order$filter$region);
  863.     }
  864.         $page 1;
  865.         if(!empty($request->get('page')))
  866.             $page $request->get('page');
  867.         if(is_numeric($page)){
  868.             // Paginate the results of the query
  869.             $twigData['products'] = $paginator->paginate(
  870.             $productsQuery,
  871.             $request->query->getInt('page'$page),
  872.             24
  873.         );
  874.         if($forceRoute){
  875.             $twigData['products']->setUsedRoute('viewCategory');
  876.             $twigData['products']->setParam('name'$category->getUrlName());
  877.             $twigData['products']->setParam('sub1'$sub1);
  878.             $twigData['products']->setParam('sub2'$sub2);
  879.             $twigData['products']->setParam('sub3'$sub3);
  880.         }
  881.         $twigData['productsAmount'] = $twigData['products']->getTotalItemCount();
  882.         }else{
  883.             $this->addFlash('error'"le numéro de la page n'est pas valide");
  884.             return $this->redirectToRoute('viewCategory',[
  885.                 'name' => $category->getUrlName(),
  886.             ]);
  887.         }
  888.       
  889.       
  890.         $twigData['regions'] = $this->entityMana->getRepository(Region::class)->findBy(['province'=>'Qc']);
  891.         $twigData['conservations'] = $this->entityMana->getRepository(Conservation::class)->findAll();
  892.         $twigData['category'] = $findCategory;
  893.         // dd($twigData);
  894.         return $twigData;
  895.     }
  896.     /**
  897.      * @route({
  898.      *          "fr": "/vendeur/produit/editer/{id}",
  899.      *          "en": "/seller/product/edit/{id}"
  900.      *      },
  901.      *      options = {
  902.      *          "expose" = true
  903.      *      },
  904.      *      name="adminEditProduct")
  905.      * @Template("admin/product/product.html.twig")
  906.      * @Security("has_role('ROLE_ADMIN')")
  907.      */
  908.     public function editProduct(Request $requestUserService $userServImageService $imageServProductService $prodServProduct $product=nullDistributorService $distributorServ){
  909.         //Check if user is allowed to modify first
  910.         if(!$prodServ->allowedToModify($product))
  911.             die('Not allowed');
  912.         if(empty($product)){
  913.             $productId $request->get('productId');
  914.             $product $prodServ->getProductById($productId);
  915.             if(!$prodServ->allowedToModify($product))
  916.                 die('Hummm.... No product access, hacking?');
  917.         }
  918.         if ($request->get("action") == "edit_product_variation") {
  919.           return $this->redirect("/vendeur/produit/editer/".$request->get("product_id"));
  920.         }
  921.         if ($request->get("action") == "deactivate_product_variation") {
  922.           $productVariation $this->entityMana->getRepository(Product::class)->findOneBy([
  923.             'id' => $request->get("product_id"),
  924.           ]);
  925.           if ($productVariation) {
  926.             $productVariation->setAvailable(0);
  927.             $this->entityMana->persist($productVariation);
  928.             $this->entityMana->flush();
  929.           }
  930.           return $this->redirect("/vendeur/produit/editer/".$product->getId());
  931.         }
  932.         if ($request->get("action") == "deassign_variation") {
  933.           $productVariation $this->entityMana->getRepository(Product::class)->findOneBy([
  934.             'id' => $request->get("product_id"),
  935.           ]);
  936.           if ($productVariation) {
  937.             $productVariation->setParentProductId(null);
  938.             $this->entityMana->persist($productVariation);
  939.             $this->entityMana->flush();
  940.           }
  941.           return $this->redirect("/vendeur/produit/editer/".$product->getId());
  942.         }
  943.         if ($request->get("action") == "assign_this_product_to_parent") {
  944.           $product->setParentProductId($request->get("product_id"));
  945.           $this->entityMana->persist($product);
  946.           $this->entityMana->flush();
  947.           return $this->redirect("/vendeur/produit/editer/".$request->get("product_id"));
  948.         }
  949.         if ($request->get("action") == "generate_product_variation") {
  950.           $company $product->getCompany();
  951.           $productVariation = new Product();
  952.           $productVariation->setParentProductId($product->getId());
  953.           $productVariation->setOrigName($product->getOrigName());
  954.           $productVariation->setDeliveryType($product->getDeliveryType());
  955.           $productVariation->setActionWhenExpired($product->getActionWhenExpired());
  956.           $productVariation->setCategories($product->getCategories());
  957.           $productVariation->setConservation($product->getConservation());
  958.           $productVariation->setSubCategory($product->getSubCategory());
  959.           $productVariation->setRegion($product->getRegion());
  960.           $productVariation->setOrigBrandName($product->getOrigBrandName());
  961.           $productVariation->setDescription($product->getDescription());
  962.           $productVariation->setIngredients($product->getIngredients());
  963.           $productVariation->setOrigin($product->getOrigin());
  964.           $productVariation->setAvailable(1);
  965.           $tags $product->getTags();
  966.           foreach($tags as $tag) {
  967.             $productVariation->addTag($tag);
  968.           }
  969.           $sp = new Storage();
  970.           $sp->addProduct($productVariation);
  971.           $sp->setType("product");
  972.           $this->entityMana->persist($sp);
  973.           $sb = new Storage();
  974.           $sb->addProduct($productVariation);
  975.           $sb->setType("box");
  976.           $this->entityMana->persist($sb);
  977.           $ss = new Storage();
  978.           $ss->addProduct($productVariation);
  979.           $ss->setType("skid");
  980.           $this->entityMana->persist($ss);
  981.           $p = new Pricing();
  982.           $p->setPrice("0.00");
  983.           $p->setCurrency("CAD");
  984.           $p->setStorage($sp);
  985.           $p->setQuantity(1);
  986.           $productVariation->addPricing($p);
  987.           $productVariation->setCompany($company);
  988.           $productVariation->setIsConsumer(true);
  989.         //   $productVariation->setIsDisplayedInAssociationOnly(count($company->getAssociations())>0);
  990.           $productVariation->setIsDisplayedInAssociationOnly(0);
  991.           $this->entityMana->persist($productVariation);
  992.           $this->entityMana->flush();
  993.           return $this->redirect("/vendeur/produit/editer/".$product->getId());
  994.         }
  995.         $twigData = array();
  996.         $twigData['productEntry']= true;
  997.         $twigData['company'] = $product->getCompany();
  998.         $twigData['product'] = $product;
  999.         $companyProducts $this->entityMana->getRepository(Product::class)->findBy([
  1000.           'company' => $product->getCompany(),
  1001.           'parentProductId' => null,
  1002.         ]);
  1003.         $twigData['companyProducts'] = $companyProducts;
  1004.         $twigData['parent'] = false;
  1005.         if ($product->getParentProductId()) {
  1006.           $productParent $this->entityMana->getRepository(Product::class)->findOneBy([
  1007.             'id' => $product->getParentProductId(),
  1008.           ]);
  1009.           if ($productParent) {
  1010.             $twigData['parent'] = $productParent;
  1011.           }
  1012.         }
  1013.         $twigData['variations'] = [];
  1014.         $productVariations $this->entityMana->getRepository(Product::class)->findBy([
  1015.           'parentProductId' => $product->getId(),
  1016.           'available' => 1
  1017.         ]);
  1018.         if ($productVariations) {
  1019.           $twigData['variations'] = $productVariations;
  1020.         }
  1021.         $twigData['editProduct'] = $product->getId();
  1022.         if(!$request->isXmlHttpRequest() && $product->getPricings()->count() < 1){
  1023.             $product->addPricing(new Pricing());
  1024.         }
  1025.         $twigData['pageTitle'] = 'Edition du produit '.$product->getName();
  1026.        
  1027.         $form $this->createForm(ProductType::class, $product);
  1028.         $form->handleRequest($request);
  1029.         $twigData['addNewForm'] = $form->createView();
  1030.         if($request->isXmlHttpRequest()){
  1031.             //Ok let's save that new product
  1032.             $newProduct $form->getData();
  1033.             // if ($newProduct->getAlimentsDuQuebec() == true){
  1034.             //     $findAlimentDuQuebec = $this->entityMana->getRepository(Certification::class)->findBy(['name' => 'Aliments du Québec']);
  1035.             //     $newProduct->setAlimentsDuQuebecCertification($findAlimentDuQuebec[0]->getId());
  1036.             // }
  1037.             $this->entityMana->persist($newProduct);
  1038.             $this->entityMana->flush();
  1039.             $this->saveDataFromForm($newProduct$request$imageServ$userServtrue);
  1040.             //Let's update Solex if the product is already with them
  1041.             //if($_ENV['APP_ENV'] != 'dev'){
  1042.                 if($newProduct->isShippedByMaturin() && !empty($newProduct->getSolexId())){
  1043.                     $distributorServ->setProduct($newProduct);
  1044.                 }elseif($newProduct->isShippedByMaturin() && $newProduct->getIsJustInTime()){
  1045.                     $distributorServ->setProduct($newProduct);
  1046.                 }
  1047.             //}
  1048.             $response = new JsonResponse();
  1049.             $response->setData(array(
  1050.                 'success' => 1
  1051.             ));
  1052.             return $response;
  1053.         }
  1054.         return $twigData;
  1055.     }
  1056.     /**
  1057.      * @Route({
  1058.      *      "fr": "/livraison/priceDetail/ajax_search/{isFrozen}/{retailPrice}",
  1059.      *      "en": "/delivery/priceDetail/ajax_search/{isFrozen}/{retailPrice}"
  1060.      *      },
  1061.      *      name="priceDetailAJAXSearch"
  1062.      * )
  1063.      *@Security("has_role('ROLE_ADMIN')")
  1064.      */
  1065.     public function priceDetailAJAXSearch($isFrozen$retailPrice,PaymentService $paymentService)
  1066.     {
  1067.         $result = [];
  1068.         $CommandPreparationfees 1.10;
  1069.         $wrapingFees 0.55;
  1070.         if ($isFrozen == 1) {
  1071.             $wrapingFees 1.15;
  1072.         }
  1073.         $result['CommandPreparationfees'] = $CommandPreparationfees;
  1074.         $result['wrapingFees'] = $wrapingFees;
  1075.         if($retailPrice <= 6)
  1076.             $maturinPercentFees round($retailPrice 0.0852); //8.5%
  1077.         else
  1078.             $maturinPercentFees round($retailPrice 0.1152); //11.5%
  1079.         $result['maturinPercentFees'] = $maturinPercentFees;
  1080.         $creditPercentFees round($retailPrice 0.0352); //3.5%
  1081.         $result['creditPercentFees'] = $creditPercentFees;
  1082.         $fees round($maturinPercentFees +  $creditPercentFees $CommandPreparationfees $wrapingFees2);
  1083.         $result['feesTotal'] = $fees;
  1084.         $totalTaxable $fees;
  1085.         $totaltaxes $paymentService->calculateTaxes($totalTaxable"QC");
  1086.         $taxesToPay round($totaltaxes['totalTax'], 2);
  1087.         $result['taxesToPay'] = $taxesToPay;
  1088.         $feesTotal $fees $taxesToPay;
  1089.         $amountReceived round($retailPrice $feesTotal2);
  1090.         $result['amountReceived'] = $amountReceived;
  1091.         $amountAfterTaxes round($amountReceived +  $taxesToPay2);
  1092.         $result['amountAfterTaxes'] =  $retailPrice $fees;
  1093.         $totalFees=($retailPrice $amountAfterTaxes)/$retailPrice;
  1094.         $result['totalFees'] =$totalFees*100;
  1095.         $beneficeMarge $totalFees;
  1096.         $result['beneficeMarge'] =  $beneficeMarge*100;
  1097.         $buyerCost round($retailPrice 0.922); // 8% fees which the buyer see;
  1098.         $result['buyerCost'] = $buyerCost;
  1099.         die(json_encode(["results" => $result]));
  1100.     }
  1101.     /**
  1102.      * @route({
  1103.      *          "fr": "/vendeur/produit/nouveau/{id}/{cloneProductId}",
  1104.      *          "en": "/seller/product/new/{id}/{cloneProductId}"
  1105.      *      },
  1106.      *      options = {
  1107.      *          "expose" = true
  1108.      *      },
  1109.      *      defaults={
  1110.      *          "cloneProductId" = false,
  1111.      *          "id" = false
  1112.      *      },
  1113.      *      name="adminNewProduct")
  1114.      * @Security("has_role('ROLE_ADMIN')")
  1115.      * @Template("admin/product/product.html.twig")
  1116.      */
  1117.     public function newProduct(Request $requestUserService $userServImageService $imageServCompany $company=nullProductService $ProductService$cloneProductIdUrlGeneratorInterface $routerDistributorService $distributorServ){
  1118.         $twigData = array();
  1119.         $twigData['productEntry']= true;
  1120.         $user $userServ->getUser();
  1121.         if(empty($company)){
  1122.             $companies $user->getCompanies();
  1123.             if(count($companies) > 1){
  1124.                 $this->addFlash('error'"Vous avez plusieur boutiques, pour accéder au paiement utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
  1125.                 return $this->redirectToRoute('dashboard');
  1126.             }else{
  1127.                 $company $companies->get(0);
  1128.                 return $this->redirectToRoute('adminNewProduct', array('id' => $company->getId()));
  1129.             }
  1130.         }
  1131.         if(empty($company)){
  1132.             $this->addFlash('error'"Nous n'arrivons pas a trouver votre boutique, utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
  1133.             return $this->redirectToRoute('dashboard');
  1134.         }
  1135.         if($cloneProductId){
  1136.             $cloneProduct $ProductService->getProductById($cloneProductId);
  1137.             $cloneProduct->setMainImage(null);
  1138.             $product = clone $cloneProduct;
  1139.             //$product->purgeImages();
  1140.             //$product->purgeMainImage();
  1141.             $product->setNutritionFact(NULL);
  1142.             $product->setValidatedByDistributor(false);
  1143.             $product->setSolexId(null);
  1144.             $product->setQtyReadyToShip(0);
  1145.             $product->setId(NULL);
  1146.             // $product->setIsDisplayedInAssociationOnly($cloneProduct->getIsDisplayedInAssociationOnly());
  1147.             $product->setIsDisplayedInAssociationOnly(0);
  1148.             $product->purgeImages();
  1149.             //Clone subscriptions too
  1150.             if($cloneProduct->getIsSubscribable()){
  1151.                 $product->setIsSubscribable($cloneProduct->getIsSubscribable());
  1152.                 $product->setIsOnlySubscribable($cloneProduct->getIsOnlySubscribable());
  1153.                 $product->setIsOnlySubscribableToType($cloneProduct->getIsOnlySubscribableToType());
  1154.             }
  1155.         }else{
  1156.             $product = new Product();
  1157.             if(!$request->isXmlHttpRequest()){
  1158.                 $p = new Pricing();
  1159.                 $p->setQuantity(1);
  1160.                 $product->addPricing($p);
  1161.             }
  1162.             $product->setCompany($company);
  1163.             $product->setIsConsumer(true);
  1164.             // $product->setIsDisplayedInAssociationOnly(count($company->getAssociations())>0);
  1165.             $product->setIsDisplayedInAssociationOnly(0);
  1166.         }
  1167.         $twigData['product'] = $product;
  1168.         $form $this->createForm(ProductType::class, $product);
  1169.         //Add the company if the user is part of that company
  1170.         if(!$userServ->getUser()->getCompanies()->contains($company) && !$userServ->isGod())
  1171.             die('Error, you arent suppose to see this. Reported');
  1172.         $twigData['company'] = $company;
  1173.         $form->handleRequest($request);
  1174.         $twigData['addNewForm'] = $form->createView();
  1175.         if($request->isXmlHttpRequest()){
  1176.             //Ok let's save that new product
  1177.             //$newProduct = $form->getData();
  1178.             $newProduct $product;
  1179.             //Set the company
  1180.             $newProduct->setCompany($company);
  1181.             if(!empty($request->get('draft')))
  1182.                 $newProduct->setDraft(true);
  1183.             $this->entityMana->persist($newProduct);
  1184.             $this->entityMana->flush();
  1185.             $this->saveDataFromForm($newProduct$request$imageServ$userServ);
  1186.             if(empty($request->get('draft'))){
  1187.                 if($newProduct->isShippedByMaturin() && !$newProduct->getIsJustInTime()){
  1188.                     //Product saved, let's send a notification
  1189.                     $urlInventory $router->generate'replenishment', array ('_locale' => $userServ->getUser()->getLocale(), 'id' => $newProduct->getCompany()->getId()));
  1190.                     $userServ->addNotification('info''Mise en inventaire''Veuillez planifier un rendez-vous pour la mise en inventaire du produit '.$newProduct->getName().' <a href="'.$urlInventory.'">ici</a>');
  1191.                 }
  1192.                 if($newProduct->isShippedByMaturin() && $newProduct->getIsJustInTime()){
  1193.                     $distributorServ->setProduct($newProduct);
  1194.                 }
  1195.                 $response = new JsonResponse();
  1196.                 $response->setData(array(
  1197.                     'success' => 1
  1198.                 ));
  1199.                 return $response;
  1200.             }else{
  1201.                 //It's a draft
  1202.                 $response = new JsonResponse();
  1203.                 $response->setData(array(
  1204.                     'success' => 1,
  1205.                     'preview' => $this->generateUrl('viewProduct', array('producerUrl' => $newProduct->getCompany()->getUrlName(), 'productName' => $newProduct->getUrlName(), 'id' => $newProduct->getId()))
  1206.                 ));
  1207.                 return $response;
  1208.             }
  1209.         }
  1210.         return $twigData;
  1211.     }
  1212.     /*
  1213.      * @TODO move all this in the form instead
  1214.      */
  1215.     private function saveDataFromForm($newProduct$request$imageServ$userServ$edit=false){
  1216.         //Let's start by deleting the temporary images not needed
  1217.         $delImages json_decode($request->get('imagesToDelete'));
  1218.         foreach($delImages as $delImage){
  1219.                 $imageServ->deleteImage($delImagefalse$newProduct);
  1220.         }
  1221.         //Let's build the Images for the new product
  1222.         $Images json_decode($request->get('imagesAndDescriptions'));
  1223.         $order 1;
  1224.         foreach($Images as $newImage){
  1225.             $image $imageServ->getImage($newImage->id);
  1226.             if($image){
  1227.                 $image->setDescription($newImage->description);
  1228.                 $image->setDisplayOrder($order);
  1229.                 $image->setCategory('product');
  1230.                 $image->addProduct($newProduct);
  1231.                 $this->entityMana->persist($image);
  1232.                 if($order == 1)
  1233.                     $newProduct->setMainImage($image);
  1234.                 $order++;
  1235.             }
  1236.         }
  1237.         $this->entityMana->flush();
  1238.         //Erasing the pricing before saving them
  1239.         //Easier for editing right now
  1240.         if(!empty($request->get('prices'))){
  1241.             $pricings $newProduct->getPricings();
  1242.             foreach($pricings as $pricing){
  1243.                 $newProduct->removePricing($pricing);
  1244.                 $this->entityMana->remove($pricing);
  1245.             }
  1246.             $this->entityMana->flush();
  1247.             //Building the pricing
  1248.             //Need to be incorporated in the Forms at some point
  1249.             $pricings json_decode($request->get('prices'));
  1250.             foreach($pricings as $pricing){
  1251.                 $price = new Pricing();
  1252.                 $price->setCurrency('CAD');
  1253.                 $price->setPrice($pricing->price);
  1254.                 $price->addProduct($newProduct);
  1255.                 if(!empty($pricing->qty) && $this->userServ->isGod())
  1256.                     $price->setQuantity($pricing->qty);
  1257.                 else
  1258.                     $price->setQuantity(1);
  1259.                 /*
  1260.                  * Old code put at some point to bypass the code above
  1261.                  * forgot why it was removed or forced to 1
  1262.                  */
  1263.                 //$price->setQuantity(1);
  1264.                 $storage_found false;
  1265.                 foreach($newProduct->getStorages() as $storage){
  1266.                     if($storage->getType() == $pricing->unit){
  1267.                         $storage_found true;
  1268.                         $price->setStorage($storage);
  1269.                         break;
  1270.                     }
  1271.                 }
  1272.                 if (!$storage_found) {
  1273.                   $s = new Storage();
  1274.                   $s->setType($pricing->unit);
  1275.                   $s->setQuantityProduct(0);
  1276.                   $newProduct->addStorage($s);
  1277.                   $price->setStorage($s);
  1278.                 }
  1279.                 /*
  1280.                 if($pricing->unit == 'vrac' && !$vrac){
  1281.                     $s = new Storage();
  1282.                     $s->setType('vrac');
  1283.                     $s->setQuantityProduct(0);
  1284.                     $newProduct->addStorage($s);
  1285.                     $price->setStorage($s);
  1286.                 }
  1287.                  */
  1288.                 $this->entityMana->persist($price);
  1289.                 $newProduct->addPricing($price);
  1290.             }
  1291.         }
  1292.         //Building the tags
  1293.         $formTags json_decode($request->get('tags'));
  1294.         $newTags = new ArrayCollection();
  1295.         foreach($formTags as $tag){
  1296.             $newTag $this->entityMana->getRepository(Tag::class)->findOneByName($tag);
  1297.             //One with this name already exist in the database, let's link to that one
  1298.             if(empty($newTag)){
  1299.                 //This tag don't exist let's create
  1300.                 $newTag = new Tag();
  1301.                 $newTag->setName(trim($tag));
  1302.                 $newTag->setLocale($userServ->getUser()->getLocale());
  1303.                 $this->entityMana->persist($newTag);
  1304.             }
  1305.             $newProduct->addTag($newTag);
  1306.             $newTags[]=$newTag;
  1307.         }
  1308.         //For when editing we need to remove those not good too
  1309.         if(!empty($formTags)){
  1310.             foreach($newProduct->getTags() as $t){
  1311.                 if(!$newTags->contains($t))
  1312.                     $newProduct->removeTag($t);
  1313.             }
  1314.         }
  1315.         //Fix a weird bug with the Ajax category refresh
  1316.         if(!empty($_POST['product']['subCategory']) && is_numeric($_POST['product']['subCategory'])){
  1317.             $category $this->entityMana->getRepository(category::class)->find($_POST['product']['subCategory']);
  1318.             $newProduct->setSubCategory($category);
  1319.         }
  1320.         //Fix a bug when switching from Independant shipping back to Maturin
  1321.         if($newProduct->isShippedByMaturin()){
  1322.             if($newProduct->getQtyReadyToShip() == 1)
  1323.                 $newProduct->setQtyReadyToShip(0);
  1324.         } else {
  1325.             $newProduct->setQtyReadyToShip(1);
  1326.         }
  1327.         // ugly fix
  1328.         if (!empty($_POST['product']['qtyReadyToShip']) && is_numeric($_POST['product']['qtyReadyToShip'])
  1329.             && ((int)$_POST['product']['qtyReadyToShip']) > 1){
  1330.             // product[qtyReadyToShip]
  1331.             $newProduct->setQtyReadyToShip((int)$_POST['product']['qtyReadyToShip']);
  1332.         }
  1333.         //End of saving the Ingredients
  1334.         $this->entityMana->persist($newProduct);
  1335.         $this->entityMana->flush();
  1336.     }
  1337.     /**
  1338.      * @route( "/vendeur/produits/update/{id}",
  1339.      *      name="adminUpdateProducts")
  1340.      */
  1341.     public function updateProducts(Company $companyDistributorService $distributorServRequest $request){
  1342.         if($company->hasInventoryWithMaturin()){
  1343.             $distributorServ->updateProductsOf($company);
  1344.         }
  1345.         $this->addFlash('success''Mise a jour fait de '.$company->getName());
  1346.         $url $_SERVER['HTTP_REFERER'];
  1347.         return $this->redirect($url301);
  1348.     }
  1349.     /**
  1350.      * @route({
  1351.      *          "fr": "/vendeur/produits/liste/{id}",
  1352.      *          "en": "/seller/product/list/{id}"
  1353.      *      },
  1354.      *      defaults = {
  1355.      *          "id" = false
  1356.      *      },
  1357.      *      options = { "expose" = true },
  1358.      *      name="adminListProducts")
  1359.      * @Template("admin/product/list.html.twig")
  1360.      */
  1361.     public function listProduct(ProductService $ProductServiceEntityManagerInterface $emRequest $requestCompany $company=nullDistributorService $distributorServUserService $userServ){
  1362.         $twigData = array();
  1363.         if(empty($company)){
  1364.             $user $userServ->getUser();
  1365.             $companies $user->getCompanies();
  1366.             if(count($companies) > 1){
  1367.                 $this->addFlash('error'"Vous avez plusieur boutiques, pour accéder a l'inventaire via le menu");
  1368.                 return $this->redirectToRoute('dashboard');
  1369.             }else{
  1370.                 $company $companies->get(0);
  1371.             }
  1372.         }
  1373.         //@SECuritY
  1374.         if(!$this->companyServ->allowedToModify($company) || empty($company)){
  1375.             $this->addFlash('error'"Vous n'avez pas d'accès Ã  cette boutique, veuillez utiliser le menu");
  1376.             return $this->redirectToRoute('dashboard');
  1377.         }
  1378.         /*
  1379.          * Conflict with the cart, when a sale occur the quantity change
  1380.          * If the producer check the list of product when a order was done but not shipped yet
  1381.          * The quantity will reset to the one in Inventory which can make a "sale" happen
  1382.          * as quantity is available again
  1383.          */
  1384.         if($company->hasInventoryWithMaturin()) 
  1385.             $distributorServ->updateProductsOf($company);
  1386.     $twigData['products'] = $em->getRepository(Product::class)
  1387.             ->findBy([
  1388.                 'company' => $company,
  1389.                 'draft' => false
  1390.             ] );
  1391.         $twigData['company']=$company;
  1392.                 // $dateExpirations = [];
  1393.                 // // dump($twigData['products']);
  1394.                 
  1395.                 //     for($i=0; $i < count($twigData['products']);$i++){
  1396.                 //         // dump($dateExpirations);
  1397.                 //         //if (in_array($twigData['products'][$i]->getOrigName(), $dateExpirations)){
  1398.                 //             // dump('nom existe');
  1399.                 //         //}else{
  1400.                 //             if(empty($dateExpirations)){
  1401.                 //                 $dateExpirations[] = [ 
  1402.                 //                     'id' => $twigData['products'][$i]->getId(),
  1403.                 //                     'origName' => $twigData['products'][$i]->getOrigName(),
  1404.                 //                     'expirationDate' =>$twigData['products'][$i]->getExpirationDate()
  1405.                 //                 ];
  1406.                 //             }else{
  1407.                 //                 if ($twigData['products'][$i]->getExpirationDate() < $twigData['products'][$i-1]->getExpirationDate()){
  1408.                 //                     $dateExpirations[] = [ 
  1409.                 //                         'id' => $twigData['products'][$i]->getId(),
  1410.                 //                         'origName' => $twigData['products'][$i]->getOrigName(),
  1411.                 //                         'expirationDate' =>$twigData['products'][$i]->getExpirationDate()
  1412.                 //                     ];
  1413.                 //                 }
  1414.                 //             //     dump($twigData['products'][$i]->getOrigName()) ;
  1415.                 //             //    dump($twigData['products'][$i]->getExpirationDate()) ;
  1416.                 //             }
  1417.                            
  1418.                 //         }
  1419.                 //     //}
  1420.                 //     $twigData['expirationDates'] = $dateExpirations;
  1421.          
  1422.                 
  1423.             
  1424.          
  1425.         return $twigData;
  1426.         
  1427.     }
  1428.     /**
  1429.      * @Route("/API/setProduct/{action}",
  1430.      *      options = { "expose" = true },
  1431.      *      name = "setProductByAction"
  1432.      * )
  1433.      *
  1434.      * @Security("has_role('ROLE_ADMIN')")
  1435.      *
  1436.      */
  1437.     public function setProductByActionFromAPI($actionRequest $requestProductService $productServ){
  1438.         $action strtolower($action);
  1439.         $success false;
  1440.         switch($action){
  1441.             case 'available':
  1442.                 $id $request->get('id');
  1443.                 $available $request->get('available');
  1444.                 $product $productServ->getProductById($id);
  1445.                 if($productServ->allowedToModify($product)){
  1446.                     $product->setAvailable($available);
  1447.                     $this->entityMana->persist($product);
  1448.                     $this->entityMana->flush();
  1449.                     $success true;
  1450.                 }
  1451.                 break;
  1452.             case 'delete':
  1453.                 $id $request->get('id');
  1454.                 if($productServ->deleteProductById($id))
  1455.                     $success true;
  1456.                 break;
  1457.         }
  1458.         $response = new jsonresponse();
  1459.         $response->setdata(array(
  1460.             'success' => $success
  1461.         ));
  1462.             return $response;
  1463.     }
  1464.     /**
  1465.      * @Route("/API/getProduct/{action}",
  1466.      *      options = { "expose" = true },
  1467.      *      name = "getProductByAction"
  1468.      * )
  1469.      *
  1470.      */
  1471.     public function getProductByActionFromAPI($actionRequest $requestProductService $productServPaginatorInterface $paginatorUserService $userServ$forcedValues false$returnJSON true){
  1472.         $action strtolower($action);
  1473.         $success false;
  1474.         $data = array();
  1475.         switch($action){
  1476.             case 'getcategories':
  1477.                 $id $request->get('id');
  1478.                 $category $this->entityMana->getRepository(Category::class)->findOneBy(['id' => $id]);
  1479.                 $subCategory $this->entityMana->getRepository(Category::class)->getSubCategories($categorytrue);
  1480.                 if($subCategory){
  1481.                     $group = array();
  1482.                     foreach($subCategory as $sub){
  1483.                         $group[$sub->getSubcategory()->getName()][] = "<option value='".$sub->getId()."'>".$sub->getName()."</option>";
  1484.                     }
  1485.                     $data '';
  1486.                     foreach($group as $key => $choice){
  1487.                         $data .= '<optgroup label="'.$key.'">'.implode(''$choice).'</optgroup>';
  1488.                     }
  1489.                     $success true;
  1490.                 }
  1491.                 break;
  1492.             case 'getproductsbytokenpagination':
  1493.                 /*
  1494.                 $page = $request->get('page');
  1495.                 $token = $request->get('token');
  1496.                 $search = $this->entityMana->getRepository(UserSearch::class)->findOneBy(['token' => $token]);
  1497.                  */
  1498.                 if($search){
  1499.                     $forcedValues = array(
  1500.                         'page' => $page,
  1501.                         'filters' => $search->getRawFilters(),
  1502.                         'token' => $token
  1503.                     );
  1504.                     return $this->getProductByActionFromAPI($search->getSearch(), $request$productServ$paginator$userServ$forcedValues);
  1505.                 }
  1506.                 break;
  1507.             case 'getproductsbyfiltering':
  1508.                 $data = array(
  1509.                     'html' => '',
  1510.                     'amount' => '0'
  1511.                 );
  1512.                 $page 1;
  1513.                 if($forcedValues){
  1514.                     $filters json_decode($forcedValues['filters']);
  1515.                     $page $forcedValues['page'];
  1516.                 }else
  1517.                     $filters json_decode($request->get('filters'));
  1518.                 $filter['pricings']=array();
  1519.                 $filter['conservation']=array();
  1520.                 $filter['region']=array();
  1521.                 $filter['deliveryType']=array();
  1522.                 foreach($filters as $k => $f){
  1523.                     switch(strtolower($f->type)){
  1524.                         case 'aliment_quebec':
  1525.                             $filter['alimentsDuQuebec']=1;
  1526.                             break;
  1527.                         case 'prix_laureat':
  1528.                             $filter['isPrixLaureat']=1;
  1529.                             break;
  1530.                         case 'certification':
  1531.                             $filter['alimentsDuQuebecCertification']=$f->id;
  1532.                             break;
  1533.                         case "category":
  1534.                             $cat $this->entityMana->getRepository(Category::class)->findOneBy(array('id' => $f->id));
  1535.                             if($cat){
  1536.                                 $products $this->productServ->getProductsFromCategory($catfalse);
  1537.                             }
  1538.                             break;
  1539.                         case 'shipping':
  1540.                             $filter['DeliveryType'][] = $f->id;
  1541.                             break;
  1542.                         case "price":
  1543.                             $filter['pricings'][]=$f->id;
  1544.                             break;
  1545.                         case "region":
  1546.                             $filter['region'][]=$this->entityMana->getRepository(Region::class)->findOneBy(array('id' => $f->id));
  1547.                             break;
  1548.                         case "conservation":
  1549.                             $filter['conservation'][]=$this->entityMana->getRepository(Conservation::class)->findOneBy(array('id' => $f->id));
  1550.                             break;
  1551.                         case "page":
  1552.                             if(empty($forcedValues))
  1553.                                 $page $f->id;
  1554.                             break;
  1555.                     }
  1556.                 }
  1557.                 //If no category and selecting at large
  1558.                 if(empty($products))
  1559.                     $products $this->entityMana->getRepository(Product::class)->getBaseProductsForSearching();
  1560.                 $join false;
  1561.                 foreach($filter as $k => $v){
  1562.                     if(!empty($v)){
  1563.                         if($k == 'pricings'){
  1564.                             $pricing = array();
  1565.                             foreach($v as $p){
  1566.                                 //Because of the multiple here, we need to do a query build
  1567.                                 //Let's not forget that Maturin has a 8% increase in price so this is why there is a double
  1568.                                 //query here
  1569.                                 switch($p){
  1570.                                     case '0';
  1571.                                         $now = new \DateTime();
  1572.                                         $products->setParameter('now'$now);
  1573.                                         $products->leftJoin('p.discountPricings''discount');
  1574.                                         $products->andWhere('discount.startDate <= :now');
  1575.                                         $products->andWhere('discount.endDate >= :now');
  1576.                                         $pricing[] = '(discount.isADiscount = 1)';
  1577.                                         break;
  1578.                                     case '10';
  1579.                                         $mPricing 10 - (10 0.08);
  1580.                                         $pricing[] = '(pricing.price < 10 and p.DeliveryType = 1)';
  1581.                                         $pricing[] = '(pricing.price < '.$mPricing.' and p.DeliveryType = 0)';
  1582.                                         break;
  1583.                                     case '10-25';
  1584.                                         $minPricing 10 - (10 0.08);
  1585.                                         $maxPricing 25 - (25 0.08);
  1586.                                         $pricing[] = '(pricing.price >= 10 and pricing.price < 25 and p.DeliveryType=1)';
  1587.                                         $pricing[] = '(pricing.price >= '.$minPricing.' and pricing.price < '.$maxPricing.' and p.DeliveryType=0)';
  1588.                                         break;
  1589.                                     case '25-50';
  1590.                                         $minPricing 25 - (25 0.08);
  1591.                                         $maxPricing 50 - (50 0.08);
  1592.                                         $pricing[] = '(pricing.price >= 25 and pricing.price < 50 and p.DeliveryType=1)';
  1593.                                         $pricing[] = '(pricing.price >= '.$minPricing.' and pricing.price < '.$maxPricing.' and p.DeliveryType=0)';
  1594.                                         break;
  1595.                                     case '50';
  1596.                                         $maxPricing 50 - (50 0.08);
  1597.                                         $pricing[] = '(pricing.price >= 50 and p.DeliveryType=1)';
  1598.                                         $pricing[] = '(pricing.price >= '.$maxPricing.' and p.DeliveryType=0)';
  1599.                                         break;
  1600.                                 }
  1601.                             }
  1602.                             if(!empty($pricing) && count($pricing) > 0){
  1603.                                 if(!$join){
  1604.                                     $products->leftJoin('p.pricings''pricing');
  1605.                                     $join true;
  1606.                                 }
  1607.                                 if(count($pricing) == 1){
  1608.                                     $products->andWhere(current($pricing));
  1609.                                 }else{
  1610.                                     $query implode(' OR '$pricing);
  1611.                                     $products->andWhere($query);
  1612.                                 }
  1613.                             }
  1614.                         }else{
  1615.                             //If it's a array
  1616.                             if(is_array($v)){
  1617.                                 $products->andWhere("p.$k IN ( :filter_".$k.")");
  1618.                                 $products->setParameter('filter_'.$k$v);
  1619.                             }else{
  1620.                                 $products->andWhere("p.$k = :filter_".$k);
  1621.                                 $products->setParameter('filter_'.$k$v);
  1622.                             }
  1623.                         }
  1624.                     }
  1625.                 }
  1626.                 $paginatorProducts false;
  1627.                 if(!empty($products)){
  1628.                     $products $products->getQuery();
  1629.                     if(!$returnJSON)
  1630.                         return $products;
  1631.                     // Paginate the results of the query
  1632.                     $twigData['products'] = $paginator->paginate(
  1633.                         $products,
  1634.                         $request->query->getInt('page'$page),
  1635.                         24
  1636.                     );
  1637.                     $data['amount'] = $twigData['products']->getTotalItemCount();
  1638.                     $products $products->getResult();
  1639.                     //Let's save the search for pagination and others
  1640.                     $twigData['ajax'] = true;
  1641.                     $twigData['masonryProducts'] = $products;
  1642.                     if(!$forcedValues){
  1643.                         $twigData['searchToken'] = uniqid();
  1644.                         $userServ->saveSearch($action$data['amount'], 'adv'$twigData['searchToken'], $request->get('filters'));
  1645.                     }else{
  1646.                         $twigData['searchToken'] = $forcedValues['token'];
  1647.                     }
  1648.                     $data['html'] = $this
  1649.                         ->get('twig')
  1650.                         ->render('frontend/productMasonry.html.twig'$twigData);
  1651.                 }else{
  1652.                     $products $this->entityMana->getRepository(Product::class)->getSalableProducts();
  1653.                     $data['html'] = $this
  1654.                         ->get('twig')
  1655.                         ->render('frontend/productMasonry.html.twig', array(
  1656.                             'masonryProducts' => $products,
  1657.                             'ajax' => true
  1658.                     ));
  1659.                 }
  1660.                 $success true;
  1661.                 break;
  1662.         }
  1663.         $response = new jsonresponse();
  1664.         if($returnJSON){
  1665.             if(!empty($twigData['searchToken'])){
  1666.                 $response->setdata(array(
  1667.                     'success' => $success,
  1668.                     'data' => $data,
  1669.                     'token' => $twigData['searchToken']
  1670.                 ));
  1671.             }else{
  1672.                 $response->setdata(array(
  1673.                     'success' => $success,
  1674.                     'data' => $data,
  1675.                     'token' => ''
  1676.                 ));
  1677.             }
  1678.             return $response;
  1679.         }else{
  1680.             return $rawResults;
  1681.         }
  1682.     }
  1683. }