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.         $clientFolder = ($information?->getCompanyCountry() === 'Belgique') ? 'BE' : 'LU';
  107.         foreach ($allProducts as $index => $prod) {
  108.             $quantity = 0;
  109.             if ($allProducts[$index]['lotNumber']) {
  110.                 // keep stock only for the client's folder and valid warehouses
  111.                 $allProducts[$index]['lotNumber'] = array_values(array_filter($allProducts[$index]['lotNumber'], function ($lot) use ($excludedDepots, $clientFolder) {
  112.                     $folder = $lot['folderMercator'] ?? null;
  113.                     if ($folder !== null && $folder !== $clientFolder) {
  114.                         return false;
  115.                     }
  116.                     return $lot['depot'] !== LotNumber::PHYSICAL_DEPOT && $lot['stock'] > 0;
  117.                 }));
  118.                 if (count($allProducts[$index]['lotNumber']) === 1 && $allProducts[$index]['lotNumber'][0]['depot'] === LotNumber::ONLINE_DEPOT) {
  119.                     $quantity = $allProducts[$index]['lotNumber'][0]['stock'];
  120.                 } else {
  121.                     array_walk($allProducts[$index]['lotNumber'], function ($lot) use (&$quantity, $excludedDepots) {
  122.                         if (!in_array($lot['depot'], $excludedDepots)) {
  123.                             $quantity += $lot['stock'];
  124.                         }
  125.                     });
  126.                 }
  127.             }
  128.             $allProducts[$index]['quantity'] = $quantity;
  129.         }
  130.         
  131.         // Trouve le produit spécifique dans le tableau
  132.         $productData = null;
  133.         foreach ($allProducts as $prod) {
  134.             if ($prod['id'] == $id) {
  135.                 $productData = $prod;
  136.                 break;
  137.             }
  138.         }
  139.         
  140.         if (!$productData) {
  141.             throw $this->createNotFoundException('Produit non trouvé');
  142.         }
  143.         // Récupère l'entité produit pour les relations
  144.         $product = $manager->getRepository(Products::class)->find($id);
  145.         
  146.         // Filtre les lots valides avec DLU (pour l'affichage)
  147.         $validLots = [];
  148.         if (isset($productData['lotNumber']) && is_array($productData['lotNumber'])) {
  149.             foreach ($productData['lotNumber'] as $lotData) {
  150.                 if (isset($lotData['dlu']) && $lotData['dlu'] !== null && $lotData['stock'] > 0) {
  151.                     $validLots[] = $lotData;
  152.                 }
  153.             }
  154.             
  155.             // Trie par DLU (du plus lointain au plus proche)
  156.             usort($validLots, function($a, $b) {
  157.                 if (!isset($a['dlu']) || !isset($b['dlu'])) return 0;
  158.                 if (!($a['dlu'] instanceof \DateTime) || !($b['dlu'] instanceof \DateTime)) return 0;
  159.                 return $b['dlu']->getTimestamp() - $a['dlu']->getTimestamp();
  160.             });
  161.         }
  162.         // Calcul du prix pharmacie avec remise si applicable
  163.         $pricePharmacyWithRebate = null;
  164.         if ($information && $information->getCompanyTypePro() === 'Pharmacie' && $product->getPricePharmacy()) {
  165.             $percentPharmacy = $user->getAdditionalPercentage();
  166.             $pricePharmacyWithRebate = $product->getPricePharmacy() - ($product->getPricePharmacy() * $percentPharmacy / 100);
  167.         }
  168.         $crossedPriceDiscount = $crossedPriceDiscountService->resolve($product->getId(), $product->getPrice());
  169.         $country = $information?->getCompanyCountry();
  170.         $folder = $country === 'Belgique' ? 'BE' : 'LU';
  171.         $groupedLots = [];
  172.         foreach ($validLots as $lotData) {
  173.             $number = trim((string) ($lotData['lotNumber'] ?? ''));
  174.             if ($number === '') {
  175.                 continue;
  176.             }
  177.             $dlu = ($lotData['dlu'] ?? null) instanceof \DateTimeInterface ? $lotData['dlu'] : null;
  178.             if (!isset($groupedLots[$number])) {
  179.                 $groupedLots[$number] = ['dlu' => $dlu];
  180.             } elseif ($dlu && ($groupedLots[$number]['dlu'] === null || $dlu < $groupedLots[$number]['dlu'])) {
  181.                 $groupedLots[$number]['dlu'] = $dlu;
  182.             }
  183.         }
  184.         $lotChoices = [];
  185.         foreach ($groupedLots as $number => $row) {
  186.             $stock = $quickSaleOffers->stock($product, $number, $folder);
  187.             if ($stock < 1) {
  188.                 continue;
  189.             }
  190.             $offer = $quickSaleOffers->lotOffer((int) $product->getId(), $number, $country);
  191.             $quickSale = $offer !== null
  192.                 && (float) $offer['displayPercent'] > 0
  193.                 && (float) $offer['finalPrice'] < (float) $product->getPrice();
  194.             $lotChoices[] = [
  195.                 'lot' => (string) $number,
  196.                 'dlu' => $row['dlu'] ? $row['dlu']->format('d/m/Y') : '',
  197.                 'dluTs' => $row['dlu'] ? $row['dlu']->getTimestamp() : 0,
  198.                 'stock' => $stock,
  199.                 'quickSale' => $quickSale,
  200.                 'finalPrice' => $quickSale ? (float) $offer['finalPrice'] : null,
  201.                 'percentLabel' => $quickSale ? $offer['percentLabel'] : null,
  202.             ];
  203.         }
  204.         usort($lotChoices, static function (array $a, array $b): int {
  205.             if ($a['quickSale'] !== $b['quickSale']) {
  206.                 return $a['quickSale'] ? -1 : 1;
  207.             }
  208.             if ($a['quickSale']) {
  209.                 return $a['finalPrice'] <=> $b['finalPrice'];
  210.             }
  211.             return $b['dluTs'] <=> $a['dluTs'];
  212.         });
  213.         foreach ($lotChoices as &$choice) {
  214.             unset($choice['dluTs']);
  215.         }
  216.         unset($choice);
  217.         $hasQuickSale = false;
  218.         foreach ($lotChoices as $choice) {
  219.             if ($choice['quickSale']) {
  220.                 $hasQuickSale = true;
  221.                 break;
  222.             }
  223.         }
  224.         if (!$hasQuickSale) {
  225.             $lotChoices = [];
  226.         }
  227.         return $this->render('products/show.html.twig', [
  228.             'product' => $product,
  229.             'productData' => $productData,
  230.             'crossedPriceDiscount' => $crossedPriceDiscount,
  231.             'information' => $information,
  232.             'user' => $user,
  233.             'validLots' => $validLots,
  234.             'lotChoices' => $lotChoices,
  235.             'totalQuantity' => $productData['quantity'],
  236.             'pricePharmacyWithRebate' => $pricePharmacyWithRebate,
  237.             'checkControl' => $checkControl
  238.         ]);
  239.     }
  240.     #[Route('/productsJson/{brand}', name: 'productsJson')]
  241.     public function allProductJson(EntityManagerInterface $manager, CrossedPriceDiscountService $crossedPriceDiscountService, QuickSaleOffers $quickSaleOffers, $brand = null): JsonResponse
  242.     {
  243.         $checkControl = $manager->getRepository(CustomerControl::class)->findOneBy(array('user' => $this->getUser(), 'finish' => false));
  244.         if (!$checkControl) {
  245.             $user = $this->getUser();
  246.         } else {
  247.             $user = $checkControl->getCustomer();
  248.         }
  249.         $information = $manager->getRepository(AdditionalCompanyInformation::class)->findOneBy(array('user' => $user));
  250.         if ($brand == null) {
  251.             $products = $manager->getRepository(Products::class)->getAllProduct($information);
  252.         } elseif ($brand == 'dlu-gooddeal') {
  253.             $products = $manager->getRepository(Products::class)->getAllProductWithGoodDeals($information);
  254.         } elseif ($brand == 'action-shock') {
  255.             $products = $manager->getRepository(Products::class)->getAllProductshockDeals($information);
  256.         } elseif ($brand == 'special-discount') {
  257.             $products = $manager->getRepository(Products::class)->getAllProductSpecialDiscount($information);
  258.         } elseif ($brand == 'action-special') {
  259.             // Combine les produits "action-shock" et "special-discount"
  260.             $productsActionShock = $manager->getRepository(Products::class)->getAllProductshockDeals($information);
  261.             $productsSpecialDiscount = $manager->getRepository(Products::class)->getAllProductSpecialDiscount($information);
  262.             
  263.             // Fusionne les deux tableaux
  264.             $products = array_merge($productsActionShock, $productsSpecialDiscount);
  265.             
  266.             // Élimine les doublons éventuels en se basant sur l'ID du produit
  267.             $uniqueProducts = [];
  268.             $uniqueIds = [];
  269.             foreach ($products as $product) {
  270.                 if (!in_array($product['id'], $uniqueIds)) {
  271.                     $uniqueIds[] = $product['id'];
  272.                     $uniqueProducts[] = $product;
  273.                 }
  274.             }
  275.             $products = $uniqueProducts;
  276.         } elseif ($brand == 'tools') {
  277.             $products = $manager->getRepository(Products::class)->getAllProductTools($information);
  278.         } else {
  279.             if ($brand == "Jacob") {
  280.                 $products = $manager->getRepository(Products::class)->getAllProductWithBrandJacob($brand, $information);
  281.             } else {
  282.                 $products = $manager->getRepository(Products::class)->getAllProductWithBrand($brand, $information);
  283.             }
  284.         }
  285.         // Liège === stock de la boutique physique
  286.         // online === stock boutique en ligne si produit pas mercator
  287.         $excludedDepots = LotNumber::EXCLUDED_DEPOTS;
  288.         $clientFolder = ($information?->getCompanyCountry() === 'Belgique') ? 'BE' : 'LU';
  289.         foreach ($products as $index => $product) {
  290.             $quantity = 0;
  291.             if ($products[$index]['lotNumber']) {
  292.                 // keep stock only for the client's folder and valid warehouses
  293.                 $products[$index]['lotNumber'] = array_values(array_filter($products[$index]['lotNumber'], function ($lot) use ($excludedDepots, $clientFolder) {
  294.                     $folder = $lot['folderMercator'] ?? null;
  295.                     if ($folder !== null && $folder !== $clientFolder) {
  296.                         return false;
  297.                     }
  298.                     return $lot['depot'] !== LotNumber::PHYSICAL_DEPOT && $lot['stock'] > 0;
  299.                 }));
  300.                 if (count($products[$index]['lotNumber']) === 1 && $products[$index]['lotNumber'][0]['depot'] === LotNumber::ONLINE_DEPOT) {
  301.                     $quantity = $products[$index]['lotNumber'][0]['stock'];
  302.                 } else {
  303.                     array_walk($products[$index]['lotNumber'], function ($lot) use (&$quantity, $excludedDepots) {
  304.                         if (!in_array($lot['depot'], $excludedDepots)) {
  305.                             $quantity += $lot['stock'];
  306.                         }
  307.                     });
  308.                 }
  309.             }
  310.             $products[$index]['quantity'] = $quantity;
  311.         }
  312.         $products = $crossedPriceDiscountService->decorateProducts($products);
  313.         if ($information) {
  314.             $products = $quickSaleOffers->decorate($products, $information->getCompanyCountry());
  315.         }
  316.         return new JsonResponse($products, headers: ['Content-Type' => 'application/json;charset=UTF-8']);
  317.     }
  318. }