src/Controller/ProductsController.php line 26

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\ActionShock;
  4. use App\Entity\AdditionalCompanyInformation;
  5. use App\Entity\CustomerControl;
  6. use App\Entity\LotNumber;
  7. use App\Entity\Products;
  8. use App\Entity\FreeProductPromotion;
  9. use App\Entity\SpecialDiscount;
  10. use App\Repository\LotNumberRepository;
  11. use App\Service\ActionShockService;
  12. use App\Service\CrossedPriceDiscountService;
  13. use App\Service\QuickSaleOffers;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. class ProductsController extends AbstractController
  20. {
  21.     #[Route('/products', name: 'products')]
  22.     public function index(EntityManagerInterface $manager, ActionShockService $actionShockService, CrossedPriceDiscountService $crossedPriceDiscountService, QuickSaleOffers $quickSaleOffers): Response
  23.     {
  24.         $actionShockService->updateActionShocksStatus();
  25.         $additionalInformations = null;
  26.         $checkControl = $manager->getRepository(CustomerControl::class)->findOneBy(array('user' => $this->getUser(), 'finish' => false));
  27.         if (!$checkControl) {
  28.             $user = $this->getUser();
  29.         } else {
  30.             $user = $checkControl->getCustomer();
  31.         }
  32.         if ($user != null) {
  33.             $additionalInformations = $manager->getRepository(AdditionalCompanyInformation::class)->findOneBy(array('user' => $user));
  34.             if ($additionalInformations->getCompanyCountry() == null) {
  35.                 $this->addFlash('danger', 'Veuillez remplir vos coordonnées!');
  36.                 return $this->redirectToRoute('profile');
  37.             }
  38.         }
  39.         $information = $manager->getRepository(AdditionalCompanyInformation::class)->findOneBy(array('user' => $user));
  40.         $products = $manager->getRepository(Products::class)->getAllProduct($information);
  41.         $products = $this->calculateRebatePricePharmacy($products);
  42.         $products = $crossedPriceDiscountService->decorateProducts($products);
  43.         $specialDiscounts = $manager->getRepository(SpecialDiscount::class)->findAll();
  44.         if ($specialDiscounts != null) {
  45.             $specialDiscount = $specialDiscounts[0];
  46.         } else {
  47.             $specialDiscount = null;
  48.         }
  49.         if (!$checkControl) {
  50.             $checkControl = null;
  51.         }
  52.         $freeProductPromotions = $manager->getRepository(FreeProductPromotion::class)->findAllActiveIndexedByReference();
  53.         return $this->render('products/index.html.twig', [
  54.             'products' => $products,
  55.             'shockActionTypes' => ActionShock::TYPES,
  56.             'user' => $user,
  57.             'information' => $additionalInformations,
  58.             'checkControl' => $checkControl,
  59.             'specialDiscount' => $specialDiscount,
  60.             'freeProductPromotions' => $freeProductPromotions,
  61.             'quickSaleBanner' => $additionalInformations
  62.                 ? $quickSaleOffers->banner($additionalInformations->getCompanyCountry())
  63.                 : null,
  64.         ]);
  65.     }
  66.     private function calculateRebatePricePharmacy($products)
  67.     {
  68.         foreach ($products as &$product) {
  69.             $totalRebate = ($product['pricePharmacy'] / 100) * $this->getUser()->getAdditionalPercentage();
  70.             $item['totalRebate'] = floatval(number_format($totalRebate, 2, '.', ''));
  71.             $item['PriceRebateInclude'] = floatval(number_format($product['pricePharmacy'] - $item['totalRebate'], 2, '.', ''));
  72.             $product['pricePharmacyWithRebate'] = $item['PriceRebateInclude'];
  73.         }
  74.         //        dd($products);
  75.         return $products;
  76.     }
  77.     private function slugify(string $text): string
  78.     {
  79.         // Remplace les caractères non-ASCII
  80.         $text = iconv('UTF-8', 'ASCII//TRANSLIT', $text);
  81.         // Remplace les caractères non alphanumériques par des tirets
  82.         $text = preg_replace('/[^a-z0-9]+/i', '-', $text);
  83.         // Supprime les tirets en début et fin
  84.         $text = trim($text, '-');
  85.         // Convertit en minuscules
  86.         $text = strtolower($text);
  87.         
  88.         return $text;
  89.     }
  90.     #[Route('/product/{id}-{slug}', name: 'product_show', requirements: ['id' => '\d+'])]
  91.     public function show(int $id, string $slug, EntityManagerInterface $manager, CrossedPriceDiscountService $crossedPriceDiscountService, QuickSaleOffers $quickSaleOffers): Response
  92.     {
  93.         $checkControl = $manager->getRepository(CustomerControl::class)->findOneBy(array('user' => $this->getUser(), 'finish' => false));
  94.         if (!$checkControl) {
  95.             $user = $this->getUser();
  96.         } else {
  97.             $user = $checkControl->getCustomer();
  98.         }
  99.         $information = $manager->getRepository(AdditionalCompanyInformation::class)->findOneBy(array('user' => $user));
  100.         
  101.         // Récupère TOUS les produits avec la même logique que le DataTable
  102.         $allProducts = $manager->getRepository(Products::class)->getAllProduct($information);
  103.         
  104.         // Applique le même filtrage de stock que allProductJson
  105.         $excludedDepots = LotNumber::EXCLUDED_DEPOTS;
  106.         foreach ($allProducts as $index => $prod) {
  107.             $quantity = 0;
  108.             if ($allProducts[$index]['lotNumber']) {
  109.                 // keep stock only for valid warehouses
  110.                 $allProducts[$index]['lotNumber'] = array_values(array_filter($allProducts[$index]['lotNumber'], function ($lot) use ($excludedDepots) {
  111.                     return $lot['depot'] !== LotNumber::PHYSICAL_DEPOT && $lot['stock'] > 0;
  112.                 }));
  113.                 if (count($allProducts[$index]['lotNumber']) === 1 && $allProducts[$index]['lotNumber'][0]['depot'] === LotNumber::ONLINE_DEPOT) {
  114.                     $quantity = $allProducts[$index]['lotNumber'][0]['stock'];
  115.                 } else {
  116.                     array_walk($allProducts[$index]['lotNumber'], function ($lot) use (&$quantity, $excludedDepots) {
  117.                         if (!in_array($lot['depot'], $excludedDepots)) {
  118.                             $quantity += $lot['stock'];
  119.                         }
  120.                     });
  121.                 }
  122.             }
  123.             $allProducts[$index]['quantity'] = $quantity;
  124.         }
  125.         
  126.         // Trouve le produit spécifique dans le tableau
  127.         $productData = null;
  128.         foreach ($allProducts as $prod) {
  129.             if ($prod['id'] == $id) {
  130.                 $productData = $prod;
  131.                 break;
  132.             }
  133.         }
  134.         
  135.         if (!$productData) {
  136.             throw $this->createNotFoundException('Produit non trouvé');
  137.         }
  138.         // Récupère l'entité produit pour les relations
  139.         $product = $manager->getRepository(Products::class)->find($id);
  140.         
  141.         // Filtre les lots valides avec DLU (pour l'affichage)
  142.         $validLots = [];
  143.         if (isset($productData['lotNumber']) && is_array($productData['lotNumber'])) {
  144.             foreach ($productData['lotNumber'] as $lotData) {
  145.                 if (isset($lotData['dlu']) && $lotData['dlu'] !== null && $lotData['stock'] > 0) {
  146.                     $validLots[] = $lotData;
  147.                 }
  148.             }
  149.             
  150.             // Trie par DLU (du plus lointain au plus proche)
  151.             usort($validLots, function($a, $b) {
  152.                 if (!isset($a['dlu']) || !isset($b['dlu'])) return 0;
  153.                 if (!($a['dlu'] instanceof \DateTime) || !($b['dlu'] instanceof \DateTime)) return 0;
  154.                 return $b['dlu']->getTimestamp() - $a['dlu']->getTimestamp();
  155.             });
  156.         }
  157.         // Calcul du prix pharmacie avec remise si applicable
  158.         $pricePharmacyWithRebate = null;
  159.         if ($information && $information->getCompanyTypePro() === 'Pharmacie' && $product->getPricePharmacy()) {
  160.             $percentPharmacy = $user->getAdditionalPercentage();
  161.             $pricePharmacyWithRebate = $product->getPricePharmacy() - ($product->getPricePharmacy() * $percentPharmacy / 100);
  162.         }
  163.         $crossedPriceDiscount = $crossedPriceDiscountService->resolve($product->getId(), $product->getPrice());
  164.         $country = $information?->getCompanyCountry();
  165.         $folder = $country === 'Belgique' ? 'BE' : 'LU';
  166.         $groupedLots = [];
  167.         foreach ($validLots as $lotData) {
  168.             $number = trim((string) ($lotData['lotNumber'] ?? ''));
  169.             if ($number === '') {
  170.                 continue;
  171.             }
  172.             $dlu = ($lotData['dlu'] ?? null) instanceof \DateTimeInterface ? $lotData['dlu'] : null;
  173.             if (!isset($groupedLots[$number])) {
  174.                 $groupedLots[$number] = ['dlu' => $dlu];
  175.             } elseif ($dlu && ($groupedLots[$number]['dlu'] === null || $dlu < $groupedLots[$number]['dlu'])) {
  176.                 $groupedLots[$number]['dlu'] = $dlu;
  177.             }
  178.         }
  179.         $lotChoices = [];
  180.         foreach ($groupedLots as $number => $row) {
  181.             $stock = $quickSaleOffers->stock($product, $number, $folder);
  182.             if ($stock < 1) {
  183.                 continue;
  184.             }
  185.             $offer = $quickSaleOffers->lotOffer((int) $product->getId(), $number, $country);
  186.             $quickSale = $offer !== null
  187.                 && (float) $offer['displayPercent'] > 0
  188.                 && (float) $offer['finalPrice'] < (float) $product->getPrice();
  189.             $lotChoices[] = [
  190.                 'lot' => (string) $number,
  191.                 'dlu' => $row['dlu'] ? $row['dlu']->format('d/m/Y') : '',
  192.                 'dluTs' => $row['dlu'] ? $row['dlu']->getTimestamp() : 0,
  193.                 'stock' => $stock,
  194.                 'quickSale' => $quickSale,
  195.                 'finalPrice' => $quickSale ? (float) $offer['finalPrice'] : null,
  196.                 'percentLabel' => $quickSale ? $offer['percentLabel'] : null,
  197.             ];
  198.         }
  199.         usort($lotChoices, static function (array $a, array $b): int {
  200.             if ($a['quickSale'] !== $b['quickSale']) {
  201.                 return $a['quickSale'] ? -1 : 1;
  202.             }
  203.             if ($a['quickSale']) {
  204.                 return $a['finalPrice'] <=> $b['finalPrice'];
  205.             }
  206.             return $b['dluTs'] <=> $a['dluTs'];
  207.         });
  208.         foreach ($lotChoices as &$choice) {
  209.             unset($choice['dluTs']);
  210.         }
  211.         unset($choice);
  212.         return $this->render('products/show.html.twig', [
  213.             'product' => $product,
  214.             'productData' => $productData,
  215.             'crossedPriceDiscount' => $crossedPriceDiscount,
  216.             'information' => $information,
  217.             'user' => $user,
  218.             'validLots' => $validLots,
  219.             'lotChoices' => $lotChoices,
  220.             'totalQuantity' => $productData['quantity'],
  221.             'pricePharmacyWithRebate' => $pricePharmacyWithRebate,
  222.             'checkControl' => $checkControl
  223.         ]);
  224.     }
  225.     #[Route('/productsJson/{brand}', name: 'productsJson')]
  226.     public function allProductJson(EntityManagerInterface $manager, CrossedPriceDiscountService $crossedPriceDiscountService, QuickSaleOffers $quickSaleOffers, $brand = null): JsonResponse
  227.     {
  228.         $checkControl = $manager->getRepository(CustomerControl::class)->findOneBy(array('user' => $this->getUser(), 'finish' => false));
  229.         if (!$checkControl) {
  230.             $user = $this->getUser();
  231.         } else {
  232.             $user = $checkControl->getCustomer();
  233.         }
  234.         $information = $manager->getRepository(AdditionalCompanyInformation::class)->findOneBy(array('user' => $user));
  235.         if ($brand == null) {
  236.             $products = $manager->getRepository(Products::class)->getAllProduct($information);
  237.         } elseif ($brand == 'dlu-gooddeal') {
  238.             $products = $manager->getRepository(Products::class)->getAllProductWithGoodDeals($information);
  239.         } elseif ($brand == 'action-shock') {
  240.             $products = $manager->getRepository(Products::class)->getAllProductshockDeals($information);
  241.         } elseif ($brand == 'special-discount') {
  242.             $products = $manager->getRepository(Products::class)->getAllProductSpecialDiscount($information);
  243.         } elseif ($brand == 'action-special') {
  244.             // Combine les produits "action-shock" et "special-discount"
  245.             $productsActionShock = $manager->getRepository(Products::class)->getAllProductshockDeals($information);
  246.             $productsSpecialDiscount = $manager->getRepository(Products::class)->getAllProductSpecialDiscount($information);
  247.             
  248.             // Fusionne les deux tableaux
  249.             $products = array_merge($productsActionShock, $productsSpecialDiscount);
  250.             
  251.             // Élimine les doublons éventuels en se basant sur l'ID du produit
  252.             $uniqueProducts = [];
  253.             $uniqueIds = [];
  254.             foreach ($products as $product) {
  255.                 if (!in_array($product['id'], $uniqueIds)) {
  256.                     $uniqueIds[] = $product['id'];
  257.                     $uniqueProducts[] = $product;
  258.                 }
  259.             }
  260.             $products = $uniqueProducts;
  261.         } elseif ($brand == 'tools') {
  262.             $products = $manager->getRepository(Products::class)->getAllProductTools($information);
  263.         } else {
  264.             if ($brand == "Jacob") {
  265.                 $products = $manager->getRepository(Products::class)->getAllProductWithBrandJacob($brand, $information);
  266.             } else {
  267.                 $products = $manager->getRepository(Products::class)->getAllProductWithBrand($brand, $information);
  268.             }
  269.         }
  270.         // Liège === stock de la boutique physique
  271.         // online === stock boutique en ligne si produit pas mercator
  272.         $excludedDepots = LotNumber::EXCLUDED_DEPOTS;
  273.         foreach ($products as $index => $product) {
  274.             $quantity = 0;
  275.             if ($products[$index]['lotNumber']) {
  276.                 // keep stock only for valid warehouses
  277.                 $products[$index]['lotNumber'] = array_values(array_filter($products[$index]['lotNumber'], function ($lot) use ($excludedDepots) {
  278.                     return $lot['depot'] !== LotNumber::PHYSICAL_DEPOT && $lot['stock'] > 0;
  279.                 }));
  280.                 if (count($products[$index]['lotNumber']) === 1 && $products[$index]['lotNumber'][0]['depot'] === LotNumber::ONLINE_DEPOT) {
  281.                     $quantity = $products[$index]['lotNumber'][0]['stock'];
  282.                 } else {
  283.                     array_walk($products[$index]['lotNumber'], function ($lot) use (&$quantity, $excludedDepots) {
  284.                         if (!in_array($lot['depot'], $excludedDepots)) {
  285.                             $quantity += $lot['stock'];
  286.                         }
  287.                     });
  288.                 }
  289.             }
  290.             $products[$index]['quantity'] = $quantity;
  291.         }
  292.         $products = $crossedPriceDiscountService->decorateProducts($products);
  293.         if ($information) {
  294.             $products = $quickSaleOffers->decorate($products, $information->getCompanyCountry());
  295.         }
  296.         return new JsonResponse($products, headers: ['Content-Type' => 'application/json;charset=UTF-8']);
  297.     }
  298. }