src/Controller/DefaultController.php line 24

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