src/Controller/DefaultController.php line 72

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Model\DataObject\AbstractProduct;
  4. use App\Model\ShopCategory;
  5. use Pimcore\Bundle\EcommerceFrameworkBundle\Factory;
  6. use Pimcore\Bundle\EcommerceFrameworkBundle\FilterService\ListHelper;
  7. use Pimcore\Bundle\EcommerceFrameworkBundle\IndexService\ProductList\ProductListInterface;
  8. use Pimcore\Config;
  9. use Pimcore\Controller\FrontendController;
  10. use Pimcore\Model\DataObject\Product;
  11. use Pimcore\Model\DataObject\ProductCategory;
  12. use Pimcore\Model\DataObject\ProductMarca;
  13. use Pimcore\Model\Document;
  14. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  15. use Symfony\Component\HttpFoundation\JsonResponse;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  19. use Symfony\Component\Process\Exception\ProcessFailedException;
  20. use Symfony\Component\Process\Process;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Contracts\Translation\TranslatorInterface;
  23. class DefaultController extends FrontendController
  24. {
  25.     private function getCategories(Factory $ecommerceFactory$parentId$level 1$values null): array
  26.     {
  27.         if ($values === null){
  28.             $indexService $ecommerceFactory->getIndexService();
  29.             $products $indexService->getProductListForCurrentTenant();
  30.             $products->setVariantMode(ProductListInterface::VARIANT_MODE_HIDE);
  31.             $products->addCondition("productstatus NOT IN ('new', 'decatelogized', 'for_delete') OR productstatus IS NULL"'productstatus');
  32.             $filterService $ecommerceFactory->getFilterService();
  33.             $filterDefinition Config::getWebsiteConfig()->get('fallbackFilterdefinition');
  34.             $listHelper = new ListHelper();
  35.             $listHelper->setupProductList($filterDefinition$products$params$filterServicetrue);
  36.             $rawValues $filterService->getFilterValues($filterDefinition->getFilters()->getItems()[1], $products, ['parentCategoryIds' => null])['values'];
  37.             $values = [];
  38.             foreach ($rawValues as $entry) {
  39.                 $values[$entry['value']] = $entry['count'];
  40.             }
  41.         }
  42.         $categoryList = new ProductCategory\Listing();
  43.         $categoryList->setUnpublished(false);
  44.         $categoryList->setOrderKey("o_key");
  45.         $categoryList->setOrder("ASC");
  46.         $categoryList->setCondition("o_parentId = ?", [$parentId]);
  47.         $loadedCategories $categoryList->load();
  48.         $result = [];
  49.         foreach ($loadedCategories as $category) {
  50.             if (!isset($values[$category->getId()])) {
  51.                 continue;
  52.             }
  53.             $subcategories = [];
  54.             if ($level 3) {
  55.                 $subcategories $this->getCategories($ecommerceFactory$category->getId(), $level 1$values);
  56.             }
  57.             $result[] = [
  58.                 'category' => $category,
  59.                 'children' => $subcategories,
  60.             ];
  61.         }
  62.         return $result;
  63.     }
  64.     public function navbarAction(Factory $ecommerceFactory): Response
  65.     {
  66.         $categories $this->getCategories($ecommerceFactory10);
  67.         return $this->render('layout/includes/navegation/navbar.html.twig', [
  68.             'categories' => $categories
  69.         ]);
  70.     }
  71.     #[Route('/featuredProducts/{categoryId}'name'featured_products'methods: ['GET'])]
  72.     public function featuredProductAction($categoryIdRequest $request):Response
  73.     {
  74.         $category ProductCategory::getById($categoryId);
  75.         $featuredProduct $category->getFeaturedproduct();
  76.         if ($request->getLocale() === 'en') {
  77.             $document Document::getById(8);// English Document
  78.         }else{
  79.             $document Document::getById(1);// Spanish Document
  80.         }
  81.         return $this->render('layout/includes/navegation/featuredProduct.html.twig',[
  82.             'featuredProduct' => $featuredProduct,
  83.             'title' => $category->getFeaturedProductTitle(),
  84.             'document' => $document,
  85.             'prefix' => $request->getLocale(),
  86.         ]);
  87.     }
  88.     private function getBrandListResponse(?int $categoryIdRequest $requestFactory $ecommerceFactory): JsonResponse
  89.     {
  90.         $locale $request->getLocale();
  91.         $prefix $locale === 'en' 'en' 'es';
  92.         $params = ['prefix' => $prefix];
  93.         $document $locale === 'en' Document::getById(8) : Document::getById(1);
  94.         $params['document'] = $document;
  95.         $indexService $ecommerceFactory->getIndexService();
  96.         $productListing $indexService->getProductListForCurrentTenant();
  97.         $productListing->setVariantMode(ProductListInterface::VARIANT_MODE_HIDE);
  98.         $productListing->addCondition("productstatus NOT IN ('new', 'decatelogized', 'for_delete') OR productstatus IS NULL"'productstatus');
  99.         $categoryUrl null;
  100.         if ($categoryId !== null) {
  101.             $category ShopCategory::getById($categoryId);
  102.             if ($category) {
  103.                 // Always filter by category
  104.                 $params['parentCategoryIds'] = $categoryId;
  105.                 $params['rootCategory'] = $category;
  106.                 $params['document'] = $document;
  107.                 // Include parentCategoryIds in the URL only if it's a subcategory
  108.                 $urlParams = [
  109.                     'rootCategory' => $category,
  110.                     'document' => $document,
  111.                 ];
  112.                 if ($this->hasParentCategory($category)) {
  113.                     $urlParams['parentCategoryIds'] = $categoryId;
  114.                 }
  115.                 // Generate the final category URL with the appropriate parameters
  116.                 $categoryUrl $category->getDetailUrl($urlParams);
  117.             }
  118.         }
  119.         $filterDefinition Config::getWebsiteConfig()->get('fallbackFilterdefinition');
  120.         $filterService $ecommerceFactory->getFilterService();
  121.         (new ListHelper())->setupProductList($filterDefinition$productListing$params$filterServicetrue);
  122.         $brandFilter null;
  123.         foreach ($filterDefinition->getFilters() as $filter) {
  124.             if ($filter instanceof \Pimcore\Model\DataObject\Fieldcollection\Data\FilterMultiSelectBrand) {
  125.                 $brandFilter $filter;
  126.                 break;
  127.             }
  128.         }
  129.         if (!$brandFilter) {
  130.             throw new \RuntimeException('Brand filter not found in FilterDefinition');
  131.         }
  132.         $brandData $filterService->getFilterValues($brandFilter$productListing, ['marca' => null]);
  133.         $brands = [];
  134.         foreach ($brandData['values'] as $value) {
  135.             $brand ProductMarca::getById($value['value']);
  136.             if (!$brand || !$brand->isPublished()) {
  137.                 continue;
  138.             }
  139.             $url $categoryId
  140.                 $categoryUrl . (str_contains($categoryUrl'?') ? '&' '?') . 'marca[]=' $brand->getId()
  141.                 : '/' $prefix '/productos/marcas/' .
  142.                 preg_replace('/[^a-zA-Z0-9\-]/'''str_replace(' '''$brand->getName())) . '_m' $brand->getId();
  143.             $brands[] = [
  144.                 'id' => $brand->getId(),
  145.                 'name' => $brand->getName(),
  146.                 'url' => $url,
  147.                 'image' => $brand->getLogo()
  148.                     ? $brand->getLogo()->getThumbnail('navbar-brands')->getPath()
  149.                     : null,
  150.             ];
  151.         }
  152.         usort($brands, static fn($a$b) => strcmp($a['name'], $b['name']));
  153.         return new JsonResponse(['brands' => $brands]);
  154.     }
  155.     private function hasParentCategory(ShopCategory $category): bool
  156.     {
  157.         $parent $category->getParent();
  158.         return $parent instanceof \App\Model\ShopCategory;
  159.     }
  160.     #[Route('/load-brands/{categoryId}'name'load_brands'methods: ['GET'])]
  161.     public function loadBrandsAction(Request $requestint $categoryIdFactory $ecommerceFactory): JsonResponse
  162.     {
  163.         return $this->getBrandListResponse($categoryId$request$ecommerceFactory);
  164.     }
  165.     #[Route('/load-brands'name'load_all_brands'methods: ['GET'])]
  166.     public function loadAllBrandsAction(Request $requestFactory $ecommerceFactory): JsonResponse
  167.     {
  168.         return $this->getBrandListResponse(null$request$ecommerceFactory);
  169.     }
  170.     public function usermanualAction(){
  171.         return $this->render('layout/includes/user-manual-links.html.twig');
  172.     }
  173.     public function addProductAction(Request $request){
  174.         if($request->get('type') == 'object')
  175.         {
  176.             if($object AbstractProduct::getById($request->get('id'))){
  177.                 return $this->render('Content/newsProduct.html.twig',['object' => $object]);
  178.             }
  179.         }
  180.         throw new NotFoundHttpException('Object not found.');
  181.     }
  182.     #[Route('/admin/send-registration-emails'name'send_emails'methods: ['POST'])]
  183.     #[IsGranted('ROLE_PIMCORE_USER')]
  184.     public function sendEmails(): JsonResponse
  185.     {
  186.         try {
  187.             $projectDir $this->getParameter('kernel.project_dir');
  188.             $process = new Process(['php'$projectDir '/bin/console''send-registration-mail']);
  189.             $process->setTimeout(300); // 5 minutes
  190.             $process->run();
  191.             if (!$process->isSuccessful()) {
  192.                 throw new ProcessFailedException($process);
  193.             }
  194.             $outputLines explode("\n"trim($process->getOutput()));
  195.             $lastLine end($outputLines);
  196.             $summary json_decode($lastLinetrue);
  197.             if (!is_array($summary) || !isset($summary['total'], $summary['successful'], $summary['failed'])) {
  198.                 throw new \Exception('Invalid output from command');
  199.             }
  200.             return new JsonResponse([
  201.                 'success' => true,
  202.                 'message' => 'Emails sent successfully',
  203.                 'summary' => $summary
  204.             ]);
  205.         } catch (\Exception $e) {
  206.             return new JsonResponse([
  207.                 'success' => false,
  208.                 'error' => $e->getMessage()
  209.             ], 500);
  210.         }
  211.     }
  212. }