src/Controller/Frontend/ProfileController.php line 21

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Frontend;
  3. use App\Annotation\Log;
  4. use App\Constant\Common;
  5. use App\Entity\Campaign;
  6. use App\Entity\Profile;
  7. use App\Entity\Status;
  8. use App\Exception\BadRequestException;
  9. use App\Misc\CaptchaHelper;
  10. use App\Service\ProfileFileService;
  11. use App\Utilities\ServiceUtil;
  12. use Psr\Log\LoggerInterface;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Contracts\Translation\TranslatorInterface;
  16. class ProfileController extends BaseFrontendController
  17. {
  18.     /**
  19.      * @Route("/{_locale}/dossier-inscription/step1", name="profile.step1", methods={"GET"})
  20.      */
  21.     public function profileStep1(TranslatorInterface $translator)
  22.     {
  23.         $siteName = $translator->trans('siteName');
  24.         $this->addTitle($translator->trans(
  25.             'profile_step1.title',
  26.             [
  27.                 '%siteName%' => $siteName
  28.             ]
  29.         ));
  30.         $this->setDescription($translator->trans(
  31.             'profile_step1.desc',
  32.             [
  33.                 '%siteName%' => $siteName
  34.             ]
  35.         ));
  36.         // get profile logged in
  37.         $data['formData'] = [
  38.             'errors' => [],
  39.             'inputValues' => []
  40.         ];
  41.         if ($this->getUser()) {
  42.             $data['formData']['inputValues'] = $this->currentService->getProfileByUserId($this->getUser()->getId());
  43.         }
  44.         $data = array_merge($data, $this->stepData());
  45.         if (isset($data['formData']['inputValues']['year'])) {
  46.             $data['year'] = $data['formData']['inputValues']['year'];
  47.         }
  48.         return $this->render('user/profile/profile_step1.html.twig', $data);
  49.     }
  50.     /**
  51.      * @Route("/{_locale}/dossier-inscription/step2", name="profile.step2", methods={"GET"})
  52.      */
  53.     public function profileStep2(TranslatorInterface $translator)
  54.     {
  55.         if (!$this->getUser()) {
  56.             return $this->redirectToRoute('profile.step1');
  57.         }
  58.         $siteName = $translator->trans('siteName');
  59.         $this->addTitle($translator->trans(
  60.             'profile_step1.title',
  61.             [
  62.                 '%siteName%' => $siteName
  63.             ]
  64.         ));
  65.         $this->setDescription($translator->trans(
  66.             'profile_step1.desc',
  67.             [
  68.                 '%siteName%' => $siteName
  69.             ]
  70.         ));
  71.         $data['formData'] = [
  72.             'errors' => [],
  73.             'inputValues' => $this->currentService->getProfileByUserId($this->getUser()->getId())
  74.         ];
  75.         $data = array_merge($data, $this->stepData());
  76.         if (isset($data['formData']['inputValues']['year'])) {
  77.             $data['year'] = $data['formData']['inputValues']['year'];
  78.         }
  79.         return $this->render('user/profile/profile_step2.html.twig', $data);
  80.     }
  81.     /**
  82.      * @Route("/{_locale}/dossier-inscription/step3", name="profile.step3", methods={"GET"})
  83.      */
  84.     public function profileStep3(TranslatorInterface $translator)
  85.     {
  86.         if (!$this->getUser()) {
  87.             return $this->redirectToRoute('profile.step1');
  88.         }
  89.         $siteName = $translator->trans('siteName');
  90.         $this->addTitle($translator->trans(
  91.             'profile_step1.title',
  92.             [
  93.                 '%siteName%' => $siteName
  94.             ]
  95.         ));
  96.         $this->setDescription($translator->trans(
  97.             'profile_step1.desc',
  98.             [
  99.                 '%siteName%' => $siteName
  100.             ]
  101.         ));
  102.         $data['formData'] = [
  103.             'errors' => [],
  104.             'inputValues' => $this->currentService->getProfileByUserId($this->getUser()->getId())
  105.         ];
  106.         $data = array_merge($data, $this->stepData());
  107.         if (isset($data['formData']['inputValues']['year'])) {
  108.             $data['year'] = $data['formData']['inputValues']['year'];
  109.         }
  110.         return $this->render('user/profile/profile_step3.html.twig', $data);
  111.     }
  112.     /**
  113.      * @Route("/{_locale}/dossier-inscription/step4", name="profile.step4", methods={"GET"})
  114.      */
  115.     public function profileStep4(TranslatorInterface $translator)
  116.     {
  117.         if (!$this->getUser()) {
  118.             return $this->redirectToRoute('profile.step1');
  119.         }
  120.         $siteName = $translator->trans('siteName');
  121.         $this->addTitle($translator->trans(
  122.             'profile_step1.title',
  123.             [
  124.                 '%siteName%' => $siteName
  125.             ]
  126.         ));
  127.         $this->setDescription($translator->trans(
  128.             'profile_step1.desc',
  129.             [
  130.                 '%siteName%' => $siteName
  131.             ]
  132.         ));
  133.         $data['formData'] = [
  134.             'errors' => [],
  135.             'inputValues' => $this->currentService->getProfileByUserId($this->getUser()->getId())
  136.         ];
  137.         $data = array_merge($data, $this->stepData());
  138.         if (isset($data['formData']['inputValues']['year'])) {
  139.             $data['year'] = $data['formData']['inputValues']['year'];
  140.         }
  141.         return $this->render('user/profile/profile_step4.html.twig', $data);
  142.     }
  143.     /**
  144.      * @Route("/{_locale}/profile/step1", name="profile.step1_save", methods={"POST", "PUT"})
  145.      * @Log
  146.      */
  147.     public function profileStep1Save(
  148.         Request $request,
  149.         CaptchaHelper $captchaHelper,
  150.         TranslatorInterface $translator
  151.     ) {
  152.         // new profile
  153.         if ($request->getMethod() === 'POST') {
  154.             // Check captcha is valid
  155.             if ($this->getParameter('captcha_enabled') && !$captchaHelper->isCaptchaValid($request)) {
  156.                 return $this->json(ServiceUtil::processFailed([
  157.                     'errorMessage' => $translator->trans('message.captcha_is_not_valid')
  158.                 ]));
  159.             }
  160.             $campaign = $this->campaignRepo->findOneBy(['id' => Campaign::APPLICATION]);
  161.             if ($campaign) {
  162.                 $request->request->set('campaign', $campaign->getId());
  163.             }
  164.             if(!$request->get('programs')){
  165.                 $data = $this->stepData();
  166.                 $data['formData'] = [
  167.                     'errors' => [],
  168.                     'inputValues' => $request->request->all()
  169.                 ];
  170.                 $data['valid_programs'] = $translator->trans('message.programme_is_not_valid');
  171.                 return $this->render('user/profile/profile_step1.html.twig', $data);
  172.             }
  173.             try {
  174.                 $this->currentService->addProfile($request);
  175.                 return $this->redirectToRoute('profile.step2', ['new_user'=> 1]);
  176.             } catch (BadRequestException $badRequestException) {
  177.                 $data = $this->stepData();
  178.                 $data['formData'] = [
  179.                     'errors' => [],
  180.                     'inputValues' => $request->request->all()
  181.                 ];
  182.                 $error = $badRequestException->getMessages();
  183.                 if ($error['entityName'] === 'User') {
  184.                     foreach ($error['data'] as $field => $message) {
  185.                         $data['formData']['errors']['user[' . $field . ']'] = $message;
  186.                     }
  187.                 }
  188.                 $data['validated'] = true;
  189.                 return $this->render('user/profile/profile_step1.html.twig', $data);
  190.             }
  191.         }
  192.         // update step 1  and ?? go to step 2 ?
  193.         $this->userService->updateProfileUser($request->get('user'));
  194.         $this->currentService->updateProfile($request);
  195.         return $this->redirectToRoute('profile.step2');
  196.     }
  197.     /**
  198.      * @Route("/{_locale}/profile/step2", name="profile.step2_save", methods={"PUT"})
  199.      */
  200.     public function profileStep2Save(Request $request)
  201.     {
  202.         $this->currentService->updateProfile($request, 'App\DTO\Profile\UpdateProfileStep2Input');
  203.         return $this->redirectToRoute('profile.step3');
  204.     }
  205.     /**
  206.      * @Route("/{_locale}/profile/step3", name="profile.step3_save", methods={"PUT"})
  207.      */
  208.     public function profileStep3Save(Request $request)
  209.     {
  210.         $this->currentService->updateProfile($request, 'App\DTO\Profile\UpdateProfileStep3Input');
  211.         return $this->redirectToRoute('profile.step4');
  212.     }
  213.     /**
  214.      * @Route("/{_locale}/profile/step4", name="profile.step4_save", methods={"PUT"})
  215.      */
  216.     public function profileStep4Save(Request $request)
  217.     {
  218.         $isSent = $request->get('isSent');
  219.         // Step 4 has both plain text user[...] fields (from analyzed document data,
  220.         // landed in the POST body) and a user[media] file upload (landed in the
  221.         // files bag). Merge both so neither is silently dropped.
  222.         $userInput = array_merge(
  223.             (array) $request->get('user'),
  224.             array_filter((array) $request->files->get('user'), static fn($f) => null !== $f)
  225.         );
  226.         $this->userService->updateProfileUser($userInput);
  227.         $request->files->remove('user');
  228.         $this->currentService->updateProfile($request, 'App\DTO\Profile\UpdateProfileStep4Input', true);
  229.         $param = [];
  230.         if(!$isSent){
  231.             $param = ['new_user'=> 1];
  232.         }
  233.         return $this->redirectToRoute('user.application', $param);
  234.     }
  235.     public function stepData()
  236.     {
  237.         $data = [];
  238.         $data['studyLevels'] = $this->studyLevelRepository->findAll();
  239.         $data['cursuses'] = $this->cursusRepository->findAll();
  240.         $data['programsByLevel'] = $this->programService->getActiveProgramGroupByLevel();
  241.         $france = $this->countryRepo->find(1);
  242.         $data['countries'] = array_merge([$france], $this->countryRepo->getAll(['except_id' => 1, 'sort_asc' => 'name'], 'ENTITY'));
  243.         $data['departments'] = array_map(function ($department) {
  244.             return ['value' => $department, 'text' => $department];
  245.         }, $this->commonService->frenchDepartments);
  246.         $data['campuses'] = $this->campusRepository->getAll(['filter_status' => 1, 'memberOf_programs' => 'notNull','sort_asc' => 'ordering'], 'ENTITY');
  247.         $year = (int) date("Y");
  248.         $currentAcademicYear = $year . '-' . ($year + 1);
  249.         $nextAcademicYear    = ($year + 1) . '-' . ($year + 2);
  250.         if (date("Y-m-d") > date("Y") . '-10-01') {
  251.             $data['year'] = $nextAcademicYear;
  252.             $data['years'] = [
  253.                 ['value' => $currentAcademicYear, 'text' => $currentAcademicYear],
  254.                 ['value' => $nextAcademicYear,    'text' => $nextAcademicYear],
  255.             ];
  256.         } else {
  257.             $data['year'] = $currentAcademicYear;
  258.             $data['years'] = [
  259.                 ['value' => $currentAcademicYear, 'text' => $currentAcademicYear],
  260.             ];
  261.         }
  262.         return $data;
  263.     }
  264.     /**
  265.      * @Route("/{_locale}/fiche-de-renseigenement-alternance", name="fiche_de_renseigenement", methods={"GET"})
  266.      */
  267.     public function ficheDeRenseigenement(Request $request)
  268.     {
  269.         $token = $request->get('token');
  270.         if (!$token) {
  271.             return $this->render('pages/404.html.twig');
  272.         }
  273.         $tokenStorage = explode('_MpTKRipu85cN', $token);
  274.         if (is_array($tokenStorage)) {
  275.             $profile = $this->profileRepo->find(base64_decode($tokenStorage[0]));
  276.         } else {
  277.             return $this->render('pages/404.html.twig');
  278.         }
  279.         $data = [];
  280.         $data['profile'] = $this->currentService->autoMapper->map($profile, 'App\DTO\Profile\ProfileOutput');
  281.         // dd($data['profile']);
  282.         $data['session'] = (int) $profile->getYear() ? explode('-', $profile->getYear())[0] : null;
  283.         $data['contractTypes'] = Common::contractTypes();
  284.         $data['specificPrivate'] = Common::CONTRACT_SPECIFIC_TYPES;
  285.         $data['specificPublic'] = Common::CONTRACT_SPECIFIC_PUBLIC_TYPES;
  286.         $data['employers'] = Common::CONTRACT_SPECIFIC_EMPLOYERS;
  287.         //set default list specifics
  288.         $data['specifics'] =  Common::CONTRACT_SPECIFIC_TYPES;
  289.         if (isset($data['profile']->entreprise['entreprise']['type']) && $data['profile']->entreprise['entreprise']['type'] == 2) {
  290.             $data['specifics'] =  Common::CONTRACT_SPECIFIC_PUBLIC_TYPES;
  291.         }
  292.         $data['sendMail'] = 0;
  293.         if ($request->get('mode') == 'public') {
  294.             $data['sendMail'] = 1;
  295.         }
  296.         return $this->render('fiche/index.html.twig', $data);
  297.     }
  298.     /**
  299.      * @Route("/{_locale}/fiche-save", name="fiche.save", methods={"PUT"})
  300.      */
  301.     public function ficheSave(Request $request)
  302.     {
  303.         $contract = $request->get('contract');
  304.         if ($contract) {
  305.             $fullSupport = 0;
  306.             $annualCompanyTotal = 0;
  307.             if (isset($contract['contract']['annualSupport1'])) {
  308.                 if ($contract['contract']['annualSupport1']) {
  309.                     $fullSupport = $fullSupport + $contract['contract']['annualSupport1'];
  310.                 }
  311.                 if ($contract['contract']['annualCompany1']) {
  312.                     $annualCompanyTotal = $annualCompanyTotal + $contract['contract']['annualCompany1'];
  313.                 }
  314.             }
  315.             if (isset($contract['contract']['annualSupport2'])) {
  316.                 if ($contract['contract']['annualSupport2']) {
  317.                     $fullSupport = $fullSupport + $contract['contract']['annualSupport2'];
  318.                 }
  319.                 if ($contract['contract']['annualCompany2']) {
  320.                     $annualCompanyTotal = $annualCompanyTotal + $contract['contract']['annualCompany2'];
  321.                 }
  322.             }
  323.             if (isset($contract['contract']['annualSupport3'])) {
  324.                 if ($contract['contract']['annualSupport3']) {
  325.                     $fullSupport = $fullSupport + $contract['contract']['annualSupport3'];
  326.                 }
  327.                 if ($contract['contract']['annualCompany3']) {
  328.                     $annualCompanyTotal = $annualCompanyTotal + $contract['contract']['annualCompany3'];
  329.                 }
  330.             }
  331.             $contract['contract']['fullSupport'] = $fullSupport;
  332.             $contract['contract']['annualCompanyTotal'] = $annualCompanyTotal;
  333.             $contract['contract']['totalTrainingCost'] = $fullSupport + $annualCompanyTotal;
  334.         }
  335.         $conditions = $request->get('entreprise');
  336.         $trainingHours = 0;
  337.         if ($conditions) {
  338.             if (isset($conditions['contract']['conditions'])) {
  339.                 foreach ($conditions['contract']['conditions'] as $condition) {
  340.                     $trainingHours = $trainingHours + $condition['hour'];
  341.                 }
  342.             }
  343.             $contract['contract']['trainingHours'] = $trainingHours;
  344.         }
  345.         $request->request->set('contract', $contract);
  346.         $profile = $this->currentService->updateProfile($request, 'App\DTO\Profile\UpdateProfileFicheInput');
  347.         if ($request->get('sendMail')) {
  348.             $this->userService->sendFicheEmail($this->currentService->autoMapper->map($profile, 'App\DTO\Profile\ProfileOutput'), 'private');
  349.         }
  350.         return $this->json(ServiceUtil::processSuccessful());
  351.     }
  352.     /**
  353.      * @Route("/qcm-result", name="qcm_result.save", methods={"POST"})
  354.      */
  355.     public function QcmResult(Request $request)
  356.     {
  357.         $response = json_decode($request->getContent(), 1);
  358.         if ($response['token'] && $response['email']) {
  359.             $profile = $this->currentRepo->getProfileByToken($response['email'], $response['token']);
  360.             if ($profile) {
  361.                 $dataQcmResults = [
  362.                     'isDoneTest' => $response['isDoneTest'],
  363.                     'questions' => $response['questions']
  364.                 ];
  365.                 $profile->setQcmResults($dataQcmResults);
  366.                 $this->currentRepo->save($profile);
  367.             } else {
  368.                 return $this->json(ServiceUtil::processFailed([BadRequestException::NO_ENTITY]));
  369.             }
  370.         } else {
  371.             return $this->json(ServiceUtil::processFailed([BadRequestException::WRONG_INPUT]));
  372.         }
  373.         return $this->json(ServiceUtil::processSuccessful());
  374.     }
  375.     /**
  376.      * @Route("/{_locale}/scolarite", requirements={"_locale": "en|fr"}, defaults={"_locale"="fr"}, name="user.scolarite")
  377.      */
  378.     public function scolarite(TranslatorInterface $translator)
  379.     {
  380.         if (!$this->getUser()) return $this->redirectToRoute('home');
  381.         $userId = $this->getUser()->getId();
  382.         $profile = $this->profileRepo->getProfileByUserId(['filter_id' => $userId]);
  383.         if($profile['status']['id'] != Status::STATUS_STUDENT_ENROLLED) return $this->redirectToRoute('home');
  384.         $siteName = $this->getParameter('site_name');
  385.         $this->addTitle($translator->trans(
  386.             'scolarite.title',
  387.             [
  388.                 '%siteName%' => $siteName
  389.             ]
  390.         ));
  391.         $this->setDescription($translator->trans(
  392.             'scolarite.desc',
  393.             [
  394.                 '%siteName%' => $siteName
  395.             ]
  396.         ));
  397.         return $this->render('scolarite/index.html.twig', ['profile' => $profile]);
  398.     }
  399.     /**
  400.      * @Route("/{_locale}/inscription", requirements={"_locale": "en|fr"}, defaults={"_locale"="fr"}, name="user.inscription")
  401.      */
  402.     public function inscription(TranslatorInterface $translator)
  403.     {
  404.         if (!$this->getUser()) return $this->redirectToRoute('home');
  405.         $userId = $this->getUser()->getId();
  406.         $profile = $this->profileRepo->getProfileByUserId(['filter_id' => $userId]);
  407.         if($profile['status']['id'] != Status::STATUS_STUDENT_ELIGIBLE) return $this->redirectToRoute('home');
  408.         $siteName = $this->getParameter('site_name');
  409.         $this->addTitle($translator->trans(
  410.             'inscription.title',
  411.             [
  412.                 '%siteName%' => $siteName
  413.             ]
  414.         ));
  415.         $this->setDescription($translator->trans(
  416.             'inscription.desc',
  417.             [
  418.                 '%siteName%' => $siteName
  419.             ]
  420.         ));
  421.         if($profile['selectedProgram']['level'] == 3){
  422.             $fileInscription = 'Contrat_d_inscription_MASTER_ESTIAM_2026-2027_Paris_new.docx';
  423.         } else{
  424.             $fileInscription = 'Contrat_d_inscription_BACHELOR_ESTIAM_2026-2027_Paris_new.docx';
  425.         }
  426.         return $this->render('inscription/index.html.twig', ['fileInscription' => $fileInscription]);
  427.     }
  428.     /**
  429.      * @Route("/profile/upload-file", name="profile.upload_file")
  430.      */
  431.     public function uploadFile(Request $request)
  432.     {
  433.         if (!$this->getUser())  return $this->json(ServiceUtil::processFailed(['message' => "Unauthorized"]));
  434.         $userId = $this->getUser()->getId();
  435.         $profile = $this->profileRepo->findOneBy(['user' => $userId]);
  436.         $result = $this->profileFileService->saveFiles($profile, $request);
  437.         $renderedMacro = $this->render('scolarite/wapper.macro.twig.html', ['item' => $result[0]]);
  438.         return $this->json(ServiceUtil::processSuccessful([$renderedMacro]));
  439.     }
  440.     /**
  441.      * @Route("/profile/remove-file", name="profile.remove_file")
  442.      */
  443.     public function removeFile(Request $request, TranslatorInterface $translator)
  444.     {
  445.         if (!$this->getUser())  return $this->json(ServiceUtil::processFailed(['message' => "Unauthorized"]));
  446.         $profileFile = $this->profileFileService->get($request->request->get('id'));
  447.         $this->profileFileService->removeProfileFilesByProfileFilesId($profileFile);
  448.         return $this->json(ServiceUtil::processSuccessful());
  449.     }
  450.     /**
  451.      * @Route("/api/analyze-file", name="profile.analyze_file", methods={"POST"})
  452.      *
  453.      * Starts document analysis and returns quickly (dedup-cache hit, or a
  454.      * pending token) instead of blocking on the full OpenAI call, which can
  455.      * take longer than the server's request timeout. The actual analysis
  456.      * runs after the response is flushed to the client (see
  457.      * fastcgi_finish_request below); the frontend polls analyzeFileStatus()
  458.      * with the returned token until it's done.
  459.      */
  460.     public function analyzeFile(Request $request, ProfileFileService $profileFileService)
  461.     {
  462.         $file = $request->files->get('file');
  463.         if (!$file) {
  464.             return $this->json(ServiceUtil::processFailed(['message' => "No file uploaded"]));
  465.         }
  466.         try {
  467.             $result = $profileFileService->startAnalyzeFile($file);
  468.         } catch (\Exception $e) {
  469.             return $this->json(ServiceUtil::processFailed(['message' => "Error analyzing file: " . $e->getMessage()]));
  470.         }
  471.         if ($result['cached']) {
  472.             return $this->json(ServiceUtil::processSuccessful([$result['data']]));
  473.         }
  474.         $response = $this->json(ServiceUtil::processSuccessful([
  475.             ['status' => 'pending', 'token' => $result['token']]
  476.         ]));
  477.         $response->send();
  478.         if (function_exists('fastcgi_finish_request')) {
  479.             fastcgi_finish_request();
  480.         }
  481.         $profileFileService->runAnalysis($result['mediaId']);
  482.         return $response;
  483.     }
  484.     /**
  485.      * @Route("/api/analyze-file/status/{token}", name="profile.analyze_file_status", methods={"GET"}, requirements={"token"=".+"})
  486.      */
  487.     public function analyzeFileStatus(string $token, ProfileFileService $profileFileService)
  488.     {
  489.         try {
  490.             $status = $profileFileService->getAnalysisStatus($token);
  491.             return $this->json(ServiceUtil::processSuccessful([$status]));
  492.         } catch (\Exception $e) {
  493.             return $this->json(ServiceUtil::processFailed(['message' => $e->getMessage()]));
  494.         }
  495.     }
  496. }