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

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