src/Controller/CronController.php line 80

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: mint
  5.  * Date: 14/11/19
  6.  * Time: 12:08
  7.  */
  8. namespace App\Controller;
  9. use App\Entity\PaidCourseList;
  10. use App\Entity\TeacherSchedule;
  11. use App\Entity\UserPlacementTest;
  12. use App\Notification\EmailNotification;
  13. use App\Notification\SlackClient;
  14. use App\Notification\SlackNotification\LevelTestSlackNotification;
  15. use App\Repository\HolidayRepository;
  16. use App\Repository\HomeworkRepository;
  17. use App\Repository\PaidCourseListRepository;
  18. use App\Repository\TeacherRepository;
  19. use App\Repository\TeacherScheduleRepository;
  20. use App\Repository\SubscriptionOrderRepository;
  21. use App\Repository\ActiveCampainSubscribeLostLogRepository;
  22. use App\Repository\SessionOrderRepository;
  23. use App\Repository\UserPlacementTestRepository;
  24. use DateTimeImmutable;
  25. use Doctrine\ORM\EntityManagerInterface;
  26. use Symfony\Bundle\FrameworkBundle\Console\Application;
  27. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  28. use Symfony\Component\Console\Input\ArrayInput;
  29. use Symfony\Component\Console\Output\BufferedOutput;
  30. use Symfony\Component\HttpFoundation\Request;
  31. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  32. use Symfony\Component\HttpKernel\KernelInterface;
  33. use Symfony\Component\Routing\Annotation\Route;
  34. use Symfony\Component\Filesystem\Filesystem;
  35. use App\Service\DropboxHelper;
  36. use App\Service\ActiveCampaignHelper;
  37. use App\Entity\Homework;
  38. use Symfony\Component\HttpFoundation\Response;
  39. /**
  40.  * @Route("/cron")
  41.  */
  42. class CronController extends AbstractController
  43. {
  44.     private $teacherScheduleRepository;
  45.     private $em;
  46.     private $paidCourseListRepository;
  47.     private $slackClient;
  48.     private $emailNotification;
  49.     private $homeworkRepository;
  50.     private $teacherRepository;
  51.     private $holidayRepository;
  52.     private $userPlacementTestRepository;
  53.     private $levelTestSlackNotification;
  54.     public function __construct(TeacherScheduleRepository $teacherScheduleRepositoryEntityManagerInterface $emPaidCourseListRepository $paidCourseListRepositorySlackClient $slackClientEmailNotification $emailNotificationHomeworkRepository $homeworkRepositoryTeacherRepository $teacherRepositoryHolidayRepository $holidayRepositoryUserPlacementTestRepository $userPlacementTestRepositoryLevelTestSlackNotification $levelTestSlackNotification)
  55.     {
  56.         $this->teacherScheduleRepository $teacherScheduleRepository;
  57.         $this->em $em;
  58.         $this->paidCourseListRepository $paidCourseListRepository;
  59.         $this->slackClient $slackClient;
  60.         $this->emailNotification $emailNotification;
  61.         $this->homeworkRepository $homeworkRepository;
  62.         $this->teacherRepository $teacherRepository;
  63.         $this->holidayRepository $holidayRepository;
  64.         $this->userPlacementTestRepository $userPlacementTestRepository;
  65.         $this->levelTestSlackNotification $levelTestSlackNotification;
  66.     }
  67.     /**
  68.      * @Route("/mail/{nbMessage}", name="mail", requirements={"nbMessage" = "\d+" }, defaults={"nbMessage"= 50})
  69.      */
  70.     public function sendSpool(Request $requestint $nbMessageKernelInterface $kernel): Response
  71.     {
  72.         if ($request->get('key') !== "9WQUYNHO8FVA1Z6TSP3R3Z3LSR667ZY9MU226S32") {
  73.             throw new NotFoundHttpException();
  74.         }
  75.         $application = new Application($kernel);
  76.         $application->setAutoExit(false);
  77.         $input = new ArrayInput(
  78.             [
  79.                 'command'         => 'swiftmailer:spool:send',
  80.                 '--message-limit' => $nbMessage,
  81.             ]
  82.         );
  83.         $output = new BufferedOutput();
  84.         $application->run($input$output);
  85.         $content $output->fetch();
  86.         return new Response($content);
  87.     }
  88.     /**
  89.      * @Route("/launch/addweek", name="cronjob_launch_addweek")
  90.      */
  91.     public function addWeekToAllFreeSchedules(Request $request): Response
  92.     {
  93.         if ($request->get('key') !== "4CUpjp16dF1aehxO") {
  94.             throw new NotFoundHttpException();
  95.         }
  96.         $currentDate = new \DateTimeImmutable('22:58');
  97.         $holiday $this->holidayRepository->findOneBy([
  98.             'name' => "Ramadan"
  99.         ]);
  100.         $holiday2 $this->holidayRepository->findOneBy([
  101.             'name' => "Eid Adha"
  102.         ]);
  103.         $startHoliday $holiday->getStartAt();
  104.         $endHoliday $holiday->getEndAt();
  105.         $startHoliday2 $holiday2->getStartAt();
  106.         $endHoliday2 $holiday2->getEndAt();
  107.         $freeSchedules $this->teacherScheduleRepository->findFreeSchedules();
  108.         //Rajouter une semaine à tous les plannings libre dont la date "isfree" est AVANT la date du jour
  109.         /** @var TeacherSchedule $schedule */
  110.         foreach ($freeSchedules as $schedule) {
  111.             //$oldFreeDate = DateTimeImmutable::createFromMutable($schedule->getFreeDate());
  112.             //$newFreeDate = $oldFreeDate->modify('+1 week');
  113.             $newFreeDate DateTimeImmutable::createFromMutable($schedule->getFreeDate());
  114.             if ($newFreeDate $startHoliday and $newFreeDate $endHoliday) {
  115.                 if ($schedule->getIsForLevelTest() == false){
  116.                     while ($newFreeDate $startHoliday and $newFreeDate $endHoliday) {
  117.                         $newFreeDate $newFreeDate->modify('+1 week');
  118.                     }
  119.                 }
  120.             }
  121.             if ($newFreeDate $startHoliday2 and $newFreeDate $endHoliday2) {
  122.                 if ($schedule->getIsForLevelTest() == false){
  123.                     while ($newFreeDate $startHoliday2 and $newFreeDate $endHoliday2) {
  124.                         $newFreeDate $newFreeDate->modify('+1 week');
  125.                     }
  126.                 }
  127.             }
  128.             while ($newFreeDate $currentDate){
  129.                 $newFreeDate $newFreeDate->modify('+1 week');
  130.             }
  131.             $schedule->setFreeDate($newFreeDate)
  132.                 ->setUpdateAt(new \DateTime());
  133.                 //->setUpdateBy('cron');
  134.             $this->em->persist($schedule);
  135.         }
  136.         $this->em->flush();
  137.         return new Response('semaine ajoutée avec success');
  138.     }
  139.     /**
  140.      * @Route("/launch/checkreport", name="cronjob_launch_checkreport")
  141.      */
  142.     public function checkReportsToStudentsSent(Request $request): Response
  143.     {
  144.         if ($request->get('key') !== "4CUpjp16dF1aehxO") {
  145.             throw new NotFoundHttpException();
  146.         }
  147.         $now = new \DateTimeImmutable();
  148.         $previousWeek $now->modify('-6 days');
  149.         $coursesOfTheWeek $this->paidCourseListRepository->getAllCoursesOfTheWeek($previousWeek$now);
  150.         $coursesWithoutReport = [];
  151.         $teachers = [];
  152.         /** @var PaidCourseList $course */
  153.         foreach ($coursesOfTheWeek as $course) {
  154.             if ($course->getSubscriptionLessonReport() == null) {
  155.                 $coursesWithoutReport[] = $course;
  156.                 $teachers[] = $course->getTeacherSchedule()->getTeacher()->getUserId()->getFullname();
  157.             }
  158.         }
  159.         if ($coursesWithoutReport != null) {
  160.             $results array_count_values($teachers);
  161.             //$this->slackClient->notifyAllNbOfReportNotSendByTeacher($results);
  162.             $this->emailNotification->sendResultCheckReportsNotSentToSecretary($coursesWithoutReport$now$previousWeek);
  163.             $this->slackClient->notifyTeacherPrivateReportNotSent($coursesWithoutReport);
  164.         }
  165.         return new Response('notification has been sent with success');
  166.     }
  167.     /**
  168.      * @Route("/launch/checkhomeworks", name="cronjob_launch_checkhomeworks")
  169.      */
  170.     public function checkUncorrectedHomework(Request $request): Response
  171.     {
  172.         ///launch/checkhomeworks?key=4CUpjp16dF1aehxO
  173.         if ($request->get('key') !== "4CUpjp16dF1aehxO") {
  174.             throw new NotFoundHttpException();
  175.         }
  176.         $grader $this->teacherRepository->findOneBy([
  177.             'isGrader' => true
  178.         ]);
  179.         $uncorrectedHomeworks $this->homeworkRepository->getUncorrectedHomeworkFromTwoDays();
  180.         $this->slackClient->notifyTeacherHomeworkUncorrected($uncorrectedHomeworks);
  181.         //$this->slackClient->notifyGraderHomeworkUncorrected($uncorrectedHomeworks, $grader);
  182.         //$this->slackClient->notifyAdminHomeworkUncorrected($uncorrectedHomeworks);
  183.         return new Response('rappel envoyé avec success');
  184.     }
  185.     /**
  186.      * @Route("/launch/checkleveltest", name="cronjob_launch_checkleveltest")
  187.      */
  188.     public function checkUncorrectedLevelTest(Request $request): Response
  189.     {
  190.         if ($request->get('key') !== "4CUpjp16dF1aehxO") {
  191.             throw new NotFoundHttpException();
  192.         }
  193.         //TODO REQUETE A VERIFIER
  194.         //$uncorrectedLevelTest = $this->userPlacementTestRepository->findUncorrectedLevelTest();
  195.         //$this->levelTestSlackNotification->alertUncorrectedTest($uncorrectedLevelTest);
  196.         return new Response('rappel envoyé avec success');
  197.     }
  198.     /**
  199.      * @Route("/launch/checkunbookedleveltest", name="cronjob_launch_checkunbookedleveltest")
  200.      */
  201.     public function checkUnbookedLevelTest(Request $requestEmailNotification\LevelTestEmailNotification $emailNotification): Response
  202.     {
  203.         if ($request->get('key') !== "4CUpjp16dF1aehxO") {
  204.             throw new NotFoundHttpException();
  205.         }
  206.         $unbookededLevelTest $this->userPlacementTestRepository->findUnbookedLevelTestForReminder();
  207.         // a envoyer lundi, mercredi samedi à 3h du mat
  208.         /** @var UserPlacementTest $test */
  209.         foreach ($unbookededLevelTest as $test){
  210.             $emailNotification->sendReminderToStudentToBookTest($test);
  211.         }
  212.         return new Response('rappel envoyé avec success');
  213.     }
  214.     /**
  215.      * @Route("/supprimer-devoirs-expirer", name="supprimer_devoirs_expirer")
  216.      * @param Request $request
  217.      * @param EntityManagerInterface $em
  218.      * @param Filesystem $filesystem
  219.      * @param DropboxHelper $dropBox
  220.      * @return Response
  221.      */
  222.     public function deleteHomework(Request $requestEntityManagerInterface $emFilesystem $filesystemDropboxHelper $dropBox): Response
  223.     {
  224.         if ($request->get('key') !== "3AKZp7q8emtgKJvdH7") {
  225.             throw new NotFoundHttpException();
  226.         }
  227.         $em->getConnection()->getConfiguration()->setSQLLogger(null);
  228.         $i 1;
  229.         $batchSize 200;
  230.         $limit 0;
  231.         // recuperer les anciens devoirs 
  232.         $oldHomeworks $em->getRepository(Homework::class)->getOldHomeworksForExpiredCourses($limit);
  233.         $log "";
  234.         foreach ($oldHomeworks as $homework) {
  235.             if ($homework->getRelatedToSubscription() != null or $homework->getRelatedToGroupCourses() != null) {
  236.                 if ($homework->getRelatedToSubscription() != null)
  237.                     $log .= "Supression des devoirs de l'abonnement n° : " $homework->getRelatedToSubscription()->getId() . " dernier cours: " $homework->getRelatedToSubscription()->getLastPaidCourse()->format('d/m/Y') . "<br>";
  238.                 if ($homework->getRelatedToGroupCourses())
  239.                     $log .= "Supression des devoirs de groupe de l'élève n° : " $homework->getRelatedToGroupCourses()->getId() . " dernier cours : " $homework->getRelatedToGroupCourses()->getSession()->getEndDate()->format('d/m/Y') . "<br>";
  240.             }
  241.             // supprimer les fichiers attacher au devoirs 
  242.             $homeworks $homework->getHomeworkFiles();
  243.             foreach ($homeworks as $doc) {
  244.                 //  Supprimer le fichier dans Dropbox 
  245.                 if ($doc->getIsDropBox()) {
  246.                     $json $doc->getDropBoxJson();
  247.                     $data json_decode($json);
  248.                     $dropBox->supprimerFichier($data);
  249.                 } else {
  250.                     $filename $doc->getFileName();
  251.                     if ($filesystem->exists($filename)) {
  252.                         $filesystem->remove($filename);
  253.                     }
  254.                 }
  255.                 $em->remove($doc);
  256.             }
  257.             // supprimer les fichiers attacher au corrections
  258.             $corrections $homework->getCorrectionFiles();
  259.             foreach ($corrections as $file) {
  260.                 //  Supprimer le fichier dans Dropbox 
  261.                 if ($file->getIsDropBox()) {
  262.                     $json $file->getDropBoxJson();
  263.                     $data json_decode($json);
  264.                     $dropBox->supprimerFichier($data);
  265.                 } else {
  266.                     $filename $file->getFileName();
  267.                     if ($filesystem->exists($filename)) {
  268.                         $filesystem->remove($filename);
  269.                     }
  270.                 }
  271.                 $em->remove($file);
  272.             }
  273.             //ici on efface LE Devoir
  274.             $em->remove($homework);
  275.             $i++;
  276.             if (($i $batchSize) === 0) {
  277.                 $em->flush();
  278.             }
  279.         }
  280.         $em->flush();
  281.         $em->clear();
  282.         return new Response($log);
  283.     }
  284.     /**
  285.      * @Route("/test-active-campaign", name="test_active_campaign")
  286.      * @param Request $request
  287.      * @param EntityManagerInterface $em
  288.      * @param Filesystem $filesystem
  289.      * @param ActiveCampaignHelper $activeCampaign
  290.      * @return Response
  291.      */
  292.     public function testActiveCampaign(Request $requestEntityManagerInterface $emFilesystem $filesystemActiveCampaignHelper $activeCampaignHelperSubscriptionOrderRepository $subscriptionOrderRepositorySessionOrderRepository $sessionOrderRepository): Response
  293.     {
  294.         if ($request->get('key') !== "3AKZp7q8emtgKJvdH7") {
  295.             throw new NotFoundHttpException();
  296.         }
  297.         $log "";
  298.         $em->getConnection()->getConfiguration()->setSQLLogger(null);
  299.         $debug true;
  300.         if ($debug) {
  301.             // Tester SubscriptionOrder *********************************
  302.             $idtest 2234// sans participant
  303.             //$idtest = 3031 ; // avec participant 
  304.             $subscriptionOrder $subscriptionOrderRepository->findOneBy(['id' => $idtest]);
  305.             // Abonnement 
  306.             //$activeCampaignHelper->addOrder($subscriptionOrder);
  307.             // Désabonnement
  308.             $activeCampaignHelper->unsubscribeOrder($subscriptionOrder);
  309.             // Tester SessionOrder **************************************
  310.             //$idtest = 605; // sans participant
  311.             $idtest 597// avec participant
  312.             $sessionOrder $sessionOrderRepository->findOneBy(['id' => $idtest]);
  313.             // Abonnement 
  314.             //$activeCampaignHelper->addOrder($sessionOrder);
  315.             // Désabonnement
  316.             $activeCampaignHelper->unsubscribeOrder($sessionOrder);
  317.         }
  318.         return new Response($log);
  319.     }
  320.     /**
  321.      * @Route("/update-contact-unsubscribe", name="update_contact_unsubscribe")
  322.      * @param Request $request
  323.      * @param EntityManagerInterface $em
  324.      * @param Filesystem $filesystem
  325.      * @param ActiveCampaignHelper $activeCampaign
  326.      * @return Response
  327.      */
  328.     public function updateContactUnsubscribe(Request $requestEntityManagerInterface $emFilesystem $filesystemSubscriptionOrderRepository $subscriptionOrderRepositoryActiveCampaignHelper $activeCampaignHelperSessionOrderRepository $sessionOrderRepository): Response
  329.     {
  330.         if ($request->get('key') !== "3AKZp7q8emtgKJvdH7") {
  331.             throw new NotFoundHttpException();
  332.         }
  333.         $em->getConnection()->getConfiguration()->setSQLLogger(null);
  334.         $log "";
  335.         $executeUnsubscribe $request->get('executeUnsubscribe');
  336.         $i 1;
  337.         $batchSize 10;
  338.         $limit 50;
  339.         // recuperer Subscription Orders OLD
  340.         $subscriptionOrders $subscriptionOrderRepository->getCanceledStudentWithoutRemainCourses($limit);
  341.         $log .= " ************************* Debut SubscriptionOrder *************************** <br>";
  342.         foreach ($subscriptionOrders as $order) {
  343.             $user $order->getUser();
  344.             $participant $order->getParticipant();
  345.             $log .= "SubscriptionOrder N° " $order->getId() . " est Canceled <br>";
  346.             $log .= "User : <strong>" $user->getLastName() . " " $user->getFirstName() . "</strong> - Email : <strong>" $user->getEmail() . "</strong> <br>";
  347.             if ($participant != null) {
  348.                 $log .= "Participant : <strong>" $participant->getLastName() . " " $participant->getFirstName() . "</strong> <br>";
  349.             }
  350.             $log .= "<br>";
  351.             if ($executeUnsubscribe == 1) {
  352.                 $log .= "Unsubscribe : OK !! <br>";
  353.                 $activeCampaignHelper->unsubscribeOrder($order);
  354.                 $log .= "<br>";
  355.             }
  356.             $i++;
  357.             if (($i $batchSize) === 0) {
  358.                 $em->flush();
  359.             }
  360.         }
  361.         $em->flush();
  362.         $em->clear();
  363.         $log .= " ************************* Fin SubscriptionOrder *************************** <br>";
  364.         // Get All Oold Session Orders     
  365.         $sessionsOrders $sessionOrderRepository->getAllOldOrderSession($limit);
  366.         $log .= " ************************* Debut SessionOrder *************************** <br><br>";
  367.         $i 1;
  368.         foreach ($sessionsOrders as $order) {
  369.             $user $order->getStudents();
  370.             $participant $order->getParticipant();
  371.             $log .= "SessionOrder N° " $order->getId() . " est Expirer <br>";
  372.             $log .= "User : <strong>" $user->getLastName() . " " $user->getFirstName() . "</strong> - Email : <strong>" $user->getEmail() . "</strong> <br>";
  373.             if ($participant != null) {
  374.                 $log .= "Participant : <strong>" $participant->getLastName() . " " $participant->getFirstName() . "</strong> <br>";
  375.             }
  376.             $log .= "<br>";
  377.             if ($executeUnsubscribe == 1) {
  378.                 $log .= "Unsubscribe : OK !! <br>";
  379.                 $activeCampaignHelper->unsubscribeOrder($order);
  380.                 $log .= "<br>";
  381.             }
  382.             $i++;
  383.             if (($i $batchSize) === 0) {
  384.                 $em->flush();
  385.             }
  386.         }
  387.         $em->flush();
  388.         $em->clear();
  389.         $log .= " ************************* Fin SessionOrder *************************** <br>";
  390.         return new Response($log);
  391.     }
  392.     /**
  393.      * @Route("/add-contact-subscribe-lost", name="add_contact_subscribe_lost")
  394.      * @param Request $request
  395.      * @param EntityManagerInterface $em
  396.      * @param Filesystem $filesystem
  397.      * @param ActiveCampaignHelper $activeCampaign
  398.      * @return Response
  399.      */
  400.     public function addContactSubscribeLost(Request $requestEntityManagerInterface $emFilesystem $filesystemActiveCampainSubscribeLostLogRepository $activeCampainSubscribeLostLogRepositoryActiveCampaignHelper $activeCampaignHelper): Response
  401.     {
  402.         if ($request->get('key') !== "3AKZp7q8emtgKJvdH7") {
  403.             throw new NotFoundHttpException();
  404.         }
  405.         $log "";
  406.         // recuperer Subscription Orders OLD
  407.         $subscribeLostLogs $activeCampainSubscribeLostLogRepository->findAll();
  408.         foreach ($subscribeLostLogs as $subscribeLostLog) {
  409.             if ($subscribeLostLog->getSubscription() != null) {
  410.                 $log .= " ************************* Debut SubscriptionOrder *************************** <br>";
  411.                 $order $subscribeLostLog->getSubscription();
  412.                 if ($activeCampaignHelper->addOrder($order)) {
  413.                     $user $order->getUser();
  414.                     $participant $order->getParticipant();
  415.                     $log .= "SubscriptionOrder N° " $order->getId() . " a été Ajouter <br>";
  416.                     $log .= "User : <strong>" $user->getLastName() . " " $user->getFirstName() . "</strong> - Email : <strong>" $user->getEmail() . "</strong> <br>";
  417.                     if ($participant != null) {
  418.                         $log .= "Participant : <strong>" $participant->getLastName() . " " $participant->getFirstName() . "</strong> <br>";
  419.                     }
  420.                     $this->em->remove($subscribeLostLog);
  421.                     $this->em->flush();
  422.                 }
  423.                 $log .= "<br>";
  424.                 $log .= " ************************* Fin SubscriptionOrder *************************** <br>";
  425.             }
  426.             if ($subscribeLostLog->getGroupSession() != null) {
  427.                 $log .= " ************************* Debut SessionOrder *************************** <br><br>";
  428.                 $order $subscribeLostLog->getGroupSession();
  429.                 $log .= "<br>";
  430.                 if ($activeCampaignHelper->addOrder($order)) {
  431.                     $user $order->getStudents();
  432.                     $participant $order->getParticipant();
  433.                     $log .= "SessionOrder N° " $order->getId() . " a ete Ajouter <br>";
  434.                     $log .= "User : <strong>" $user->getLastName() . " " $user->getFirstName() . "</strong> - Email : <strong>" $user->getEmail() . "</strong> <br>";
  435.                     if ($participant != null) {
  436.                         $log .= "Participant : <strong>" $participant->getLastName() . " " $participant->getFirstName() . "</strong> <br>";
  437.                     }
  438.                     $this->em->remove($subscribeLostLog);
  439.                     $this->em->flush();
  440.                 }
  441.                 $log .= "<br>";
  442.                 $log .= " ************************* Fin SessionOrder *************************** <br>";
  443.             }
  444.         }
  445.         return new Response($log);
  446.     }
  447. }