src/Controller/ThemesWebsite/Whileresume/Website/CandidatesController.php line 128

Open in your IDE?
  1. <?php
  2. namespace App\Controller\ThemesWebsite\Whileresume\Website;
  3. use App\Entity\Articles\Articles;
  4. use App\Entity\Core\Users;
  5. use App\Entity\Cvs\Candidates;
  6. use App\Entity\Cvs\Jobs;
  7. use App\Entity\Cvs\JobsHasLikes;
  8. use App\Entity\Cvs\KeywordsLandingJobs;
  9. use App\Entity\Cvs\LandingJobs;
  10. use App\Entity\Pages\Pages;
  11. use App\Form\Core\UsersEmailForm;
  12. use App\Security\LoginFormAuthenticator;
  13. use App\Services\Core\RequestData;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Knp\Component\Pager\PaginatorInterface;
  16. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
  17. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  18. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  21. use Symfony\Component\HttpFoundation\Cookie;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\HttpFoundation\RedirectResponse;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Component\Routing\Annotation\Route;
  27. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  28. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  29. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  30. use Symfony\Component\Security\Core\User\UserInterface;
  31. use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface;
  32. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  33. use Symfony\Component\Security\Http\Authentication\AuthenticatorManagerInterface;
  34. use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
  35. use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
  36. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordCredentialsBadge;
  37. use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
  38. use Twig\Environment;
  39. class CandidatesController extends AbstractController
  40. {
  41.     private $rd;
  42.     private $em;
  43.     private $passwordEncoder;
  44.     private $ms;
  45.     private $us;
  46.     private $authenticator;
  47.     private $userAuthenticator;
  48.     private $paginator;
  49.     private $twig;
  50.     public function __construct(RequestData                  $rd,
  51.                                 EntityManagerInterface       $em,
  52.                                 UserPasswordEncoderInterface $passwordEncoder,
  53.                                 \App\Services\Mails          $ms,
  54.                                 \App\Services\Core\Users     $us,
  55.                                 UserAuthenticatorInterface   $userAuthenticator,
  56.                                 LoginFormAuthenticator       $authenticator,
  57.                                 PaginatorInterface           $paginator,
  58.                                 Environment $twig,
  59.     ) {
  60.         $this->rd $rd;
  61.         $this->em $em;
  62.         $this->passwordEncoder $passwordEncoder;
  63.         $this->ms $ms;
  64.         $this->authenticator $authenticator;
  65.         $this->userAuthenticator $userAuthenticator;
  66.         $this->us $us;
  67.         $this->paginator $paginator;
  68.         $this->twig $twig;
  69.     }
  70.     /**
  71.      * Homepage principal
  72.      * @param Request $request
  73.      * @return Response
  74.      */
  75.     public function homepage(Request $request): Response
  76.     {
  77.         $locale $request->getLocale();
  78.         // Page meta (title, description, robots, etc.)
  79.         $page $this->em->getRepository(Pages::class)->findOneBy(['name' => 'homepage''locale' => $locale]);
  80.         // Articles : 6 derniers pour la section "Conseils carrière"
  81.         $articles $this->em->getRepository(Articles::class)->getArticles(6$locale);
  82.         // Stat hero : nombre total d'offres en ligne
  83.         $totalJobs $this->em->getRepository(Jobs::class)->countAllOnlineJobs();
  84.         // Mots-clés populaires (categories) — affichés en pills + sections d'offres associées
  85.         $keywordsEntities $this->em->getRepository(KeywordsLandingJobs::class)->findByLocaleForHomepage($locale);
  86.         $popularKeywords = [];
  87.         $popularJobs = [];
  88.         $jobsRepo $this->em->getRepository(Jobs::class);
  89.         foreach ($keywordsEntities as $kw) {
  90.             $label   $kw->getLabel() ?? $kw->getSearchKeyword();
  91.             $icon    $kw->getIcon() ?? '';
  92.             $keyword $kw->getSearchKeyword() ?? $kw->getLabel();
  93.             // Liste utilisée pour la barre de pills "Recherchez par catégorie"
  94.             $popularKeywords[] = [
  95.                 'label'   => $label,
  96.                 'icon'    => $icon,
  97.                 'keyword' => $keyword,
  98.             ];
  99.             // Pour chaque keyword, on ramène 4 offres pour la section "Offres populaires"
  100.             $popularJobs[] = [
  101.                 'label' => $label,
  102.                 'icon'  => $icon,
  103.                 'jobs'  => $jobsRepo->findByKeyword($keyword$locale4),
  104.             ];
  105.         }
  106.         // Incrémenter compteur de vues
  107.         if ($page !== null) {
  108.             $page->setViews((int)$page->getViews() + 1);
  109.             $this->em->persist($page);
  110.             $this->em->flush();
  111.         }
  112.         return $this->render('application/whileresume/website/candidates/homepage.html.twig', [
  113.             'page'            => $page,
  114.             'articles'        => $articles,
  115.             'totalJobs'       => $totalJobs,
  116.             'popularKeywords' => $popularKeywords,
  117.             'popularJobs'     => $popularJobs,
  118.         ]);
  119.     }
  120.     private function jobsKeyword($keyword)
  121.     {
  122.         return $this->em->getRepository(Jobs::class)->searchJobs($keyword,'en',0,10);
  123.     }
  124.     /**
  125.      * API : Recherche d'offres (AJAX)
  126.      */
  127.     public function searchJobsApi(Request $request): JsonResponse
  128.     {
  129.         $locale $request->getLocale();
  130.         $query trim($request->query->get('q'''));
  131.         $offset max(0, (int) $request->query->get('offset'0));
  132.         $limit min(20max(1, (int) $request->query->get('limit'10)));
  133.         $jobsRepo $this->em->getRepository(Jobs::class);
  134.         $jobs $jobsRepo->searchJobs($query$locale$offset$limit);
  135.         $total $jobsRepo->countSearchJobs($query$locale);
  136.         // Récupérer les likes du candidat connecté
  137.         $likedJobIds = [];
  138.         $user $this->getUser();
  139.         if ($user !== null && method_exists($user'getCandidate') && $user->getCandidate() !== null) {
  140.             $likes $this->em->getRepository(JobsHasLikes::class)->findBy(['candidate' => $user->getCandidate()]);
  141.             foreach ($likes as $like) {
  142.                 if ($like->getJob() !== null) {
  143.                     $likedJobIds[] = $like->getJob()->getId();
  144.                 }
  145.             }
  146.         }
  147.         $results = [];
  148.         foreach ($jobs as $job) {
  149.             $results[] = $this->serializeJob($job$likedJobIds);
  150.         }
  151.         return new JsonResponse([
  152.             'jobs' => $results,
  153.             'total' => $total,
  154.             'offset' => $offset,
  155.             'limit' => $limit,
  156.             'hasMore' => ($offset $limit) < $total,
  157.         ]);
  158.     }
  159.     /**
  160.      * API : Like / Unlike une offre (AJAX)
  161.      */
  162.     public function toggleJobLikeApi(Request $request): JsonResponse
  163.     {
  164.         $user $this->getUser();
  165.         if ($user === null) {
  166.             return new JsonResponse(['error' => 'Vous devez être connecté.'], 401);
  167.         }
  168.         $candidate $user->getCandidate();
  169.         if ($candidate === null) {
  170.             return new JsonResponse(['error' => 'Vous devez être candidat pour liker une offre.'], 403);
  171.         }
  172.         $data json_decode($request->getContent(), true);
  173.         $jobId $data['jobId'] ?? null;
  174.         if ($jobId === null) {
  175.             return new JsonResponse(['error' => 'ID de l\'offre manquant.'], 400);
  176.         }
  177.         $job $this->em->getRepository(Jobs::class)->find($jobId);
  178.         if ($job === null) {
  179.             return new JsonResponse(['error' => 'Offre introuvable.'], 404);
  180.         }
  181.         // Vérifier si le like existe déjà
  182.         $existingLike $this->em->getRepository(JobsHasLikes::class)->findOneBy([
  183.             'job' => $job,
  184.             'candidate' => $candidate,
  185.         ]);
  186.         if ($existingLike !== null) {
  187.             // Unlike
  188.             $this->em->remove($existingLike);
  189.             $this->em->flush();
  190.             return new JsonResponse(['liked' => false'jobId' => $jobId]);
  191.         }
  192.         // Like
  193.         $like = new JobsHasLikes();
  194.         $like->setJob($job);
  195.         $like->setCandidate($candidate);
  196.         $this->em->persist($like);
  197.         $this->em->flush();
  198.         return new JsonResponse(['liked' => true'jobId' => $jobId]);
  199.     }
  200.     // ======================================================================
  201.     // HELPERS
  202.     // ======================================================================
  203.     /**
  204.      * Sérialise un Job en tableau pour la réponse JSON
  205.      */
  206.     private function serializeJob(Jobs $job, array $likedJobIds): array
  207.     {
  208.         $now = new \DateTime();
  209.         $diffDays $job->getCreatedAt() ? $now->diff($job->getCreatedAt())->days 999;
  210.         // Image du job (Vich uploader) — adapter le chemin si nécessaire
  211.         $imageUrl null;
  212.         if ($job->getImage() && $job->getImage()->getName()) {
  213.             $imageUrl '/uploads/cv_files/' $job->getImage()->getName();
  214.         }
  215.         return [
  216.             'id' => $job->getId(),
  217.             'jobTitle' => $job->getJobTitle(),
  218.             'companyName' => $job->getCompanyName() ?? 'Entreprise',
  219.             'city' => $job->getCity() ?? '',
  220.             'employmentType' => $job->getEmploymentType() ?? 'CDI',
  221.             'experienceLevel' => $job->getExperienceLevel() ?? '',
  222.             'remoteWork' => $job->getRemoteWork() ?? '',
  223.             'salary' => $this->formatSalary($job->getSalaryMin(), $job->getSalaryMax(), $job->getDevise()),
  224.             'slug' => $job->getSlug(),
  225.             'isNew' => $diffDays <= 7,
  226.             'isLiked' => in_array($job->getId(), $likedJobIds),
  227.             'image' => $imageUrl,
  228.             'logo' => $job->getCompanyName() ? mb_strtoupper(mb_substr($job->getCompanyName(), 01)) : '?',
  229.             'category' => $job->getCategory() ?? '',
  230.         ];
  231.     }
  232.     /**
  233.      * Formate le salaire en string lisible : "55-70k€"
  234.      */
  235.     private function formatSalary(?int $min, ?int $max, ?string $devise): string
  236.     {
  237.         $symbol = ($devise === 'USD' || $devise === '$') ? '$' '€';
  238.         if ($min && $max) {
  239.             return floor($min 1000) . '-' floor($max 1000) . 'k' $symbol;
  240.         }
  241.         if ($min) {
  242.             return floor($min 1000) . 'k' $symbol '+';
  243.         }
  244.         if ($max) {
  245.             return '< ' floor($max 1000) . 'k' $symbol;
  246.         }
  247.         return '';
  248.     }
  249.     // ======================================================================
  250.     // MÉTHODES EXISTANTES (inchangées)
  251.     // ======================================================================
  252.     public function homepageLanding(Request $request$slug): Response
  253.     {
  254.         $locale $request->getLocale();
  255.         $user $this->getUser();
  256.         $landing $this->em->getRepository(LandingJobs::class)->findOneBy(['type' => 'candidates''locale' => $locale]);
  257.         if($landing === null) {
  258.             throw new \RuntimeException('No exist');
  259.         }
  260.         $articles $this->em->getRepository(Articles::class)->getArticles(6,$locale);
  261.         // Nombre total d'offres en ligne sur tout le site
  262.         $totalJobs $this->em->getRepository(Jobs::class)->countAllOnlineJobs();
  263.         // Données pour utilisateur connecté
  264.         $likedJobIds = [];
  265.         if ($user !== null) {
  266.             if (method_exists($user'getCandidate') && $user->getCandidate() !== null) {
  267.                 $likes $this->em->getRepository(JobsHasLikes::class)->findBy(['candidate' => $user->getCandidate()]);
  268.                 foreach ($likes as $like) {
  269.                     if ($like->getJob() !== null) {
  270.                         $likedJobIds[] = $like->getJob()->getId();
  271.                     }
  272.                 }
  273.             }
  274.         }
  275.         // Charger les keywords populaires associés à cette landing page
  276.         $keywordsEntities $this->em->getRepository(KeywordsLandingJobs::class)->findByLanding($landing);
  277.         $popularKeywords = [];
  278.         foreach ($keywordsEntities as $kw) {
  279.             $popularKeywords[] = [
  280.                 'label' => $kw->getLabel() ?? $kw->getSearchKeyword(),
  281.                 'icon' => $kw->getIcon() ?? '',
  282.                 'keyword' => $kw->getSearchKeyword() ?? $kw->getLabel(),
  283.                 'searchKeyword' => $kw->getSearchKeyword() ?? $kw->getLabel(),
  284.             ];
  285.         }
  286.         // Offres populaires par keyword (pour l'animation visiteur, comme la homepage)
  287.         $jobsRepo $this->em->getRepository(Jobs::class);
  288.         $popularJobsForVisitor = [];
  289.         foreach ($popularKeywords as $pk) {
  290.             $jobs $jobsRepo->findByKeyword($pk['keyword'], $locale4);
  291.             $serializedJobs = [];
  292.             foreach ($jobs as $job) {
  293.                 $now = new \DateTime();
  294.                 $diffDays $job->getCreatedAt() ? $now->diff($job->getCreatedAt())->days 999;
  295.                 $daysUntilExpiry 30 $diffDays;
  296.                 $serializedJobs[] = [
  297.                     'jobTitle' => $job->getJobTitle() ?? 'Poste',
  298.                     'city' => $job->getCity() ?? 'Non précisé',
  299.                     'employmentType' => $job->getEmploymentType() ?? 'CDI',
  300.                     'createdAt' => $job->getCreatedAt() ? $job->getCreatedAt()->format('d/m/Y') : '',
  301.                     'diffDays' => $diffDays,
  302.                     'daysUntilExpiry' => $daysUntilExpiry,
  303.                     'slug' => $job->getSlug(),
  304.                 ];
  305.             }
  306.             $popularJobsForVisitor[] = [
  307.                 'text' => $pk['label'],
  308.                 'icon' => $pk['icon'],
  309.                 'searchKeyword' => $pk['keyword'],
  310.                 'jobs' => $serializedJobs,
  311.             ];
  312.         }
  313.         return $this->render('application/whileresume/website/candidates/landing_'.$locale.'.html.twig',[
  314.             'landing' => $landing,
  315.             'articles' => $articles,
  316.             'totalJobs' => $totalJobs,
  317.             'popularKeywords' => $popularKeywords,
  318.             'likedJobIds' => $likedJobIds,
  319.             'popularJobsForVisitor' => $popularJobsForVisitor,
  320.         ]);
  321.     }
  322.     /**
  323.      * Déposer un CV
  324.      * @param Request $request
  325.      * @return Response
  326.      */
  327.     public function resume(Request $request): Response
  328.     {
  329.         $session $request->getSession();
  330.         $locale $request->getLocale();
  331.         $user $this->getUser();
  332.         $errorMessage "";
  333.         $page $this->em->getRepository(Pages::class)->findOneBy(['name' => 'resume''locale' => $locale]);
  334.         $form $this->createForm(UsersEmailForm::class);
  335.         $form->handleRequest($request);
  336.         if ($form->isSubmitted() && $form->isValid()) {
  337.             $data $request->request->all();
  338.             $data $data['users_email_form'];
  339.             if($data['acceptTerm'] == "1") {
  340.                 if($data['password']['first'] != $data['password']['second']) {
  341.                     if($locale == "fr") {
  342.                         $session->getFlashBag()->add('danger''Votre second mot de passe n\'est pas identique');
  343.                         return $this->redirectToRoute('whileresume_resume_fr');
  344.                     }
  345.                     $session->getFlashBag()->add('danger''Your second password is not identical');
  346.                     return $this->redirectToRoute('whileresume_resume_en');
  347.                 }
  348.                 $verificationUser $this->em->getRepository(Users::class)->findOneBy(['email' => $data['email']]);
  349.                 if ($verificationUser == null) {
  350.                     $candidate = new Candidates();
  351.                     $candidate->setEmail($data['email']);
  352.                     $candidate->setUpdatedAt(new \DateTime("now"));
  353.                     $candidate->setCreatedAt(new \DateTime("now"));
  354.                     $candidate->setOnline(false);
  355.                     $candidate->setAvailability("offline");
  356.                     $this->em->persist($candidate);
  357.                     $this->em->flush();
  358.                     $us1 $this->generateUniqueSlug($candidate->getId(),10);
  359.                     $us2 $this->generateUniqueSlug($candidate->getId(),10);
  360.                     $candidate->setSlug($us1);
  361.                     $candidate->setSlugAnonyme($us2);
  362.                     $this->em->persist($candidate);
  363.                     $this->em->flush();
  364.                     $newUser = new Users();
  365.                     $newUser->setEmail($data['email']);
  366.                     $newUser->setUsername("");
  367.                     $newUser->setVerification(false);
  368.                     $newUser->setNotificationsMessages(true);
  369.                     $newUser->setNotificationsSuivis(true);
  370.                     $newUser->setPremium(false);
  371.                     $newUser->setFirst(true);
  372.                     $newUser->setEnabled(true);
  373.                     $newUser->setPassword($this->passwordEncoder->encodePassword($newUser,$data['password']['first']));
  374.                     $newUser->setRoles(['ROLE_USER']);
  375.                     $newUser->setTypeAccount("candidate");
  376.                     $newUser->setUpdatedAt(new \DateTime("now"));
  377.                     $newUser->setCreatedAt(new \DateTime("now"));
  378.                     $newUser->setCandidate($candidate);
  379.                     $this->em->persist($newUser);
  380.                     $this->em->flush();
  381.                     $title "Find your next tech talents in just a few minutes!";
  382.                     if($locale == "fr") {
  383.                         $title "🎉 Bienvenue ! Votre profil peut déjà attirer des recruteurs !";
  384.                     }
  385.                     $descriptionHTML $this->twig->render("application/whileresume/gestion/emails/"$locale ."/register_candidate.html.twig",[
  386.                         'title' => $title,
  387.                         'email' => $data['email']
  388.                     ]);
  389.                     $this->ms->webhook($title,$descriptionHTMLnull$data['email'], nullnull);
  390.                     $this->userAuthenticator->authenticateUser($newUser$this->authenticator$request);
  391.                     if($locale == "en") {
  392.                         return $this->redirectToRoute('customer_homepage');
  393.                     }
  394.                     return $this->redirectToRoute('locale_customer_homepage',['_locale' => $locale]);
  395.                 }
  396.                 if($locale == "fr") {
  397.                     $session->getFlashBag()->add('danger'$errorMessage);
  398.                     return $this->redirectToRoute('whileresume_resume_fr');
  399.                 }
  400.                 $errorMessage "You are already registered with this email";
  401.                 $session->getFlashBag()->add('danger'$errorMessage);
  402.                 return $this->redirectToRoute('whileresume_resume_en');
  403.             }
  404.         }
  405.         return $this->render('application/whileresume/website/candidates/resume_'.$locale.'.html.twig',[
  406.             'form' => $form->createView(),
  407.             'page' => $page
  408.         ]);
  409.     }
  410.     private function generateUniqueSlug(int $userIdint $length 8): string
  411.     {
  412.         $characters '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  413.         $slug '';
  414.         for ($i 0$i $length$i++) {
  415.             $slug .= $characters[random_int(0strlen($characters) - 1)];
  416.         }
  417.         return $userId '-' $slug;
  418.     }
  419. }