src/Aqarmap/Bundle/UserBundle/Controller/UserController.php line 255

Open in your IDE?
  1. <?php
  2. namespace Aqarmap\Bundle\UserBundle\Controller;
  3. use Aqarmap\Bundle\FeatureToggleBundle\Service\FeatureToggleManager;
  4. use Aqarmap\Bundle\ListingBundle\Entity\Location;
  5. use Aqarmap\Bundle\ListingBundle\Entity\PropertyType;
  6. use Aqarmap\Bundle\ListingBundle\Entity\Section;
  7. use Aqarmap\Bundle\ListingBundle\Form\QuickLeadType;
  8. use Aqarmap\Bundle\ListingBundle\Service\FavouriteService;
  9. use Aqarmap\Bundle\ListingBundle\Service\ListingManager;
  10. use Aqarmap\Bundle\ListingBundle\Service\LocationManager;
  11. use Aqarmap\Bundle\ListingBundle\Service\TopCustomerService;
  12. use Aqarmap\Bundle\MainBundle\Contract\ProducerFactoryInterface;
  13. use Aqarmap\Bundle\NotifierBundle\Service\V3\NotifierSubscriptionService;
  14. use Aqarmap\Bundle\UserBundle\Constant\UserInterestStatus;
  15. use Aqarmap\Bundle\UserBundle\Entity\User;
  16. use Aqarmap\Bundle\UserBundle\Entity\UserInterest;
  17. use Aqarmap\Bundle\UserBundle\Form\QuickRegistrationFormType;
  18. use Aqarmap\Bundle\UserBundle\Services\GoogleUserManager;
  19. use Aqarmap\Bundle\UserBundle\Services\UserActivityService;
  20. use Aqarmap\Bundle\UserBundle\Services\UserManager;
  21. use Aqarmap\Bundle\UserBundle\Services\V3\UserAuthenticationService as UserAuthenticationServiceV3;
  22. use Doctrine\ORM\EntityManagerInterface;
  23. use FOS\RestBundle\Controller\Annotations as Rest;
  24. use FOS\UserBundle\Model\UserManagerInterface;
  25. use JMS\Serializer\SerializerInterface;
  26. use Knp\Component\Pager\PaginatorInterface;
  27. use Predis\ClientInterface as RedisClient;
  28. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  29. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  30. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  31. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  32. use Symfony\Component\Form\FormFactoryInterface;
  33. use Symfony\Component\Form\FormInterface;
  34. use Symfony\Component\HttpFoundation\RedirectResponse;
  35. use Symfony\Component\HttpFoundation\Request;
  36. use Symfony\Component\HttpFoundation\Response;
  37. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  38. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  39. use Symfony\Component\Routing\Annotation\Route;
  40. use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface;
  41. use Symfony\Contracts\Translation\TranslatorInterface;
  42. /**
  43.  * @Route("/user")
  44.  */
  45. class UserController extends AbstractController
  46. {
  47.     private UserManager $userManager;
  48.     /**
  49.      * @var LocationManager
  50.      */
  51.     private $locationManager;
  52.     /**
  53.      * @var TokenStorageInterface
  54.      */
  55.     private $tokenStorage;
  56.     /**
  57.      * @var EntityManagerInterface
  58.      */
  59.     private $entityManager;
  60.     /**
  61.      * @var PaginatorInterface
  62.      */
  63.     private $paginator;
  64.     /**
  65.      * @var SessionInterface
  66.      */
  67.     private $session;
  68.     /**
  69.      * @var TranslatorInterface
  70.      */
  71.     private $translator;
  72.     /**
  73.      * @var FeatureToggleManager
  74.      */
  75.     private $featureToggleManager;
  76.     /**
  77.      * @var TopCustomerService
  78.      */
  79.     private $topCustomerService;
  80.     /**
  81.      * @var FavouriteService
  82.      */
  83.     private $favouriteService;
  84.     /**
  85.      * @var UserActivityService
  86.      */
  87.     private $userActivityService;
  88.     /**
  89.      * @var NotifierSubscriptionService
  90.      */
  91.     private $notifierSubscriptionService;
  92.     /**
  93.      * @var UserManagerInterface
  94.      */
  95.     private $fosUserManager;
  96.     /**
  97.      * @var GoogleUserManager
  98.      */
  99.     private $googleUserManager;
  100.     /**
  101.      * @var UserAuthenticationServiceV3
  102.      */
  103.     private $userAuthenticationServiceV3;
  104.     private \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface $usageTrackingTokenStorage;
  105.     public function __construct(
  106.         EntityManagerInterface $entityManager,
  107.         PaginatorInterface $paginator,
  108.         EventDispatcherInterface $eventDispatcher,
  109.         TokenStorageInterface $tokenStorage,
  110.         FormFactoryInterface $fosFormFactory,
  111.         SerializerInterface $jmsSerializer,
  112.         RedisClient $redis,
  113.         FeatureToggleManager $featureToggleManager,
  114.         TranslatorInterface $translator,
  115.         ProducerFactoryInterface $producerFactory,
  116.         TopCustomerService $topCustomerService,
  117.         ListingManager $listingManager,
  118.         FavouriteService $favouriteService,
  119.         SessionInterface $session,
  120.         LocationManager $locationManager,
  121.         UserActivityService $userActivityService,
  122.         NotifierSubscriptionService $notifierSubscriptionService,
  123.         UserManagerInterface $fosUserManager,
  124.         UserManager $userManager,
  125.         GoogleUserManager $googleUserManager,
  126.         UserAuthenticationServiceV3 $userAuthenticationServiceV3,
  127.         \Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface $usageTrackingTokenStorage
  128.     ) {
  129.         $this->entityManager $entityManager;
  130.         $this->paginator $paginator;
  131.         $this->userManager $userManager;
  132.         $this->tokenStorage $tokenStorage;
  133.         $this->favouriteService $favouriteService;
  134.         $this->topCustomerService $topCustomerService;
  135.         $this->featureToggleManager $featureToggleManager;
  136.         $this->userActivityService $userActivityService;
  137.         $this->locationManager $locationManager;
  138.         $this->translator $translator;
  139.         $this->session $session;
  140.         $this->fosUserManager $fosUserManager;
  141.         $this->notifierSubscriptionService $notifierSubscriptionService;
  142.         $this->googleUserManager $googleUserManager;
  143.         $this->userAuthenticationServiceV3 $userAuthenticationServiceV3;
  144.         $this->usageTrackingTokenStorage $usageTrackingTokenStorage;
  145.     }
  146.     /**
  147.      * User listings.
  148.      *
  149.      * @Route("/{id}/{type}/{location}", requirements={"id": "\d+", "type": "agent|company|", "location": ".+[^/]"}, name="aqarmap_user_listings")
  150.      * @Route("/{id}/{location}", requirements={"id": "\d+", "location": ".+[^/]"}, name="aqarmap_user_listings_without_type")
  151.      *
  152.      * @ParamConverter("location", options={"mapping":{"location":"slug"}})
  153.      *
  154.      * @return array|RedirectResponse|Response
  155.      *
  156.      * @throws \Exception
  157.      */
  158.     public function index(int $idRequest $request, ?Location $location null, ?string $type null)
  159.     {
  160.         $em $this->entityManager;
  161.         $user $em->getRepository(User::class)->find($id);
  162.         if (!$user) {
  163.             throw new NotFoundHttpException('User Not Found');
  164.         }
  165.         $pageNumber max($request->query->getInt('page'1), 1);
  166.         if (== $request->query->getInt('page')) {
  167.             return $this->redirectToFirstPage($request$user$location);
  168.         }
  169.         $isAgentProfileToggled $this->featureToggleManager
  170.             ->isEnabled('web.agents.section');
  171.         $isTopCustomer $this->topCustomerService->isTopCustomer($user) && $isAgentProfileToggled;
  172.         $users = [$user];
  173.         $agents = [];
  174.         if ($user->getChildren()->count()) {
  175.             $users array_merge($users$user->getChildren()->toArray());
  176.             $agents $user->getChildren();
  177.         }
  178.         $query $this->userManager->getListingsByLocation($users$location);
  179.         if (empty($query->getQuery()->getScalarResult()) && $location) {
  180.             return $this->redirect($this->generateUrl('aqarmap_user_listings', [
  181.                 'id' => $user->getId(),
  182.                 'location' => $location->getParent() ? $location->getParent()->getSlug() : null,
  183.             ]), Response::HTTP_MOVED_PERMANENTLY);
  184.         }
  185.         if (!\in_array($request->get('sort'), ['l.publishedAt''l.price''l.area'])) {
  186.             $request->query->set('sort''l.publishedAt');
  187.         }
  188.         $paginator $this->paginator;
  189.         $listings $paginator->paginate(
  190.             $query,
  191.             $pageNumber,
  192.             $isTopCustomer 9
  193.         );
  194.         if ($pageNumber && empty($listings->getItems())) {
  195.             return $this->redirectToFirstPage($request$user$location);
  196.         }
  197.         $userManager $this->userManager;
  198.         $liveListingsCount $userManager->countLiveListing($user);
  199.         if ($isTopCustomer) {
  200.             $locationManager $this->locationManager;
  201.             return $this->render('@AqarmapUser/Profile/agent.html.twig', [
  202.                 'results' => $listings,
  203.                 'user' => $user,
  204.                 'servedLocationsPills' => $this
  205.                     ->topCustomerService
  206.                     ->getServedLocations($users$location1),
  207.                 'isCompanyProfile' => (bool) $user->getChildrenCount(),
  208.                 'companyAgents' => $agents,
  209.                 'location' => $location,
  210.                 'form' => $this->createQuickLeadForm()->createView(),
  211.                 'liveListingsCount' => $liveListingsCount,
  212.                 'leadsCount' => $user->getClientServedCount(),
  213.                 'servedLocations' => $locationManager
  214.                     ->buildServingLeveledLocationsArray($users1$request->getLocale()),
  215.                 'agent' => true,
  216.             ]);
  217.         }
  218.         return $this->render('@AqarmapUser/User/index.html.twig', [
  219.             'liveListingsCount' => $liveListingsCount,
  220.             'entity' => $listings,
  221.             'user' => $user,
  222.             'agent' => $user,
  223.         ]);
  224.     }
  225.     /**
  226.      * Unset User Logo.
  227.      *
  228.      * @Route("/logo/unset", name="aqarmap_user_logo_unset")
  229.      *
  230.      * @Security("is_granted('ROLE_USER')")
  231.      */
  232.     public function unsetLogo()
  233.     {
  234.         /** @var User $user */
  235.         $user $this->getUser();
  236.         $user->setLogo(null);
  237.         $user->setIsValidLogo(false);
  238.         $response = new Response();
  239.         $response->headers->clearCookie('hide_logo_request');
  240.         $response->sendHeaders();
  241.         $userManager $this->fosUserManager;
  242.         $userManager->updateUser($user);
  243.         $this->session->getFlashBag()->add(
  244.             'success',
  245.             $this->translator->trans('profile.flash.user_updated')
  246.         );
  247.         return new RedirectResponse($this->generateUrl('fos_user_profile_edit'));
  248.     }
  249.     /**
  250.      * Quick Registration Action.
  251.      *
  252.      * @Route("/", name="aqarmap_user_insert", options={"expose"=true}, methods={"POST"})
  253.      *
  254.      * @Rest\View()
  255.      */
  256.     public function post(Request $request)
  257.     {
  258.         $userManager $this->fosUserManager;
  259.         /** @var User $user */
  260.         $user $userManager->createUser();
  261.         $form $this->createForm(QuickRegistrationFormType::class, $user, [
  262.             'method' => 'POST',
  263.             'action' => $this->generateUrl('aqarmap_user_insert'),
  264.             'validation_groups' => ['simplified'],
  265.             'onlyEmail' => true,
  266.         ]);
  267.         $form->handleRequest($request);
  268.         // Marking the user as a quick registered
  269.         $user->setIsQucikRegistered(true);
  270.         $usernameFromEmail explode('@'$user->getEmail());
  271.         $user->setFullName($usernameFromEmail[0]);
  272.         $registered $this->userManager->quickRegister($user$form$requesttruefalsefalse$request->get('registerWithPassword'false));
  273.         if (true === $registered) {
  274.             return [
  275.                 'status' => 'ok',
  276.                 'message' => $this->translator->trans('popup_form.success'),
  277.             ];
  278.         }
  279.         return $form;
  280.     }
  281.     /**
  282.      * @Route("/interests/", name="aqarmap_my_interests")
  283.      *
  284.      * @Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")
  285.      */
  286.     public function myInterests(Request $request)
  287.     {
  288.         $user $this->getUser();
  289.         $em $this->entityManager;
  290.         // Creating pagination
  291.         $paginator $this->paginator;
  292.         $pagination $paginator->paginate(
  293.             $em->getRepository(UserInterest::class)->getUserInterests($user20),
  294.             $request->query->get('page'1),
  295.             20
  296.         );
  297.         return [
  298.             'interests' => $pagination,
  299.         ];
  300.     }
  301.     /**
  302.      * @Route("/interests/{id}/pause", requirements={"id" = "\d+"}, name="aqarmap_interests_pause", methods={"GET"})
  303.      *
  304.      * @Security("is_granted('ROLE_ADMIN') or is_granted('ROLE_OWNER', entity)")
  305.      */
  306.     public function pauseInterest(Request $requestUserInterest $entity): RedirectResponse
  307.     {
  308.         if (!$entity) {
  309.             throw $this->createNotFoundException('Unable to find this Interest.');
  310.         }
  311.         $em $this->entityManager;
  312.         $entity->setStatus(UserInterestStatus::PAUSED);
  313.         // Save Changes
  314.         $em->persist($entity);
  315.         $em->flush();
  316.         // Set success flash message
  317.         $this->session->getFlashBag()->add(
  318.             'info',
  319.             $this->translator->trans('interest.paused_successfully')
  320.         );
  321.         return $this->redirect($request->headers->get('referer') ?: $this->generateUrl('homepage'));
  322.     }
  323.     /**
  324.      * User Activity.
  325.      *
  326.      * @Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")
  327.      *
  328.      * @Route("/activity/{step}", name="user_activity", options={"expose"=true})
  329.      * @Route("/{userKey}/activity/{step}", name="user_activity_share", options={"expose"=true})
  330.      */
  331.     public function activity(Request $request): Response
  332.     {
  333.         $request->query->add([
  334.             'user_key' => $request->attributes->get('userKey'),
  335.             'limit' => 1,
  336.         ]);
  337.         if ($request->attributes->get('userKey')) {
  338.             $favourite $this->favouriteService->getUserFavourite($request)->getResult();
  339.         }
  340.         return $this->render('@AqarmapUser/User/activity.html.twig', [
  341.             'favourite' => current($favourite ?? []),
  342.             'featureToggle' => $this->userActivityService->getFeatureToggles(),
  343.         ]);
  344.     }
  345.     /**
  346.      * User Inbox.
  347.      *
  348.      * @Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")
  349.      *
  350.      * @Route("/inbox/", name="user_inbox", options={"expose"=true})
  351.      */
  352.     public function inbox(): Response
  353.     {
  354.         $entityManager $this->getDoctrine();
  355.         $featureToggleManager $this->featureToggleManager;
  356.         return $this->render('@AqarmapUser/User/inbox.html.twig', [
  357.             'location' => $entityManager->getRepository(Location::class)->getFirstRoot(),
  358.             'propertyType' => $entityManager->getRepository(PropertyType::class)->getFirstRoot(),
  359.             'section' => $entityManager->getRepository(Section::class)->getFirstSection(),
  360.             'featureToggle' => [
  361.                 'web.whats.app.chat' => $featureToggleManager->isEnabled('web.whats.app.chat'),
  362.             ],
  363.         ]);
  364.     }
  365.     /**
  366.      * User Message.
  367.      *
  368.      * @Security("is_granted('IS_AUTHENTICATED_REMEMBERED')")
  369.      *
  370.      * @Route("/messages/{id}", name="user_message", options={"expose"=true})
  371.      */
  372.     public function messages(): Response
  373.     {
  374.         $featureToggleManager $this->featureToggleManager;
  375.         return $this->render('@AqarmapUser/User/inbox.html.twig', [
  376.             'featureToggle' => [
  377.                 'web.whats.app.chat' => $featureToggleManager->isEnabled('web.whats.app.chat'),
  378.             ],
  379.         ]);
  380.     }
  381.     public function createQuickLeadForm(): FormInterface
  382.     {
  383.         return $this->createForm(
  384.             QuickLeadType::class,
  385.             null,
  386.             [
  387.                 'action' => $this->generateUrl('add_quick_lead'),
  388.                 'method' => 'POST',
  389.             ]
  390.         );
  391.     }
  392.     /**
  393.      * @Route("/interests/unsubscribe/{locationId}", name="aqarmap_poke_notifier_unsubscribe", methods={"GET"})
  394.      */
  395.     public function unsubscribeLocationNotifier(Request $requestint $locationId): RedirectResponse
  396.     {
  397.         $token $request->query->get('token');
  398.         $subscriptionService $this->notifierSubscriptionService;
  399.         $subscriptionService->unsubscribeLocation($locationId$token);
  400.         return $this->redirect($this->generateUrl('homepage'));
  401.     }
  402.     /**
  403.      * @Route("/interests/unsubscribe", name="aqarmap_all_poke_notifiers_unsubscribe", methods={"GET"})
  404.      */
  405.     public function unsubscribeAllNotifiers(Request $request): RedirectResponse
  406.     {
  407.         $token $request->query->get('token');
  408.         $subscriptionService $this->notifierSubscriptionService;
  409.         $subscriptionService->unsubscribeAll($token);
  410.         return $this->redirect($this->generateUrl('homepage'));
  411.     }
  412.     /**
  413.      * Google login action.
  414.      *
  415.      * @Route("/google/login", name="user_google_login")
  416.      *
  417.      * @return RedirectResponse
  418.      */
  419.     public function googleLogin(Request $request)
  420.     {
  421.         $isGoogleToggleEnabled $this->featureToggleManager->isEnabled('web.google.onetab');
  422.         if (!$isGoogleToggleEnabled) {
  423.             return $this->redirect($this->generateUrl('homepage'));
  424.         }
  425.         $client $this->googleUserManager->createGoogleClient();
  426.         $code $request->query->get('code');
  427.         if (!$code) {
  428.             $referer $request->headers->get('referer');
  429.             $this->get('session')->set('referer_url'$referer);
  430.             return $this->redirect($client->createAuthUrl());
  431.         }
  432.         try {
  433.             $refererPage $this->get('session')->get('referer_url') ?: $this->generateUrl('homepage');
  434.             $userData $this->googleUserManager->getUserDataFromToken($client$code);
  435.         } catch (\Exception $exception) {
  436.             $this->addFlash('danger'$this->translator->trans('user.something_went_wrong'));
  437.             return $this->redirect($refererPage);
  438.         }
  439.         $userHasNoRetrievedData = (!$userData->getId() && !$userData->getName() && !$userData->getEmail());
  440.         if ($userHasNoRetrievedData) {
  441.             $this->addFlash('danger'$this->translator->trans('user.something_went_wrong'));
  442.             return $this->redirect($refererPage);
  443.         }
  444.         $user $this->googleUserManager->createOrUpdateUser($userData);
  445.         $data = [];
  446.         $data['token'] = $this->googleUserManager->createUserAccessToken($request->request->get('aqarmap_teleport_client_id'), $user);
  447.         $data['referer'] = $refererPage;
  448.         $userToken $this->userAuthenticationServiceV3->generateToken($userfalse);
  449.         $this->usageTrackingTokenStorage->setToken($userToken);
  450.         $this->get('session')->set('_security_main'serialize($userToken));
  451.         return $this->render('@AqarmapUser/User/google_call_back.html.twig', ['data' => $data]);
  452.     }
  453.     private function redirectToFirstPage(Request $requestUser $user, ?Location $location null): RedirectResponse
  454.     {
  455.         $request->query->remove('page');
  456.         return $this->redirect($this->generateUrl('aqarmap_user_listings', [
  457.             'id' => $user->getId(),
  458.             'location' => $location $location->getSlug() : null,
  459.         ]), Response::HTTP_MOVED_PERMANENTLY);
  460.     }
  461. }