src/Controller/MassiveNotificationController.php line 397

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\Routing\Annotation\Route;
  6. use App\Entity\Menu;
  7. use App\Entity\User;
  8. use App\Entity\UserToken;
  9. use App\Entity\Notification;
  10. use App\Entity\MassiveNotification;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  15. use App\Service\AppApiService;
  16. use App\Service\FirebaseService;
  17. use App\Service\NotificationService;
  18. use App\Entity\AppPersonalAccount;
  19. use App\Entity\MediaObject;
  20. use App\Entity\AppCounterReading;
  21. use App\Entity\DataReception;
  22. use App\Entity\Accounts;
  23. use App\Entity\ServiceOrderHistory;
  24. use Symfony\Component\HttpKernel\KernelInterface
  25. use Psr\Log\LoggerInterface;
  26. use Sentry;
  27. use App\Repository\NotificationRepository;
  28. use App\Message\NotificationMessage;
  29. use Symfony\Component\Messenger\MessageBusInterface;
  30. use Symfony\Component\Messenger\Bridge\Amqp\Transport\AmqpStamp;
  31. use Symfony\Component\Messenger\Stamp\SentStamp;
  32. use Symfony\Component\Messenger\Exception\TransportExceptionInterface;
  33. use Symfony\Component\Security\Core\Security;
  34. class MassiveNotificationController extends AbstractController
  35. {
  36.     public $datetime;
  37.     public $entityManager;
  38.     public $passwordEncoder;
  39.     public $appApiService;
  40.     public $firebaseService;
  41.     public $notificationService;
  42.     public $notifications;
  43.     private $kernel;
  44.     private LoggerInterface $logger;
  45.     private $bus;
  46.     private Security $security;
  47.     
  48.     public function __construct
  49.         ?\DateTimeInterface $datetime
  50.         EntityManagerInterface $entityManager
  51.         AppApiService $appApiService
  52.         KernelInterface $kernel
  53.         FirebaseService $firebaseService
  54.         NotificationService $notificationService
  55.         LoggerInterface $logger,  
  56.         NotificationRepository $notifications,
  57.         MessageBusInterface $bus,
  58.         Security $security
  59.     ){
  60.         $this->datetime $datetime;
  61.         $this->entityManager $entityManager;
  62.         $this->appApiService $appApiService;
  63.         $this->firebaseService $firebaseService;
  64.         $this->notificationService $notificationService;
  65.         $this->kernel $kernel;
  66.         $this->logger $logger;
  67.         $this->notifications $notifications;
  68.         $this->bus $bus;
  69.         $this->security $security;
  70.     }
  71.     public function valid($requestFilds$requiredFilds){
  72.         $errors '';
  73.         foreach($requiredFilds as $f){
  74.             if(!isset($requestFilds[$f]))
  75.                 $errors .= $f"
  76.         }
  77.         return $errors;
  78.     }
  79.     
  80.     private function customAuth($request){
  81.         $validUser $_ENV['MY_API_USER'];
  82.         $validPassword $_ENV['MY_API_PASSWORD'];
  83.         $login $request->server->get('PHP_AUTH_USER');
  84.         $password $request->server->get('PHP_AUTH_PW');
  85.         if ($login !== $validUser || $password !== $validPassword) {
  86.             return false;
  87.         }
  88.         return true;
  89.     }
  90.     // #[Route('/api/massive/notification-create', name: 'massive_create_notfication', methods: ['POST'])]
  91.     // public function massive_create_notfication(Request $request)
  92.     // {
  93.     //     $user = $this->security->getUser();
  94.     //     $data = json_decode($request->getContent(), true);
  95.     //     // if( $this->)
  96.     //     echo '<pre>'; print_r($data);
  97.     //     $massiveNotification = new \App\Entity\MassiveNotification();
  98.     //     $massiveNotification->setName('Масове сповіщення '.date('Y-m-d H:i:s'));
  99.     //     $massiveNotification->setTitle($data['title']);
  100.     //     $massiveNotification->setBody($data['body']);
  101.     //     $massiveNotification->setType('i'));
  102.     //     echo 'ok'; die;
  103.     // }
  104.     
  105.     private function searchIdByToken$targetToken$data) {
  106.         $foundId null
  107.         foreach ($data as $id => $tokens) {          // $data = твій великий Array
  108.             if (!is_array($tokens)) continue;
  109.             if (in_array($targetToken$tokenstrue)) { // true = строгe порівняння
  110.                 $foundId $id;
  111.                 break;
  112.             }
  113.         }
  114.         return $foundId;
  115.     }
  116.     #[Route('/api/send-notfication-masive'name'send_notfication_masive'methods: ['GET'])]
  117.     public function send_notfication_masive(Request $request)
  118.     {
  119.         $send 0;
  120.         $err 0;
  121.         
  122.         /** Масовані розсилки розділені ns_msg_id, бо в них однакові тексти, тому шукаю перший ліпший і потім всі інші по ns_msg_id  */
  123.         $MassiveNotification $this->entityManager->getRepository(MassiveNotification::class)->findOneBy(['status' => 'new']);
  124.         // $firstNotification = $this->entityManager->getRepository(Notification::class)->findOneBy(['status' => 'new_all', 'allUsers' => true, 'massiveNotification' => $MassiveNotification]);
  125.         if($MassiveNotification){
  126.             file_put_contents('/var/www/symfony_docker/var/log/MassiveNotification.log',  $MassiveNotification->getId() . " NOTIFICATIONS Massive ************************" .  date('H:i:s') . "\n"FILE_APPEND);
  127.             $notifications $this->entityManager->getRepository(Notification::class)->findBy(['status' => 'new_all''massiveNotification' => $MassiveNotification]);
  128.             
  129.             if(count($notifications) == 0){
  130.                 file_put_contents('/var/www/symfony_docker/var/log/MassiveNotification.log',  $MassiveNotification->getId() .  date('H:i:s') . "Немає нових сповіщень для розсилки\n"FILE_APPEND);
  131.                 $MassiveNotification->setStatus('error');
  132.                 $MassiveNotification->setDescription('Немає нових сповіщень для розсилки');
  133.                 $this->entityManager->persist($MassiveNotification);
  134.                 $this->entityManager->flush();
  135.                 $response = new JsonResponse();
  136.                 $response->setData(['send' => 0'err' => 0'error' => 'Немає нових сповіщень для розсилки']); 
  137.                 return $response
  138.             }
  139.             file_put_contents('/var/www/symfony_docker/var/log/MassiveNotification.log',  "MassiveNotification ID: " $MassiveNotification->getId() .  date('H:i:s') . " Кількість сповіщень: " count($notifications) . "\n"FILE_APPEND);
  140.             // echo count($notifications);
  141.             // die;
  142.             $unikTokensNotificationsId = [];
  143.             $unikTokens = [];
  144.                 if($notifications){
  145.                     // Витягуємо всі ID
  146.                         $notificationIds array_map(fn($n) => $n->getId(), $notifications);
  147.                         // Масове оновлення статусу та дати
  148.                         $this->entityManager->createQuery(
  149.                             'UPDATE App\Entity\Notification n
  150.                             SET n.status = :newStatus, 
  151.                                 n.dateSend = :now 
  152.                             WHERE n.id IN (:ids)'
  153.                         )
  154.                         ->setParameter('newStatus''in_progress')
  155.                         ->setParameter('now', new \DateTime())
  156.                         ->setParameter('ids'$notificationIds)
  157.                         ->execute();
  158.                     file_put_contents('/var/www/symfony_docker/var/log/MassiveNotification.log',  "MassiveNotification ID: " $MassiveNotification->getId() .  date('H:i:s') . " Поставили статус in_progress: " count($notificationIds) . "\n"FILE_APPEND);
  159.                     /** Шукаю ключі  Fcm */
  160.                     foreach($notifications as $notification){
  161.                         $send 0;
  162.                         $user $notification->getUsers();
  163.                         // $tokensArr = [];
  164.                         if($user){
  165.                             $device_id $user->getDeviceId();
  166.                             $tokens $this->entityManager->getRepository(UserToken::class)->findBy(['users' => $user'active' => true]);
  167.                             if(empty($tokens)){
  168.                                 $notification->setStatus('not_token');
  169.                                 $notification->setError($notification->getError() .  "\n" date('Y-m-d H:i:s') . "Не вказані токени користувача");
  170.                                 $this->entityManager->persist($notification);
  171.                                 continue;
  172.                             }
  173.                             $search_dublicate_tokens = [];
  174.                             foreach($tokens as $token){
  175.                                 if(empty($token->getTokenFcm())){
  176.                                     $token->setActive(false);
  177.                                     $this->entityManager->persist($token);
  178.                                     continue;
  179.                                 }
  180.                                 $unikTokensNotificationsId[$notification->getId()][]= $token->getTokenFcm();
  181.                                 $unikTokens[]= $token->getTokenFcm();
  182.                                 // file_put_contents('/var/www/symfony_docker/var/log/errorrrrrr.log',  "st - " .  date('H:i:s') . "\n", FILE_APPEND);
  183.                             }
  184.                         }else{
  185.                             $notification->setStatus('error');
  186.                             $notification->setError($notification->getError() .  "\n" date('Y-m-d H:i:s') . "Користувач не знайдений");
  187.                             $this->entityManager->persist($notification);
  188.                             continue;
  189.                         }
  190.                             
  191.                     }
  192.                     $this->entityManager->flush();
  193.                 }else{
  194.                     $rez = ['rez' => false'error' => "Незнайдено нових сповіщень!"];
  195.                 }
  196.                 
  197.             
  198.             /** Беру тільки унікальні ключі */
  199.             $unikTokens =  array_unique($unikTokens) ;
  200.             
  201.             if(count($unikTokens) > 0){
  202.                 file_put_contents('/var/www/symfony_docker/var/log/MassiveNotification.log',  "MassiveNotification ID: " $MassiveNotification->getId() .  date('H:i:s') . " Унікальних токенів для розсилки: " count($unikTokens) . "\n"FILE_APPEND);
  203.                 /** Розділяю по чергах 450 бо там ліміт 500*/
  204.                 $chunks array_chunk($unikTokens450);
  205.            
  206.                 /** йду почергах */
  207.                 foreach($chunks as $key => $chunkToken){
  208.                     file_put_contents('/var/www/symfony_docker/var/log/MassiveNotification.log',  "MassiveNotification ID: " $MassiveNotification->getId() .  date('H:i:s') . " Обробка черги номер: " . ($key 1) . "\n"FILE_APPEND);
  209.                     $resultJson $this->firebaseService->massiveTokensSendCurl([
  210.                         'tokens' => $chunkToken,
  211.                         'title' => $MassiveNotification->getTitle(),
  212.                         'body' => $MassiveNotification->getBody(),
  213.                         'type' => 'text',
  214.                     ]);
  215.                 
  216.                     // file_put_contents('/var/www/symfony_docker/var/log/MassiveNotification.log',  "MassiveNotification ID: " . $MassiveNotification->getId() .  date('H:i:s') . " Результат розсилки: " . $resultJson . "\n", FILE_APPEND);
  217.                     $results json_decode($resultJsontrue);
  218.                     /** Обробка результатів */
  219.                     $errorsIds = [];
  220.                     $successIds = [];
  221.                         foreach($results['Responses'] as $i => $res){
  222.                             /** Шукаю id всіх відправлених і дані всіх не відправлених */
  223.                             if(!$res['Success']){
  224.                                 $t $chunkToken[$i];
  225.                                 $idN $this->searchIdByToken($t$unikTokensNotificationsId);
  226.                                 $errorsIds[] = $idN;
  227.                                 $errors[$idN] = [
  228.                                     'id_notification' => $idN,
  229.                                     'token' => $t,
  230.                                     'error' => $res['Error']
  231.                                 ];
  232.                             }else{
  233.                                 $t $chunkToken[$i];
  234.                                 $idN $this->searchIdByToken($t$unikTokensNotificationsId);
  235.                                 $successIds[] = $idN;
  236.                             }
  237.                         }
  238.                         if(count($successIds) > 0){
  239.                             /** Оновлю всі відправленні */
  240.                         
  241.                            // Масове оновлення статусу та дати
  242.                             $this->entityManager->createQuery(
  243.                                 'UPDATE App\Entity\Notification n
  244.                                 SET n.status = :newStatus
  245.                                 WHERE n.id IN (:ids)'
  246.                             )
  247.                             ->setParameter('newStatus''send')
  248.                             ->setParameter('ids'$successIds)
  249.                             ->execute();
  250.                         }
  251.                         if(count($errorsIds) > 0){
  252.                             /** Обробляю всі з помилками */
  253.                             foreach($notifications as $notification){
  254.                                 if(in_array($notification->getId(), $errorsIds)){
  255.                                     $notification->setStatus('error');
  256.                                     $errorInfo $errors[$notification->getId()];
  257.                                     $notification->setError($notification->getError() .  "\n" date('Y-m-d H:i:s') . $errorInfo['token'] . "\n" $errorInfo['error']);
  258.                                     $this->entityManager->persist($notification);
  259.                                 }
  260.                             }
  261.                             $this->entityManager->flush();
  262.                         }
  263.                         file_put_contents('/var/www/symfony_docker/var/log/MassiveNotification.log',  "MassiveNotification ID: " $MassiveNotification->getId() .  date('H:i:s') . " Черга номер: " . ($key 1) . " Відправлено: " count($successIds) . " Помилок: " count($errorsIds) . "\n"FILE_APPEND);
  264.                 }
  265.                 /** Оновлюю статус масового сповіщення */
  266.                 $MassiveNotification->setStatus('send');
  267.                 $MassiveNotification->setDescription('Розсилка завершена. Відправлено ' count($successIds) . ' сповіщень, з помилками ' count($errorsIds));
  268.                 $this->entityManager->persist($MassiveNotification);
  269.                 $this->entityManager->flush();
  270.                 file_put_contents('/var/www/symfony_docker/var/log/MassiveNotification.log',  "MassiveNotification ID: " $MassiveNotification->getId() .  date('H:i:s') . " Розсилка завершена. Відправлено: " count($successIds) . " Помилок: " count($errorsIds) . "\n"FILE_APPEND);
  271.             }else{
  272.                 $MassiveNotification->setStatus('error');
  273.                 $MassiveNotification->setDescription('Немає токенів для розсилки');
  274.                 $this->entityManager->persist($MassiveNotification);
  275.                 $this->entityManager->flush();
  276.             }
  277.          
  278.             $response = new JsonResponse();
  279.             $response->setData(['send' => count($successIds), 'err' => count($errorsIds)]);
  280.             file_put_contents('/var/www/symfony_docker/var/log/errorrrrrr.log',  "***********END*************" .  date('H:i:s') . "\n"FILE_APPEND);
  281.             return $response;
  282.         }else{
  283.             $response = new JsonResponse();
  284.             $response->setData(['send' => 0'err' => 0'error' => 'Нема масових сповіщень']);
  285.             return $response;
  286.         }
  287.     }
  288.     /**
  289.      * шукаю сповіщення які зависли в in_progress
  290.      */
  291.     #[Route('/api/check-notfication-masive'name'check_notfication_masive'methods: ['GET'])]
  292.     public function check_notfication_masive(Request $request)
  293.     {
  294.         $now = new \DateTime();
  295.         $interval = new \DateInterval('PT5M'); // 5 хвилин
  296.         $thresholdTime = (clone $now)->sub($interval);
  297.         /** шукаю масове сповіщення яке в процесі */
  298.         $notification $this->entityManager->getRepository(Notification::class)->findOneBy(['status' => 'in_progress''allUsers' => true]);
  299.         if(! $notification) {
  300.             $response = new JsonResponse();
  301.             $response->setData(['status' => 'No in_progress notifications found']);
  302.             return $response;
  303.         }
  304.         /** Перевіряю чи дата відправки більше ніж 5 хвилин тому */
  305.         if($notification->getDateSend() > $thresholdTime) {
  306.             $response = new JsonResponse();
  307.             $response->setData(['status' => 'No stuck notifications found']);
  308.             return $response;
  309.         }
  310.         /** Оновлюю статус масового сповіщення */
  311.         $notificationMassive $notification->getMassiveNotification();
  312.         $notificationMassive->setStatus('new');
  313.         
  314.         // $notifications = $this->entityManager->getRepository(Notification::class)->findBy(['status' => 'in_progress']);
  315.         $notifications $this->entityManager->getRepository(Notification::class)->findBy(['status' => 'in_progress''massiveNotification' => $notificationMassive]);
  316.         if($notifications){
  317.                     // Витягуємо всі ID
  318.             $notificationIds array_map(fn($n) => $n->getId(), $notifications);
  319.             // Масове оновлення статусу та дати
  320.             $this->entityManager->createQuery(
  321.                 'UPDATE App\Entity\Notification n
  322.                 SET n.status = :newStatus, 
  323.                     n.dateSend = :now,
  324.                     n.error = CONCAT(n.error, :now_str)
  325.                 WHERE n.id IN (:ids)'
  326.             )
  327.             ->setParameter('newStatus''new_all')
  328.             ->setParameter('now', new \DateTime())
  329.             ->setParameter('ids'$notificationIds)
  330.             ->setParameter('now_str'"\n" date('Y-m-d H:i:s') . " - Перевідправлено через зависання")
  331.             ->execute();
  332.         }
  333.         $this->entityManager->persist($notificationMassive);
  334.         $this->entityManager->flush();
  335.         $response = new JsonResponse();
  336.         $response->setData(['status' => 'Check completed']);
  337.         return $response;
  338.     }
  339.     
  340.     /** Додавання масових сповіщень в чергу RABBIT з статусом "new_all" */
  341.     #[Route('/api/add-notification-massive-in-queue'name'add_notification_massive_in_queue'methods: ['GET'])]
  342.     public function add_notification_massive_in_queue(Request $request)
  343.     {
  344.         /** Перевірка чи не запущено крон  */
  345.         if(file_exists('/var/www/symfony_docker/var/log/notificationMassiveCron.log')){
  346.             $logCron file_get_contents('/var/www/symfony_docker/var/log/notificationMassiveCron.log');
  347.             if(!empty( $logCron )){
  348.                 $fileContents json_decode($logCrontrue);
  349.                 $lastRunTime = isset($fileContents['start']) ? strtotime($fileContents['start']) : 0;
  350.                 $currentTime time();
  351.                 if( $fileContents['cron'] == 'Start' ){
  352.                 
  353.                     // Якщо останній запуск був менше ніж 5 хвилин тому, завершуємо виконання
  354.                     echo "$currentTime - $lastRunTime = " . ($currentTime $lastRunTime);
  355.                     if (($currentTime $lastRunTime) > 300) {
  356.                         $logCron =  json_encode([
  357.                             'cron' => 'Stop',
  358.                             'stop' => date('Y-m-d H:i:s'),
  359.                             'info' => 'The cron job was run less than 5 minutes ago. Exiting to prevent overlap.'
  360.                         ]);
  361.                         file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveCron.log',  $logCron);
  362.                     }
  363.                     var_dump($logCron);
  364.                     die;
  365.                 }
  366.             }
  367.             
  368.         }
  369.         file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveCron.log',  json_encode([
  370.             'cron' => 'Start',
  371.             'start' => date('Y-m-d H:i:s'),
  372.             'info' => 'Start notification cron'
  373.         ]));
  374.         
  375.         
  376.         // file_put_contents('/var/www/symfony_docker/var/log/notificationCron.log');
  377.               $send 0;
  378.         $err 0;
  379.         
  380.         /** Масовані розсилки розділені ns_msg_id, бо в них однакові тексти, тому шукаю перший ліпший і потім всі інші по ns_msg_id  */
  381.         $MassiveNotification $this->entityManager->getRepository(MassiveNotification::class)->findOneBy(['status' => 'new']);
  382.         // $firstNotification = $this->entityManager->getRepository(Notification::class)->findOneBy(['status' => 'new_all', 'allUsers' => true, 'massiveNotification' => $MassiveNotification]);
  383.         if($MassiveNotification){
  384.             file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveAddInQueue.log',  $MassiveNotification->getId() . " NOTIFICATIONS Massive ************************" .  date('H:i:s') . "\n"FILE_APPEND);
  385.             $notifications $this->entityManager->createQueryBuilder()
  386.                     ->select('n.id')
  387.                     ->from(Notification::class, 'n')
  388.                     ->where('n.status = :status')
  389.                     ->andWhere('n.massiveNotification = :mn')
  390.                     ->setParameter('status''new_all')
  391.                     ->setParameter('mn'$MassiveNotification)
  392.                     ->getQuery()
  393.                     ->getSingleColumnResult();
  394.             
  395.             if(count($notifications) == 0){
  396.                 file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveAddInQueue.log',  $MassiveNotification->getId() .  date('H:i:s') . "Немає нових сповіщень для розсилки\n"FILE_APPEND);
  397.                 $MassiveNotification->setStatus('send');
  398.                 $MassiveNotification->setDescription('Немає нових сповіщень для розсилки');
  399.                 $this->entityManager->persist($MassiveNotification);
  400.                 $this->entityManager->flush();
  401.                     // $logCron =  json_encode([
  402.                     //     'cron' => 'Stop',
  403.                     //     'stop' => date('Y-m-d H:i:s'),
  404.                     //     'info' => 'Notification cron complete'
  405.                     // ]);
  406.                     // file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveCron.log',  $logCron);
  407.                 $response = new JsonResponse();
  408.                 $response->setData(['send' => 0'err' => 0'error' => 'Немає нових сповіщень для розсилки']); 
  409.                 return $response
  410.             }
  411.             file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveAddInQueue.log',  "MassiveNotification ID: " $MassiveNotification->getId() .  date('H:i:s') . " Кількість сповіщень: " count($notifications) . "\n"FILE_APPEND);
  412.             // $notifications = 
  413.             
  414.             $notificationsChunk array_chunk($notifications1000);
  415.             // echo '<pre>';
  416.     
  417.                     
  418.             foreach($notificationsChunk as $notification){
  419.                 $send 0;
  420.                 $priority 1;
  421.                 file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveAddInQueue.log'"#{$MassiveNotification->getId()} add to 1000items rabbitmq - " json_encode($notification) .  date('H:i:s.u') . "\n"FILE_APPEND);
  422.                 $queued false;
  423.                 $error  null;
  424.                 try {
  425.                     // print_r($notification);
  426.                     $env $this->bus->dispatch(new NotificationMessage($MassiveNotification->getId(), $notification'send-notification-massive'$priority));
  427.                     // Якщо повідомлення надіслано у транспорт — з’являться SentStamp-и
  428.                     $sentStamps $env->all(SentStamp::class);
  429.                     if (!empty($sentStamps)) {
  430.                         $send++;
  431.                         file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveAddInQueue.log'"#{$MassiveNotification->getId()} 1000items rabbitmq-success " .  date('H:i:s.u') . "\n"FILE_APPEND);
  432.                         $queued true;
  433.                         // для логів можна подивитись куди саме:
  434.                         $targets array_map(fn(SentStamp $s) => $s->getSenderAlias() ?? $s->getTransportName(), $sentStamps);
  435.                         file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveAddInQueue.log',  'Sent to: '.implode(', '$targets).PHP_EOLFILE_APPEND);
  436.                     } else {
  437.                         $err++;
  438.                         // це означає, що роутінг не відправив у транспорт (наприклад, sync bus)
  439.                         $queued false;
  440.                         $error  'No SentStamp: message was not routed to a transport';
  441.                         file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveAddInQueue.log'"#{$MassiveNotification->getId()} rabbitmq-error " .  date('H:i:s.u') . " - No SentStamp: message was not routed to a transport\n"FILE_APPEND);
  442.                     }
  443.                 } catch (TransportExceptionInterface $e) {
  444.                     // Помилки транспорту/брокера (у т.ч. коли confirm_publish=true і брокер не підтвердив)
  445.                     $queued false;
  446.                     $error  $e->getMessage();
  447.                     $err++;
  448.                     file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveAddInQueue.log'"#{$MassiveNotification->getId()} rabbitmq-TransportExceptionInterface " .  date('H:i:s.u') . " - " $e->getMessage() . "\n"FILE_APPEND);
  449.                 } catch (\Throwable $e) {
  450.                     // будь-яка інша помилка
  451.                     $queued false;
  452.                     $error  $e->getMessage();
  453.                     $err++;
  454.                     file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveAddInQueue.log'"#{$MassiveNotification->getId()} rabbitmq-Throwable " .  date('H:i:s.u') . " - " $e->getMessage() . "\n"FILE_APPEND);
  455.                 }
  456.             }
  457.             $MassiveNotification->setStatus('send');
  458.             $MassiveNotification->setDescription('Розсилка в чергу завершена. Додано в чергу ' . ($send $err) . ' сповіщень, з помилками ' $err);
  459.             $this->entityManager->persist($MassiveNotification);
  460.             $this->entityManager->flush();
  461.             // die;
  462.         }
  463.     
  464.         $logCron =  json_encode([
  465.             'cron' => 'Stop',
  466.             'stop' => date('Y-m-d H:i:s'),
  467.             'info' => 'Notification cron complete'
  468.         ]);
  469.         file_put_contents('/var/www/symfony_docker/var/log/notificationMassiveCron.log',  $logCron);
  470.         $response = new JsonResponse();
  471.         $response->setData(['send' => $send'err' => $err]);
  472.         return $response;
  473.     }
  474. }