src/Controller/CossBundle/RecipientController.php line 124

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: grego
  5.  * Date: 30/09/2024
  6.  * Time: 12:34
  7.  */
  8. namespace App\Controller\CossBundle;
  9. use App\Entity\Badge;
  10. use App\Entity\Proof;
  11. use App\Entity\ProofMessage;
  12. use App\Entity\Recipient;
  13. use App\Entity\User;
  14. use App\Form\AddRecipientType;
  15. use App\Form\RecipientsProofFormType;
  16. use App\Manager\CossManager;
  17. use App\Manager\ImportExportManager;
  18. use App\Manager\MailerManager;
  19. use App\Repository\RecipientRepository;
  20. use DateTime;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  23. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  24. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  25. use Symfony\Component\Form\Extension\Core\Type\FileType;
  26. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  27. use Symfony\Component\Form\Extension\Core\Type\TextType;
  28. use Symfony\Component\HttpFoundation\JsonResponse;
  29. use Symfony\Component\HttpFoundation\Request;
  30. use Symfony\Component\HttpFoundation\Response;
  31. use Symfony\Component\HttpFoundation\StreamedResponse;
  32. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  33. use Symfony\Contracts\Translation\TranslatorInterface;
  34. use Symfony\Component\Routing\Annotation\Route;
  35. class RecipientController extends AbstractController
  36. {
  37.     /**
  38.      * @Route("/recipients", name="recipients_list")
  39.      */
  40.     public function listAction(Request $requestEntityManagerInterface $em){
  41.         $user $this->getUser();
  42.         $request->setLocale($user->getLocale());
  43.         $recipients $em->getRepository(Recipient::class)->getAllValidatedRecipients($user);
  44.         $users $em->getRepository(Recipient::class)->getAllValidatorUsers($user"all");
  45.         return $this->render('CossBundle/Recipient/list.html.twig', array(
  46.             'recipients' => $recipients,
  47.             'users' => $users
  48.         ));
  49.     }
  50.     /**
  51.      * @Route("/recipients/link/{appUser}/{id}", name="recipients_link_user")
  52.      */
  53.     public function linkRecipientAction(Request $requestEntityManagerInterface $emTranslatorInterface $translatorCossManager $cossManager$appUser$id){
  54.         $user $this->getUser();
  55.         $request->setLocale($user->getLocale());
  56.         $recipient $em->getRepository(Recipient::class)->find($id);
  57.         $appUser $em->getRepository(User::class)->find($appUser);
  58.         $access false;
  59.         if (in_array'ROLE_SUPER_ADMIN'$user->getRoles() )){
  60.             $access true;
  61.         } elseif ($appUser->getValidator() == $user){
  62.             $access true;
  63.         }
  64.         if(!$access){
  65.             $msg $translator->trans(
  66.                 "Vous n'avez pas accès cet utilisateur",
  67.                 array(), 'coss'
  68.             );
  69.             $this->addFlash("error"$msg);
  70.             return $this->redirectToRoute('recipients_list');
  71.         }
  72.         $existingRecipient $em->getRepository(Recipient::class)->findOneBy(array('user' => $recipient->getUser(), 'appUser' => $appUser ));
  73.         if($existingRecipient){
  74.             $msg $translator->trans(
  75.                 "Ce répondant est déjà rattaché à l'utilisateur sélectionné",
  76.                 array(), 'coss'
  77.             );
  78.             $this->addFlash("error"$msg);
  79.             return $this->redirectToRoute('recipients_list');
  80.         } else {
  81.             $newRecipient = new Recipient();
  82.             $newRecipient->setUser($recipient->getUser());
  83.             $newRecipient->setAppUser($appUser);
  84.             $newRecipient->setType($recipient->getType());
  85.             $newRecipient->setTitle($recipient->getTitle());
  86.             $newRecipient->setCompany($recipient->getCompany());
  87.             $newRecipient->setStatus(RecipientRepository::STATUS_VALIDATED);
  88.             $newRecipient->setValidatedAt(new DateTime());
  89.             $newRecipient->setSources(array('admin'));
  90.             $em->persist($newRecipient);
  91.             $em->flush();
  92.             // Check new badges after new validated recipient
  93.             $cossManager->sendMissingBadges($appUser);
  94.             $msg $translator->trans(
  95.                 "Le répondant %recipient% a été rattaché à %user%",
  96.                 array('%user%' => $appUser->getEmail(), '%recipient%' => $recipient->getUser()->getEmail()), 'coss'
  97.             );
  98.             $this->addFlash("success"$msg);
  99.         }
  100.         return $this->redirectToRoute('recipients_list');
  101.     }
  102.     /**
  103.      * @Route("/recipients/list/{listType}", name="recipients_list_all_users")
  104.      */
  105.     public function listAllUsersAction(Request $requestEntityManagerInterface $em$listType "to_validate"){
  106.         $user $this->getUser();
  107.         $request->setLocale($user->getLocale());
  108.         $users $em->getRepository(Recipient::class)->getAllValidatorUsers($user$listType);
  109.         return $this->render('CossBundle/Recipient/list_all_users.html.twig', array(
  110.             'users' => $users,
  111.             'listType' => $listType
  112.         ));
  113.     }
  114.     /**
  115.      * @Route("/recipients/{appUser}", name="list_user_recipients")
  116.      */
  117.     public function listRecipientsAction(Request $request$appUserEntityManagerInterface $emTranslatorInterface $translatorMailerManager $mailerManagerCossManager $cossManager)
  118.     {
  119.         $user $this->getUser();
  120.         $request->setLocale($user->getLocale());
  121.         $appUser $em->getRepository(User::class)->find($appUser);
  122.         $access false;
  123.         if (in_array'ROLE_SUPER_ADMIN'$user->getRoles() )){
  124.             $access true;
  125.         } elseif ($appUser->getValidator() == $user){
  126.             $access true;
  127.         }
  128.         if(!$access){
  129.             $msg $translator->trans(
  130.                 "Vous n'avez pas accès à cette liste de répondants",
  131.                 array(), 'coss'
  132.             );
  133.             $this->addFlash("error"$msg);
  134.             return $this->redirectToRoute('recipients_list_all_users');
  135.         }
  136.         $recipients $em->getRepository(Recipient::class)->getUserRecipients($appUser);
  137.         $recipientsAnalysis = array();
  138.         foreach ($recipients as $recipient){
  139.             $analysisData $recipient->getAnalysisData();
  140.             if($analysisData){
  141.                 $score 50;
  142.                 foreach ($analysisData['criterias'] as $criteria) {
  143.                     $impact $criteria['impact'];
  144.                     // Supprimer le "%" potentiel et convertir en entier
  145.                     $value = (int) str_replace('%'''$impact);
  146.                     $score += $value;
  147.                 }
  148.                 // Score entre 0 et 100
  149.                 $score max(0min(100$score));
  150.                 $recipientsAnalysis[] = array(
  151.                     "firstname" => $recipient->getUser()->getFirstname(),
  152.                     "lastname" => $recipient->getUser()->getLastname(),
  153.                     "email" => $recipient->getUser()->getEmail(),
  154.                     "title" => $recipient->getTitle(),
  155.                     "company" => $recipient->getCompany(),
  156.                     "type" => $recipient->getTypeClear(),
  157.                     "relation_level" => $analysisData['relation_level'],
  158.                     "admin_analysis" => $analysisData['admin_analysis'],
  159.                     "score" => $score,
  160.                     "criterias" => $analysisData['criterias'],
  161.                 );
  162.             }
  163.         }
  164.         if(count($recipients) < 5){
  165.             if($request->getSession()->get('hideModal') == true){
  166.                 $showModal false;
  167.             } else {
  168.                 $showModal true;
  169.             }
  170.         } else {
  171.             $showModal false;
  172.         }
  173.         $recipientsForm $this->createFormBuilder()
  174.             ->add('validatedRecipientsIds'TextType::class, array('label' => false'mapped' => false))
  175.             ->add('deletedRecipientsIds'TextType::class, array('label' => false'mapped' => false))
  176.             ->add('infoRecipientsIds'TextType::class, array('label' => false'mapped' => false))
  177.             ->add('save'SubmitType::class, array('label' => false))
  178.             ->getForm();
  179.         $recipientsForm->handleRequest($request);
  180.         if ($recipientsForm->isSubmitted() && $recipientsForm->isValid()) {
  181.             $recipientsValidated false;
  182.             $recipientsDeleted false;
  183.             $recipientsInfo false;
  184.             $recipientsValidatedData = array();
  185.             $recipientsDeletedData = array();
  186.             $recipientsInfoData = array();
  187.             $validatedRecipientsIds  $recipientsForm->get('validatedRecipientsIds')->getData();
  188.             $validatedRecipients explode(";"$validatedRecipientsIds);
  189.             foreach ($validatedRecipients as $id){
  190.                 if($id){
  191.                     $recipient $em->getRepository(Recipient::class)->find($id);
  192.                     if($recipient) {
  193.                         $recipient->setStatus(RecipientRepository::STATUS_VALIDATED);
  194.                         $recipient->setValidatedAt(new Datetime());
  195.                         $em->persist($recipient);
  196.                         $recipientsValidated true;
  197.                         $recipientsValidatedData[] = $recipient;
  198.                     }
  199.                 }
  200.             }
  201.             // Check new badges after new validated recipient
  202.             $cossManager->sendMissingBadges($appUser);
  203.             $deletedRecipientsIds  $recipientsForm->get('deletedRecipientsIds')->getData();
  204.             $deletedRecipients explode(";"$deletedRecipientsIds);
  205.             foreach ($deletedRecipients as $id){
  206.                 if($id){
  207.                     $recipient $em->getRepository(Recipient::class)->find($id);
  208.                     if($recipient) {
  209.                         $em->remove($recipient);
  210.                         $recipientsDeleted true;
  211.                         $recipientsDeletedData[] = $recipient;
  212.                     }
  213.                 }
  214.             }
  215.             $infoRecipientsIds  $recipientsForm->get('infoRecipientsIds')->getData();
  216.             $infoRecipients explode(";"$infoRecipientsIds);
  217.             foreach ($infoRecipients as $id){
  218.                 if($id){
  219.                     $recipient $em->getRepository(Recipient::class)->find($id);
  220.                     if($recipient) {
  221.                         $recipient->setStatus(RecipientRepository::STATUS_INFO);
  222.                         $recipientsInfo true;
  223.                         $recipientsInfoData[] = $recipient;
  224.                     }
  225.                 }
  226.             }
  227.             $em->flush();
  228.             $recipientsData = array(
  229.                 "validated" => $recipientsValidatedData,
  230.                 "deleted" => $recipientsDeletedData,
  231.                 "info" => $recipientsInfoData
  232.             );
  233.             if($recipientsValidated || $recipientsDeleted || $recipientsInfo){
  234.                 if($recipientsValidated && !$recipientsDeleted && !$recipientsInfo){
  235.                     // Send email only validated
  236.                     $mailerManager->setRecipientsOnlyValidatedEmail($appUser$recipientsData);
  237.                 }elseif($recipientsDeleted && !$recipientsValidated && !$recipientsInfo){
  238.                     // Send email only deleted
  239.                     $mailerManager->setRecipientsOnlyDeletedEmail($appUser$recipientsData);
  240.                 }elseif($recipientsInfo && !$recipientsValidated && !$recipientsDeleted){
  241.                     // Send email only info
  242.                     $mailerManager->setRecipientsOnlyInfoEmail($appUser$recipientsData);
  243.                 } else {
  244.                     // Send email with correct cases
  245.                     $mailerManager->setRecipientsMultiCaseEmail($appUser$recipientsData);
  246.                 }
  247.             }
  248.             return $this->redirectToRoute('list_user_recipients', array('appUser' => $appUser->getId()));
  249.         }
  250.         $proofMessages $em->getRepository(ProofMessage::class)->findAll();
  251.         return $this->render('CossBundle/Recipient/list_user.html.twig', array(
  252.             'recipients' => $recipients,
  253.             'recipientsAnalysis' => $recipientsAnalysis,
  254.             'appUser' => $appUser,
  255.             'showModal' => $showModal,
  256.             'proofMessages' => $proofMessages,
  257.             'form' => $recipientsForm->createView(),
  258.         ));
  259.     }
  260.     /**
  261.      * @Route("/recipients/comment/add/{recipientId}", name="recipient_comment_add")
  262.      */
  263.     public function addRecipientCommentAction(Request $requestEntityManagerInterface $em$recipientId)
  264.     {
  265.         if ($request->isXmlHttpRequest()) {
  266.             $user $this->getUser();
  267.             $request->setLocale($user->getLocale());
  268.             $comment $request->request->get('comment');
  269.             $recipient $em->getRepository(Recipient::class)->find($recipientId);
  270.             if($recipient){
  271.                 $recipient->setComment($comment);
  272.                 $em->persist($recipient);
  273.                 $em->flush();
  274.                 return new JsonResponse(
  275.                     array(
  276.                         'status' => 'ok',
  277.                         'comment' => $comment,
  278.                         'recipientId' => $recipient->getId()
  279.                     ), 200);
  280.             } else {
  281.                 return new JsonResponse(
  282.                     array(
  283.                         'status' => 'error',
  284.                     ), 200);
  285.             }
  286.         } else {
  287.             return New Response(""401);
  288.         }
  289.     }
  290.     /**
  291.      * @Route("/recipient/{appUser}/{mode}/{id}", name="edit_recipient")
  292.      */
  293.     public function addRecipientAction(Request $request$appUser$modeEntityManagerInterface $emTranslatorInterface $translatorCossManager $cossManagerMailerManager $mailerManagerUserPasswordHasherInterface $passwordHasher$id null)
  294.     {
  295.         $nextAction 'save';
  296.         $user $this->getUser();
  297.         $request->setLocale($user->getLocale());
  298.         $appUser $em->getRepository(User::class)->find($appUser);
  299.         $access false;
  300.         if (in_array'ROLE_SUPER_ADMIN'$user->getRoles() )){
  301.             $access true;
  302.         } elseif ($appUser->getValidator() == $user){
  303.             $access true;
  304.         }
  305.         if(!$access){
  306.             $msg $translator->trans(
  307.                 "Vous n'avez pas accès à cette liste de répondants",
  308.                 array(), 'coss'
  309.             );
  310.             $this->addFlash("error"$msg);
  311.             return $this->redirectToRoute('recipients_list_all_users');
  312.         }
  313.         $isValidatorValidEmail $cossManager->getValidatorIsValidEmail($user);
  314.         if(!$isValidatorValidEmail){
  315.             $msg $translator->trans(
  316.                 "Vous devez avoir un email professionnel pour ajouter des répondants",
  317.                 array(), 'coss'
  318.             );
  319.             $this->addFlash("error"$msg);
  320.             return $this->redirectToRoute('list_user_recipients', array('appUser' => $appUser->getId()));
  321.         }
  322.         if($id) {
  323.             $recipients $em->getRepository(Recipient::class)->getUserRecipients($appUser);
  324.             $recipient $em->getRepository(Recipient::class)->find($id);
  325.             $ids array_map(function ($val) {
  326.                 return $val->getId();
  327.             }, $recipients);
  328.             if (!in_array($recipient->getId(), $ids)) {
  329.                 $msg $translator->trans(
  330.                     "Vous n'avez pas accès à cet utilisateur",
  331.                     array(), 'coss'
  332.                 );
  333.                 $this->addFlash("error"$msg);
  334.                 return $this->redirectToRoute('list_user_recipients', array('appUser' => $appUser->getId()));
  335.             }
  336.         } else {
  337.             $recipient null;
  338.         }
  339.         $addRecipientForm $this->createAddRecipientForm($recipient);
  340.         $addRecipientForm->handleRequest($request);
  341.         if ($addRecipientForm->isSubmitted() && $addRecipientForm->isValid()) {
  342.             $nextAction $addRecipientForm->get('saveAndAdd')->isClicked()
  343.                 ? 'save_add'
  344.                 'save';
  345.             if($addRecipientForm['email']->getData()){
  346.                 $isValidEmail $cossManager->getRecipientValidEmail($addRecipientForm['email']->getData());
  347.                 if($isValidEmail){
  348.                     $existingUser $em->getRepository(User::class)->findOneBy(array('email' => $addRecipientForm['email']->getData()));
  349.                     if($existingUser){
  350.                         $existingUser->setFirstname($addRecipientForm['firstname']->getData());
  351.                         $existingUser->setLastname($addRecipientForm['lastname']->getData());
  352.                         $existingUser->setEmail($addRecipientForm['email']->getData());
  353.                         $existingUser->setUsername($addRecipientForm['email']->getData());
  354.                         $em->persist($existingUser);
  355.                         $em->flush();
  356.                         $msg $translator->trans(
  357.                             "L'utilisateur %user% a été mis à jour",
  358.                             array('%user%' => $addRecipientForm['email']->getData()), 'coss'
  359.                         );
  360.                         $this->addFlash("success"$msg);
  361.                         $existingRecipient $em->getRepository(Recipient::class)->findOneBy(array('user' => $existingUser'appUser' => $appUser ));
  362.                         if(!$existingRecipient){
  363.                             $newRecipient = new Recipient();
  364.                             $newRecipient->setUser($existingUser);
  365.                             $newRecipient->setAppUser($appUser);
  366.                             $newRecipient->setType($addRecipientForm['type']->getData());
  367.                             $newRecipient->setTitle($addRecipientForm['title']->getData());
  368.                             $newRecipient->setCompany($addRecipientForm['company']->getData());
  369.                             $newRecipient->setStatus(RecipientRepository::STATUS_VALIDATED);
  370.                             $newRecipient->setSources(array('admin'));
  371.                             $newRecipient->setValidatedAt(new DateTime());
  372.                             $em->persist($newRecipient);
  373.                             $em->flush();
  374.                             // Check new badges after new validated recipient
  375.                             $cossManager->sendMissingBadges($appUser);
  376.                             $msg $translator->trans(
  377.                                 "L'utilisateur %user% a été ajouté aux répondants de %sender%",
  378.                                 array('%user%' => $addRecipientForm['email']->getData(), '%sender%' => $appUser->getEmail()), 'coss'
  379.                             );
  380.                             $this->addFlash("success"$msg);
  381.                         } else {
  382.                             $existingRecipient->setUser($existingUser);
  383.                             $existingRecipient->setAppUser($appUser);
  384.                             $existingRecipient->setType($addRecipientForm['type']->getData());
  385.                             $existingRecipient->setTitle($addRecipientForm['title']->getData());
  386.                             $existingRecipient->setCompany($addRecipientForm['company']->getData());
  387.                             $em->persist($existingRecipient);
  388.                             $em->flush();
  389.                         }
  390.                     } else {
  391.                         $newUser = new User();
  392.                         $newUser->setFirstname($addRecipientForm['firstname']->getData());
  393.                         $newUser->setLastname($addRecipientForm['lastname']->getData());
  394.                         $newUser->setEmail($addRecipientForm['email']->getData());
  395.                         $newUser->setUsername($addRecipientForm['email']->getData());
  396.                         $newUser->setEnabled(false);
  397.                         $newUser->setLocale($user->getLocale());
  398.                         $plainpassword substrstr_shuffle'abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789' ), 010 );
  399.                         $password $passwordHasher->hashPassword(
  400.                             $newUser,
  401.                             $plainpassword
  402.                         );
  403.                         $newUser->setPassword($password);
  404.                         $em->persist($newUser);
  405.                         $em->flush();
  406.                         $newRecipient = new Recipient();
  407.                         $newRecipient->setUser($newUser);
  408.                         $newRecipient->setAppUser($appUser);
  409.                         $newRecipient->setType($addRecipientForm['type']->getData());
  410.                         $newRecipient->setTitle($addRecipientForm['title']->getData());
  411.                         $newRecipient->setCompany($addRecipientForm['company']->getData());
  412.                         $newRecipient->setSources(array('admin'));
  413.                         $newRecipient->setStatus(RecipientRepository::STATUS_VALIDATED);
  414.                         $newRecipient->setValidatedAt(new DateTime());
  415.                         $em->persist($newRecipient);
  416.                         $em->flush();
  417.                         // Check new badges after new validated recipient
  418.                         $cossManager->sendMissingBadges($appUser);
  419.                         $msg $translator->trans(
  420.                             "L'utilisateur %user% a été ajouté aux répondants de %sender%",
  421.                             array('%user%' => $addRecipientForm['email']->getData(), '%sender%' => $appUser->getEmail()), 'coss'
  422.                         );
  423.                         $this->addFlash("success"$msg);
  424.                     }
  425.                     $request->getSession()->set('hideModal'true);
  426.                 } else{
  427.                     $error $translator->trans(
  428.                         "Vous devez saisir des emails professionnels de collaborateurs.",
  429.                         array(), 'coss'
  430.                     );
  431.                     $this->addFlash("error"$error);
  432.                 }
  433.             }
  434.         }
  435.         if($nextAction == "save_add"){
  436.             return $this->redirectToRoute('edit_recipient', array('appUser' => $appUser->getId(), 'mode' => 'add'));
  437.         }
  438.         return $this->render('CossBundle/Recipient/add.html.twig', array(
  439.             'addRecipientForm' => $addRecipientForm->createView(),
  440.             'mode' => $mode,
  441.             'appUser' => $appUser
  442.         ));
  443.     }
  444.     /**
  445.      * @Route("/recipients/download/{appUser}", name="download_recipients")
  446.      */
  447.     public function downloadRecipientsAction(Request $requestEntityManagerInterface $em$appUserCossManager $cossManagerTranslatorInterface $translator){
  448.         $user $this->getUser();
  449.         $request->setLocale($user->getLocale());
  450.         $appUser $em->getRepository(User::class)->find($appUser);
  451.         $access false;
  452.         if (in_array'ROLE_SUPER_ADMIN'$user->getRoles() )){
  453.             $access true;
  454.         } elseif ($appUser->getValidator() == $user){
  455.             $access true;
  456.         }
  457.         if(!$access){
  458.             $msg $translator->trans(
  459.                 "Vous n'avez pas accès à cette liste de répondants",
  460.                 array(), 'coss'
  461.             );
  462.             $this->addFlash("error"$msg);
  463.             return $this->redirectToRoute('recipients_list_all_users');
  464.         }
  465.         $recipients $em->getRepository(Recipient::class)->getUserRecipients($appUser);
  466.         $today = new Datetime();
  467.         $fileName "export_recipients_".$today->format('d_m_Y').".csv";
  468.         $response = new StreamedResponse();
  469.         $response->setCallback(function() use ($recipients) {
  470.             $handle fopen('php://output''w+');
  471.             fputcsv($handle, ['firstname''lastname''email''type''title''company''status'], ';');
  472.             foreach ($recipients as $recipient) {
  473.                 fputcsv(
  474.                     $handle,
  475.                     [$recipient->getUser()->getFirstname(), $recipient->getUser()->getLastname(), $recipient->getUser()->getEmail(), $recipient->getTypeClear(), $recipient->getTitle(), $recipient->getCompany(), $recipient->getStatus()],
  476.                     ';'
  477.                 );
  478.             }
  479.             fclose($handle);
  480.         });
  481.         $response->setStatusCode(200);
  482.         $response->headers->set('Content-Type''text/csv; charset=utf-8');
  483.         $response->headers->set('Content-Disposition','attachment; filename='.$fileName.'');
  484.         return $response;
  485.     }
  486.     /**
  487.      * @Route("/recipients/import/{appUser}", name="import_recipients")
  488.      */
  489.     public function importRecipientsAction(Request $request$appUserEntityManagerInterface $emTranslatorInterface $translatorCossManager $cossManagerImportExportManager $importExportManagerUserPasswordHasherInterface $passwordHasherMailerManager $mailerManager)
  490.     {
  491.         $user $this->getUser();
  492.         $appUser $em->getRepository(User::class)->find($appUser);
  493.         $access false;
  494.         if (in_array'ROLE_SUPER_ADMIN'$user->getRoles() )){
  495.             $access true;
  496.         } elseif ($appUser->getValidator() == $user){
  497.             $access true;
  498.         }
  499.         if(!$access){
  500.             $msg $translator->trans(
  501.                 "Vous n'avez pas accès à cette liste de répondants",
  502.                 array(), 'coss'
  503.             );
  504.             $this->addFlash("error"$msg);
  505.             return $this->redirectToRoute('recipients_list_all_users');
  506.         }
  507.         $form $this->createFormBuilder()
  508.             ->add('importFile'FileType::class, array('label' => false'required' => false))
  509.             ->getForm();
  510.         if ($request->getMethod('post') == 'POST') {
  511.             // Bind request to the form
  512.             $form->handleRequest($request);
  513.             // If form is valid
  514.             if ($form->isValid()) {
  515.                 $fileImport $form['importFile']->getData();
  516.                 // CHECK ENCODING && EXTENSION
  517.                 $extension $fileImport->guessExtension();
  518.                 if ($extension != "txt" && $extension != "csv" && $extension != "xls" && $extension != "xlsx") {
  519.                     $error $translator->trans(
  520.                         "Merci de sélectionner un fichier au format CSV ou Excel",
  521.                         array(), 'import_export'
  522.                     );
  523.                     $this->addFlash("error"$error);
  524.                 } else {
  525.                     $ok true;
  526.                     if ($extension == "txt" || $extension == "csv") {
  527.                         if (!mb_detect_encoding($fileImport'UTF-8'true)) {
  528.                             $error $translator->trans(
  529.                                 "Merci de sélectionner un fichier encodé en UTF-8",
  530.                                 array(), 'import_export'
  531.                             );
  532.                             $this->addFlash("error"$error);
  533.                             $ok false;
  534.                         } else {
  535.                             $users $importExportManager->openCSVFile($fileImport);
  536.                         }
  537.                     } else if ($extension == "xls" || $extension == "xlsx") {
  538.                         $users $importExportManager->openExcelFile($fileImportfalse);
  539.                     }
  540.                     if ($ok) {
  541.                         foreach ($users['users'] as $i => $utilisateur) {
  542.                             if (count($users['fields']) != count($utilisateur)) {
  543.                                 if (count($utilisateur) == 1) {
  544.                                     $error $translator->trans("La ligne %value% est peut-être vide, si ce n'est pas le cas, merci de corriger cette ligne.", array('%value%' => ($i 1)), 'import_export');
  545.                                     $this->addFlash("error"$error);
  546.                                     break;
  547.                                 } else {
  548.                                     $error $translator->trans("Le nombre de champs ne correspond pas à l'entête pour l'utilisateur en ligne : %value%", array('%value%' => ($i 1)), 'import_export');
  549.                                     $this->addFlash("error"$error);
  550.                                     break;
  551.                                 }
  552.                             } else {
  553.                                 // Traite l'utilisateur courant
  554.                                 $utilisateur["email"] = trim(preg_replace('/\s+/'' '$utilisateur["email"]));
  555.                                 $isValidEmail $cossManager->getRecipientValidEmail($utilisateur['email']);
  556.                                 if ($isValidEmail) {
  557.                                     $existingUser $em->getRepository(User::class)->findOneBy(array('email' => $utilisateur['email']));
  558.                                     if ($existingUser) {
  559.                                         $existingUser->setFirstname($utilisateur['firstname']);
  560.                                         $existingUser->setLastname($utilisateur['lastname']);
  561.                                         $existingUser->setEmail($utilisateur['email']);
  562.                                         $existingUser->setUsername($utilisateur['email']);
  563.                                         $em->persist($existingUser);
  564.                                         $em->flush();
  565.                                         $msg $translator->trans(
  566.                                             "L'utilisateur %user% a été mis à jour",
  567.                                             array('%user%' => $utilisateur['email']), 'coss'
  568.                                         );
  569.                                         $this->addFlash("success"$msg);
  570.                                         $existingRecipient $em->getRepository(Recipient::class)->findOneBy(array('appUser' => $appUser'user' => $existingUser));
  571.                                         if (!$existingRecipient) {
  572.                                             $newRecipient = new Recipient();
  573.                                             $newRecipient->setUser($existingUser);
  574.                                             $newRecipient->setAppUser($appUser);
  575.                                             $newRecipient->setStatus(RecipientRepository::STATUS_VALIDATED);
  576.                                             $newRecipient->setValidatedAt(new DateTime());
  577.                                             $newRecipient->setType($utilisateur['type']);
  578.                                             $newRecipient->setTitle($utilisateur['title']);
  579.                                             $newRecipient->setCompany($utilisateur['company']);
  580.                                             $newRecipient->setSources(array('admin'));
  581.                                             $em->persist($newRecipient);
  582.                                             $em->flush();
  583.                                             // Check new badges after new validated recipient
  584.                                             $cossManager->sendMissingBadges($appUser);
  585.                                             $msg $translator->trans(
  586.                                                 "L'utilisateur %user% a été ajouté aux répondants de vos utilisateurs",
  587.                                                 array('%user%' => $utilisateur['email']), 'coss'
  588.                                             );
  589.                                             $this->addFlash("success"$msg);
  590.                                         }
  591.                                     } else {
  592.                                         $newUser = new User();
  593.                                         $newUser->setFirstname($utilisateur['firstname']);
  594.                                         $newUser->setLastname($utilisateur['lastname']);
  595.                                         $newUser->setEmail($utilisateur['email']);
  596.                                         $newUser->setUsername($utilisateur['email']);
  597.                                         $newUser->setEnabled(false);
  598.                                         $newUser->setLocale($user->getLocale());
  599.                                         $plainpassword substr(str_shuffle('abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789'), 010);
  600.                                         $password $passwordHasher->hashPassword(
  601.                                             $newUser,
  602.                                             $plainpassword
  603.                                         );
  604.                                         $newUser->setPassword($password);
  605.                                         $em->persist($newUser);
  606.                                         $em->flush();
  607.                                         $msg $translator->trans(
  608.                                             "L'utilisateur %user% a été ajouté",
  609.                                             array('%user%' => $utilisateur['email']), 'coss'
  610.                                         );
  611.                                         $this->addFlash("success"$msg);
  612.                                         $newRecipient = new Recipient();
  613.                                         $newRecipient->setUser($newUser);
  614.                                         $newRecipient->setAppUser($appUser);
  615.                                         $newRecipient->setStatus(RecipientRepository::STATUS_VALIDATED);
  616.                                         $newRecipient->setValidatedAt(new DateTime());
  617.                                         $newRecipient->setType($utilisateur['type']);
  618.                                         $newRecipient->setTitle($utilisateur['title']);
  619.                                         $newRecipient->setCompany($utilisateur['company']);
  620.                                         $newRecipient->setSources(array('admin'));
  621.                                         $em->persist($newRecipient);
  622.                                         $em->flush();
  623.                                         // Check new badges after new validated recipient
  624.                                         $cossManager->sendMissingBadges($appUser);
  625.                                         $msg $translator->trans(
  626.                                             "L'utilisateur %user% a été ajouté aux répondants de vos utilisateurs",
  627.                                             array('%user%' => $utilisateur['email']), 'coss'
  628.                                         );
  629.                                         $this->addFlash("success"$msg);
  630.                                     }
  631.                                 } else {
  632.                                     $error $translator->trans(
  633.                                         "Vous devez saisir des emails professionnels de collaborateurs.",
  634.                                         array(), 'coss'
  635.                                     );
  636.                                     $this->addFlash("error"$error);
  637.                                     break;
  638.                                 }
  639.                             }
  640.                         }
  641.                     } else {
  642.                         $error $translator->trans("Une erreur est survenue lors de l'ouverture du fichier", array(), 'import_export');
  643.                         $this->addFlash("error"$error);
  644.                     }
  645.                 }
  646.             }
  647.         }
  648.         return $this->render('CossBundle/Import/import_recipients.html.twig', array(
  649.             "form" => $form->createView()
  650.         ));
  651.     }
  652.     /**
  653.      * @Route("/recipients/import/template/csv", name="import_recipients_template_csv")
  654.      */
  655.     public function generateImportRecipientsTemplateCSV(Request $request)
  656.     {
  657.         $response = new StreamedResponse();
  658.         $response->setCallback(function(){
  659.             $handle fopen('php://output''w+');
  660.             fwrite($handleimplode(';', ['"firstname"','"lastname"','"email"''"type"''"title"''"company"']) . PHP_EOL);
  661.             fwrite($handleimplode(';', ['"Paul"','"Dupont"','"paul@dupont.com"''"SUPERIOR"''"Directeur Marketing"''"EDF"']) . PHP_EOL);
  662.             fwrite($handleimplode(';', ['"Pierre"','"Dulac"','"pierre@dulac.com"''"SUPERIOR"''"Manager"''"McDonalds"']) . PHP_EOL);
  663.             fwrite($handleimplode(';', ['"Marie"','"Lannau"','"marie@lannau.com"''"PAIR"''"Développeur"''5Feedback']) . PHP_EOL);
  664.             fwrite($handleimplode(';', ['"Jacques"','"Mattel"','"jacques@mattel.com"''"GUEST"''"Client"''Microsoft']) . PHP_EOL);
  665.             fclose($handle);
  666.         });
  667.         $filename "tutor_import_template.csv";
  668.         $response->setStatusCode(200);
  669.         $response->headers->set('Content-Type''text/csv; charset=utf-8');
  670.         $response->headers->set('Content-Disposition','attachment; filename='.$filename.'');
  671.         return $response;
  672.     }
  673.     /**
  674.      * @Route("/recipients/import/template/excel", name="import_recipients_template_excel")
  675.      */
  676.     public function generateImportRecipientsTemplateExcel(Request $request)
  677.     {
  678.         $response = new StreamedResponse();
  679.         $response->setCallback(function(){
  680.             $spreadsheet = new Spreadsheet();
  681.             $sheet $spreadsheet->getActiveSheet();
  682.             $sheet->setCellValue('A1''firstname');
  683.             $sheet->setCellValue('B1''lastname');
  684.             $sheet->setCellValue('C1''email');
  685.             $sheet->setCellValue('D1''type');
  686.             $sheet->setCellValue('E1''title');
  687.             $sheet->setCellValue('F1''company');
  688.             $sheet->setCellValue('A2''Paul');
  689.             $sheet->setCellValue('B2''Dupont');
  690.             $sheet->setCellValue('C2''paul@dupont.com');
  691.             $sheet->setCellValue('D2''SUPERIOR');
  692.             $sheet->setCellValue('E2''Directeur Marketing');
  693.             $sheet->setCellValue('F2''EDF');
  694.             $sheet->setCellValue('A3''Pierre');
  695.             $sheet->setCellValue('B3''Dulac');
  696.             $sheet->setCellValue('C3''pierre@dulac.com');
  697.             $sheet->setCellValue('D3''SUPERIOR');
  698.             $sheet->setCellValue('E3''Manager');
  699.             $sheet->setCellValue('F3''McDonalds');
  700.             $sheet->setCellValue('A4''Marie');
  701.             $sheet->setCellValue('B4''Lannau');
  702.             $sheet->setCellValue('C4''marie@lannau.com');
  703.             $sheet->setCellValue('D4''PAIR');
  704.             $sheet->setCellValue('E4''Développeur');
  705.             $sheet->setCellValue('F4''5Feedback');
  706.             $sheet->setCellValue('A5''Jacques');
  707.             $sheet->setCellValue('B5''Mattel');
  708.             $sheet->setCellValue('C5''jacques@mattel.com');
  709.             $sheet->setCellValue('D5''GUEST');
  710.             $sheet->setCellValue('E5''Client');
  711.             $sheet->setCellValue('F5''Microsoft');
  712.             $writer = new Xlsx($spreadsheet);
  713.             $writer->save('php://output');
  714.         });
  715.         $filename "recipients_import_template.xlsx";
  716.         $response->setStatusCode(200);
  717.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  718.         $response->headers->set('Content-Disposition','attachment; filename='.$filename.'');
  719.         return $response;
  720.     }
  721.     /**
  722.      * @Route("/guest/recipients/proof/{id}/{token}", name="user_recipients_proof")
  723.      */
  724.     public function guestUserRecipientsProofAction(Request $requestEntityManagerInterface $emMailerManager $mailerManagerTranslatorInterface$translator$id$token)
  725.     {
  726.         $appUser $em->getRepository(User::class)->find($id);
  727.         if ($appUser->getRecipientProofGuestToken() == $token) {
  728.             $recipients $em->getRepository(Recipient::class)->getUserProofRecipients($appUser);
  729.             $recipientsForm $this->createRecipientsProofForm($recipients);
  730.             $recipientsForm->handleRequest($request);
  731.             if ($recipientsForm->isSubmitted() && $recipientsForm->isValid()) {
  732.                 $proofs = array();
  733.                 $persist true;
  734.                 foreach ($recipients as $i => $recipient) {
  735.                     $email $recipientsForm->get('email_' $i)->getData();
  736.                     $comment $recipientsForm->get('comment_' $i)->getData();
  737.                     $file $recipientsForm->get('file_' $i)->getData();
  738.                     $delete $recipientsForm->get('delete_' $i)->getData();
  739.                     if ($delete) {
  740.                         $em->remove($recipient);
  741.                     } else {
  742.                         $proof = new Proof();
  743.                         if ($email) {
  744.                             if (filter_var($emailFILTER_VALIDATE_EMAIL)) {
  745.                                 // Get the domain part of the email
  746.                                 $domain substr($emailstrpos($email'@') + 1);
  747.                                 // Check if the domain matches
  748.                                 if ($domain != "5feedback.com" && $domain != "globalcoss.com") {
  749.                                     $proof->setEmail($email);
  750.                                 } else {
  751.                                     $this->addFlash('error'$translator->trans("Vous avez saisi un email non autorisé.", [], 'coss'));
  752.                                     $persist false;
  753.                                 }
  754.                             } else {
  755.                                 $this->addFlash('error'$translator->trans("Merci de saisir un email valide.", [], 'coss'));
  756.                                 $persist false;
  757.                             }
  758.                         }
  759.                         $proof->setRecipient($recipient);
  760.                         if($comment){
  761.                             $proof->setComment($comment);
  762.                         }
  763.                         if($file){
  764.                             $proof->setFile($file);
  765.                         }
  766.                         $em->persist($proof);
  767.                         $proofs[] = $proof;
  768.                     }
  769.                 }
  770.                 if($persist){
  771.                     $em->flush();
  772.                     $mailerManager->sendCOSSNewProofEmail($appUser$recipients$proofs);
  773.                     return $this->render('CossBundle/Recipient/proof_success.html.twig', array());
  774.                 }
  775.             }
  776.             return $this->render('CossBundle/Recipient/proofs_form.html.twig', array(
  777.                 "recipients" => $recipients,
  778.                 "recipientsCount" => count($recipients),
  779.                 'form' => $recipientsForm->createView(),
  780.             ));
  781.         } else {
  782.             return $this->render('CossBundle/Recipient/error.html.twig', array());
  783.         }
  784.     }
  785.     /**
  786.      * @Route("/guest/recipients/proof/{id}", name="recipient_proofs")
  787.      */
  788.     public function guestRecipientProofsAction(Request $requestEntityManagerInterface $em$id)
  789.     {
  790.         $user $this->getUser();
  791.         $request->setLocale($user->getLocale());
  792.         $recipient $em->getRepository(Recipient::class)->find($id);
  793.         if($recipient){
  794.             return $this->render('CossBundle/Recipient/proofs_modal.html.twig', array(
  795.                 'proofs' => $recipient->getProofs()
  796.             ));
  797.         } else {
  798.             return $this->render('CossBundle/Recipient/error_modal.html.twig', array());
  799.         }
  800.     }
  801.     /**
  802.      * @Route("/recipients/validate/proof/{id}", name="validate_recipient_proof")
  803.      */
  804.     public function validateRecipientProofAction(Request $requestEntityManagerInterface $em$id)
  805.     {
  806.         $user $this->getUser();
  807.         $request->setLocale($user->getLocale());
  808.         $proof $em->getRepository(Proof::class)->find($id);
  809.         if($proof){
  810.             $recipient $proof->getRecipient();
  811.             $email $proof->getEmail();
  812.             if($email){
  813.                 $existingUser $em->getRepository(User::class)->findOneBy(array('email' => $email));
  814.                 if($existingUser){
  815.                     $recipient->setUser($existingUser);
  816.                     $em->persist($recipient);
  817.                 } else {
  818.                     $recipientUser $recipient->getUser();
  819.                     $recipientUser->setEmail($email);
  820.                     $recipientUser->setUsername($email);
  821.                     $em->persist($recipientUser);
  822.                 }
  823.             }
  824.             $recipient->setStatus(RecipientRepository::STATUS_VALIDATED);
  825.             $recipient->setValidatedAt(new Datetime());
  826.             $em->persist($recipient);
  827.             $em->flush();
  828.             return $this->redirectToRoute('list_user_recipients', array('appUser' => $proof->getRecipient()->getAppUser()));
  829.         } else {
  830.             return $this->redirectToRoute('list_user_recipients', array('appUser' => $proof->getRecipient()->getAppUser()));
  831.         }
  832.     }
  833.     /**
  834.      * @Route("recipients/list/validation/{token}/{id}", name="recipients_list_validation")
  835.      */
  836.     public function recipientsListValidationAction(Request $request$token$idEntityManagerInterface $emCossManager $cossManagerMailerManager $mailerManager)
  837.     {
  838.         $appUser $em->getRepository(User::class)->find($id);
  839.         if($appUser){
  840.             $validator $appUser->getValidator();
  841.             if($mailerManager->getRecipientGuestToken($validator$appUser) == $token) {
  842.                 $recipients $em->getRepository(Recipient::class)->getUserRecipients($appUser);
  843.                 $recipientsListForm $this->createFormBuilder()
  844.                     ->add('validatedIds'TextType::class, array('label' => false'mapped' => false))
  845.                     ->add('canceledIds'TextType::class, array('label' => false'mapped' => false))
  846.                     ->add('save'SubmitType::class, array('label' => false))
  847.                     ->getForm();
  848.                 $recipientsListForm->handleRequest($request);
  849.                 if ($recipientsListForm->isSubmitted() && $recipientsListForm->isValid()) {
  850.                     $validatedIds  $recipientsListForm->get('validatedIds')->getData();
  851.                     $validated explode(";"$validatedIds);
  852.                     foreach ($validated as $id){
  853.                         if($id){
  854.                             $recipient $em->getRepository(Recipient::class)->find($id);
  855.                             if($recipient) {
  856.                                 $recipient->setStatus(RecipientRepository::STATUS_VALIDATED);
  857.                                 $recipient->setValidatedAt(new Datetime());
  858.                                 $em->persist($recipient);
  859.                             }
  860.                         }
  861.                     }
  862.                     $canceledIds  $recipientsListForm->get('canceledIds')->getData();
  863.                     $canceled explode(";"$canceledIds);
  864.                     foreach ($canceled as $id){
  865.                         if($id){
  866.                             $recipient $em->getRepository(Recipient::class)->find($id);
  867.                             if($recipient) {
  868.                                 $em->remove($recipient);
  869.                             }
  870.                         }
  871.                     }
  872.                     $em->flush();
  873.                     // Check new badges after new validated recipient
  874.                     $cossManager->sendMissingBadges($appUser);
  875.                     return $this->render('CossBundle/Recipient/success.html.twig');
  876.                 }
  877.                 $recipientsArray = array();
  878.                 foreach($recipients as $r){
  879.                     $recipientsArray[] = $r->getUser()->getEmail();
  880.                 }
  881.                 return $this->render('CossBundle/Recipient/index.html.twig',
  882.                     array(
  883.                         'recipients' => $recipients,
  884.                         'recipientsArray' => $recipientsArray,
  885.                         'form' => $recipientsListForm->createView(),
  886.                         'token' => $token,
  887.                         'appUser' => $appUser,
  888.                         'appUser_id' => $appUser->getId()
  889.                     )
  890.                 );
  891.             } else {
  892.                 return $this->render('CossBundle/Recipient/error.html.twig');
  893.             }
  894.         } else {
  895.             return $this->render('CossBundle/Recipient/error.html.twig');
  896.         }
  897.     }
  898.     /**
  899.      * @Route("recipients/list/add-user/{token}/{id}", name="recipients_list_add_user_validation")
  900.      */
  901.     public function recipientsListAddUserAction(Request $request$token$idEntityManagerInterface $emCossManager $cossManagerMailerManager $mailerManager)
  902.     {
  903.         if ($request->isXmlHttpRequest()) {
  904.             $appUser $em->getRepository(User::class)->find($id);
  905.             if($appUser){
  906.                 $validator $appUser->getValidator();
  907.                 if($mailerManager->getRecipientGuestToken($validator$appUser) == $token) {
  908.                     $lastname $request->get('lastname');
  909.                     $firstname $request->get('firstname');
  910.                     $email $request->get('email');
  911.                     $title $request->get('title');
  912.                     $type $request->get('type');
  913.                     $company $request->get('company');
  914.                     if($type == "SUPERIOR" || $type == "superior"){
  915.                         $formattedType RecipientRepository::SUPERIOR_RECIPIENT;
  916.                     } elseif ($type == "PAIR" || $type == "pair"){
  917.                         $formattedType RecipientRepository::PAIR_RECIPIENT;
  918.                     }elseif ($type == "GUEST" || $type == "guest"){
  919.                         $formattedType RecipientRepository::GUEST_RECIPIENT;
  920.                     } else {
  921.                         $formattedType RecipientRepository::GUEST_RECIPIENT;
  922.                     }
  923.                     $u $em->getRepository(User::class)->findOneBy(array('email' => $email));
  924.                     if (!$u) {
  925.                         $u = new User();
  926.                         $u->setFirstname($firstname);
  927.                         $u->setLastname($lastname);
  928.                         $u->setEmail($email);
  929.                         $u->setUsername($email);
  930.                         $u->setLocale($request->getLocale());
  931.                         $u->setPlainPassword(substr(str_shuffle(str_repeat($x='0123456789abcdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ'ceil(12/strlen($x)) )),1,12));
  932.                         $em->persist($u);
  933.                         $em->flush();
  934.                         $newRecipient = new Recipient();
  935.                         $newRecipient->setUser($u);
  936.                         $newRecipient->setAppUser($appUser);
  937.                         $newRecipient->setType($formattedType);
  938.                         $newRecipient->setTitle($title);
  939.                         $newRecipient->setCompany($company);
  940.                         $newRecipient->setStatus(RecipientRepository::STATUS_VALIDATED);
  941.                         $newRecipient->setSources(array('admin'));
  942.                         $newRecipient->setValidatedAt(new Datetime());
  943.                         $em->persist$newRecipient);
  944.                         $em->flush();
  945.                         // Check new badges after new validated recipient
  946.                         $cossManager->sendMissingBadges($appUser);
  947.                         return new JsonResponse(array('status' => 'ok''user' => array('id' => $newRecipient->getId(), 'firstname' => $firstname'lastname' => $lastname'email' => $email'title' => $title'type' => $newRecipient->getTypeClear())));
  948.                     } else {
  949.                         $recipient $em->getRepository(Recipient::class)->findOneBy(array('appUser' => $appUser'user' => $u));
  950.                         if(!$recipient){
  951.                             $recipient = new Recipient();
  952.                             $recipient->setUser($u);
  953.                             $recipient->setAppUser($appUser);
  954.                             $recipient->setType($formattedType);
  955.                             $recipient->setTitle($title);
  956.                             $recipient->setCompany($company);
  957.                             $recipient->setStatus(RecipientRepository::STATUS_VALIDATED);
  958.                             $recipient->setSources(array('admin'));
  959.                             $recipient->setValidatedAt(new DateTime());
  960.                             $em->persist$recipient);
  961.                             $em->flush();
  962.                             // Check new badges after new validated recipient
  963.                             $cossManager->sendMissingBadges($appUser);
  964.                         }
  965.                         return new JsonResponse(array('status' => 'ok''user' => array('id' => $recipient->getId(), 'firstname' => $firstname'lastname' => $lastname'email' => $email'title' => $title'type' => $recipient->getTypeClear())));
  966.                     }
  967.                 } else {
  968.                     return new JsonResponse(array('status' => 'error'));
  969.                 }
  970.             } else {
  971.                 return new JsonResponse(array('status' => 'error'));
  972.             }
  973.         } else {
  974.             return New Response(""401);
  975.         }
  976.     }
  977.     private function createAddRecipientForm($recipient){
  978.         $form $this->createForm(AddRecipientType::class, new AddRecipientType(), array('recipient' => $recipient));
  979.         return $form;
  980.     }
  981.     private function createRecipientsProofForm($recipients)
  982.     {
  983.         $form $this->createForm(RecipientsProofFormType::class, new RecipientsProofFormType(), array(
  984.             'recipients' => $recipients,
  985.         ));
  986.         return $form;
  987.     }
  988. }