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.                                 \Sentry\withScope(function (\Sentry\State\Scope $scope) use ($recipient$mailObject$mailContent$mailerManager) {
  163.                                     $scope->setUser([
  164.                                         'id' => $recipient->getId(),
  165.                                         'email' => $recipient->getEmail(),
  166.                                     ]);
  167.                                     $scope->setTag('type''email');
  168.                                     try {
  169.                                         $mailerManager->sendRecipientRecall($recipient$mailObject$mailContent);
  170.                                     } catch (\Throwable $e) {
  171.                                         \Sentry\captureException($e);
  172.                                     }
  173.                                 });
  174.                             }
  175.                         }
  176.                     }
  177.                 break;
  178.                 case "3_days_end":
  179.                     // Recall 3 days before participation ends for recipients who havn't answered
  180.                     $participations $entityManager->getRepository(Participation::class)->getParticipationsBefore3Days();
  181.                     foreach($participations as $participation){
  182.                         $template $entityManager->getRepository(MailTemplate::class)->findOneBy(array('type' => MailTemplateRepository::RECIPIENT_SECOND_RECALL'program' => $participation->getCampaign()->getProgram()));
  183.                         foreach ($participation->getRecipients() as $recipient){
  184.                             if($recipient->getStatus() == RecipientRepository::STATUS_ACTIVE && count($recipient->getQuizAnswers()) == 0){
  185.                                 // Générer l'URL du répondant
  186.                                 $recipientLink $this->generateUrl('quiz_answer', ['participationId' => $participation->getId() ,'token' => $recipient->getToken()],
  187.                                     UrlGeneratorInterface::ABSOLUTE_URL
  188.                                 );
  189.                                 $mailObject $template->getObject();
  190.                                 $mailObject str_replace('_FIRSTNAME_'$recipient->getFirstname(), $mailObject);
  191.                                 $mailObject str_replace('_FULLNAME_'$recipient->getParticipation()->getParticipant()->getFirstname()." ".$recipient->getParticipation()->getParticipant()->getLastname(), $mailObject);
  192.                                 $mailContent $template->getContent();
  193.                                 $mailContent str_replace('_LINK_'$recipientLink$mailContent);
  194.                                 $mailContent str_replace('_FIRSTNAME_'$recipient->getFirstname(), $mailContent);
  195.                                 $mailContent str_replace('_FULLNAME_'$recipient->getParticipation()->getParticipant()->getFirstname()." ".$recipient->getParticipation()->getParticipant()->getLastname(), $mailContent);
  196.                                 \Sentry\withScope(function (\Sentry\State\Scope $scope) use ($recipient$mailObject$mailContent$mailerManager) {
  197.                                     $scope->setUser([
  198.                                         'id' => $recipient->getId(),
  199.                                         'email' => $recipient->getEmail(),
  200.                                     ]);
  201.                                     $scope->setTag('type''email');
  202.                                     try {
  203.                                         $mailerManager->sendRecipientRecall($recipient$mailObject$mailContent);
  204.                                     } catch (\Throwable $e) {
  205.                                         \Sentry\captureException($e);
  206.                                     }
  207.                                 });
  208.                             }
  209.                         }
  210.                     }
  211.                 break;
  212.             }
  213.             return New Response(""200);
  214.         } else {
  215.             return New Response("access denied"401);
  216.         }
  217.     }
  218.     /**
  219.      * @Route("/cron/prepare/reports/{token}")
  220.      */
  221.     public function prepareReports($tokenRequest $requestEntityManagerInterface $entityManagerReportManager $reportManager)
  222.     {
  223.         if ($token == $this->CRON_TOKEN) {
  224.             $participationsWithReportsToGenerate $entityManager->getRepository(Participation::class)->getParticipationsWithReportsToGenerate();
  225.             foreach ($participationsWithReportsToGenerate as $participation){
  226.                 $reportManager->prepareParticipationReport($participation);
  227.                 // Check if campaign is over
  228.                 $campaign $participation->getCampaign();
  229.                 $otherParticipations $campaign->getParticipations();
  230.                 $endCampaign true;
  231.                 foreach ($otherParticipations as $otherParticipation) {
  232.                     if($otherParticipation->getReportData() == null){
  233.                         $endCampaign false;
  234.                     }
  235.                 }
  236.                 if($endCampaign){
  237.                     $campaign->setStatus(CampaignRepository::STATUS_FINISHED);
  238.                     $entityManager->persist($campaign);
  239.                     $entityManager->flush();
  240.                 }
  241.             }
  242.             return New Response(""200);
  243.         } else {
  244.             return New Response("access denied"401);
  245.         }
  246.     }
  247.     /**
  248.      * @Route("/cron/archive/campaigns/{token}")
  249.      */
  250.     public function archiveCampaigns($tokenRequest $requestEntityManagerInterface $entityManager)
  251.     {
  252.         if ($token == $this->CRON_TOKEN) {
  253.             $finishedCampaigns $entityManager->getRepository(Campaign::class)->findBy(array('status' => CampaignRepository::STATUS_FINISHED));
  254.             foreach ($finishedCampaigns as $campaign){
  255.                 $today = new DateTime();
  256.                 $end $campaign->getEndDate();
  257.                 $end $end->modify('+30 days');
  258.                 if($today $end){
  259.                     foreach ($campaign->getParticipations() as $participation) {
  260.                         $uid uniqid();
  261.                         $user $participation->getParticipant();
  262.                         $user->setFirstname("xxxxxxxx");
  263.                         $user->setLastname("xxxxxxxx");
  264.                         $user->setEmail("xxxxxxxx".$uid);
  265.                         $user->setUsername("xxxxxxxx".$uid);
  266.                         $user->setEnabled(false);
  267.                         $user->setRoles(array());
  268.                         $user->setDeletedAt(new \Datetime());
  269.                         $entityManager->persist($user);
  270.                         $entityManager->flush();
  271.                     }
  272.                     $campaign->setStatus(CampaignRepository::STATUS_ARCHIVED);
  273.                     $entityManager->persist($campaign);
  274.                     $entityManager->flush();
  275.                 }
  276.             }
  277.             return New Response(""200);
  278.         } else {
  279.             return New Response("access denied"401);
  280.         }
  281.     }
  282.     /**
  283.      * @Route("/cron/debug/mistral")
  284.      */
  285.     public function debugMistral(Request $requestEntityManagerInterface $entityManagerMistralManager $mistralManagerKernelInterface $kernel,  Environment $twigPdf $snappyMediaManagerInterface $mediaManager)
  286.     {
  287.         $participation $entityManager->getRepository(Participation::class)->find(5);
  288.         $strengths = array();
  289.         $weaknesses = array();
  290.         foreach($participation->getReportData()['questions'] as $i => $question){
  291.             if($i == 0){
  292.                 $strengths $mistralManager->generateWordCloud($participation->getParticipant()->getLocale(), $question['answers']);
  293.             }
  294.             if($i == 1){
  295.                 $weaknesses $mistralManager->generateWordCloud($participation->getParticipant()->getLocale(), $question['answers']);
  296.             }
  297.         }
  298.         $reportData $participation->getReportData();
  299.         $reportData['strengths'] = $strengths['data']['words'];
  300.         $reportData['weaknesses'] = $weaknesses['data']['words'];
  301.         $participation->setReportData($reportData);
  302.         $entityManager->persist($participation);
  303.         $entityManager->flush();
  304.         die();
  305.     }
  306. }