src/Controller/AdminBundle/CRONController.php line 66

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: grego
  5.  * Date: 07/11/2022
  6.  * Time: 12:25
  7.  */
  8. namespace App\Controller\AdminBundle;
  9. use App\Entity\BatchEmail;
  10. use App\Entity\Campaign;
  11. use App\Entity\MailTemplate;
  12. use App\Entity\Participation;
  13. use App\Entity\SonataMediaMedia;
  14. use App\Entity\User;
  15. use App\Manager\CossManager;
  16. use App\Manager\MailerManager;
  17. use App\Manager\MistralManager;
  18. use App\Manager\ReportManager;
  19. use App\Manager\UserManager;
  20. use App\Repository\BatchEmailRepository;
  21. use App\Repository\CampaignRepository;
  22. use App\Repository\MailTemplateRepository;
  23. use App\Repository\ParticipationRepository;
  24. use App\Repository\RecipientRepository;
  25. use DateTime;
  26. use Doctrine\ORM\EntityManagerInterface;
  27. use Exception;
  28. use Knp\Snappy\Pdf;
  29. use PhpOffice\PhpSpreadsheet\Shared\Date;
  30. use Sonata\MediaBundle\Provider\Pool;
  31. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  32. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  33. use Symfony\Component\HttpFoundation\Request;
  34. use Symfony\Component\HttpFoundation\Response;
  35. use Symfony\Component\HttpFoundation\StreamedResponse;
  36. use Symfony\Component\HttpKernel\KernelInterface;
  37. use Symfony\Component\Routing\Annotation\Route;
  38. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  39. use Symfony\Contracts\Translation\TranslatorInterface;
  40. use Twig\Environment;
  41. use Symfony\Component\HttpFoundation\File\File;
  42. use Sonata\MediaBundle\Model\MediaManagerInterface;
  43. class CRONController extends AbstractController
  44. {
  45.     private $CRON_TOKEN "ffd6600b2594eafae3b2f0528a4cb51a";
  46.     /**
  47.      * @Route("/cron/debug/quality/{token}")
  48.      */
  49.     public function debugQuality($tokenEntityManagerInterface $entityManagerMailerManager $mailerManagerUserManager $userManagerCossManager $cossManagerMistralManager $mistralManagerTranslatorInterface $translatorParameterBagInterface $parameterBag){
  50.         set_time_limit(0);
  51.         ini_set('max_execution_time'3600); //3600 seconds = 1 heure
  52.         ini_set('memory_limit''-1');
  53.         $user $entityManager->getRepository(User::class)->find(145);
  54.         return New Response("OK"200);
  55.     }
  56.     /**
  57.      * @Route("/cron/send/batch/email/{token}")
  58.      */
  59.     public function sendBatchEmail($tokenRequest $requestEntityManagerInterface $entityManagerMailerManager $mailerManager)
  60.     {
  61.         if ($token == $this->CRON_TOKEN) {
  62.             $batchEmails $entityManager->getRepository(BatchEmail::class)->getPendingBatchEmailsPastFiveMinuts();
  63.             foreach ($batchEmails as $batchEmail) {
  64.                 $recipient $batchEmail->getRecipient();
  65.                 // Générer l'URL du répondant
  66.                 $recipientLink $this->generateUrl('quiz_answer', ['participationId' => $recipient->getParticipation()->getId() ,'token' => $recipient->getToken()],
  67.                     UrlGeneratorInterface::ABSOLUTE_URL
  68.                 );
  69.                 $mailTemplate $entityManager->getRepository(MailTemplate::class)->findOneBy(array('type' => $batchEmail->getType(), 'program' => $recipient->getParticipation()->getCampaign()->getProgram()));
  70.                 \Sentry\withScope(function (\Sentry\State\Scope $scope) use ($recipient$mailTemplate$recipientLink$mailerManager) {
  71.                     $scope->setUser([
  72.                         'id' => $recipient->getId(),
  73.                         'email' => $recipient->getEmail(),
  74.                     ]);
  75.                     $scope->setTag('type''email');
  76.                     try {
  77.                         $mailerManager->sendBatchEmail($recipient$mailTemplate$recipientLink$recipient->getParticipation()->getParticipant()->getLocale());
  78.                     } catch (\Throwable $e) {
  79.                         \Sentry\captureException($e);
  80.                     }
  81.                 });
  82.                 $batchEmail->setStatus(BatchEmailRepository::STATUS_TREATED);
  83.                 $entityManager->persist($batchEmail);
  84.             }
  85.             $entityManager->flush();
  86.             return New Response(""200);
  87.         } else {
  88.             return New Response("access denied"401);
  89.         }
  90.     }
  91.     /**
  92.      * @Route("/cron/send/recall/email/{type}/{token}")
  93.      */
  94.     public function sendRecallEmail($type$tokenRequest $requestEntityManagerInterface $entityManagerMailerManager $mailerManagerTranslatorInterface $translator)
  95.     {
  96.         if ($token == $this->CRON_TOKEN) {
  97.             switch($type){
  98.                 case "1_week_start":
  99.                     // Recall 1 week after participation started only if no active recipients
  100.                     $participations $entityManager->getRepository(Participation::class)->getParticipationsWithNoActiveRecipientsAfter1Week();
  101.                     foreach($participations as $participation){
  102.                         $template $entityManager->getRepository(MailTemplate::class)->findOneBy(array('type' => MailTemplateRepository::PARTICIPANT_RECALL'program' => $participation->getCampaign()->getProgram()));
  103.                         // Générer l'URL du participant
  104.                         $participationLink $this->generateUrl('participation_recipients', ['campaignToken' => $participation->getCampaign()->getToken()],
  105.                             UrlGeneratorInterface::ABSOLUTE_URL
  106.                         );
  107.                         $mailObject $template->getObject();
  108.                         $mailObject str_replace('_PROGRAM_NAME_'$participation->getCampaign()->getProgram()->getName(), $mailObject);
  109.                         $mailObject str_replace('_FIRSTNAME_'$participation->getParticipant()->getFirstname(), $mailObject);
  110.                         $mailObject str_replace('_FULLNAME_'$participation->getParticipant()->getFirstname()." ".$participation->getParticipant()->getLastname(), $mailObject);
  111.                         $mailContent $template->getContent();
  112.                         $mailContent str_replace('_PROGRAM_NAME_'$participation->getCampaign()->getProgram()->getName(), $mailContent);
  113.                         $mailContent str_replace('_LINK_'$participationLink$mailContent);
  114.                         $mailContent str_replace('_FIRSTNAME_'$participation->getParticipant()->getFirstname(), $mailContent);
  115.                         $mailContent str_replace('_FULLNAME_'$participation->getParticipant()->getFirstname()." ".$participation->getParticipant()->getLastname(), $mailContent);
  116.                         $formatterFR = new \IntlDateFormatter(
  117.                             'fr_FR',
  118.                             \IntlDateFormatter::LONG,
  119.                             \IntlDateFormatter::NONE
  120.                         );
  121.                         $dateFormattedFR $formatterFR->format($participation->getEndDate());
  122.                         $formatterEN = new \IntlDateFormatter(
  123.                             'en_US',
  124.                             \IntlDateFormatter::LONG,
  125.                             \IntlDateFormatter::NONE
  126.                         );
  127.                         $dateFormattedEN $formatterEN->format($participation->getEndDate());
  128.                         $mailContent str_replace("_FIN_DE_CAMPAGNE_"$dateFormattedFR$mailContent);
  129.                         $mailContent str_replace("_END_OF_CAMPAIGN_"$dateFormattedEN$mailContent);
  130.                         \Sentry\withScope(function (\Sentry\State\Scope $scope) use ($participation$mailObject$mailContent$mailerManager) {
  131.                             $scope->setUser([
  132.                                 'id' => $participation->getParticipant()->getId(),
  133.                                 'email' => $participation->getParticipant()->getEmail(),
  134.                             ]);
  135.                             $scope->setTag('type''email');
  136.                             try {
  137.                                 $mailerManager->sendParticipantRecall($participation$mailObject$mailContent);
  138.                             } catch (\Throwable $e) {
  139.                                 \Sentry\captureException($e);
  140.                             }
  141.                         });
  142.                     }
  143.                     break;
  144.                 case "10_days_end":
  145.                     // Recall 10 days before participation ends for recipients who havn't answered
  146.                     $participations $entityManager->getRepository(Participation::class)->getParticipationsBefore10Days();
  147.                     foreach($participations as $participation){
  148.                         $template $entityManager->getRepository(MailTemplate::class)->findOneBy(array('type' => MailTemplateRepository::RECIPIENT_FIRST_RECALL'program' => $participation->getCampaign()->getProgram()));
  149.                         foreach ($participation->getRecipients() as $recipient){
  150.                             if($recipient->getStatus() == RecipientRepository::STATUS_ACTIVE && count($recipient->getQuizAnswers()) == 0){
  151.                                 // Générer l'URL du répondant
  152.                                 $recipientLink $this->generateUrl('quiz_answer', ['participationId' => $participation->getId() ,'token' => $recipient->getToken()],
  153.                                     UrlGeneratorInterface::ABSOLUTE_URL
  154.                                 );
  155.                                 $mailObject $template->getObject();
  156.                                 $mailObject str_replace('_FIRSTNAME_'$recipient->getFirstname(), $mailObject);
  157.                                 $mailObject str_replace('_FULLNAME_'$recipient->getParticipation()->getParticipant()->getFirstname()." ".$recipient->getParticipation()->getParticipant()->getLastname(), $mailObject);
  158.                                 $mailContent $template->getContent();
  159.                                 $mailContent str_replace('_LINK_'$recipientLink$mailContent);
  160.                                 $mailContent str_replace('_FIRSTNAME_'$recipient->getFirstname(), $mailContent);
  161.                                 $mailContent str_replace('_FULLNAME_'$recipient->getParticipation()->getParticipant()->getFirstname()." ".$recipient->getParticipation()->getParticipant()->getLastname(), $mailContent);
  162.                                 $formatterFR = new \IntlDateFormatter(
  163.                                     'fr_FR',
  164.                                     \IntlDateFormatter::LONG,
  165.                                     \IntlDateFormatter::NONE
  166.                                 );
  167.                                 $dateFormattedFR $formatterFR->format($participation->getEndDate());
  168.                                 $formatterEN = new \IntlDateFormatter(
  169.                                     'en_US',
  170.                                     \IntlDateFormatter::LONG,
  171.                                     \IntlDateFormatter::NONE
  172.                                 );
  173.                                 $dateFormattedEN $formatterEN->format($participation->getEndDate());
  174.                                 $mailContent str_replace("_FIN_DE_CAMPAGNE_"$dateFormattedFR$mailContent);
  175.                                 $mailContent str_replace("_END_OF_CAMPAIGN_"$dateFormattedEN$mailContent);
  176.                                 \Sentry\withScope(function (\Sentry\State\Scope $scope) use ($recipient$mailObject$mailContent$mailerManager) {
  177.                                     $scope->setUser([
  178.                                         'id' => $recipient->getId(),
  179.                                         'email' => $recipient->getEmail(),
  180.                                     ]);
  181.                                     $scope->setTag('type''email');
  182.                                     try {
  183.                                         $mailerManager->sendRecipientRecall($recipient$mailObject$mailContent);
  184.                                     } catch (\Throwable $e) {
  185.                                         \Sentry\captureException($e);
  186.                                     }
  187.                                 });
  188.                             }
  189.                         }
  190.                     }
  191.                 break;
  192.                 case "3_days_end":
  193.                     // Recall 3 days before participation ends for recipients who havn't answered
  194.                     $participations $entityManager->getRepository(Participation::class)->getParticipationsBefore3Days();
  195.                     foreach($participations as $participation){
  196.                         $template $entityManager->getRepository(MailTemplate::class)->findOneBy(array('type' => MailTemplateRepository::RECIPIENT_SECOND_RECALL'program' => $participation->getCampaign()->getProgram()));
  197.                         foreach ($participation->getRecipients() as $recipient){
  198.                             if($recipient->getStatus() == RecipientRepository::STATUS_ACTIVE && count($recipient->getQuizAnswers()) == 0){
  199.                                 // Générer l'URL du répondant
  200.                                 $recipientLink $this->generateUrl('quiz_answer', ['participationId' => $participation->getId() ,'token' => $recipient->getToken()],
  201.                                     UrlGeneratorInterface::ABSOLUTE_URL
  202.                                 );
  203.                                 $mailObject $template->getObject();
  204.                                 $mailObject str_replace('_FIRSTNAME_'$recipient->getFirstname(), $mailObject);
  205.                                 $mailObject str_replace('_FULLNAME_'$recipient->getParticipation()->getParticipant()->getFirstname()." ".$recipient->getParticipation()->getParticipant()->getLastname(), $mailObject);
  206.                                 $mailContent $template->getContent();
  207.                                 $mailContent str_replace('_LINK_'$recipientLink$mailContent);
  208.                                 $mailContent str_replace('_FIRSTNAME_'$recipient->getFirstname(), $mailContent);
  209.                                 $mailContent str_replace('_FULLNAME_'$recipient->getParticipation()->getParticipant()->getFirstname()." ".$recipient->getParticipation()->getParticipant()->getLastname(), $mailContent);
  210.                                 $formatterFR = new \IntlDateFormatter(
  211.                                     'fr_FR',
  212.                                     \IntlDateFormatter::LONG,
  213.                                     \IntlDateFormatter::NONE
  214.                                 );
  215.                                 $dateFormattedFR $formatterFR->format($participation->getEndDate());
  216.                                 $formatterEN = new \IntlDateFormatter(
  217.                                     'en_US',
  218.                                     \IntlDateFormatter::LONG,
  219.                                     \IntlDateFormatter::NONE
  220.                                 );
  221.                                 $dateFormattedEN $formatterEN->format($participation->getEndDate());
  222.                                 $mailContent str_replace("_FIN_DE_CAMPAGNE_"$dateFormattedFR$mailContent);
  223.                                 $mailContent str_replace("_END_OF_CAMPAIGN_"$dateFormattedEN$mailContent);
  224.                                 \Sentry\withScope(function (\Sentry\State\Scope $scope) use ($recipient$mailObject$mailContent$mailerManager) {
  225.                                     $scope->setUser([
  226.                                         'id' => $recipient->getId(),
  227.                                         'email' => $recipient->getEmail(),
  228.                                     ]);
  229.                                     $scope->setTag('type''email');
  230.                                     try {
  231.                                         $mailerManager->sendRecipientRecall($recipient$mailObject$mailContent);
  232.                                     } catch (\Throwable $e) {
  233.                                         \Sentry\captureException($e);
  234.                                     }
  235.                                 });
  236.                             }
  237.                         }
  238.                     }
  239.                 break;
  240.             }
  241.             return New Response(""200);
  242.         } else {
  243.             return New Response("access denied"401);
  244.         }
  245.     }
  246.     /**
  247.      * @Route("/cron/prepare/reports/{token}")
  248.      */
  249.     public function prepareReports($tokenRequest $requestEntityManagerInterface $entityManagerReportManager $reportManager)
  250.     {
  251.         if ($token == $this->CRON_TOKEN) {
  252.             $participationsWithReportsToGenerate $entityManager->getRepository(Participation::class)->getParticipationsWithReportsToGenerate();
  253.             foreach ($participationsWithReportsToGenerate as $participation){
  254.                 $reportManager->prepareParticipationReport($participation);
  255.                 // Check if campaign is over
  256.                 $campaign $participation->getCampaign();
  257.                 $otherParticipations $campaign->getParticipations();
  258.                 $endCampaign true;
  259.                 foreach ($otherParticipations as $otherParticipation) {
  260.                     if($otherParticipation->getReportData() == null){
  261.                         $endCampaign false;
  262.                     }
  263.                 }
  264.                 if($endCampaign){
  265.                     $campaign->setStatus(CampaignRepository::STATUS_FINISHED);
  266.                     $entityManager->persist($campaign);
  267.                     $entityManager->flush();
  268.                 }
  269.             }
  270.             return New Response(""200);
  271.         } else {
  272.             return New Response("access denied"401);
  273.         }
  274.     }
  275.     /**
  276.      * @Route("/cron/archive/campaigns/{token}")
  277.      */
  278.     public function archiveCampaigns($tokenRequest $requestEntityManagerInterface $entityManager)
  279.     {
  280.         if ($token == $this->CRON_TOKEN) {
  281.             $finishedCampaigns $entityManager->getRepository(Campaign::class)->findBy(array('status' => CampaignRepository::STATUS_FINISHED));
  282.             foreach ($finishedCampaigns as $campaign){
  283.                 $today = new DateTime();
  284.                 $end $campaign->getEndDate();
  285.                 $end $end->modify('+30 days');
  286.                 if($today $end){
  287.                     foreach ($campaign->getParticipations() as $participation) {
  288.                         $uid uniqid();
  289.                         $user $participation->getParticipant();
  290.                         $user->setFirstname("xxxxxxxx");
  291.                         $user->setLastname("xxxxxxxx");
  292.                         $user->setEmail("xxxxxxxx".$uid);
  293.                         $user->setUsername("xxxxxxxx".$uid);
  294.                         $user->setEnabled(false);
  295.                         $user->setRoles(array());
  296.                         $user->setDeletedAt(new \Datetime());
  297.                         $entityManager->persist($user);
  298.                         $entityManager->flush();
  299.                     }
  300.                     $campaign->setStatus(CampaignRepository::STATUS_ARCHIVED);
  301.                     $entityManager->persist($campaign);
  302.                     $entityManager->flush();
  303.                 }
  304.             }
  305.             return New Response(""200);
  306.         } else {
  307.             return New Response("access denied"401);
  308.         }
  309.     }
  310.     /**
  311.      * @Route("/cron/debug/mistral")
  312.      */
  313.     public function debugMistral(Request $requestEntityManagerInterface $entityManagerMistralManager $mistralManagerKernelInterface $kernel,  Environment $twigPdf $snappyMediaManagerInterface $mediaManager)
  314.     {
  315.         $participation $entityManager->getRepository(Participation::class)->find(5);
  316.         $strengths = array();
  317.         $weaknesses = array();
  318.         foreach($participation->getReportData()['questions'] as $i => $question){
  319.             if($i == 0){
  320.                 $strengths $mistralManager->generateWordCloud($participation->getParticipant()->getLocale(), $question['answers']);
  321.             }
  322.             if($i == 1){
  323.                 $weaknesses $mistralManager->generateWordCloud($participation->getParticipant()->getLocale(), $question['answers']);
  324.             }
  325.         }
  326.         $reportData $participation->getReportData();
  327.         $reportData['strengths'] = $strengths['data']['words'];
  328.         $reportData['weaknesses'] = $weaknesses['data']['words'];
  329.         $participation->setReportData($reportData);
  330.         $entityManager->persist($participation);
  331.         $entityManager->flush();
  332.         die();
  333.     }
  334. }