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

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