src/Controller/Uniqskills/ZUSCatalogueController.php line 435

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