src/EventSubscriber/CampaignSubscriber.php line 153

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Campaign;
  4. use App\Entity\ChatNotification;
  5. use App\Event\Campaign\CampaignNoWorkflowEvent;
  6. use App\EventSubscriber\Mission as MissionEvent;
  7. use App\Entity\Message;
  8. use App\Entity\Product;
  9. use App\Entity\Workflow;
  10. use App\Entity\Mission;
  11. use App\Entity\MissionParticipant;
  12. use App\Entity\NotificationToSend;
  13. use App\Entity\SystemEmail;
  14. use App\Entity\User;
  15. use App\Enum\FreqNotification;
  16. use App\Enum\Manager;
  17. use App\Enum\Notification;
  18. use App\Enum\NotificationType;
  19. use App\Enum\Role;
  20. use App\Event\Campaign\CampaignCancelledEvent;
  21. use App\Event\Campaign\CampaignCreatedEvent;
  22. use App\Event\User\UserRelaunchedEvent;
  23. use App\Event\User\UserMissionAddedEvent;
  24. use App\Event\Campaign\CampaignEvaluationEvent;
  25. use App\Event\Campaign\CampaignModifiedEvent;
  26. use App\Event\Campaign\CampaignValidatedEvent;
  27. use App\Event\Campaign\CampaignDeletedEvent;
  28. use App\Event\Campaign\CampaignWaitingEvent;
  29. use App\Event\Campaign\CampaignResumeEvent;
  30. use App\Event\Campaign\CampaignDeclineEvent;
  31. use App\Event\Campaign\CampaignWaitingNotResentEvent;
  32. use App\Event\Chat\MessageSentEvent;
  33. use App\Repository\ChatNotificationRepository;
  34. use App\Repository\MessageRepository;
  35. use App\Repository\NotificationToSendRepository;
  36. use App\Repository\SystemEmailRepository;
  37. use App\Repository\UserRepository;
  38. use App\Service\NotificationService;
  39. use Doctrine\ORM\EntityManagerInterface;
  40. use Symfony\Bridge\Twig\Mime\NotificationEmail;
  41. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  42. use Symfony\Component\Mailer\MailerInterface;
  43. use Symfony\Component\Mime\Address;
  44. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  45. use Symfony\Component\Routing\RouterInterface;
  46. use App\Enum\AdminMail;
  47. use App\Enum\ProductType;
  48. use App\Event\Campaign\CampaignNotFinishedEvent;
  49. use App\Event\Campaign\CampaignNotifyThatDeliveryDateChangeEvent;
  50. use App\Event\Campaign\CampaignRecurrentEvent;
  51. use App\Event\Campaign\DevisCreatedNotFinished;
  52. use App\Event\Client\PremiumPackageEvent;
  53. use App\Event\DevisCreatedWithNewClientEvent
  54. use App\Event\Campaign\CampaignResendEvent;
  55. use App\Event\Campaign\CampaignValidationCancelledEvent;
  56. use App\Event\Campaign\CampaignValidatedPerActivationEvent;
  57. use App\Event\Campaign\CampaignWaitingValidationEvent;
  58. use App\Event\Client\NoticeOfInsufficientBudgetEvent;
  59. use App\Event\Confidentiality\ConfidentialityRequestEvent;
  60. use App\Event\Confidentiality\ConfidentialityRequestButInfoCompanyNotCompletEvent;
  61. use App\Event\SubContractor\SubContractorMissionAddedEvent;
  62. use App\Repository\MissionParticipantRepository;
  63. use App\Service\RelanceService;
  64. use App\Service\WorkflowStepService;
  65. use Doctrine\Common\Collections\Collection;
  66. use Symfony\Component\Security\Core\Security;
  67. use App\Service\SendNotificationService;
  68. use App\Service\CampaignService;
  69. use App\Service\ConfidentialityService;
  70. use App\Service\FirebaseCloudeMessagingService;
  71. use App\Service\PriceService;
  72. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  73. use App\Service\DynamicHostService;
  74. use App\Service\MissionService;
  75. use App\Service\ChatService
  76. class CampaignSubscriber implements EventSubscriberInterface
  77. {
  78.     public function __construct(
  79.         private RouterInterface $router,
  80.         private MailerInterface $mailer,
  81.         private ChatNotificationRepository $notificationRepository,
  82.         private EntityManagerInterface $entityManager,
  83.         private SystemEmailRepository $systemEmailRepository,
  84.         private UserRepository $userRepository,
  85.         private NotificationService $notificationService,
  86.         private NotificationToSendRepository $notificationToSendRepository,
  87.         private Security $security,
  88.         private WorkflowStepService $workflowStepService,
  89.         private RelanceService $relanceService,
  90.         private SendNotificationService $sendNotificationService,
  91.         private CampaignService $campaignService,
  92.         private ConfidentialityService $confidentialityService,
  93.         private EventDispatcherInterface $dispatcher
  94.         private PriceService $priceService,
  95.         private MissionParticipantRepository $missionParticipantRepository
  96.         private FirebaseCloudeMessagingService $firebaseCloudeMessagingService
  97.         private DynamicHostService $dynamicHostService
  98.         private MissionService $missionService
  99.         private MessageRepository $messageRepository
  100.         private ChatService $chatService
  101.     ) {
  102.     }
  103.     public static function getSubscribedEvents()
  104.     {
  105.         return [
  106.             CampaignValidatedEvent::NAME => 'onCampaignValidated',
  107.             CampaignCancelledEvent::NAME => 'onCampaignCancelled',
  108.             CampaignCreatedEvent::NAME => 'onCampaignCreated',
  109.             CampaignModifiedEvent::NAME => 'onCampaignModified',
  110.             CampaignWaitingEvent::NAME => 'onCampaignWaiting',
  111.             CampaignResumeEvent::NAME => 'onCampaignResume',
  112.             UserRelaunchedEvent::NAME => 'onUserRelaunched',
  113.             CampaignDeclineEvent::NAME => 'onCampaignDecline',
  114.             CampaignWaitingNotResentEvent::NAME => 'onCampaignWaitingNotResent',
  115.             CampaignEvaluationEvent::NAME => 'onCampaignEvaluation',
  116.             MessageSentEvent::NAME => 'onMessageSent',
  117.             CampaignNotFinishedEvent::NAME => 'onCampaignNotFinished',
  118.             DevisCreatedNotFinished::NAME => 'onDevisCreatedNotFinished',
  119.             PremiumPackageEvent::NAME => 'onClientGetPremiumPackage',
  120.             CampaignResendEvent::NAME => 'onCampaignResend',
  121.             CampaignNotifyThatDeliveryDateChangeEvent::NAME => "onDeliveryDateChange",
  122.             CampaignDeletedEvent::NAME => "onCampaignDeletedEvent",
  123.             CampaignRecurrentEvent::NAME => "onCampaignRecurrent",
  124.             CampaignValidationCancelledEvent::NAME => 'oncampaignValidationCancelled',
  125.             CampaignWaitingValidationEvent::NAME => 'onCampaignWaitingValidation',
  126.             CampaignValidatedPerActivationEvent::NAME => 'onCampaignValidatedPerActivation',
  127.             DevisCreatedWithNewClientEvent::NAME=>'onDevisCreatedWithNewClientEvent',
  128.             CampaignNoWorkflowEvent::NAME=>'onCampaignNoWorkflowEvent'
  129.         ];
  130.     }
  131.     
  132.     public function onCampaignNoWorkflowEvent(CampaignNoWorkflowEvent $event){
  133.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::MISSION_NO_WORKFLOW]);
  134.         $admins $this->dynamicHostService->getMailAdmin();
  135.         $missions $event->getMissions(); 
  136.         // desactivate permanantly
  137.         // foreach ($admins as $admin) {
  138.         //     foreach ($missions as $key => $mission) {
  139.         //         $this->notificationService->create( $email,  $admin->value, null,  null,  null,  $mission->getCampaign(),  null,  false,  false,  null,  null, $mission,  null,  null,  null,  null,  null,  null,  null);
  140.         //     }
  141.         // }
  142.     }
  143.     public function onDevisCreatedWithNewClientEvent(DevisCreatedWithNewClientEvent $event){
  144.         $admins $this->dynamicHostService->getMailAdmin();
  145.         $campaign $event->getCampaign(); 
  146.         $filelinksUrl =  $event->getFileLinks(); 
  147.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::DEVIS_CREATED_WITH_NEW_CLIENT]);
  148.        
  149.         foreach ($admins as $key => $admin) {
  150.             $this->notificationService->create($email$admin->value,null$campaign->getOrderedBy()->getCompany(), null$campaignnullfalsefalsenullnullnullnullnullnullnullnullnull$filelinksUrl);
  151.         }
  152.     }
  153.     public function onCampaignValidatedPerActivation(CampaignValidatedPerActivationEvent $event){
  154.           $this->sendMailAddCampaign($event->getCampaign());
  155.          
  156.     }
  157.     public function oncampaignValidationCancelled(CampaignValidationCancelledEvent $event){
  158.          $admins $this->dynamicHostService->getMailAdmin();
  159.         $campaign $event->getCampaign();
  160.         $user$event->getUser();
  161.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::VALIDATION_CANCELLED]);
  162.         foreach ($admins as $key => $admin) {
  163.             $this->notificationService->create($email$admin->value,$user$campaign->getOrderedBy()->getCompany(), null$campaign);
  164.         }
  165.     }
  166.     public function onCampaignWaitingValidation(CampaignWaitingValidationEvent $event){
  167.         $campaign $event->getCampaign();
  168.         $userAlreadSendEmail = [];
  169.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CAMPAIGN_WAITING_VALIDATION]);
  170.         foreach ($campaign->getMissions() as $mission) {
  171.             foreach ($mission->getParticipants() as $participant) {
  172.                 if(!in_array($participant->getUser()->getId(), $userAlreadSendEmail) && ($participant->getRole() == ROLE::ROLE_VALIDATOR || in_array('ROLE_CLIENT'$participant->getUser()->getRoles()))){
  173.                     $this->notificationService->create($email$participant->getUser(), $participant->getUser(), $campaign->getOrderedBy()->getCompany(), null$campaign);
  174.                     $userAlreadSendEmail=[...$userAlreadSendEmail,$participant->getUser()->getId() ];
  175.                 }
  176.             }
  177.         }
  178.     }
  179.     public function onCampaignRecurrent(CampaignRecurrentEvent $event)
  180.     {
  181.         $campaign $event->getCampaign();
  182.         $contcontactProjectIsOK $event->contactProjectIsOK();
  183.         $isNewRecurrent $event->isNew();
  184.         if (!$contcontactProjectIsOK) {
  185.             $product = new Product();
  186.             $product->setName("Espace de discussion");
  187.             $product->setFrontId(0);
  188.             $product->setType(ProductType::AU_TEMPS_PASSE);
  189.             $this->entityManager->persist($product);
  190.             $today = new \DateTime();
  191.             $mission  = new Mission();
  192.         
  193.           
  194.             $workflow $this->entityManager->getRepository(Workflow::class)->findOneBy(['template'=>1,'name'=>'Discussion']);
  195.             $newWorkflow = clone($workflow);
  196.             $reference  $campaign->getMissions()->first()!= null $campaign->getMissions()->first()->getReference($campaign->getOrderedBy()) : $this->missionService->generateReference();
  197.             $mission->setProduct($product)
  198.                     ->setQuantity(1)
  199.                     ->setDesiredDelivery($today->add(new \DateInterval('P1Y')))
  200.                     ->setState('provisional')
  201.                     ->setWorkflow($newWorkflow)
  202.                     ->setCampaign($campaign)
  203.                     ->setReference($reference);
  204.                     ;
  205.             $campaign->addMission($mission); 
  206.             $this->entityManager->persist($campaign);
  207.             $this->entityManager->flush();
  208.             $this->missionService->addHistorique($mission$campaign->getOrderedBy(), 'campaign_initiate_by_recurrent');
  209.             $contactProject array_column($this->userRepository->getContactProjectByCompany($campaign->getCompany()),'id');
  210.             $contactProject array_unique($contactProject);
  211.             // foreach ($contactProject as $contact) {
  212.             //     $userContact = $this->userRepository->find($contact);
  213.             //     $missionParticipantContactProject = (new MissionParticipant())
  214.             //                             ->setUser($userContact)
  215.             //                             ->setMission($mission)
  216.             //                             ->setRole(Role::PROJECT_CONTACT);
  217.             //     $mission->addParticipant($missionParticipantContactProject);
  218.                
  219.             // }
  220.             foreach ($campaign->getMissions() as $mission) {
  221.                 //ajouter contact projet (commande via back)
  222.                 $contactProject array_unique($contactProject);
  223.                 foreach ($contactProject as $contact) {
  224.                     $userContact $this->userRepository->find($contact);
  225.                     $missionParticipantContactProject = (new MissionParticipant())
  226.                                             ->setUser($userContact)
  227.                                             ->setMission($mission)
  228.                                             ->setRole(Role::PROJECT_CONTACT);
  229.                     $mission->addParticipant($missionParticipantContactProject);
  230.                 }
  231.                 if (empty($contactProject)) {
  232.                     $company $this->dynamicHostService->getCompany();
  233.                         $admins $this->userRepository->getAllAdmin();
  234.                   
  235.                     if (!is_null($company)) {//if company is not null so it is agency
  236.                         $admins $this->userRepository->getAdminAgencyByCompany($company);
  237.                        
  238.                     }
  239.                     foreach ($admins as $key => $admin) {
  240.                             $missionParticipantContactProject = (new MissionParticipant())
  241.                                             ->setUser($admin)
  242.                                             ->setMission($mission)
  243.                                             ->setRole(Role::PROJECT_CONTACT);
  244.                             $mission->addParticipant($missionParticipantContactProject);
  245.                     }
  246.                 }
  247.             }
  248.             if (empty($contactProject)) {
  249.                     $company $this->dynamicHostService->getCompany($campaign?->getOrderedBy());
  250.                     $admins $this->userRepository->getAllAdmin();
  251.                     if (!is_null($company)) {//if company is not null so it is agency
  252.                         $admins $this->userRepository->getAdminAgencyByCompany($company);
  253.                     }
  254.                     foreach ($admins as $key => $admin) {
  255.                             $missionParticipantContactProject = (new MissionParticipant())
  256.                                             ->setUser($admin)
  257.                                             ->setMission($mission)
  258.                                             ->setRole(Role::PROJECT_CONTACT);
  259.                             $mission->addParticipant($missionParticipantContactProject);
  260.                     }
  261.                 }
  262.             //$campaign->addMission($mission); 
  263.             $this->entityManager->persist($mission);
  264.             $this->entityManager->persist($campaign);
  265.             $this->entityManager->flush();
  266.             
  267.             $this->campaignService->addDefaultClient($mission);
  268.         }
  269.        
  270.         
  271.    
  272.         if($campaign->getRecurringState() == 'waiting_validation'){
  273.             $userAlreadSendEmail=[];
  274.             $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::VALIDATION_RECURRENT_CAMPAING]);
  275.             foreach ($campaign->getMissions() as $mission) {
  276.                 foreach ($mission->getParticipants() as $participant) {
  277.             
  278.                     if(!in_array($participant->getUser()->getId(), $userAlreadSendEmail) && ($participant->getRole() == ROLE::ROLE_VALIDATOR || in_array('ROLE_CLIENT'$participant->getUser()->getRoles()))){
  279.                         $this->notificationService->create($email$participant->getUser(), $participant->getUser(), $campaign->getOrderedBy()->getCompany(), null$campaign);
  280.                         $userAlreadSendEmail=[...$userAlreadSendEmail,$participant->getUser()->getId() ];
  281.                     }
  282.                 }
  283.             }
  284.         }else{
  285.             if ($isNewRecurrent) {
  286.                 $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::NEW_COMMAND_RECURRENT]);
  287.             } else {
  288.                 $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::COMMAND_RECURRENT]);
  289.             }
  290.             
  291.              $this->notificationService->create($email$campaign->getOrderedBy(), $campaign->getOrderedBy(), $campaign->getOrderedBy()->getCompany(), null$campaign);
  292.         }
  293.         
  294.     }
  295.     public function onCampaignDeletedEvent(CampaignDeletedEvent $event)
  296.     {
  297.         $campaign $event->getCampaign();
  298.         $user $event->getUser();
  299.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CAMPAING_DELETE]);
  300.          $admins $this->dynamicHostService->getMailAdmin();
  301.         foreach ($admins as $admin) {
  302.             $this->notificationService->create($email$admin->value$user$user->getCompany(), null$campaign);
  303.         }
  304.         return;
  305.     }
  306.     public function onClientGetPremiumPackage(PremiumPackageEvent $event)
  307.     {
  308.         $client $event->getClient();
  309.          $admins $this->dynamicHostService->getMailAdmin();
  310.         $otherEmail $event->getEmailOther();
  311.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::MODIFICATION_INTERVENANT]);
  312.         foreach ($admins as $admin) {
  313.             $this->notificationService->create($email$admin->value$client$client->getCompany(), nullnullnullfalsefalse$otherEmail);
  314.         }
  315.         return;
  316.     }
  317.     public function onDevisCreatedNotFinished(DevisCreatedNotFinished $event)
  318.     {
  319.         $campaign $event->getCampaign();
  320.         $user $event->getUser();
  321.          $admins $this->dynamicHostService->getMailAdmin();
  322.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::DEMANDE_NON_TERMINER_CLIENT_DEVIS]);
  323.         foreach ($admins as $admin) {
  324.             $this->notificationService->create($email$admin->value$user$user->getCompany(), null$campaign);
  325.         }
  326.         return;
  327.     }
  328.     public function onCampaignNotFinished(CampaignNotFinishedEvent $event)
  329.     {
  330.         $campaign $event->getCampaign();
  331.         $mission $event->getMission();
  332.         $user $event->getUser();
  333.         $admins $this->dynamicHostService->getMailAdmin();
  334.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::DEMANDE_NON_TERMINER_CLIENT]);
  335.         foreach ($admins as $admin) {
  336.             $this->notificationService->create($email$admin->value$user$user->getCompany(), null$campaign);
  337.         }
  338.         return;
  339.     }
  340.     public function onCampaignCreated(CampaignCreatedEvent $event)
  341.     {
  342.        
  343.         $allEmail=[];
  344.         $campaign $event->getCampaign();
  345.         $type $event->getType();
  346.         $contactProject $event->getContactProject();
  347.         $createdInBack $event->getCreatedInBack();
  348.         $alreadyClone $event->alreadyClone();
  349.         $allUserInMission $event->getListUser();
  350.         $isNewClientAdded $event->isNewClientAdded();
  351.         $campaignTypeInitiation '';
  352.         $launchJustOne true;
  353.         if (!$campaign instanceof Campaign) {
  354.             return;
  355.         }
  356.        
  357.         //if contactProject is empty search default contact projet in company
  358.         if (empty($contactProject) and !is_null($campaign?->getCompany()) /*and !$createdInBack*/) {
  359.        
  360.             $contactProject array_column($this->userRepository->getContactProjectByCompany($campaign->getCompany()),'id');
  361.         }
  362.       
  363.         $admins $this->dynamicHostService->getMailAdmin();
  364.     
  365.         $alreadySent = [];
  366.     
  367.         if ($campaign->getMissions()->count() === 0) {
  368.          
  369.             if ($type == 'CREATION_DEVIS'){
  370.             
  371.                 $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CREATION_DEVIS], [], $campaign->getOrderedBy());
  372.           
  373.            
  374.             }elseif($type =='CREATION_DEVIS_PUBLIC'){
  375.                 $campaignTypeInitiation 'devis_public';
  376.                 if($isNewClientAdded){
  377.                     $filelinksUrl =  $event->getLinkAttachments(); 
  378.                     $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::DEVIS_CREATED_WITH_NEW_CLIENT],[], $campaign->getOrderedBy());
  379.     
  380.                     foreach ($admins as $key => $admin) {
  381.                         $this->notificationService->create($email$admin->value,null$campaign->getOrderedBy()->getCompany(), null$campaignnullfalsefalsenullnullnullnullnullnullnullnullnull$filelinksUrl);
  382.                     }
  383.     
  384.                     $email null
  385.                 }else{
  386.                     $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CREATION_DEVIS],[], $campaign->getOrderedBy());
  387.                 }
  388.                
  389.             }
  390.             else{
  391.                
  392.                 $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::DEMANDE_DEVIS_NOTIF_ADMIN],[], $campaign->getOrderedBy());
  393.             }
  394.         } else {
  395.             
  396.             $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CREATION_CAMPAGNE],[], $campaign->getOrderedBy());
  397.            
  398.         }
  399.         if($type == 'CREATION_DEVIS'){
  400.             $campaignTypeInitiation 'campaign_initiate_by_tunnel_devis';
  401.         }
  402.         elseif($type == 'CREATION_DEVIS_PUBLIC'){
  403.             $campaignTypeInitiation 'devis_public';
  404.         }
  405.         elseif($type == 'CREER_PAR_ADMIN'){
  406.             $campaignTypeInitiation 'campaign_initiate_by_admin';
  407.         }
  408.         elseif($type == 'TUNNEL_MAIL'){
  409.             $campaignTypeInitiation 'campaign_initiate_by_mail';
  410.         }
  411.         elseif($type == 'TUNNEL_COMMANDE'){
  412.             $campaignTypeInitiation 'campaign_initiate_by_tunnel_client';
  413.         }else{
  414.             $campaignTypeInitiation 'campaign_initiate_by_tunnel_client';
  415.         }
  416.         if (null !== $email) {
  417.             $files = (false !== $campaign->getMissions()->first()) ? $campaign->getMissions()->first()->getFileMissions() : null;
  418.          
  419.              $allEmail[] = $email;
  420.             foreach ($admins as $admin) {
  421.                 $this->notificationService->create($email$admin->value$campaign->getOrderedBy(), $campaign->getOrderedBy()->getCompany(), null$campaign$files);
  422.             }
  423.           
  424.         }
  425.      
  426.         foreach ($campaign->getMissions() as $mission) {
  427.       
  428.             //ajouter contact projet (commande via back)
  429.             $contactProject array_unique($contactProject);
  430.             if (!$alreadyClone) {
  431.                
  432.                 foreach ($contactProject as $contact) {
  433.                     $userContact $this->userRepository->find($contact);
  434.                     $missionParticipantContactProject = (new MissionParticipant())
  435.                                             ->setUser($userContact)
  436.                                             ->setMission($mission)
  437.                                             ->setRole(Role::PROJECT_CONTACT);
  438.                     $mission->addParticipant($missionParticipantContactProject);
  439.                 }
  440.                 if (empty($contactProject)) {
  441.                
  442.                     $company $this->dynamicHostService->getCompany();
  443.                         $admins $this->userRepository->getAllAdmin();
  444.                   
  445.                     if (!is_null($company)) {//if company is not null so it is agency
  446.                         $admins $this->userRepository->getAdminAgencyByCompany($company);
  447.                        
  448.                     }
  449.                    
  450.                     foreach ($admins as $key => $admin) {
  451.                             $missionParticipantContactProject = (new MissionParticipant())
  452.                                             ->setUser($admin)
  453.                                             ->setMission($mission)
  454.                                             ->setRole(Role::PROJECT_CONTACT);
  455.                             $mission->addParticipant($missionParticipantContactProject);
  456.                     }
  457.                 }
  458.             }
  459.         
  460.             $count 0;
  461.             foreach ($mission->getParticipants() as $participant) {
  462.             
  463.                 if (in_array('ROLE_BOT'$participant->getUser()->getRoles())) {
  464.                     $admins $this->dynamicHostService->getMailAdmin();
  465.                     $emailForBot $this->systemEmailRepository->findOneBy(['code' => SystemEmail::PRESTATAIRE_ASSOCIE],[], $campaign->getOrderedBy());
  466.                     $allEmail[] = $emailForBot;
  467.                     foreach ($admins as $admin) {
  468.                         $this->notificationService->create($emailForBot$admin->value$participant->getUser(), $mission->getCampaign()->getOrderedBy()->getCompany(), null$campaign);
  469.                          
  470.                     }
  471.                    
  472.                 } else {
  473.                     if ($participant->getRole() === Role::ROLE_SUBCONTRACTOR) {
  474.                         $count++;
  475.                         if (!in_array($participant->getUser()->getEmail(), $alreadySent)) {
  476.                             $event = new SubContractorMissionAddedEvent($participant->getUser(), $mission);
  477.                             $this->dispatcher->dispatch($eventSubContractorMissionAddedEvent::NAME);   
  478.                             $alreadySent[]=$participant->getUser()->getEmail();
  479.                         }
  480.                     }
  481.                     
  482.                     $participant->getUser()->setAutorizationDateAt(new \DateTimeImmutable());
  483.                     $this->entityManager->flush();
  484.                 }
  485.             }
  486.            
  487.             if ($count === && true === $launchJustOne && $mission->getProduct()->getName() != "Espace de discussion") {
  488.                 $launchJustOne false;
  489.                 $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::MISSION_SANS_PARTENAIRE],[], $campaign->getOrderedBy());
  490.                 $allEmail[] = $email;
  491.                 if (null !== $email) {
  492.                      $admins $this->dynamicHostService->getMailAdmin();
  493.                     foreach ($admins as $admin) {
  494.                         $this->notificationService->create($email$admin->value$campaign->getOrderedBy(), $campaign->getOrderedBy()->getCompany(), null$campaign);
  495.                     }
  496.                     if (null !== $email->getSmsContent()) {
  497.                          $admins $this->dynamicHostService->getMailAdmin();
  498.                         foreach ($admins as $admin) {
  499.                             $this->notificationService->create($email$admin->value$campaign->getOrderedBy(), $campaign->getOrderedBy()->getCompany(), null$campaignnulltrue);
  500.                         }
  501.                     }
  502.                 }
  503.             }
  504.           
  505.             $this->campaignService->addHistoriqueMission(mission$missionuser$campaign->getOrderedBy(), action"new_project");
  506.             
  507.             $validators =  $this->campaignService->getValidatorMissionList(mission$mission);
  508.             if (sizeof($validators)) {
  509.                 $this->campaignService->addHistoriqueMission(mission$missionuser$campaign->getOrderedBy(), action"add_validator_list"option$validators);
  510.             }
  511.         }
  512.        
  513.         if ($campaign->getMissions()->count() === 0) {
  514.             $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::DEMANDE_DEVIS_NOTIF_CLIENT],[], $campaign->getOrderedBy());
  515.         } elseif ($mission->getProduct()->getType() == ProductType::A_EVALUER) {
  516.             $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CLIENT_CAMPAGNE_A_EVALUER_CREEE],[], $campaign->getOrderedBy());
  517.         } elseif( $type != 'CREATION_DEVIS_PUBLIC') {
  518.             $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CLIENT_CAMPAGNE_CREEE],[], $campaign->getOrderedBy());
  519.         }
  520.         if (null !== $email  && !in_array($campaign->getOrderedBy()->getRoles()[0], ['ROLE_ADMIN''ROLE_ADMIN_AGENCY''ROLE_MANAGER'])) {
  521.             $this->notificationService->create($email$campaign->getOrderedBy(), $campaign->getOrderedBy(), $campaign->getOrderedBy()->getCompany(), null$campaign);
  522.         }
  523.       
  524.         try {
  525.             $creditHistory $campaign->getCreditHistory(); 
  526.             $currentBlance $creditHistory->getCurrentBalance();
  527.             $totalPrice $this->priceService->totalPriceCampaign($campaignfalse);
  528.     
  529.             if($currentBlance $totalPrice 0) {
  530.                 $event = new  NoticeOfInsufficientBudgetEvent($campaign->getCompany(), $campaign);
  531.                 $this->dispatcher->dispatch($eventNoticeOfInsufficientBudgetEvent::NAME);
  532.             }
  533.         } catch (\Throwable $th) {
  534.            
  535.         }
  536.     
  537.         if (!$alreadyClone) {
  538.            
  539.             $product = new Product();
  540.             $product->setName("Espace de discussion");
  541.             $product->setFrontId(0);
  542.             $product->setType(ProductType::AU_TEMPS_PASSE);
  543.             $this->entityManager->persist($product);
  544.             $today = new \DateTime();
  545.             $mission  = new Mission();       
  546.             $workflow $this->entityManager->getRepository(Workflow::class)->findOneBy(['template'=>1,'name'=>'Discussion']);
  547.             $newWorkflow = clone($workflow);
  548.             $newWorkflow->setTemplate(0);
  549.             $reference  $campaign->getMissions()->first()!= null $campaign->getMissions()->first()->getReference() : $this->missionService->generateReference($campaign?->getOrderedBy());
  550.             $mission->setProduct($product)
  551.                     ->setQuantity(1)
  552.                     ->setDesiredDelivery($today->add(new \DateInterval('P1Y')))
  553.                     ->setState('provisional')
  554.                     ->setWorkflow($newWorkflow)
  555.                     ->setCampaign($campaign)
  556.                     ->setReference($reference);
  557.                     ;
  558.             $contactProject array_unique($contactProject);
  559.             foreach ($contactProject as $contact) {
  560.                 $userContact $this->userRepository->find($contact);
  561.                 $missionParticipantContactProject = (new MissionParticipant())
  562.                                         ->setUser($userContact)
  563.                                         ->setMission($mission)
  564.                                         ->setRole(Role::PROJECT_CONTACT);
  565.                 $mission->addParticipant($missionParticipantContactProject);
  566.                
  567.             }
  568.             if(!empty($allUserInMission)){
  569.                 $ids = [];
  570.                 foreach ($allUserInMission as $key => $users) {
  571.                     foreach ($users as $user) {
  572.                              $missionParticipant = new MissionParticipant();
  573.                              $missionParticipant->setMission($mission)->setUser($user);
  574.                         if (!in_array($user->getId(),$ids) &&  !in_array($user->getId(),$ids) && !in_array($user->getEmail(), $alreadySent) ) {
  575.                            
  576.                             if ($key == "observerListUser") {
  577.                                     $missionParticipant->setRole(Role::ROLE_OBSERVER);
  578.                             }else if ($key == "validatorListUser") {
  579.                                    $missionParticipant->setRole(Role::ROLE_VALIDATOR);
  580.                             }
  581.                             else if ($key == "observerExtenalListUser") {
  582.                                    $missionParticipant->setRole(Role::ROLE_OBSERVER_EXTERNAL);
  583.                             }
  584.                             else if ($key == "validatorExternalListUser") {
  585.                                    $missionParticipant->setRole(Role::ROLE_VALIDATOR_EXTERNAL);
  586.                             }
  587.                             else if ($key == "allContactProject") {
  588.                                    $missionParticipant->setRole(Role::PROJECT_CONTACT);
  589.                             }else if ($key == "allSubContractor") {
  590.                                    $missionParticipant->setRole(Role::ROLE_SUBCONTRACTOR);
  591.                                    //envoie de mail au participant
  592.                                     $event = new SubContractorMissionAddedEvent($missionParticipant->getUser(), $mission);
  593.                                     $this->dispatcher->dispatch($eventSubContractorMissionAddedEvent::NAME);
  594.                             }
  595.                         }
  596.                         $mission->addParticipant($missionParticipant);
  597.                         $ids[] = $user->getId();
  598.                     }
  599.                 }
  600.             }
  601.             // $this->missionService->addHistorique($mission, $campaign->getOrderedBy(), 'campaign_initiate_by_mail');
  602.            
  603.             if (empty($contactProject)) {
  604.                     $company $this->dynamicHostService->getCompany();
  605.                     $admins $this->userRepository->getAllAdmin();
  606.             
  607.                     if (!is_null($company)) {//if company is not null so it is agency
  608.                         $admins $this->userRepository->getAdminAgencyByCompany($company);
  609.                     }
  610.                     foreach ($admins as $key => $admin) {
  611.                             $missionParticipantContactProject = (new MissionParticipant())
  612.                                             ->setUser($admin)
  613.                                             ->setMission($mission)
  614.                                             ->setRole(Role::PROJECT_CONTACT);
  615.                             $mission->addParticipant($missionParticipantContactProject);
  616.                     }
  617.                 }
  618.             //add all contact
  619.                
  620.             $this->entityManager->persist($mission);
  621.             $this->entityManager->persist($campaign);
  622.             $this->entityManager->flush();
  623.             $this->campaignService->addDefaultClient($mission);
  624.             $this->confidentialityService->addSignedContractForClient($campaign->getOrderedBy(), falsetruefalse);
  625.             if(!empty($campaignTypeInitiation)){
  626.                 $this->missionService->addHistorique($mission$campaign->getOrderedBy(), $campaignTypeInitiation);
  627.             }
  628.             
  629.         }
  630.         //Send mail to contact project if mission are created
  631.         $emailAdmin= [];
  632.       
  633.         foreach ($admins as $admin) {
  634.             if ($admin instanceof User) {
  635.                 $emailAdmin[] = $admin->getEmail();
  636.             }else{
  637.                 $emailAdmin[] = $admin->value;
  638.             }
  639.         }
  640.      
  641.         foreach ($mission->getParticipants() as $participant) {
  642.            if ($participant->getRole() === Role::PROJECT_CONTACT and !in_array($participant->getUser()->getEmail(),$emailAdmin)) {
  643.                 foreach ($allEmail as $email) {
  644.                     $this->notificationService->create($email$participant->getUser()->getEmail(), $campaign->getOrderedBy(), $campaign->getOrderedBy()->getCompany(), null$campaign);
  645.                 }
  646.            }
  647.         }
  648.         $this->chatService->publicOnCampaignUpdate();
  649.         
  650.     }
  651.     public function onUserRelaunched(UserRelaunchedEvent $event)
  652.     {
  653.         $campaign $event->getCampaign();
  654.         $participant $event->getParticipant();
  655.         if (!$campaign instanceof Campaign) {
  656.             return;
  657.         }
  658.         
  659.         $emailClient $this->systemEmailRepository->findOneBy(['code' => SystemEmail::INDIVIDUEL_RELANCE_CLIENT]);
  660.         $emailSub $this->systemEmailRepository->findOneBy(['code' => SystemEmail::INDIVIDUEL_RELANCE_SOUS_TRAITANT]);
  661.         
  662.         if ($participant->getRole() === Role::ROLE_SUBCONTRACTOR) {
  663.             if (null !== $emailSub) {
  664.                 $this->notificationService->create($emailSub$participant->getUser(), $participant->getUser(), $campaign->getCompany(), null$campaign);
  665.             }
  666.         }
  667.         else {
  668.             if (null !== $emailClient){
  669.                 $this->notificationService->create($emailClient$participant->getUser(), $participant->getUser(), $campaign->getCompany(), null$campaign);
  670.             }
  671.         }
  672.     }
  673.     public function onCampaignCancelled(CampaignCancelledEvent $event)
  674.     {
  675.         $campaign $event->getCampaign();
  676.         if (!$campaign instanceof Campaign) {
  677.             return;
  678.         }
  679.         $userAlreadyHaveMail = [];
  680.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CAMPAING_CANCELLED]);
  681.         $admins $this->dynamicHostService->getMailAdmin();
  682.         if (null !== $email) {
  683.             foreach ($admins as $admin) {
  684.                 $this->notificationService->create($email$admin->value$campaign->getOrderedBy(), $campaign->getOrderedBy()->getCompany(), null$campaign);
  685.             }
  686.         }
  687.         
  688.         $emailClient $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CLIENT_CAMPAING_CANCELLED]);
  689.         $emailSub $this->systemEmailRepository->findOneBy(['code' => SystemEmail::SOUS_TRAITANT_CAMPAING_CANCELLED]);
  690.         
  691.         foreach ($campaign->getMissions() as $mission) {
  692.             foreach ($mission->getParticipants() as $participant) {
  693.                 if ($participant->getRole() === Role::ROLE_SUBCONTRACTOR) {
  694.                     if (null !== $emailSub) {
  695.                         if ((!in_array($participant->getUser()->getId(), $userAlreadyHaveMail))) {
  696.                             $this->notificationService->create($emailSub$participant->getUser(), $participant->getUser(), $campaign->getCompany(), null$mission->getCampaign());
  697.                         }
  698.                         $userAlreadyHaveMail[] = $participant->getUser()->getId();
  699.                     }
  700.                 }
  701.                 if ($participant->getRole() === Role::ROLE_VALIDATOR || $participant->getRole() === Role::ROLE_OBSERVER || $participant->getRole() === Role::ROLE_VALIDATOR_EXTERNAL || $participant->getRole() === Role::ROLE_OBSERVER_EXTERNAL ) {
  702.                     if (null !== $emailClient){
  703.                         if ((!in_array($participant->getUser()->getId(), $userAlreadyHaveMail))) {
  704.                             $this->notificationService->create($emailClient$participant->getUser(), $participant->getUser(), $campaign->getCompany(), null$mission->getCampaign());
  705.                              $userAlreadyHaveMail[] = $participant->getUser()->getId();
  706.                         }
  707.                     }
  708.                 }
  709.             }
  710.         }
  711.     }
  712.     
  713.     public function onCampaignResume(CampaignResumeEvent $event)
  714.     {
  715.         $campaign $event->getCampaign();
  716.         if (!$campaign instanceof Campaign) {
  717.             return;
  718.         }
  719.         $emailSub $this->systemEmailRepository->findOneBy(['code' => SystemEmail::SOUS_TRAITANT_CAMPAING_RESUMED]);
  720.         $emailClient $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CLIENT_CAMPAING_RESUMED]);
  721.         
  722.         foreach ($campaign->getMissions() as $mission) {
  723.             foreach ($mission->getParticipants() as $participant) {
  724.                 if ($participant->getRole() === Role::ROLE_SUBCONTRACTOR) {
  725.                     if (null !== $emailSub){
  726.                         $listResponsableMission $this->workflowStepService->getResponsableStepByMission($mission);
  727.                         $this->notificationService->create($emailSub$participant->getUser(), $participant->getUser(), $campaign->getCompany(), null$mission->getCampaign());
  728.                     }
  729.                 }
  730.                 if ($participant->getRole() === Role::ROLE_VALIDATOR || $participant->getRole() === Role::ROLE_OBSERVER || $participant->getRole() === Role::ROLE_VALIDATOR_EXTERNAL || $participant->getRole() === Role::ROLE_OBSERVER_EXTERNAL) {
  731.                     if (null !== $emailClient){
  732.                         $listResponsableMission $this->workflowStepService->getResponsableStepByMission($mission);
  733.                         $this->notificationService->create($emailClient$participant->getUser(), $participant->getUser(), $campaign->getCompany(), null$mission->getCampaign());
  734.                     }
  735.                 }
  736.             }
  737.         }
  738.     }
  739.     public function onCampaignModified(CampaignModifiedEvent $event)
  740.     {
  741.         $campaign $event->getCampaign();
  742.         if (!$campaign instanceof Campaign) {
  743.             return;
  744.         }
  745.         $notification = (new NotificationEmail())
  746.             ->to(new Address($campaign->getOrderedBy()->getEmail()))
  747.             ->subject('Votre commande ' $campaign->getName() . ' a été modifiée')
  748.             ->content('
  749.                 <p>Bonjour,</p>
  750.                 <p>Votre commande "' $campaign->getName() . '" vient d\'être modifée.</p>
  751.                 <p>L\'équipe MyFlow</p>
  752.             ')
  753.             ->action('Accéder au tableau de bord'$this->router->generate('mission_index', [], UrlGeneratorInterface::ABSOLUTE_URL))
  754.             ->markAsPublic();
  755.         $this->mailer->send($notification);
  756.     }
  757.     public function onDeliveryDateChange(CampaignNotifyThatDeliveryDateChangeEvent $event)
  758.     {
  759.         $campaign $event->getCampaign();
  760.         $mission $event->getMission();
  761.         $to = [];
  762.         $emailSysteme $this->systemEmailRepository->findOneBy(['code' => SystemEmail::DATE_DE_LIVRAISON_CHANGE]);
  763.         foreach ($campaign->getCompany()->getUsers() as $user) {
  764.             if (!(in_array("ROLE_ADMIN"$user->getRoles()) || in_array("ROLE_SUBCONTRACTOR"$user->getRoles())) && !in_array($user->getEmail(), $to)) {
  765.                 $to[] = $user->getEmail();
  766.                 $this->notificationService->create(
  767.                     $emailSysteme,
  768.                     $user->getEmail(),
  769.                     $user->getEmail(),
  770.                     $campaign->getCompany(),
  771.                     null,
  772.                     null,
  773.                     null,
  774.                     false,
  775.                     false,
  776.                     null,
  777.                     null,
  778.                     $mission
  779.                 );
  780.             }
  781.         }
  782.     }
  783.     public function onCampaignWaiting(CampaignWaitingEvent $event)
  784.     {
  785.         $campaign $event->getCampaign();
  786.         $ids = [];
  787.         if (!$campaign instanceof Campaign) {
  788.             return;
  789.         }
  790.         $userAlreadyHaveMail = [];
  791.          $admins $this->dynamicHostService->getMailAdmin();
  792.         if ($event->getSystemEmail()) {
  793.             $emailForClient $this->systemEmailRepository->findOneBy(['code' => SystemEmail::MISSION_EN_PAUSE]);
  794.             $emailForSubcontractor $this->systemEmailRepository->findOneBy(['code' => SystemEmail::EMAIL_PAUSE_FOR_SUBCONTRACTOR]);
  795.             $emailForAdmin $this->systemEmailRepository->findOneBy(['code' => SystemEmail::EMAIL_PAUSE_FOR_ADMIN]);
  796.             //email envoyé aux sous-traitants et à celui qui la commandée
  797.             $isSendToAdmin false;
  798.             foreach ($campaign->getMissions() as $mission) {
  799.                 $responsable $this->getResponsableForActionPause($mission->getParticipants());
  800.                 foreach ($mission->getParticipants() as $participant) {
  801.                     if ($participant->getUser() === $this->security->getUser()) {
  802.                         $responsable $participant->getRole()->label();
  803.                     }
  804.                     if ($participant->getRole() === Role::ROLE_SUBCONTRACTOR) {
  805.                         if ((!in_array($participant->getUser()->getId(), $userAlreadyHaveMail))) {
  806.                             $this->notificationService->create($emailForSubcontractor$participant->getUser(), $participant->getUser(), $campaign->getCompany(), null$campaignnullfalsefalsenull$responsable);
  807.                         }
  808.                         $userAlreadyHaveMail[] = $participant->getUser()->getId();
  809.                     }
  810.                     if ($participant->getRole() === Role::ROLE_VALIDATOR || $participant->getRole() === Role::ROLE_OBSERVER || $participant->getRole() === Role::ROLE_VALIDATOR_EXTERNAL || $participant->getRole() === Role::ROLE_OBSERVER_EXTERNAL and (!in_array($participant->getUser()->getId(), $userAlreadyHaveMail))) {
  811.                         $this->notificationService->create($emailForClient$participant->getUser(), $participant->getUser(), $campaign->getCompany(), null$campaignnullfalsefalsenull$responsable);
  812.                         $userAlreadyHaveMail[] = $participant->getUser()->getId();
  813.                     }
  814.                 }
  815.                 if (!$isSendToAdmin) {
  816.                     foreach ($admins as $admin) {
  817.                         if((!in_array($participant->getUser()->getId(), $userAlreadyHaveMail))){
  818.                          $this->notificationService->create($emailForAdmin$admin->value,  $admin->value$campaign->getCompany(), null$campaignnullfalsefalsenull$responsable);
  819.                         }
  820.                         $userAlreadyHaveMail[] = $participant->getUser()->getId();
  821.                     }
  822.                     $isSendToAdmin true;
  823.                 }
  824.             }
  825.         } else {
  826.             $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::RESOUMISSION_PANIER]);
  827.             if (null !== $email) {
  828.                 foreach ($campaign->getMissions() as $mission) {
  829.                     foreach ($mission->getParticipants() as $participant) {
  830.                         $userId $participant->getUser()->getId();
  831.                         if ($participant->getRole() == Role::ROLE_VALIDATOR and !in_array($userId$ids)) {
  832.                             $this->notificationService->create($email$participant->getUser(), $participant->getUser(), $participant->getUser()->getCompany(), null$campaign);
  833.                             $ids[] = $userId;
  834.                         }
  835.                     }
  836.                 }
  837.                 $this->notificationService->create($email$campaign->getOrderedBy(), $campaign->getOrderedBy(), $campaign->getOrderedBy()->getCompany(), null$campaign);
  838.             }
  839.             $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::RESOUMISSION_PANIER_ADMIN]);
  840.             foreach ($admins as $admin) {
  841.                 $this->notificationService->create($email$admin->value$campaign->getOrderedBy(), $campaign->getOrderedBy()->getCompany(), null$campaign);
  842.             }
  843.         }
  844.     }
  845.     
  846.     public function onCampaignDecline(CampaignDeclineEvent $event)
  847.     {
  848.         $campaign $event->getCampaign();
  849.       
  850.         if (!$campaign instanceof Campaign) {
  851.             return;
  852.         }
  853.         $user =  $event->getUser();
  854.          $admins $this->dynamicHostService->getMailAdmin();
  855.         if ($event->getSystemEmail()) {
  856.             $emailForSubcontractor $this->systemEmailRepository->findOneBy(['code' => SystemEmail::MISSION_REFUSEE_INTERVENANT]);
  857.             $emailForAdmin $this->systemEmailRepository->findOneBy(['code' => SystemEmail::MISSION_REFUSEE_ADMIN]);
  858.            
  859.             $this->notificationService->create($emailForSubcontractor,$user,  $user$campaign->getCompany(), null$campaignnullfalsefalsenullnull);
  860.             foreach ($admins as $admin) {
  861.                 $this->notificationService->create($emailForAdmin$admin->value,  $user$campaign->getCompany(), null$campaignnullfalsefalsenullnull);
  862.             }
  863.         }
  864.     }
  865.     public function onCampaignWaitingNotResent(CampaignWaitingNotResentEvent $event)
  866.     {
  867.         $listCampaignsWaitingNotResent $event->getListCampaignsWaitingNotResent();
  868.         if (empty($listCampaignsWaitingNotResent)) {
  869.             return;
  870.         }
  871.         $emailWaiting $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CAMPAGNE_WAITING_NOT_RESENT]);
  872.         $emailNoWorkflow $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CAMPAGNE_WAITING_NO_WORKFLOW]);
  873.         foreach ($listCampaignsWaitingNotResent as $campaign) {
  874.             if (sizeof($this->campaignService->getAllMissionsWithNoWorkflow($campaign)) > 0) {
  875.                 $this->sendEmailForAdmin($emailNoWorkflow$campaign);
  876.             } else {
  877.                 $this->sendEmailForAdmin($emailWaiting$campaign);
  878.             }
  879.         }
  880.     }
  881.     private function sendEmailForAdmin($email$campaign)
  882.     {
  883.          $admins $this->dynamicHostService->getMailAdmin();
  884.         foreach ($admins as $admin) {
  885.             $this->notificationService->create($email$admin->valuenullnullnull$campaign);
  886.         }
  887.     }
  888.     private function getResponsableForActionPause(Collection $missionParticipants)
  889.     {
  890.         foreach ($missionParticipants as $participant) {
  891.             if ($participant->getUser() === $this->security->getUser()) {
  892.                 return  $participant->getRole()->label();
  893.             }
  894.         }
  895.         return "Administrateur";
  896.     }
  897.     public function onCampaignEvaluation(CampaignEvaluationEvent $event)
  898.     {
  899.         $campaign $event->getCampaign();
  900.         if (!$campaign instanceof Campaign) {
  901.             return;
  902.         }
  903.         $alreadySent = [];
  904.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::MISSION_DEMANDE_EVALUATION]);
  905.         if (null !== $email) {
  906.             foreach ($campaign->getMissions() as $mission) {
  907.                 $isMissionModified false;
  908.                 // if ($mission->getOldCommand() != null) {
  909.                 //     [$quatity, $price, $idProduct] = explode("-", $mission->getOldCommand());
  910.                 //     $isMissionModified =  $mission->getPrice() != $price || $mission->getQuantity() != $quatity || $mission->getProduct()->getId() != $idProduct ? true : false;
  911.                 // }
  912.                 if ($mission->getProduct()->getType() == ProductType::A_EVALUER || $isMissionModified) {
  913.                     foreach ($mission->getParticipants() as $participant) {
  914.                         if ($participant->getRole() === Role::ROLE_SUBCONTRACTOR && $participant->getEstimatedIncome() == null && !in_array($participant->getUser()->getEmail(), $alreadySent)) {
  915.                             $this->notificationService->create($email$participant->getUser(), null$campaign->getCompany(), null$campaign);
  916.                             $alreadySent[] = $participant->getUser()->getEmail();
  917.                         }
  918.                     }
  919.                     // $mission->setOldCommand("{$mission->getQuantity()}-{$mission->getPrice()}-{$mission->getProduct()->getId()}-{$mission->getDesiredDelivery()->getTimestamp()}");
  920.                     $this->entityManager->flush();
  921.                 }
  922.             }
  923.         }
  924.     }
  925.     public function onMessageSent(MessageSentEvent $event)
  926.     {
  927.         $alreadySentToUser = [];
  928.         try {
  929.             $message $event->getMessage();
  930.             $exclureUser $event->getListIdUserToExclure();
  931.             
  932.             if (!$message instanceof Message) {
  933.                 return;
  934.             }
  935.             foreach ($message->getCampaign()->getMissions() as $mission) {
  936.                 foreach ($mission->getParticipants() as $participant) {
  937.                     if ($participant->getUser()->getFreqNotification() == null || in_array($participant->getUser()->getId(), $exclureUser)) {
  938.                         continue;
  939.                     }
  940.                     if ($this->checkInCanSendNotificationForMyStep(participant$participantmessage$messagemission$mission) and !in_array($participant->getUser()->getId(),$alreadySentToUser)) {
  941.                         //vérifié si c'est un message de groupe d'abord et n'enovyer le message qu'au personne qui sont dans le groupe
  942.                         if (!is_null($message->getDiscussionGroup())) {
  943.                             foreach ($message->getDiscussionGroup()->getUsers() as $userInGroup) {
  944.                                 if ($userInGroup->getId() == $participant->getUser()->getId()) {
  945.                                      $notification = (new ChatNotification())
  946.                                         ->setSendAt((new \DateTimeImmutable())->add(new \DateInterval('PT5M')))
  947.                                         ->setSendTo($participant->getUser())
  948.                                         ->setTypeOfChat(Notification::NEW_COMMENT_IN_CHAT_FOR_STEP->value)
  949.                                         ->setAlreadyRead(0)
  950.                                         ->setMessage($message)
  951.                                         ->setCampaign($message->getCampaign());
  952.                                         $this->entityManager->persist($notification);
  953.                                         $alreadySentToUser = [...$alreadySentToUser,$participant->getUser()->getId()];
  954.                                 }
  955.                             }
  956.                         }else{
  957.                             $notification = (new ChatNotification())
  958.                                 ->setSendAt((new \DateTimeImmutable())->add(new \DateInterval('PT5M')))
  959.                                 ->setSendTo($participant->getUser())
  960.                                 ->setTypeOfChat(Notification::NEW_COMMENT_IN_CHAT_FOR_STEP->value)
  961.                                 ->setAlreadyRead(0)
  962.                                 ->setMessage($message)
  963.                                 ->setCampaign($message->getCampaign());
  964.                                 $this->entityManager->persist($notification);
  965.                                 $alreadySentToUser = [...$alreadySentToUser,$participant->getUser()->getId()];
  966.                         }
  967.                         
  968.                     }
  969.                     else if (
  970.                         $participant->getUser()->getId() != $message->getUser()->getId()
  971.                         &&
  972.                         $this->sendNotificationService->readyReceivedNofication($participant->getUser(), Notification::NEW_COMMENT_IN_CHAT->value)
  973.                         // && !$this->notificationRepository->checkIfNotificationAwaiting($participant->getUser(), $mission->getCampaign())
  974.                         && 
  975.                         !in_array($participant->getUser()->getId(),$alreadySentToUser)
  976.                     ) {
  977.                         //vérifié si c'est un message de groupe d'abord et n'enovyer le message qu'au personne qui sont dans le groupe
  978.                         if (!is_null($message->getDiscussionGroup())) {
  979.                             foreach ($message->getDiscussionGroup()->getUsers() as $userInGroup) {
  980.                                 if ($userInGroup->getId() == $participant->getUser()->getId()) {
  981.                                      $notification = (new ChatNotification())
  982.                                         ->setSendAt((new \DateTimeImmutable())->add(new \DateInterval('PT5M')))
  983.                                         ->setSendTo($participant->getUser())
  984.                                         ->setTypeOfChat(Notification::NEW_COMMENT_IN_CHAT->value)
  985.                                         ->setAlreadyRead(0)
  986.                                         ->setMessage($message)
  987.                                         ->setCampaign($message->getCampaign());
  988.                                         $this->entityManager->persist($notification);
  989.                                         $alreadySentToUser = [...$alreadySentToUser,$participant->getUser()->getId()];
  990.                                 }
  991.                             }
  992.                         }else{
  993.                             $notification = (new ChatNotification())
  994.                                 ->setSendAt((new \DateTimeImmutable())->add(new \DateInterval('PT5M')))
  995.                                 ->setSendTo($participant->getUser())
  996.                                 ->setTypeOfChat(Notification::NEW_COMMENT_IN_CHAT->value)
  997.                                 ->setAlreadyRead(0)
  998.                                 ->setMessage($message)
  999.                                 ->setCampaign($message->getCampaign());
  1000.                                 $this->entityManager->persist($notification);
  1001.                                 $alreadySentToUser = [...$alreadySentToUser,$participant->getUser()->getId()];
  1002.                         }
  1003.                     }
  1004.                     
  1005.                 }
  1006.             }
  1007.             $this->entityManager->flush();
  1008.         } catch (\Throwable $th) {
  1009.     
  1010.              $adminMail $this->dynamicHostService->getMailAdmin();
  1011.             foreach ($adminMail as $admin) {
  1012.                 $this->notificationService->sendEmail(
  1013.                     new Address('caroline.b@my-flow.fr''myFlow'),
  1014.                     new Address($admin->value),
  1015.                     'Erreur dans le tchat notification',
  1016.                     $th->getMessage(),
  1017.                 );
  1018.             }
  1019.         }
  1020.     }
  1021.     private function checkInCanSendNotificationForMyStep(MissionParticipant $participantMessage $message$mission)
  1022.     {
  1023.         if (
  1024.             $participant->getUser()->getId() !== $message->getUser()->getId()
  1025.             && $this->sendNotificationService->readyReceivedNofication($participant->getUser(), Notification::NEW_COMMENT_IN_CHAT_FOR_STEP->value)
  1026.             && in_array(NotificationType::EMAIL->value$participant->getUser()->getNotificationType() ?? [])
  1027.             && !is_null($mission->getWorkflow())
  1028.             && !empty($mission->getWorkflow()->getActiveStep())
  1029.             && (
  1030.                 ($participant->getRole() === Role::ROLE_SUBCONTRACTOR && $mission->getWorkflow()->getActiveStep()->getManager() === Manager::JOB)
  1031.                 || (($participant->getRole() === Role::ROLE_VALIDATOR || $participant->getRole() === Role::ROLE_OBSERVER) && $mission->getWorkflow()->getActiveStep()->getManager() === Manager::CLIENT)
  1032.             )
  1033.         ) {
  1034.             return true;
  1035.         }
  1036.         return false;
  1037.     }
  1038.     public function onCampaignValidated(CampaignValidatedEvent $event)
  1039.     {
  1040.         $campaign $event->getCampaign();
  1041.         if (!$campaign instanceof Campaign) {
  1042.             return;
  1043.         }
  1044.         $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::NOTIFICATION_VALIDATION_RECAP_CAMPAGNE]);
  1045.          $admins $this->dynamicHostService->getMailAdmin();
  1046.         foreach ($admins as $admin) {
  1047.             $this->notificationService->create($email$admin->value$campaign->getOrderedBy(), $campaign->getOrderedBy()->getCompany(), null$campaign);
  1048.         }
  1049.         
  1050.         $this->sendMailAddCampaign($campaign);
  1051.         
  1052.         $messageText "{$this->security->getUser()->getFirstname()} a approuvé la commande"
  1053.         $sameMessagesPersisted $this->messageRepository->findLastMessageByCampaign($campaign); 
  1054.         if((!is_null$sameMessagesPersisted) && $sameMessagesPersisted->getContent() != $messageText)  || is_null($sameMessagesPersisted)){
  1055.             $message = new Message(); 
  1056.             $message->setUser($this->security->getUser())
  1057.                     ->setCampaign($campaign)
  1058.                     ->setContent$messageText)
  1059.                     ->setUserListWhoRead([$this->security->getUser()->getId()])
  1060.                     ->setOrigin(3);
  1061.                 $this->entityManager->persist($message);
  1062.         }  
  1063.         
  1064.         $this->confidentialityService->addSignedContractForClient($this->security->getUser(), falsetruefalse);
  1065.         
  1066.     }
  1067.     public function onCampaignResend(CampaignResendEvent $event)
  1068.     {
  1069.         $campaign $event->getCampaign();
  1070.         foreach ($campaign->getMissions() as $mission) {
  1071.             $this->relanceService->sendMailForResponsableStep(mission$mission);
  1072.         }
  1073.     }
  1074.     private function sendMailAddCampaign(Campaign $campaign){
  1075.         $participants = [];
  1076.         $participantSendNotificatioPush = [];
  1077.        
  1078.         $message "";
  1079.         foreach ($campaign->getMissions() as $mission) {
  1080.               foreach ($mission->getParticipants() as $participant) {
  1081.                     if(in_array($participant->getRole()->value, ['ROLE_VALIDATOR','ROLE_OBSERVER']) && $participant->getUser()->getIsNewClient() === true && !in_array($participant->getUser()->getId(), $participants)){
  1082.                        
  1083.                         $this->sendEmailMission($participant->getUser());
  1084.                         $participants = [...$participants$participant->getUser()->getId()];
  1085.                         $participant->getUser()->setIsNewClient(false);
  1086.                         $this->entityManager->flush();
  1087.                     
  1088.                     }
  1089.                     if(!in_array($participant->getUser()->getId(), $participantSendNotificatioPush)){
  1090.                         $this->sendPushNotificationMessageCampaignActivated($campaign$participant);
  1091.                         $participantSendNotificatioPush = [...$participantSendNotificatioPush,$participant->getUser()->getId()]; 
  1092.                     }
  1093.               }
  1094.         }
  1095.        
  1096.           
  1097.         
  1098.     }
  1099.     private function sendPushNotificationMessageCampaignActivated(Campaign $campaign,  MissionParticipant $missionParticipant){
  1100.         
  1101.         $message ""
  1102.         $campainName $campaign->getName();
  1103.         
  1104.         if(in_array('ROLE_SUBCONTRACTOR'$missionParticipant->getUser()->getRoles())){
  1105.             $message "A toi de jouer, la mission suivante a été validée par {$campaign->getCompany()->getName() } : $campainName ";
  1106.         }
  1107.         elseif( in_array($missionParticipant->getRole()->value,  ['ROLE_VALIDATOR','ROLE_OBSERVER'])){
  1108.             $message "Bonne nouvelle ! Cette mission vient de démarrer : $campainName ";
  1109.         }
  1110.         else{
  1111.             $message 'Vous êtes invité à contribuer à une nouvelle mission. Connectez-vous pour plus de détails.';
  1112.         }
  1113.         $firstMission $campaign->getFirstMission(); 
  1114.         $this->firebaseCloudeMessagingService->createPushNotificationByMission($missionParticipant->getUser(),   $firstMission'myFlow'$messageFirebaseCloudeMessagingService::MESSAGES);
  1115.     }
  1116.     private function sendEmailMission($user){
  1117.         $emailCreateCount $this->systemEmailRepository->findOneBy(['code' => SystemEmail::CREATION_NOUVEAU_CLIENT]);
  1118.         $attendees $this->missionParticipantRepository->getMissionForUser($user);
  1119.         foreach ($attendees as $key => $attendee) {
  1120.             $user $attendee->getUser();
  1121.             $mission $attendee->getMission();
  1122.             $company $mission->getCampaign()->getCompany();
  1123.             $email $this->systemEmailRepository->findOneBy(['code' => SystemEmail::NEW_CLIENT_PARTICIPANT]);
  1124.             $this->notificationService->create($email$user$user$company$mission->getWorkflow()?->getActiveStep(), $mission->getCampaign());
  1125.         }
  1126.         $this->notificationService->create($emailCreateCount$user$user);
  1127.     }
  1128. }