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

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.         // Form d'inscription pour la section signup intégrée à la homepage.
  107.         // Le form POST vers la page inscription qui contient déjà toute la logique
  108.         // (validation, reCAPTCHA, envoi mail de bienvenue, auth automatique).
  109.         $form $this->createForm(UsersEmailForm::class, null, [
  110.             'action' => $this->generateUrl('whileresume_resume_' $locale),
  111.             'method' => 'POST',
  112.         ]);
  113.         // Incrémenter compteur de vues
  114.         if ($page !== null) {
  115.             $page->setViews((int)$page->getViews() + 1);
  116.             $this->em->persist($page);
  117.             $this->em->flush();
  118.         }
  119.         return $this->render('application/whileresume/website/candidates/homepage.html.twig', [
  120.             'page'            => $page,
  121.             'articles'        => $articles,
  122.             'totalJobs'       => $totalJobs,
  123.             'popularKeywords' => $popularKeywords,
  124.             'popularJobs'     => $popularJobs,
  125.             'form'            => $form->createView(),
  126.         ]);
  127.     }
  128.     private function jobsKeyword($keyword)
  129.     {
  130.         return $this->em->getRepository(Jobs::class)->searchJobs($keyword,'en',0,10);
  131.     }
  132.     /**
  133.      * API : Recherche d'offres (AJAX)
  134.      */
  135.     public function searchJobsApi(Request $request): JsonResponse
  136.     {
  137.         $locale $request->getLocale();
  138.         $query trim($request->query->get('q'''));
  139.         $offset max(0, (int) $request->query->get('offset'0));
  140.         $limit min(20max(1, (int) $request->query->get('limit'10)));
  141.         $jobsRepo $this->em->getRepository(Jobs::class);
  142.         $jobs $jobsRepo->searchJobs($query$locale$offset$limit);
  143.         $total $jobsRepo->countSearchJobs($query$locale);
  144.         // Récupérer les likes du candidat connecté
  145.         $likedJobIds = [];
  146.         $user $this->getUser();
  147.         if ($user !== null && method_exists($user'getCandidate') && $user->getCandidate() !== null) {
  148.             $likes $this->em->getRepository(JobsHasLikes::class)->findBy(['candidate' => $user->getCandidate()]);
  149.             foreach ($likes as $like) {
  150.                 if ($like->getJob() !== null) {
  151.                     $likedJobIds[] = $like->getJob()->getId();
  152.                 }
  153.             }
  154.         }
  155.         $results = [];
  156.         foreach ($jobs as $job) {
  157.             $results[] = $this->serializeJob($job$likedJobIds);
  158.         }
  159.         return new JsonResponse([
  160.             'jobs' => $results,
  161.             'total' => $total,
  162.             'offset' => $offset,
  163.             'limit' => $limit,
  164.             'hasMore' => ($offset $limit) < $total,
  165.         ]);
  166.     }
  167.     /**
  168.      * API : Like / Unlike une offre (AJAX)
  169.      */
  170.     public function toggleJobLikeApi(Request $request): JsonResponse
  171.     {
  172.         $user $this->getUser();
  173.         if ($user === null) {
  174.             return new JsonResponse(['error' => 'Vous devez être connecté.'], 401);
  175.         }
  176.         $candidate $user->getCandidate();
  177.         if ($candidate === null) {
  178.             return new JsonResponse(['error' => 'Vous devez être candidat pour liker une offre.'], 403);
  179.         }
  180.         $data json_decode($request->getContent(), true);
  181.         $jobId $data['jobId'] ?? null;
  182.         if ($jobId === null) {
  183.             return new JsonResponse(['error' => 'ID de l\'offre manquant.'], 400);
  184.         }
  185.         $job $this->em->getRepository(Jobs::class)->find($jobId);
  186.         if ($job === null) {
  187.             return new JsonResponse(['error' => 'Offre introuvable.'], 404);
  188.         }
  189.         // Vérifier si le like existe déjà
  190.         $existingLike $this->em->getRepository(JobsHasLikes::class)->findOneBy([
  191.             'job' => $job,
  192.             'candidate' => $candidate,
  193.         ]);
  194.         if ($existingLike !== null) {
  195.             // Unlike
  196.             $this->em->remove($existingLike);
  197.             $this->em->flush();
  198.             return new JsonResponse(['liked' => false'jobId' => $jobId]);
  199.         }
  200.         // Like
  201.         $like = new JobsHasLikes();
  202.         $like->setJob($job);
  203.         $like->setCandidate($candidate);
  204.         $this->em->persist($like);
  205.         $this->em->flush();
  206.         return new JsonResponse(['liked' => true'jobId' => $jobId]);
  207.     }
  208.     // ======================================================================
  209.     // HELPERS
  210.     // ======================================================================
  211.     /**
  212.      * Sérialise un Job en tableau pour la réponse JSON
  213.      */
  214.     private function serializeJob(Jobs $job, array $likedJobIds): array
  215.     {
  216.         $now = new \DateTime();
  217.         $diffDays $job->getCreatedAt() ? $now->diff($job->getCreatedAt())->days 999;
  218.         // Image du job (Vich uploader) — adapter le chemin si nécessaire
  219.         $imageUrl null;
  220.         if ($job->getImage() && $job->getImage()->getName()) {
  221.             $imageUrl '/uploads/cv_files/' $job->getImage()->getName();
  222.         }
  223.         return [
  224.             'id' => $job->getId(),
  225.             'jobTitle' => $job->getJobTitle(),
  226.             'companyName' => $job->getCompanyName() ?? 'Entreprise',
  227.             'city' => $job->getCity() ?? '',
  228.             'employmentType' => $job->getEmploymentType() ?? 'CDI',
  229.             'experienceLevel' => $job->getExperienceLevel() ?? '',
  230.             'remoteWork' => $job->getRemoteWork() ?? '',
  231.             'salary' => $this->formatSalary($job->getSalaryMin(), $job->getSalaryMax(), $job->getDevise()),
  232.             'slug' => $job->getSlug(),
  233.             'isNew' => $diffDays <= 7,
  234.             'isLiked' => in_array($job->getId(), $likedJobIds),
  235.             'image' => $imageUrl,
  236.             'logo' => $job->getCompanyName() ? mb_strtoupper(mb_substr($job->getCompanyName(), 01)) : '?',
  237.             'category' => $job->getCategory() ?? '',
  238.         ];
  239.     }
  240.     /**
  241.      * Formate le salaire en string lisible : "55-70k€"
  242.      */
  243.     private function formatSalary(?int $min, ?int $max, ?string $devise): string
  244.     {
  245.         $symbol = ($devise === 'USD' || $devise === '$') ? '$' '€';
  246.         if ($min && $max) {
  247.             return floor($min 1000) . '-' floor($max 1000) . 'k' $symbol;
  248.         }
  249.         if ($min) {
  250.             return floor($min 1000) . 'k' $symbol '+';
  251.         }
  252.         if ($max) {
  253.             return '< ' floor($max 1000) . 'k' $symbol;
  254.         }
  255.         return '';
  256.     }
  257.     // ======================================================================
  258.     // MÉTHODES EXISTANTES (inchangées)
  259.     // ======================================================================
  260.     public function homepageLanding(Request $request$slug): Response
  261.     {
  262.         $locale $request->getLocale();
  263.         $user $this->getUser();
  264.         $landing $this->em->getRepository(LandingJobs::class)->findOneBy(['type' => 'candidates''locale' => $locale]);
  265.         if($landing === null) {
  266.             throw new \RuntimeException('No exist');
  267.         }
  268.         $articles $this->em->getRepository(Articles::class)->getArticles(6,$locale);
  269.         // Nombre total d'offres en ligne sur tout le site
  270.         $totalJobs $this->em->getRepository(Jobs::class)->countAllOnlineJobs();
  271.         // Données pour utilisateur connecté
  272.         $likedJobIds = [];
  273.         if ($user !== null) {
  274.             if (method_exists($user'getCandidate') && $user->getCandidate() !== null) {
  275.                 $likes $this->em->getRepository(JobsHasLikes::class)->findBy(['candidate' => $user->getCandidate()]);
  276.                 foreach ($likes as $like) {
  277.                     if ($like->getJob() !== null) {
  278.                         $likedJobIds[] = $like->getJob()->getId();
  279.                     }
  280.                 }
  281.             }
  282.         }
  283.         // Charger les keywords populaires associés à cette landing page
  284.         $keywordsEntities $this->em->getRepository(KeywordsLandingJobs::class)->findByLanding($landing);
  285.         $popularKeywords = [];
  286.         foreach ($keywordsEntities as $kw) {
  287.             $popularKeywords[] = [
  288.                 'label' => $kw->getLabel() ?? $kw->getSearchKeyword(),
  289.                 'icon' => $kw->getIcon() ?? '',
  290.                 'keyword' => $kw->getSearchKeyword() ?? $kw->getLabel(),
  291.                 'searchKeyword' => $kw->getSearchKeyword() ?? $kw->getLabel(),
  292.             ];
  293.         }
  294.         // Offres populaires par keyword (pour l'animation visiteur, comme la homepage)
  295.         $jobsRepo $this->em->getRepository(Jobs::class);
  296.         $popularJobsForVisitor = [];
  297.         foreach ($popularKeywords as $pk) {
  298.             $jobs $jobsRepo->findByKeyword($pk['keyword'], $locale4);
  299.             $serializedJobs = [];
  300.             foreach ($jobs as $job) {
  301.                 $now = new \DateTime();
  302.                 $diffDays $job->getCreatedAt() ? $now->diff($job->getCreatedAt())->days 999;
  303.                 $daysUntilExpiry 30 $diffDays;
  304.                 $serializedJobs[] = [
  305.                     'jobTitle' => $job->getJobTitle() ?? 'Poste',
  306.                     'city' => $job->getCity() ?? 'Non précisé',
  307.                     'employmentType' => $job->getEmploymentType() ?? 'CDI',
  308.                     'createdAt' => $job->getCreatedAt() ? $job->getCreatedAt()->format('d/m/Y') : '',
  309.                     'diffDays' => $diffDays,
  310.                     'daysUntilExpiry' => $daysUntilExpiry,
  311.                     'slug' => $job->getSlug(),
  312.                 ];
  313.             }
  314.             $popularJobsForVisitor[] = [
  315.                 'text' => $pk['label'],
  316.                 'icon' => $pk['icon'],
  317.                 'searchKeyword' => $pk['keyword'],
  318.                 'jobs' => $serializedJobs,
  319.             ];
  320.         }
  321.         return $this->render('application/whileresume/website/candidates/landing_'.$locale.'.html.twig',[
  322.             'landing' => $landing,
  323.             'articles' => $articles,
  324.             'totalJobs' => $totalJobs,
  325.             'popularKeywords' => $popularKeywords,
  326.             'likedJobIds' => $likedJobIds,
  327.             'popularJobsForVisitor' => $popularJobsForVisitor,
  328.         ]);
  329.     }
  330.     /**
  331.      * Déposer un CV
  332.      * @param Request $request
  333.      * @return Response
  334.      */
  335.     public function resume(Request $request): Response
  336.     {
  337.         $session $request->getSession();
  338.         $locale $request->getLocale();
  339.         $user $this->getUser();
  340.         $errorMessage "";
  341.         $page $this->em->getRepository(Pages::class)->findOneBy(['name' => 'resume''locale' => $locale]);
  342.         $form $this->createForm(UsersEmailForm::class);
  343.         $form->handleRequest($request);
  344.         if ($form->isSubmitted() && $form->isValid()) {
  345.             $data $request->request->all();
  346.             $data $data['users_email_form'];
  347.             if($data['acceptTerm'] == "1") {
  348.                 if($data['password']['first'] != $data['password']['second']) {
  349.                     if($locale == "fr") {
  350.                         $session->getFlashBag()->add('danger''Votre second mot de passe n\'est pas identique');
  351.                         return $this->redirectToRoute('whileresume_resume_fr');
  352.                     }
  353.                     $session->getFlashBag()->add('danger''Your second password is not identical');
  354.                     return $this->redirectToRoute('whileresume_resume_en');
  355.                 }
  356.                 $verificationUser $this->em->getRepository(Users::class)->findOneBy(['email' => $data['email']]);
  357.                 if ($verificationUser == null) {
  358.                     $candidate = new Candidates();
  359.                     $candidate->setEmail($data['email']);
  360.                     $candidate->setUpdatedAt(new \DateTime("now"));
  361.                     $candidate->setCreatedAt(new \DateTime("now"));
  362.                     $candidate->setOnline(false);
  363.                     $candidate->setAvailability("offline");
  364.                     $this->em->persist($candidate);
  365.                     $this->em->flush();
  366.                     $us1 $this->generateUniqueSlug($candidate->getId(),10);
  367.                     $us2 $this->generateUniqueSlug($candidate->getId(),10);
  368.                     $candidate->setSlug($us1);
  369.                     $candidate->setSlugAnonyme($us2);
  370.                     $this->em->persist($candidate);
  371.                     $this->em->flush();
  372.                     $newUser = new Users();
  373.                     $newUser->setEmail($data['email']);
  374.                     $newUser->setUsername("");
  375.                     $newUser->setVerification(false);
  376.                     $newUser->setNotificationsMessages(true);
  377.                     $newUser->setNotificationsSuivis(true);
  378.                     $newUser->setPremium(false);
  379.                     $newUser->setFirst(true);
  380.                     $newUser->setEnabled(true);
  381.                     $newUser->setPassword($this->passwordEncoder->encodePassword($newUser,$data['password']['first']));
  382.                     $newUser->setRoles(['ROLE_USER']);
  383.                     $newUser->setTypeAccount("candidate");
  384.                     $newUser->setUpdatedAt(new \DateTime("now"));
  385.                     $newUser->setCreatedAt(new \DateTime("now"));
  386.                     $newUser->setCandidate($candidate);
  387.                     $this->em->persist($newUser);
  388.                     $this->em->flush();
  389.                     $title "Find your next tech talents in just a few minutes!";
  390.                     if($locale == "fr") {
  391.                         $title "🎉 Bienvenue ! Votre profil peut déjà attirer des recruteurs !";
  392.                     }
  393.                     $descriptionHTML $this->twig->render("application/whileresume/gestion/emails/"$locale ."/register_candidate.html.twig",[
  394.                         'title' => $title,
  395.                         'email' => $data['email']
  396.                     ]);
  397.                     $this->ms->webhook($title,$descriptionHTMLnull$data['email'], nullnull);
  398.                     $this->userAuthenticator->authenticateUser($newUser$this->authenticator$request);
  399.                     if($locale == "en") {
  400.                         return $this->redirectToRoute('customer_homepage');
  401.                     }
  402.                     return $this->redirectToRoute('locale_customer_homepage',['_locale' => $locale]);
  403.                 }
  404.                 if($locale == "fr") {
  405.                     $session->getFlashBag()->add('danger'$errorMessage);
  406.                     return $this->redirectToRoute('whileresume_resume_fr');
  407.                 }
  408.                 $errorMessage "You are already registered with this email";
  409.                 $session->getFlashBag()->add('danger'$errorMessage);
  410.                 return $this->redirectToRoute('whileresume_resume_en');
  411.             }
  412.         }
  413.         return $this->render('application/whileresume/website/candidates/resume_'.$locale.'.html.twig',[
  414.             'form' => $form->createView(),
  415.             'page' => $page
  416.         ]);
  417.     }
  418.     private function generateUniqueSlug(int $userIdint $length 8): string
  419.     {
  420.         $characters '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  421.         $slug '';
  422.         for ($i 0$i $length$i++) {
  423.             $slug .= $characters[random_int(0strlen($characters) - 1)];
  424.         }
  425.         return $userId '-' $slug;
  426.     }
  427. }