src/Controller/ClientController.php line 446

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Service\AssociatedMailUserService;
  4. use App\Entity\SignedContract;
  5. use App\Entity\User;
  6. use App\Entity\CompanyData;
  7. use App\Enum\Role;
  8. use App\Enum\TypeSignedContract;
  9. use App\Event\ClientUpdatedEvent;
  10. use App\Form\ClientProfilType;
  11. use App\Form\ClientType;
  12. use App\Repository\JobRepository;
  13. use App\Service\ConfidentialityService;
  14. use App\Service\ContractService;
  15. use App\Service\CreditService;
  16. use App\Service\PdfService;
  17. use  App\Enum\Note;
  18. use App\Service\UtilsService;
  19. use Doctrine\ORM\EntityManagerInterface;
  20. use App\Enum\TypePack;
  21. use PHPUnit\Util\Json;
  22. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  23. use Symfony\Component\HttpFoundation\JsonResponse;
  24. use App\Repository\UserRepository;
  25. use App\Service\UserService;
  26. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  27. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  28. use Symfony\Component\HttpFoundation\Request;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\Routing\Annotation\Route;
  31. use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
  32. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  33. use Symfony\Component\Serializer\SerializerInterface;
  34. use GuzzleHttp\Client;
  35. use App\Event\ClientDeleteWpEvent;
  36. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  37. use App\Entity\Company;
  38. use App\Entity\CreditHistory;
  39. use App\Service\FrontAPIService;
  40. use App\Repository\CompanyRepository;
  41. use App\Repository\CampaignRepository;
  42. use App\Service\DynamicHostService;
  43. use Twig\Environment;
  44. use App\Form\NoteUserType;
  45. use App\Entity\NoteUser;
  46. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  47. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  48. use Symfony\Component\HttpFoundation\StreamedResponse;
  49. class ClientController extends AbstractController
  50. {
  51.      public function __construct(
  52.         private FrontAPIService $frontAPIService,
  53.         private DynamicHostService $dynamicHostService
  54.         private EntityManagerInterface $entityManager,
  55.     ){}
  56.     /**
  57.      * Displays all client deleted
  58.      * Only admin views this interface
  59.      * @param UserRepository $userRepository
  60.      * @return Response
  61.      */
  62.     #[Route('/admin/client/export/{type}'name'client_export'methods: ['GET'])]
  63.     public function clientExport(string $typeUserRepository $userRepositoryRequest $request){
  64.         
  65.         $users$userRepository->findUserBytype($type);
  66.         $spreadsheet = new  Spreadsheet();
  67.         // Get active sheet - it is also possible to retrieve a specific sheet
  68.         $sheet $spreadsheet->getActiveSheet();
  69.         
  70.         $title "Liste des clients";
  71.         // Set cell name and merge cells
  72.         $sheet->setCellValue('A1'$title)->mergeCells('A1:D1');
  73.         $sheet->setCellValue('A2''total')->mergeCells('A1:D1');
  74.         $sheet->setCellValue('B2'sizeof($users));
  75.     
  76.         // Set column names
  77.         $columnNames = ['NOM''PRENOM''TELEPHONE','EMAIL''STATUT','ENTREPRISE','GENRE','DATE D\'INSCRIPTION','NEWSLETTER'];
  78.         $columnLetter 'A';
  79.         foreach ($columnNames as $columnName) {
  80.             // Allow to access AA column if needed and more
  81.             
  82.             $sheet->setCellValue($columnLetter.'3'$columnName);
  83.             ++$columnLetter;
  84.         }
  85.     
  86.         // Add data for each column
  87.         
  88.         $columnValues $this->formatUserToExportCsv($users) ;
  89.     
  90.         $i 4// Beginning row for active sheet
  91.         foreach ($columnValues as $columnValue) {
  92.             $columnLetter 'A';
  93.             foreach ($columnValue as $value) {
  94.            
  95.                 $sheet->setCellValue($columnLetter.$i$value);
  96.                 ++$columnLetter;
  97.             }
  98.             $i++;
  99.         }
  100.     
  101.         $contentType 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
  102.         $writer = new Xlsx($spreadsheet) ;
  103.                 $date date('ymdhis');
  104.                 $filename "export_$type$date.xlsx";
  105.                 $response = new StreamedResponse();
  106.                 $response->headers->set('Content-Type'$contentType);
  107.                 $response->headers->set('Content-Disposition''attachment;filename="'.$filename.'"');
  108.                 $response->setPrivate();
  109.                 $response->headers->addCacheControlDirective('no-cache'true);
  110.                 $response->headers->addCacheControlDirective('must-revalidate'true);
  111.                 $response->setCallback(function() use ($writer) {
  112.                     $writer->save('php://output');
  113.                 });
  114.                 return $response;
  115.             // return $this->redirect($request->headers->get('referer'));
  116.    }
  117.    
  118.    private function formatUserToExportCsv(array $users):array
  119.    {    
  120.         $userFormated = [];
  121.         $newletter "";
  122.          foreach ($users as $user) {
  123.             $newletter 
  124.             $newletter.= $user->getFreqNotificationEverytime() != null && in_array(5$user->getFreqNotificationEverytime())  ? "Tout le temps, " "";
  125.             $newletter.= $user->getFreqNotificationPerDay() != null && in_array(5$user->getFreqNotificationPerDay())  ? "Une fois par jour, " "";
  126.             $newletter.= $user->getFreqNotificationPerWeek() != null &&  in_array(5$user->getFreqNotificationPerWeek())  ? "Une fois par semaine, " "";
  127.             $newletter.= $user->getFreqNotificationPerMonth() != null && in_array(5$user->getFreqNotificationPerMonth())  ? "Une fois par mois " "";
  128.             $userFormated = [...$userFormated,[
  129.                 "lastname" => $user->getLastname(),
  130.                 "firstname" => $user->getFirstname(),
  131.                 "cellPhone" => $user->getCellPhone() != null $user->getCellPhone(): "-" ,
  132.                 "email" => $user->getEmail()  != null $user->getEmail(): "-" ,
  133.                 "enabled" => $user->isEnabled() ? "actif" "inactif",
  134.                 "entreprise"=> $user->getCompany() != null $user->getCompany()->getName() : "-" ,
  135.                 "gender" => "Monsieur",
  136.                 "created_at" =>$user->getCreatedAt() != null ?  $user->getCreatedAt()->format('Y-m-d H:i:s') : '-',
  137.                 "newsletter"=> $newletter
  138.             ]] ;
  139.             $newletter "";
  140.          }
  141.         return $userFormated;
  142.    }
  143.     #[Route('/admin/clients/deleted'name'client_deleted'methods: ['GET'])]
  144.     #[Route('/admin/gestionnaires/deleted'name'client_gestionnaires_deleted'methods: ['GET'])]
  145.     public function deleted(UserRepository $userRepository,DynamicHostService $dynamicHostService,Request $request): Response
  146.     {
  147.         if ( $request->get('_route') === 'client_gestionnaires_deleted' && !in_array(Role::ROLE_ADMIN_AGENCY->value,$this->getUser()->getRoles())) {
  148.             throw new \NotFoundHttpException('La page que vous demandez est introuvable.');
  149.         }
  150.         $list $userRepository->findByDeleted(1);
  151.         $company $dynamicHostService->getCompany();
  152.         if (null !== $company ) {
  153.             $list $userRepository->getClientDeletedCompany($company);
  154.         }
  155.         
  156.         return $this->render('client/deleted.html.twig', [
  157.             'clients' => $list
  158.         ]);
  159.     }
  160.     #[Route('/admin/client/reactivated/{id}'name'client_toggle_availabilty_status_deleted')]
  161.     public function toggleAvailabilityStatusDeleted(User $userEntityManagerInterface $entityManager): Response
  162.     {
  163.         $user->setDeleted(0);
  164.         $entityManager->flush();
  165.         $this->addFlash(
  166.             type'success',
  167.             message'Le client '.$user.' a bien été réactivé'
  168.         );
  169.         return $this->redirectToRoute('client_deleted');
  170.     }
  171.     #[Route('/admin/client/activate/{id}/{company_id}'name'client_activate')]
  172.     public function clientActivation(string $id,string $company_id,UserRepository $userRepositoryEntityManagerInterface $entityManager,Request $request): Response
  173.     {   
  174.         $agency = !is_null($request->query->get('agency')) ? true false;
  175.         $user $userRepository->findOneBy(['id'=>$id]);
  176.         $user->setEnabled(true);
  177.         $entityManager->flush();
  178.         $this->addFlash(
  179.             type'success',
  180.             message'Le client '.$user.' a bien été activé'
  181.         );
  182.         if ($agency) {
  183.            return $this->redirectToRoute('agency_edit',['id'=>$company_id]);
  184.         }
  185.         return $this->redirectToRoute('company_edit',['id'=>$company_id]);
  186.     }
  187.     /**
  188.      * @param UserRepository $userRepository
  189.      * @return Response
  190.      */
  191.     #[Route('/admin/clients'name'client_index'methods: ['GET'])]
  192.     #[Route('/admin/gestionnaires'name'client_gestionnaire_index'methods: ['GET'])]
  193.     public function index(UserRepository $userRepository,Request $request,DynamicHostService $dynamicHostService): Response
  194.     {
  195.         
  196.         
  197.         
  198.         $role Role::ROLE_CLIENT->value;
  199.         $observer Role::ROLE_OBSERVER->value;
  200.         $validator Role::ROLE_VALIDATOR->value;
  201.         $roleClientAdmin Role::ROLE_CLIENT_ADMIN->value;
  202.         $author Role::ROLE_AUTHOR->value;
  203.         $editor Role::ROLE_EDITOR->value;
  204.         //for adminAgency only
  205.         if (in_array(Role::ROLE_ADMIN_AGENCY->value,$this->getUser()->getRoles())) {
  206.             $company $this->getUser()->getCompany();
  207.             $return = [
  208.                 'clients' => $userRepository->findByRoleClientsByCompany('ROLE_SUBCONTRACTOR','ROLE_BOT','ROLE_MANAGER',$company),
  209.             ]; 
  210.             if ($request->get('_route') === 'client_gestionnaire_index') {
  211.                 $return = [
  212.                     'clients' => $userRepository->findGestionnaireByCompany('ROLE_MANAGER',$company),
  213.                 ]; 
  214.             }
  215.         }
  216.         //for admin only
  217.         if (in_array(Role::ROLE_ADMIN->value,$this->getUser()->getRoles()) or (in_array(Role::ROLE_MANAGER->value,$this->getUser()->getRoles()) and ($this->getUser()?->getCompany()?->isTypeCompany() === false) or $this->getUser()?->getCompany()?->isTypeCompany() == null) ) {
  218.             
  219.             $return = [
  220.                 'clients' => $userRepository->findByRoleClients($role$observer$roleClientAdmin,$validator,$author$editor ),
  221.             ];
  222.             if ($request->get('_route') === 'client_gestionnaire_index') {
  223.                 $return = [
  224.                     'clients' => $userRepository->findGestionnaireMyFlow('ROLE_MANAGER'),
  225.                 ]; 
  226.             }
  227.         }else if ((in_array(Role::ROLE_MANAGER->value,$this->getUser()->getRoles()))) {
  228.             $return = [
  229.                 'clients' => $userRepository->findByRoleClients($role$observer$roleClientAdmin,$validator,$author$editor ),
  230.             ];
  231.         }
  232.         $template $request->get('_route') === 'client_gestionnaire_index' "client/index_agency.html.twig" "client/index.html.twig";
  233.         return $this->render($template$return);
  234.     }
  235.     /**
  236.      * @param User|null $user
  237.      * @param Request $request
  238.      * @param UserService $userService
  239.      * @param UserPasswordHasherInterface $hasher
  240.      * @return Response
  241.      */
  242.     #[Route('/admin/client/ajouter'name'client_new'methods: ['GET','POST'])]
  243.     #[Route('/admin/gestionnaires/ajouter'name'client_gestionaires_new'methods: ['GET','POST'])]
  244.     #[Route('/admin/client/{id}'name'client_edit'methods: ['GET','POST'])]
  245.     #[Route('/admin/gestionnaires/{id}'name'client_gestionaires_edit'methods: ['GET','POST'])]
  246.     public function handleClient(User $user nullRequest $requestUserService $userServiceUserPasswordHasherInterface $hasherEventDispatcherInterface $dispatcher,DynamicHostService $dynamicHostService,UserRepository $userRepository): Response
  247.     {   
  248.         if (null !== $user and in_array('ROLE_MANAGER',  $user->getRoles()) and $request->get('_route') === 'client_edit') {
  249.             return $this->redirectToRoute('client_gestionaires_edit', ['id' => $user->getId()], Response::HTTP_SEE_OTHER);
  250.         }
  251.         $typeAction ='edit';
  252.         $isadminAgency false;
  253.         $isManager false;
  254.         if (in_array("ROLE_ADMIN_AGENCY"$this->getUser()->getRoles())) {
  255.               
  256.                  $isadminAgency true;
  257.             }
  258.         if (in_array("ROLE_MANAGER"$this->getUser()->getRoles())) {
  259.                  $isManager true;
  260.             }
  261.         if ($user === null){
  262.             $typeAction =  'new';
  263.             $user = new User();
  264.             if (in_array("ROLE_ADMIN_AGENCY"$this->getUser()->getRoles())) {
  265.                  $user->setCompany($this->getUser()->getCompany());
  266.                  $isadminAgency true;
  267.             }
  268.             
  269.            
  270.         }
  271.         $isCreationOfGestionary false;
  272.         if ($request->get('_route') === 'client_gestionaires_new' or $request->get('_route') === 'client_gestionaires_edit') {
  273.              $isCreationOfGestionary =  true;
  274.         }
  275.       
  276.         $form $this->createForm(ClientType::class, $user,[
  277.             'isadminAgency'=>$isadminAgency,
  278.             'isManager'=>$isManager,
  279.             'isCreationOfGestionary'=>$isCreationOfGestionary,
  280.             'url'=>$request->get('_route'),
  281.             'mail_alias_default' => implode(','$user->getMailAlias() ?? [])
  282.         ]);
  283.         $form->handleRequest($request);
  284.         $company $dynamicHostService->getCompany();
  285.         if ($form->isSubmitted() && $form->isValid()) {
  286.             $entityManager $this->getDoctrine()->getManager();
  287.             $data  $form->getData();  
  288.             $dataInMapped $request->request->all();
  289.             $note $dataInMapped['note_user']['content'] ?? null;
  290.             $notePrivate $dataInMapped['note_user_private']['content'] ?? null;
  291.             
  292.             if (!is_null($note) and  !empty($note)) {
  293.                 $newNote = new NoteUser();
  294.                 $newNote->setContent($note);
  295.                 $newNote->setCreatedAt(new \DateTime());
  296.                 $newNote->setType(Note::NOTE_PUBLIC->value);
  297.                 $newNote->setUserToCommented($this->getUser());
  298.                 $entityManager->persist($newNote);
  299.                 $entityManager->flush();
  300.                 $data->addNoteUser($newNote);
  301.             }
  302.             if (!is_null($notePrivate) and !empty($notePrivate) ) {
  303.                 $newNote = new NoteUser();
  304.                 $newNote->setContent($notePrivate);
  305.                 $newNote->setCreatedAt(new \DateTime());
  306.                 $newNote->setUserToCommented($this->getUser());
  307.                 $newNote->setType(Note::NOTE_PRIVATE->value);
  308.                 $entityManager->persist($newNote);
  309.                 $entityManager->flush();
  310.                 $data->addNoteUser($newNote);
  311.             }
  312.             $emailsString $form->get('mailAliasOtherForm')->getData();  // Champ non mappé
  313.             if (!is_null($emailsString) and !empty($emailsString)) {
  314.                 $emailsArray array_map('trim'explode(','$emailsString));
  315.                 if (is_array($emailsArray) and !empty($emailsString)) {
  316.                     $data->setMailAlias($emailsArray);
  317.                 }
  318.             }
  319.            
  320.             $userExistInSameDomaine  $userRepository->getUniqUserByCompanyByEmailForSubClientManager($user->getEmail(),$company);
  321.             if (!is_null($userExistInSameDomaine) and ($request->get('_route') === 'client_new' or $request->get('_route') === 'client_gestionaires_new')){
  322.                 $this->addFlash('error'"L'utilisateur que vous tentez de créer existe déjà.");
  323.                 return $this->redirectToRoute('sub_contractor_new', [], Response::HTTP_SEE_OTHER);
  324.             }
  325.             
  326.             if ($request->get('_route') === 'client_new' or $request->get('_route') === 'client_gestionaires_new') {
  327.                 //si nouveau client creez un adresse MyFlow
  328.                 
  329.                 //end client
  330.                 if ($form->getData()->getRoles()[0] == 'ROLE_CLIENT_ADMIN'){
  331.                     $role Role::ROLE_CLIENT_ADMIN->value;
  332.                 }
  333.                 elseif($form->getData()->getRoles()[0] == 'ROLE_CLIENT'){
  334.                     $role Role::ROLE_CLIENT->value;
  335.                 }
  336.                 else{
  337.                     $role Role::ROLE_AUTHOR->value;
  338.                     //changement de Role pour manager et administrateur pour agence
  339.                     if ($form->getData()->getRoles()[0] == 'ROLE_MANAGER') {
  340.                         $role Role::ROLE_MANAGER->value;
  341.                     }
  342.                     if ($form->getData()->getRoles()[0] == 'ROLE_ADMIN_AGENCY') {
  343.                          $role Role::ROLE_ADMIN_AGENCY->value;
  344.                     }
  345.                 }
  346.                 $password $userService->generatePassword();
  347.                 $hashedPassword $hasher->hashPassword($user$password);
  348.                 $user->setRoles([$role])->setIsNewClient(false);
  349.                 if(empty($form->getData()->getPassword())) {
  350.                     $user->setPassword($hashedPassword)
  351.                          ->setEnabled(false);
  352.                 }
  353.                 $entityManager->persist($user);
  354.                 $msg $request->get('_route') === 'client_new' 'Le client a bien été ajouté' 'Le gestionnaire a bien été ajouté';
  355.                 $this->addFlash('success'$msg);
  356.                 $notification true;
  357.                  //si pas de notification par chat tout les jours alors mettre par défaut.
  358.                 $freqNotificationEverytime $form->getData()->getFreqNotificationEverytime();
  359.                 if(!in_array("0"$freqNotificationEverytime)){
  360.                     $freqNotificationEverytime[] = 0;
  361.                     $form->getData()->setFreqNotificationEverytime($freqNotificationEverytime);
  362.                 }
  363.            
  364.             } else {
  365.                 $msg $request->get('_route') === 'client_edit' 'Le client a bien été modifié' 'Le gestionnaire a bien été modifié'
  366.                     $this->addFlash('success'$msg);
  367.               
  368.                 $notification false;
  369.             }
  370.             $file $form->get('picture')->getData();
  371.             if ($file!=null) {
  372.                // $destination = $this->getParameter('file_profil_directory');
  373.                // if(!empty(trim($user->getPictureName())) && !is_null($user->getPictureName()) && file_exists("$destination/{$user->getPictureName()}") ){
  374.                //          unlink("$destination/{$user->getPictureName()}");
  375.                //  }              
  376.                 $user->setPicture($form->get('picture')->getData());
  377.             }
  378.             $entityManager->flush();
  379.             $user->setPicture(null);
  380.             $event = new ClientUpdatedEvent($user$notification);
  381.             $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  382.             if($this->isGranted("ROLE_CLIENT_ADMIN") and $typeAction == "edit"){
  383.                 if (!is_null($user->getCompany())) {
  384.                     return $this->redirectToRoute('company_edit', ['id' => $user->getCompany()->getId()], Response::HTTP_SEE_OTHER);
  385.                 }else{
  386.                     return $this->redirectToRoute('mission_index', [], Response::HTTP_SEE_OTHER);
  387.                 }
  388.                
  389.             }
  390.            
  391.             return $this->redirectToRoute('client_index', [], Response::HTTP_SEE_OTHER);
  392.             
  393.         }
  394.         return $this->renderForm('client/handle.html.twig', [
  395.             'form' => $form,
  396.             'user' => $user,
  397.             'type_action' => $typeAction,
  398.             'isCreationOfGestionary' => $isCreationOfGestionary,
  399.         ]);
  400.     }
  401.     /**
  402.      * @param Request $request
  403.      * @param UserRepository $userRepository
  404.      * @return JsonResponse
  405.      */
  406.     #[Route('/api/clients/search'name'api_clients_search')]
  407.     public function apiSearch(Request $requestUserRepository $userRepository,CompanyRepository $companyRepository)
  408.     {
  409.         $isAdmin false;
  410.         $user $request->query->get('userId') != null $userRepository->findOneBy(['id'=>$request->query->get('userId')]) :  $this->getUser(); 
  411.       
  412.         //determine if root or client admin
  413.         if (in_array("ROLE_ADMIN",  $user->getRoles())) {
  414.            $isAdmin true;
  415.         }
  416.         $query $request->query->get('query');
  417.         $query trim($query);
  418.         if ($request->query->get('client') == 2) {
  419.            
  420.             return new JsonResponse([
  421.                 'clients' => $userRepository->apiQuerySearchProject($query,false,$isAdmin),
  422.             ]); 
  423.         }else{
  424.             $companyClient null;
  425.             if ($request->query->get('client') == 1){
  426.                 $role 'ROLE_CLIENT';
  427.                 if ($request->query->get('companyId')) {
  428.                     $companyClient $companyRepository->find($request->query->get('companyId'));
  429.                 }
  430.             }else{
  431.                 $role 'ROLE_SUBCONTRACTOR';
  432.             }
  433.         }
  434.         //dd( $userRepository->apiQuerySearch($query, $role,false,$isAdmin,$companyClient));
  435.         return new JsonResponse([
  436.             'clients' => $userRepository->apiQuerySearch($query$role,false,$isAdmin,$companyClient),
  437.         ]);
  438.     }
  439.    #[Route('/api/clients/cgv/cgu'name'api_clients_cgv_cgu'methods: ['GET'])]
  440.     public function CguClient(JobRepository $jobRepository,UtilsService $utilsServiceSerializerInterface $serializer,DynamicHostService $dynamicHostService,ParameterBagInterface $parameterBagInterface,  ContractService $contractService,Environment $twig,PdfService $pdfService): JsonResponse
  441.     {
  442.         $userData = [
  443.             'cgu'=> $contractService->getCGU(null),
  444.             'cguClient'=> $contractService->getCGU(nullnull'client'),
  445.             'cgv'=>$contractService->getCGV(null)
  446.         ];
  447.          return new JsonResponse($userData,
  448.             Response::HTTP_OK,
  449.             [],
  450.         );
  451.     }
  452.      #[Route('/api/clients/creation'name'api_clients_creation'methods: ['GET'])]
  453.     public function createClients(JobRepository $jobRepository,UtilsService $utilsServiceSerializerInterface $serializer,DynamicHostService $dynamicHostService,ParameterBagInterface $parameterBagInterface,  ContractService $contractService,Environment $twig,PdfService $pdfService,EntityManagerInterface $entityManager): JsonResponse
  454.     {
  455.         $user = new User();
  456.         $user->setUserData(null);
  457.         $user->setEmail(uniqid());
  458.         $user->setRoles(['ROLE_SUBCONTRACTOR']);
  459.         $user->setDeleted(true);
  460.         $user->setEnabled(false);
  461.         $entityManager->persist($user);
  462.         $entityManager->flush();
  463.         return new JsonResponse([
  464.             'id' => $user->getId(),
  465.         ]);
  466.     }
  467.      #[Route('/api/clients/creation/role/client'name'api_clients_creation_role_client'methods: ['GET'])]
  468.     public function createClientsWithRoles(JobRepository $jobRepository,UtilsService $utilsServiceSerializerInterface $serializer,DynamicHostService $dynamicHostService,ParameterBagInterface $parameterBagInterface,  ContractService $contractService,Environment $twig,PdfService $pdfService,EntityManagerInterface $entityManager): JsonResponse
  469.     {
  470.         $user = new User();
  471.         $user->setUserData(null);
  472.         $user->setEmail(uniqid());
  473.         $user->setDeleted(true);
  474.         $user->setRoles(['ROLE_CLIENT']);
  475.         $user->setEnabled(false);
  476.         $entityManager->persist($user);
  477.         $entityManager->flush();
  478.         return new JsonResponse([
  479.             'id' => $user->getId(),
  480.         ]);
  481.     }
  482.     #[Route('/api/clients/{id}'name'api_clients'methods: ['GET'])]
  483.     public function apiClients(User $user,JobRepository $jobRepository,UtilsService $utilsServiceSerializerInterface $serializer,DynamicHostService $dynamicHostService,ParameterBagInterface $parameterBagInterface,  ContractService $contractService,Environment $twig,PdfService $pdfService): JsonResponse
  484.     {
  485.         if ($user->isEnabled()) {
  486.             return new JsonResponse([
  487.                 'alreadyEnabled' => true,
  488.             ]);
  489.         }
  490.        
  491.         $company $dynamicHostService->getCompany($user) ;
  492.         $backUrl =  $company instanceof Company $company->getDomaineName() : $parameterBagInterface->get('back_website_url'); 
  493.         $userData = [
  494.             'lastname'=> $user->getLastname(),
  495.             'firstname'=>$user->getFirstname(),
  496.             'email'=>$user->getEmail(),
  497.             'cellphone'=>$user->getCellPhone(),
  498.             'billingMethod'=>$user->getBillingMethod(),
  499.             'gender'=>$user->getGender(),
  500.             'dailyRate'=>$user->getDailyRate(),
  501.             'userData'=>[
  502.                'stateCompany'=> $user->getUserData()?->getStateCompany(),
  503.                'status'=> $user->getUserData()?->getStatus(),
  504.                'country'=> $user->getUserData()?->getCountry(),
  505.                'siren'=> $user->getUserData()?->getSiren(),
  506.                'intracommunityTva'=> $user->getUserData()?->getIntracommunityTva(),
  507.                'address'=> $user->getUserData()?->getAddress(),
  508.                'rIB'=> $user->getUserData()?->getRIB(),
  509.                'accountOwner'=> $user->getUserData()?->getAccountOwner(),
  510.                'iBAN'=> $user->getUserData()?->getIBAN(),
  511.                'bicSwift'=> $user->getUserData()?->getBicSwift(),
  512.                'spokenLanguages'=> $user->getUserData()?->getSpokenLanguages(),
  513.                'companyName'=> $user->getUserData()?->getCompanyName(),
  514.                'tva'=> $user->getUserData()?->getTva(),
  515.             ],
  516.             'salary'=>$user->getSalary(),
  517.             'cgu'=> $contractService->getCGU($user),
  518.             'cguClient'=> $contractService->getCGU($usernull'client'),
  519.             'cgv'=>$contractService->getCGV($user),
  520.             'jobs'=> $user->getJobs()!=null array_map(function($job){
  521.                     return $job->getId();
  522.                 },($user->getJobs())->toArray()) : [],
  523.             'jobsAgency'=> $utilsService->getIds($jobRepository->findByAgency($company)),
  524.             'link'=>[
  525.                 'cguSubcontractor'=>  $company  instanceof Company ?  "$backUrl/condition-generale/{$company->getId()}-cgu-sous-traitant" $contractService->getLinkMyFlowCGUSubcontractor(), 
  526.                 'cguClient'=> $company  instanceof Company ?  "$backUrl/condition-generale/{$company->getId()}-cgu-client" $contractService->getLinkMyFlowCGUClient(), 
  527.                 'cgv'=> $company  instanceof Company ?  "$backUrl/condition-generale/{$company->getId()}-cgv" $contractService->getLinkMyFlowCGV(), 
  528.             ],
  529.             'agency'=>[
  530.                 'name'=> $company instanceof Company $company->getName() : '',
  531.                 'id'=> $company instanceof Company $company->getId() : ''
  532.             ],
  533.             'contractSubClient'=>$twig->render(
  534.                 $pdfService->getLinkTwigToGenerateContratBetweenAgenceAndSubcontractor($user),
  535.                 $pdfService->getParamsToGenerateContratBetweenAgenceAndSubcontractor($user)
  536.             ),
  537.        ];
  538.         return new JsonResponse($userData,
  539.             Response::HTTP_OK,
  540.             [],
  541.         );
  542.     }
  543.     #[Route('/api/clients/{id}'name'api_edit_client'methods: ['POST'])]
  544.     public function apiEditClient(User $userConfidentialityService $confidentialityServiceRequest $requestUserPasswordHasherInterface $passwordHasherEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher): JsonResponse
  545.     {   
  546.         
  547.         $user->setFirstname($request->request->get('firstname'));
  548.         $user->setLastname($request->request->get('lastname'));
  549.         $user->setCellPhone($request->request->get('cellPhone'));
  550.         $user->setEnabled(true);
  551.         $user->setGender($request->request->get('gender'));
  552.         $hashedPassword $passwordHasher->hashPassword($user$request->request->get('password'));
  553.         $user->setPassword($hashedPassword);
  554.        
  555.         $entityManager->persist($user);
  556.         $entityManager->flush();
  557.         $event = new ClientUpdatedEvent($userfalse$request->request->get('password'), true);
  558.         $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  559.         $confidentialityService->addSignedContractForClient($usertruefalsetrue);
  560.         return new JsonResponse(['result' => 'success']);
  561.     }
  562.     #[Route('/api/clients/external/{id}'name'api_edit_external_client'methods: ['POST'])]
  563.     public function apiEditExternalClient(User $userRequest $requestUserPasswordHasherInterface $passwordHasherEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher,ConfidentialityService $confidentialityService): JsonResponse
  564.     {
  565.         
  566.         
  567.         $user->setFirstname($request->request->get('firstname'));
  568.         $user->setLastname($request->request->get('lastname'));
  569.         $user->setEmail($request->request->get('email'));
  570.         $user->setCellPhone($request->request->get('cellPhone'));
  571.         $user->setEnabled(true);
  572.         $user->setGender($request->request->get('gender'));
  573.         $user->setDeleted(false);
  574.         $hashedPassword $passwordHasher->hashPassword($user$request->request->get('password'));
  575.         $user->setPassword($hashedPassword);
  576.         $entityManager->flush();
  577.         $event = new ClientUpdatedEvent($userfalse$request->request->get('password'), true);
  578.         $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  579.          $confidentialityService->addSignedContractForClient($user,true,false,true);
  580.         return new JsonResponse(['result' => 'success']);
  581.     }
  582.     #[Route('/api/clients/external/company/{id}'name'api_edit_external_company_client'methods: ['POST'])]
  583.     public function apiEditExternalCompanyClient(User $userRequest $request,CreditService $creditServiceUserPasswordHasherInterface $passwordHasherEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher,CompanyRepository $companyRepository,ConfidentialityService $confidentialityService): JsonResponse
  584.     {
  585.               
  586.         //infos company
  587.         $adresse =  $request->request->get('adresse');
  588.         $country =  $request->request->get('pays');
  589.         $rcs =  $request->request->get('rcs');
  590.         $state =  $request->request->get('state');
  591.         //end infos company
  592.         
  593.         $logo $request->request->get('logo');
  594.         $companyExist true;
  595.         $company $companyRepository->findOneByName($request->request->get('company_name'));
  596.         if (is_null($company)) {
  597.             $companyExist false;
  598.             $company = new Company();
  599.         }
  600.         $company->setName($request->request->get('company_name'));
  601.         $company->setCreatedAt(new \DateTime());
  602.         $company->setSiren($request->request->get('siren'));
  603.         $company->setCostOfDiscountedCredit(0);
  604.         $company->setEnabled(true);
  605.         $company->setContract(3);
  606.         $company->setCustomerDiscount(0);
  607.         
  608.         
  609.         if (!is_null($request->request->get('logo')) and !$companyExist) {
  610.             //upload image company 
  611.             $frontWebSiteUrlLogo $this->getParameter('front_website_url_upload_logo_company').$logo;
  612.             $dirLogoCompany $this->getParameter('dir_logo_company_kernel').$logo;
  613.             if($this->transfertLogo($frontWebSiteUrlLogo,$dirLogoCompany))
  614.                 $company->setLogoName($logo);
  615.         }
  616.         if ($companyExist == false) {
  617.             $entityManager->persist($company);
  618.             $entityManager->flush();
  619.             $creditHistory =  new CreditHistory();
  620.             $creditHistory->setCompany($company)
  621.                           ->setName("Facturation individuelle")
  622.                           ->setTypePack(TypePack::CASH->value)
  623.                           ->setIdentifier($creditService->getNewReference())
  624.                           ->setOrderedBy($user);
  625.             $entityManager->persist($creditHistory);
  626.             $entityManager->flush();
  627.             $this->sharedResourceCategoryService->setDefaultSharedResourceCategory($company);
  628.         }
  629.         
  630.         
  631.         
  632.         $user->setCompany($company) ;
  633.         $entityManager->persist($user);
  634.         $entityManager->flush();
  635.         $response $this->frontAPIService->pushCompanyToFront($company);
  636.         if (null !== $response && null === $company->getFrontId()) {
  637.             $company->setFrontId($response['id']);
  638.             $entityManager->persist($company);
  639.             $entityManager->flush();
  640.         }
  641.         //add data company
  642.         
  643.         if ($companyExist == false) {
  644.             
  645.             $companyData = new CompanyData();
  646.             $companyData->setCountry($country)
  647.                         ->setAddress($adresse)
  648.                         ->setRcs($rcs)
  649.                         ->setState($state);
  650.             $entityManager->persist($companyData);
  651.             $company->setCompanyData($companyData);
  652.             $entityManager->persist($company);
  653.             $entityManager->flush();
  654.             
  655.         }
  656.         //mise a jour de l'utilisateur sur wordpress
  657.         $this->frontAPIService->pushClientToFront($usernull);
  658.         //link to user
  659.         $confidentialityService->addSignedContractForClient($user,true,false,true);
  660.         return new JsonResponse(['result' => 'success']);
  661.     }
  662.     public function transfertLogo($logoDir,$dirDest){
  663.         $imageUrl $logoDir;
  664.         $ch curl_init();
  665.         curl_setopt($chCURLOPT_URL$imageUrl);
  666.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  667.         $response curl_exec($ch);
  668.         if (curl_errno($ch)) {
  669.             echo 'Erreur cURL : ' curl_error($ch);
  670.             return false;
  671.         } else {
  672.             $localFilePath $dirDest;
  673.             try{
  674.                 file_put_contents($localFilePath$response);
  675.             }catch(\Exception $e){
  676.                 return false;
  677.             }
  678.         }
  679.         curl_close($ch);
  680.         return true;
  681.     }
  682.     #[Route('/admin/client/{id}/{availabilty<enable|disable>}'name'client_toggle_availabilty')]
  683.     #[Route('/admin/client_gestionnaire/{id}/{availabilty<enable|disable>}'name'client_gestionnaire_toggle_availabilty')]
  684.     public function toggleAvailability(User $userEntityManagerInterface $entityManager,Request $request): Response
  685.     {
  686.         $user->setEnabled(!$user->isEnabled());
  687.         $entityManager->flush();
  688.         $this->addFlash(
  689.             type'success',
  690.             message'Le client '.$user.' a bien été '. ($user->isEnabled() ? 'activé' 'désactivé')
  691.         );
  692.         $route $request->get('_route') === 'client_toggle_availabilty' 'client_index''client_gestionnaire_index';
  693.         return $this->redirectToRoute($route);
  694.     }
  695.     
  696.     #[Route('/admin/client/{id}/invitation'name'client_send_another_invitation')]
  697.     public function sendAnotherInvitation(EventDispatcherInterface $dispatcherUser $user): Response
  698.     {
  699.         $event = new ClientUpdatedEvent($usertruenullfalsefalse);
  700.         $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  701.         $this->addFlash(
  702.             type'success',
  703.             message'L\'email d\'invitation a bien été envoyé'
  704.         );
  705.         return $this->redirectToRoute('client_index');
  706.     }
  707.     #[Route('/admin/client/{id}/supprimer'name'client_remove'methods: ['GET','POST'])]
  708.     #[Route('/admin/gestionnaires/{id}/supprimer'name'client_gestionnaire_remove'methods: ['GET','POST'])]
  709.     public function deleteClient(User $user,UserService $userServiceEntityManagerInterface $entityManager,EventDispatcherInterface $dispatcher,ParameterBagInterface $parameterBag,Request $request)
  710.     {
  711.         
  712.         $event = new ClientDeleteWpEvent($userService->delete($user), $parameterBag);
  713.         $dispatcher->dispatch($eventClientDeleteWpEvent::NAME);
  714.         $txt "client";
  715.         $route 'client_index';
  716.         if ( $request->get('_route') === 'client_gestionnaire_remove'){
  717.             $txt "gestionnaire";
  718.             $route "client_gestionnaire_index";
  719.         }
  720.         $this->addFlash(
  721.             'success',
  722.             "Le {$txt} a bien été supprimé"
  723.         );
  724.         return $this->redirect($request->headers->get('referer')) ?  $this->redirect($request->headers->get('referer')) : $this->redirectToRoute($route);
  725.     }
  726.     #[Route('/mon-profil-client'name'my_profil_client'methods: ['GET','POST'])]
  727.     public function Profil(Request $requestEntityManagerInterface $entityManagerUserPasswordHasherInterface $hasher,EventDispatcherInterface $dispatcher): Response
  728.     {
  729.         $user $this->getUser();
  730.         $form $this->createForm(ClientProfilType::class, $user,['isadmin'=>$this->isGranted(Role::ROLE_ADMIN->value)]);
  731.         $form->handleRequest($request);
  732.         if($form->isSubmitted() && $form->isValid()){
  733.             if (!empty($form->getData()->getPlainPassword())){
  734.                 $hashedPassword $hasher->hashPassword($user$form->getData()->getPlainPassword());
  735.                 $user->setPassword($hashedPassword);
  736.             }
  737.             $file $form->get('picture')->getData();
  738.             if ($file!=null) {
  739.                 $destination $this->getParameter('file_profil_directory');
  740.                 try {
  741.                     if(!empty(trim($user->getPictureName())) && !is_null($user->getPictureName())){
  742.                         unlink("$destination/{$user->getPictureName()}");
  743.                     }
  744.                 } catch (\Throwable $th) {
  745.                     
  746.                 }
  747.                 $originalFilename pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  748.                 $originalFilename str_replace(' ','-',$originalFilename);
  749.                 //$originalFilename = preg_replace('/[^A-Za-z0-9 ]/', '', $originalFilename);
  750.                 $originalFilename $this->replaceAllSpecialCharFromString($originalFilename);
  751.                 $newFilename $originalFilename .uniqid().'.' $file->guessExtension();  
  752.                 
  753.                 $file->move(
  754.                     $destination,
  755.                     $newFilename
  756.                 );
  757.   
  758.                 $user->setPictureName($newFilename);
  759.             }
  760.             $user->setPicture(null);
  761.             $entityManager->persist($user);
  762.             $entityManager->flush();
  763.             $event = new ClientUpdatedEvent($userfalse);
  764.             $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  765.            
  766.             if($request->request->get('remove-my-account')!=null){
  767.                 return $this->redirectToRoute('my_profil_client',[
  768.                     'confirm_account_deleted'=> true,
  769.                 ]);
  770.                 
  771.             }
  772.             $this->addFlash(
  773.                 'success',
  774.                 'Votre profil a bien été modifié'
  775.             );
  776.             return $this->redirectToRoute('my_profil_client');
  777.         } elseif ($form->isSubmitted()) {
  778.             $this->addFlash(
  779.                 'error',
  780.                 'Merci de corriger les erreurs',
  781.             );
  782.         }
  783.         return $this->renderForm('client/profil.html.twig', [
  784.             'form' => $form,
  785.         ]);
  786.     }
  787.     #[Route('/admin/client/{id}/renvoie-email-inscription'name'client_resend_registration_email'methods: ['GET','POST'])]
  788.     public function resendRegistrationEmail(Request $requestUser $userEventDispatcherInterface $dispatcher)
  789.     {
  790.         $event = new ClientUpdatedEvent($usertrue);
  791.         $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  792.         $this->addFlash(
  793.             type'success',
  794.             message'L\'email d\'inscription a bien été envoyé',
  795.         );
  796.         return $this->redirect($request->headers->get('referer'));
  797.     }
  798.     
  799.     #[Route('/my-subcontractor-interlocutors/{userId}'name'my_subcontractor_interlocutors'methods: ['GET'])]
  800.     public function showInterlocutors(string $userIdUserRepository $userRepositoryCampaignRepository $campaignRepository): Response
  801.     {   
  802.         $agency $this->dynamicHostService->getCompany($this->getUser()); 
  803.         $nbYearMax 3;
  804.         $user $userRepository->find($userId);
  805.         $campaigns $campaignRepository->findAllInterlocutors($user$nbYearMax);
  806.         
  807.         $userManagerAndAdminAgency $agency != null &&  $user!= null ?  $userRepository->getManagerAndAdminAgency($agency$user) : []; 
  808.         $allParticipantsMail = [];
  809.         $allParticipants = [];
  810.         foreach ($campaigns as $campaign) {
  811.             foreach ($campaign->getMissions() as $mission) {
  812.                 foreach ($mission->getParticipants() as $participant) {
  813.                     if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR) {
  814.                         if (!in_array($participant->getUser()->getEmail(), $allParticipantsMail)) {
  815.                             $allParticipantsMail[] = $participant->getUser()->getEmail();
  816.                             $allParticipants[] = $participant;
  817.                         }
  818.                     }
  819.                 }
  820.             }
  821.         }
  822.         return $this->renderForm('client/interlocutors.html.twig', [
  823.             'subcontractors'   => $allParticipants,
  824.             'user_manager_and_admin_agency' => $userManagerAndAdminAgency,
  825.             'is_agency'=> $agency == null false true
  826.         ]);
  827.     }
  828.     private function replaceAllSpecialCharFromString($values){
  829.         $string str_replace(
  830.             ['à''á''â''ã''ä''å''ç''è''é''ê''ë''ì''í''î''ï''ñ''ò''ó''ô''õ''ö''ø''ù''ú''û''ü''ý''ÿ'],
  831.             ['a''a''a''a''a''a''c''e''e''e''e''i''i''i''i''n''o''o''o''o''o''o''u''u''u''u''y''y'],
  832.             $values
  833.         );
  834.     
  835.         return preg_replace('/[^A-Za-z0-9\- ]/'''$string);
  836.     }
  837.     #[Route('/note-client-modified/{id}-{idUser}'name'note_client_modified'methods: ['GET','POST'])]
  838.     public function noteModification(NoteUser $note,$idUserRequest $request,EntityManagerInterface $entityManager): Response
  839.     
  840.         $content $request->request->get('info_mission_edit')['content'];
  841.         if (!is_null($content) and !empty($content)) {
  842.             $note->setContent($content);
  843.             $entityManager->persist($note);
  844.             $entityManager->flush();
  845.            
  846.         }
  847.         $this->addFlash(
  848.             type'success',
  849.             message'Modification effectuée'
  850.         );
  851.         return $this->redirectToRoute('client_edit',['id'=>$idUser]);
  852.     }
  853.     #[Route('/note-client-deleted/{id}-{idUser}'name'note_client_deleted'methods: ['GET','POST'])]
  854.     public function noteDeleted(NoteUser $note,$idUserRequest $request,EntityManagerInterface $entityManager): Response
  855.     
  856.         $entityManager->remove($note);
  857.         $entityManager->flush(); 
  858.         $this->addFlash(
  859.             type'success',
  860.             message'Suppression effectuée'
  861.         );
  862.         return $this->redirectToRoute('client_edit',['id'=>$idUser]);
  863.     }
  864. }