src/Controller/Uniqskills/ZUSCatalogueController.php line 72

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Uniqskills;
  3. use App\Entity\Gos\Category;
  4. use App\Entity\Gos\Coupon;
  5. use App\Entity\Gos\OrderPart;
  6. use App\Entity\Gos\PortalSettings;
  7. use App\Entity\Gos\ProductVariant;
  8. use App\Entity\Gos\Uniqskills\Course;
  9. use App\Utils\LandingCourse;
  10. use App\Utils\SalesManago\SalesManagoEvent;
  11. use App\Utils\Uniqskills\CourseCatalog;
  12. use App\Utils\Uniqskills\FrontendCategoryTree;
  13. use App\Utils\Uniqskills\MixPanel\MixPanelService;
  14. use App\Utils\Uniqskills\SuggestedCoursesService;
  15. use Doctrine\ORM\EntityManagerInterface;
  16. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  19. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  20. use Symfony\Component\HttpFoundation\Cookie;
  21. use Symfony\Component\HttpFoundation\Request;
  22. use Symfony\Component\HttpFoundation\Session\Session;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  25. use Symfony\Component\Routing\RouterInterface;
  26. use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
  27. use Twig\Environment;
  28. /**
  29.  * @Route("/{_locale}")
  30.  */
  31. class ZUSCatalogueController extends AbstractController
  32. {
  33.     private EntityManagerInterface $em;
  34.     public function __construct(EntityManagerInterface $em)
  35.     {
  36.         $this->em $em;
  37.     }
  38.     /**
  39.      * @Route("/preview/video/{video}/{courseId}", name="fmUniqskillsVideoPreview")
  40.      */
  41.     public function showPreviewVideoAction($video$courseId 0): Response
  42.     {
  43.         return $this->render('uniqskills/catalogue/landing_new/landing_partials/videoPreview.html.twig', ['video' => $video]);
  44.     }
  45.     /**
  46.      * @Route("/kursy/{page}", name="fmUniqskillsFrontendPlCourseCataloguePage", requirements={"page"="\d+"})
  47.      * @Route("/kursy/{category}/{page}", name="fmUniqskillsFrontendPlCourseCatalogue", requirements={"page"="\d+"})
  48.      * @Route("/kursy/{category}/{subCategory}/{page}", name="fmUniqskillsFrontendPlCatalogueSubCategory", requirements={"page"="\d+"})
  49.      * @Route("/courses/{page}", name="fmUniqskillsFrontendUKCourseCataloguePage", requirements={"page"="\d+"})
  50.      * @Route("/courses/{category}/{page}", name="fmUniqskillsFrontendUKCourseCatalogue", requirements={"page"="\d+"})
  51.      * @Route("/courses/{category}/{subCategory}/{page}", name="fmUniqskillsFrontendUKCatalogueSubCategory", requirements={"page"="\d+"})
  52.      * @Route("/cursos/{page}", name="fmUniqskillsFrontendCourseCataloguePage", requirements={"page"="\d+"})
  53.      * @Route("/cursos/{category}/{page}", name="fmUniqskillsFrontendCourseCatalogue", requirements={"page"="\d+"})
  54.      * @Route("/cursos/{category}/{subCategory}/{page}", name="fmUniqskillsFrontendCatalogueSubCategory", requirements={"page"="\d+"})
  55.      * @Template()
  56.      */
  57.     public function courseCatalogueAction(
  58.         Request $request,
  59.         FrontendCategoryTree $categoryTreeService,
  60.         CourseCatalog $courseCatalogService,
  61.         MixPanelService $mixPanelService,
  62.         $category null,
  63.         $subCategory null,
  64.         $page 1
  65.     ) {
  66.         if ($request->getSession()->get('send_to_salesmanago')) {
  67.             $request->getSession()->remove('send_to_salesmanago');
  68.         }
  69.         // task GOS-1568
  70.         if (in_array($request->getLocale(), ['es''pt']) == true) {
  71.             return $this->redirectToRoute('fmUniqskillsHomePage');
  72.         }
  73.         $userCourseIdArray      $courseCatalogService->getUserCourse();
  74.         $portalSettings         $this->em->getRepository(PortalSettings::class)
  75.             ->find($request->getSession()->get('domain'));
  76.         $country                $courseCatalogService->getCountry($request);
  77.         $categories             $categoryTreeService->getCategoryTree(
  78.             $request->getLocale(),
  79.             $userCourseIdArray,
  80.             $portalSettings->getId()
  81.         );
  82.         if ($searchQuery $request->query->get('search'))
  83.         {
  84.             $mixPanelService->sendSearchQueryEvent($searchQuery$this->getUser());
  85.         }
  86.         $pagination $courseCatalogService->preparePagination(
  87.             [
  88.                 'locale'        => $request->getLocale(),
  89.                 'category'      => $category,
  90.                 'subCategory'   => $subCategory,
  91.                 'page'          => $page,
  92.                 'keyword'       => $request->query->get('keyword'0),
  93.                 'duration'      => $request->query->get('duration'0),
  94.                 'priceRange'    => $request->query->get('priceRange'0),
  95.                 'searchQuery'   => $searchQuery
  96.             ],
  97.             $userCourseIdArray,
  98.             $country,
  99.             $portalSettings
  100.         );
  101.         $breadcrumbs    $courseCatalogService->prepareBreadcrumbs($category$subCategory);
  102.         $keywords       $courseCatalogService->prepareKeywords(
  103.             $category,
  104.             $subCategory,
  105.             $request->getLocale(),
  106.             $userCourseIdArray
  107.         );
  108.         $categoryEntity $this->em->getRepository(Category::class)
  109.             ->findOneBy(
  110.                 [
  111.                     'categorySlug' => $subCategory ?? $category,
  112.                     'portalSettings' => $portalSettings->getId(),
  113.                     'isActive' => true
  114.                 ]
  115.             );
  116.         if (is_null($categoryEntity)
  117.             && !in_array($request->get('_route'), ['fmUniqskillsFrontendPlCourseCataloguePage''fmUniqskillsFrontendUKCourseCataloguePage'])
  118.         )
  119.         {
  120.            $route $_ENV['DEFAULT_LOCALE'] === 'pl'
  121.                'fmUniqskillsFrontendPlCourseCataloguePage'
  122.                'fmUniqskillsFrontendUKCourseCataloguePage';
  123.             return $this->redirectToRoute($route);
  124.         }
  125.         $parameters = [
  126.             'pagination'  => $pagination,
  127.             'categories'  => $categories,
  128.             'category'    => $categoryEntity,
  129.             'country'     => $country,
  130.             'breadcrumbs' => $breadcrumbs,
  131.             'keywords'    => $keywords
  132.         ];
  133.         return $request->isXmlHttpRequest()
  134.             ? $this->render('/uniqskills/catalogue/course_catalogue_ajax.html.twig'$parameters)
  135.             : $this->render('/uniqskills/catalogue/course_catalogue.html.twig'$parameters);
  136.     }
  137.     /**
  138.      * @Route("/{categorySlug}/{slug}/{googleAnalSlug}", name="fmUniqskillsCourseLanding")
  139.      * @Route("/{categorySlug}/{subCategory}/{keyword}/{slug}/", name="fmUniqskillsCourseLandingExpanded",
  140.      *          requirements={"categorySlug"="^(?!fm\-admin).*"})
  141.      * @Route("/{slug}/", name="fmUniqskillsCourseLandingNoCategory", requirements={"slug"="^(?!.*(login|login_check|logout|register|reset)).*$"}))
  142.      */
  143.     public function courseLandingAction(
  144.         Request $request,
  145.         LandingCourse $landingCourseUtils,
  146.         SuggestedCoursesService $suggestedCoursesService,
  147.         AuthorizationCheckerInterface $authorizationChecker,
  148.         Environment $twig,
  149.         ParameterBagInterface $parameterBag,
  150.         RouterInterface $router,
  151.         $slug,
  152.         $googleAnalSlug null,
  153.         $categorySlug null,
  154.         $subCategory null,
  155.         $keyword null
  156.     )
  157.     {
  158.         /** @var Course $course */
  159.         $em     $this->em;
  160.         $user   $this->getUser();
  161.         $course $this->em->getRepository(Course::class)->findOneBySlug($slug);
  162.         // task GOS-1569
  163.         if (empty($course) || in_array($request->getLocale(), ['es''pt']) == true)
  164.         {
  165.             return $this->redirectToRoute('fmUniqskillsHomePage');
  166.         }
  167.         if (!is_null($course))
  168.         {
  169.             $request->getSession()->set('courseNameUS'$course->getName());
  170.         }
  171.         $data $landingCourseUtils->prepareLandingData($course$user);
  172.         $redirect $landingCourseUtils->landingRedirect(
  173.             [
  174.                 'slug'          => $slug,
  175.                 'categorySlug'  => $categorySlug,
  176.                 'subCategory'   => $subCategory,
  177.                 'keyword'       => $keyword
  178.             ],
  179.             $course,
  180.             $request->getLocale()
  181.         );
  182.         if ($redirect)
  183.         {
  184.             if ($redirect === '404')
  185.             {
  186.                 throw $this->createNotFoundException('uniqskills');
  187.             }
  188.             if (is_string($redirect))
  189.             {
  190.                 return $this->redirect($redirect);
  191.             }
  192.             //add all get parameters to redirect url
  193.             foreach ($request->query->all() as $key => $param)
  194.             {
  195.                 $redirect['parameters'][$key] = $param;
  196.             }
  197.             return $this->redirectToRoute($redirect['route'], $redirect['parameters'], 301);
  198.         }
  199.         if ($course->getHasMedicalContent() && !$request->cookies->getBoolean('hideMedicalContentWarning'))
  200.         {
  201.             return $this->render('uniqskills/catalogue/landing_medical_content.html.twig', ['course' => $course]);
  202.         }
  203.         $landingFile 'landing/'
  204.             $course->getCategory()->getLanguage()->getCode()
  205.             . '/' $course->getSlug()
  206.             . '/index.html.twig';
  207.         $landing $course->getNewLandingPage();
  208.         $landingTemplateMenu false;
  209.         $buttonToCountryNotFound false;
  210.         if ($landing && $landing->getIsActive())
  211.         {
  212.             $landingPath '/uniqskills/catalogue/landing.html.twig';
  213.             if($landing->getTemplate() == 'new') {
  214.                 $landingPath '/uniqskills/catalogue/landing_new/landing.html.twig';
  215.                 $landingTemplateMenu true;
  216.             }
  217.             if ($landing->getTemplate() === 'US2024') {
  218.                 $landingPath '/uniqskills/catalogue/landing_US2024/landing.html.twig';
  219.             }
  220.             //if there are no productVariant for country and country is poland show error, else show price in USD and button to show error
  221.             if (
  222.                 empty($data['productVariants'])
  223.                 && strtoupper($request->getSession()->get('myCountryCode')) == 'PL'
  224.                 && !$authorizationChecker->isGranted('ROLE_ADMIN')
  225.             )
  226.             {
  227.                 return $this->redirectToRoute('fmUniqskillsOrderError', [
  228.                     'request'    => $request,
  229.                     'slugCourse' => $course->getSlug()
  230.                 ]);
  231.             }
  232.             elseif (empty($data['productVariants']))
  233.             {
  234.                 $buttonToCountryNotFound = [
  235.                     'route' => 'fmUniqskillsOrderError',
  236.                     'request'    => $request,
  237.                     'slugCourse' => $course->getSlug()
  238.                 ];
  239.             }
  240.         }
  241.         elseif (file_exists($landingFile))
  242.         {
  243.             $landingPath '@landing/' $landingFile;
  244.             // replace old variables price to new
  245.             $landingCourseUtils->replaceOldVariablesPriceToNew($course);
  246.             $landingCourseUtils->appendScriptToBody($course);
  247.         }
  248.         else
  249.         {
  250.             return $this->redirectToRoute('fmUniqskillsFrontendPlCourseCataloguePage');
  251.         }
  252.         $orderPart $this->em->getRepository(OrderPart::class)->findOrdersByIdCourse($course->getId());
  253.         $realSales count($orderPart);
  254.         $countOrders $realSales 200
  255.             $realSales
  256.             : ($realSales 9
  257.                 $realSales 3
  258.                 9
  259.             );
  260.         $showTimer false;
  261.         if((!$course->getIsContinuous()) && $course->getStartDate() && ($course->getStartDate() >= (new \DateTime())))
  262.         {
  263.             $showTimer $course->getStartDate();
  264.         }
  265.         $cooperators = [];
  266.         $cooperatorsOption['color'] = null;
  267.         $cooperatorsOption['center'] = null;
  268.         $cooperatorsOption['title'] = null;
  269.         $subscriptions = [];
  270.         $landingPack $landing $landingCourseUtils->buildLandingData($landing) : null;
  271.         $courseTitleRGBA null;
  272.         $defaultProductVariant null;
  273.         if ($landingPack)
  274.         {
  275.             foreach ($landingPack['modules'] as $module)
  276.             {
  277.                 if ($module['type'] == 'cooperators')
  278.                 {
  279.                     $cooperatorsOption['color'] = $module['headerColor'] ?? null;
  280.                     $cooperatorsOption['center'] = $module['centeredPosition'] ?? null;
  281.                     $cooperatorsOption['title'] = $module['cooperationTitle'] ?? null;
  282.                     foreach ($module['cooperatorList'] as $index => $cooperator)
  283.                     {
  284.                         if (
  285.                             isset($cooperator['show'])
  286.                             && $cooperator['show']
  287.                             && isset($module['cooperatorsFile_' $index])
  288.                         )
  289.                         {
  290.                             $cooperators[] = [
  291.                                 'url' => $cooperator['url'] ?? '',
  292.                                 'image' => $module['cooperatorsFile_' $index]
  293.                             ];
  294.                         }
  295.                     }
  296.                 }
  297.                 if ($module['type'] == 'payment')
  298.                 {
  299.                     $subscriptions $module['subscriptions'];
  300.                     if (!empty($subscriptions[0]['subscription']))
  301.                     {
  302.                         $defaultProductVariant $this->em->getRepository(ProductVariant::class)->find($subscriptions[0]['subscription']);
  303.                     }
  304.                     foreach ($subscriptions as $subscription)
  305.                     {
  306.                         $spv $this->em->getRepository(ProductVariant::class)->find($subscription['subscription']);
  307.                         if ($spv->getIsRecurringSubscription() && $spv->getProductVariantNo() == '1')
  308.                         {
  309.                             $subscriptionProductVariant $this->em->getRepository(ProductVariant::class)->findOneBy([
  310.                                 'productVariantNoComplete' => substr_replace($spv->getProductVariantNoComplete(), '2', -1)
  311.                             ]);
  312.                         }
  313.                     }
  314.                 }
  315.                 if ($module['type'] == 'courseTitle')
  316.                 {
  317.                     if (isset($module['overlayColor']) && strlen($module['overlayColor']))
  318.                     {
  319.                         $opacity 1;
  320.                         if (isset($module['overlayColorAlpha']) && strlen($module['overlayColorAlpha']))
  321.                         {
  322.                             $opacity $module['overlayColorAlpha'];
  323.                         }
  324.                         $courseTitleRGBA $this->hex2rgba($module['overlayColor'], $opacity);
  325.                     }
  326.                 }
  327.                 if ($module['type'] == 'courseProgram')
  328.                 {
  329.                     $freeLessonsInCourse $landingCourseUtils->getFreeLessonsInCourse($module['json']);
  330.                 }
  331.             }
  332.         }
  333.         // suggested courses
  334.         $suggestedCourses $suggestedCoursesService->findSuggestedCourses($course);
  335.         // discount code
  336.         $discountCodeExpire null;
  337.         if (isset($data['productVariants']) && count($data['productVariants']))
  338.         {
  339.             $now = new \DateTime();
  340.             if ($course->getIsContinuous() || (!$course->getIsContinuous() && ($landingCourseUtils->calcDateDiff($now$course->getStartDate()) > 0)))
  341.             {
  342.                 foreach ($subscriptions as $subscription)
  343.                 {
  344.                     if (isset($subscription['discountCode']) && $subscription['discountCode'])
  345.                     {
  346.                         /** @var Coupon $discountCode */
  347.                         $discountCode $this->em->getRepository(Coupon::class)->findOneBy(['id' => $subscription['discountCode']]);
  348.                         if ($discountCode && $landingCourseUtils->dateInBetween($now$discountCode->getDateFrom(), $discountCode->getDateTo()))
  349.                         {
  350.                             $discountCodeExpire $discountCode->getDateTo();
  351.                         }
  352.                     }
  353.                 }
  354.             }
  355.         }
  356.         $referer $request->headers->get('referer');
  357.         if (is_null($referer) OR $referer == $request->getUri()
  358.             OR (strpos($referer'/kursy') === false AND $request->getLocale() == 'pl')
  359.             OR (strpos($referer'/cursos') === false AND $request->getLocale() != 'pl'))
  360.         {
  361.             if ($request->getLocale() == 'pl')
  362.                 $referer $this->generateUrl('fmUniqskillsFrontendPlCourseCataloguePage', [], UrlGeneratorInterface::ABSOLUTE_URL);
  363.             else
  364.                 $referer $this->generateUrl('fmUniqskillsFrontendCourseCataloguePage', [], UrlGeneratorInterface::ABSOLUTE_URL);
  365.         }
  366.         $user $this->getUser();
  367.         if ($user)
  368.         {
  369.             $response = new Response();
  370.             $response->headers->setCookie(
  371.                 new Cookie('landingUrl'$request->getUri())
  372.             );
  373.             $response->sendHeaders();
  374.         }
  375.         $session = new Session();
  376.         $temporaryUserLogin $session->get('temporaryUserLogin');
  377.         $twig->enableAutoReload();
  378.         return $this->render($landingPath, [
  379.             'course'                        => $course,
  380.             'landing'                       => $landingPack,
  381.             'startDate'                     => $course->getShareDate() ? $course->getShareDate()->format('m-d-Y') : '',
  382.             'countOrders'                   => $countOrders,
  383.             'login'                         => $router->generate('fos_user_security_login'),
  384.             'register'                      => $router->generate('fos_user_registration_register'),
  385.             'preview'                       => false,
  386.             'currency'                      => '',
  387.             'courseOrderLink'               => '#subBox',
  388.             'productVariants'               => $data['productVariants'],
  389.             'productPacks'                  => $data['productPacks'],
  390.             'countryEntity'                 => $data['countryEntity'],
  391.             'courseOrderLinkSub'            => $data['courseOrderLinkSub'],
  392.             'courseGiftLinkSub'             => $data['courseGiftLinkSub'],
  393.             'codeHead'                      => $data['config']->getPortalHeadScripts(),
  394.             'codeBodyStart'                 => $data['config']->getPortalStartBodyScripts(),
  395.             'codeBodyEnd'                   => $data['config']->getPortalBodyScripts(),
  396.             'subscriptionInfo'              => $data['productVariantInfo'],
  397.             'showTimer'                     => $showTimer,
  398.             'cooperators'                   => $cooperators,
  399.             'defaultProductVariant'         => $defaultProductVariant,
  400.             'subscriptionForDefaultPrice'   => $subscriptions,
  401.             'courseTitleRGBA'               => $courseTitleRGBA,
  402.             'suggestedCourses'              => $suggestedCourses,
  403.             'landingTemplateMenu'           => $landingTemplateMenu,
  404.             'buttonToCountryNotFound'       => $buttonToCountryNotFound,
  405.             'discountCodeExpire'            => $discountCodeExpire,
  406.             'referer'                       => $referer,
  407.             'temporaryUserLogin'            => $temporaryUserLogin,
  408.             'subscriptionProductVariant'    => $subscriptionProductVariant ?? '',
  409.             'cooperatorsOption'             => $cooperatorsOption,
  410.             'freeLessonsInCourse'           => $freeLessonsInCourse ?? '',
  411.             'recaptchaPublicKey'            => $parameterBag->get('ewz_recaptcha.public_key')
  412.         ]);
  413.     }
  414.     /**
  415.      * @Route("/checkLandingPrice/{idCourse}", name="fmUniqskillsCheckLandingPrice")
  416.      */
  417.     public function checkLandingPriceAction(LandingCourse $landingCourseUtils,  $idCourse): Response
  418.     {
  419.         /** @var Course $course */
  420.         $course             $this->em->getRepository(Course::class)->find($idCourse);
  421.         $landing            $course->getNewLandingPage();
  422.         $user               $this->getUser();
  423.         $data               $landingCourseUtils->prepareLandingData($course$user);
  424.         $subscriptions      = [];
  425.         $defaultProductVariant null;
  426.         $landingPrice          false;
  427.         if ($landing)
  428.         {
  429.             $landingPack $landingCourseUtils->buildLandingData($landing);
  430.             foreach ($landingPack['modules'] as $module)
  431.             {
  432.                 if ($module['type'] == 'payment')
  433.                 {
  434.                     $subscriptions $module['subscriptions'];
  435.                     if (!empty($subscriptions[0]['subscription']))
  436.                     {
  437.                         $defaultProductVariant $this->em->getRepository(ProductVariant::class)->find($subscriptions[0]['subscription']);
  438.                     }
  439.                 }
  440.             }
  441.         }
  442.         if (!empty($subscriptions) && $defaultProductVariant != null)
  443.         {
  444.             $landingPrice true;
  445.         }
  446.         $parameters = [
  447.             'subscriptionForDefaultPrice'    => $subscriptions,
  448.             'defaultProductVariant'          => $defaultProductVariant,
  449.             'landingPrice'                   => $landingPrice,
  450.             'course'                         => $course
  451.         ];
  452.         return $this->render('uniqskills/catalogue/course_price.html.twig'$parameters);
  453.     }
  454.     private function hex2rgba($color$opacity false): string
  455.     {
  456.         $default 'rgb(0,0,0)';
  457.         if(empty($color))
  458.             return $default;
  459.         if ($color[0] == '#' ) {
  460.             $color substr$color);
  461.         }
  462.         if (strlen($color) == 6) {
  463.             $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
  464.         } elseif ( strlen$color ) == ) {
  465.             $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
  466.         } else {
  467.             return $default;
  468.         }
  469.         $rgb =  array_map('hexdec'$hex);
  470.         if($opacity){
  471.             $opacity str_replace(',','.'$opacity);
  472.             if(abs($opacity) > 1)
  473.                 $opacity 1.0;
  474.             $output 'rgba('.implode(",",$rgb).','.$opacity.')';
  475.         } else {
  476.             $output 'rgb('.implode(",",$rgb).')';
  477.         }
  478.         return $output;
  479.     }
  480. }