src/Controller/CampaignController.php line 696

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Enum\Role;
  4. use Dompdf\Dompdf;
  5. use Dompdf\Options;
  6. use App\Entity\User;
  7. use App\Enum\TypePack;
  8. use GuzzleHttp\Client;
  9. use App\Entity\Company;
  10. use App\Entity\Mission;
  11. use App\Entity\Product;
  12. use App\Form\AddMissionContactProjectType;
  13. use App\Entity\Service;
  14. use App\Enum\AdminMail;
  15. use App\Entity\Campaign;
  16. use App\Enum\ProductType;
  17. use App\Entity\Historique;
  18. use App\Form\CampaignType;
  19. use App\Entity\FileMission;
  20. use App\Enum\TypeFrequency;
  21. use App\Entity\CreditHistory;
  22. use App\Service\OrderService;
  23. use App\Service\PriceService;
  24. use App\Service\UtilsService;
  25. use App\Service\CompanyService;
  26. use App\Service\MissionService;
  27. use App\Form\CampaignCancelType;
  28. use App\Form\CampaignDeleteType;
  29. use App\Form\CampaignEditWpType;
  30. use App\Service\CampaignService;
  31. use App\Service\ContractService;
  32. use App\Event\ClientUpdatedEvent;
  33. use App\Form\ListMissionFormType;
  34. use App\Repository\JobRepository;
  35. use App\Entity\MissionParticipant;
  36. use App\Repository\UserRepository;
  37. use App\Service\ClientSoldService;
  38. use Symfony\Component\Mime\Address;
  39. use App\Enum\CampaignTypeInitiation;
  40. use App\Service\MyFlowMarginService;
  41. use App\Service\NumberFormatService;
  42. use App\Event\AdminCommandErrorEvent;
  43. use App\Repository\CompanyRepository;
  44. use App\Repository\MissionRepository;
  45. use App\Repository\ProductRepository;
  46. use App\Service\GoogleStorageService;
  47. use App\Repository\CampaignRepository;
  48. use App\Repository\WorkflowRepository;
  49. use App\Service\CampaignWpEditService;
  50. use App\Event\Mission\MissionSendEvent;
  51. use App\Event\Mission\ContactAddedEvent;
  52. use Doctrine\ORM\EntityManagerInterface;
  53. use Symfony\Component\Workflow\Registry;
  54. use App\Event\Client\PremiumPackageEvent;
  55. use App\Repository\FileMissionRepository;
  56. use App\Service\CampaignRecurrentService;
  57. use App\Repository\WorkflowStepRepository;
  58. use App\Service\MissionParticipantService;
  59. use App\Event\Campaign\CampaignResendEvent;
  60. use App\Event\Campaign\CampaignResumeEvent;
  61. use App\Repository\CreditHistoryRepository;
  62. use App\Event\Campaign\CampaignCreatedEvent;
  63. use App\Event\Campaign\CampaignDeclineEvent;
  64. use App\Event\Campaign\CampaignDeletedEvent;
  65. use App\Event\Campaign\CampaignWaitingEvent;
  66. use Symfony\Component\Filesystem\Filesystem;
  67. use Symfony\Component\HttpClient\HttpClient;
  68. use App\Event\Campaign\CampaignModifiedEvent;
  69. use Symfony\Component\HttpFoundation\Request;
  70. use Symfony\Component\Mailer\MailerInterface;
  71. use App\Event\Campaign\CampaignCancelledEvent;
  72. use App\Event\Campaign\CampaignRecurrentEvent;
  73. use App\Event\Campaign\CampaignValidatedEvent;
  74. use App\Event\Mission\MissionCanActivateEvent;
  75. use App\Form\EditSubcontractorParticipantType;
  76. use Symfony\Component\HttpFoundation\Response;
  77. use App\Event\Campaign\DevisCreatedNotFinished;
  78. use App\Service\ActivationSubcontractorService;
  79. use Symfony\Bridge\Twig\Mime\NotificationEmail;
  80. use Symfony\Component\Routing\Annotation\Route;
  81. use App\Event\Campaign\CampaignEvaluationEventt;
  82. use App\Event\Campaign\CampaignNotFinishedEvent;
  83. use App\Repository\MissionParticipantRepository;
  84. use App\Repository\BalanceTransactionsRepository;
  85. use App\Event\Mission\MissionWithoutWorkflowEvent;
  86. use Symfony\Component\HttpFoundation\JsonResponse;
  87. use App\Service\ConsumptionBalanceForCompanyService;
  88. use App\Event\Workflow\Step\WorkflowStepEnteredEvent;
  89. use Symfony\Component\Serializer\SerializerInterface;
  90. use App\Event\SubcontractorActivateOrThereIsABotEvent;
  91. use Symfony\Component\HttpFoundation\RedirectResponse;
  92. use Symfony\Component\HttpFoundation\File\UploadedFile;
  93. use App\Event\Workflow\Step\WorkflowFirstStepEnteredEvent;
  94. use App\Event\Campaign\CampaignValidatedPerActivationEvent;
  95. use App\Event\SubContractor\SubContractorMissionAddedEvent;
  96. use App\Form\DataTransformer\ProductTextToObjectTransformer;
  97. use App\Event\Mission\MissionWithoutSubContractorCheckedEvent;
  98. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  99. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  100. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  101. use App\Event\Campaign\CampaignNotifyThatDeliveryDateChangeEvent;
  102. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  103. use App\Event\Mission\MissionDesiredDeliveryUpdatedAfterValidationEvent;
  104. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  105. use App\Event\Mission\MissionDesiredDeliveryUpdatedBeforeValidationEvent;
  106. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  107. use App\Event\SubContractorVigilanceCertificateAbsentEvent;
  108. use App\Entity\BalanceTransactions;
  109. use App\Event\Campaign\CampaignEvaluationEvent;
  110. use App\Service\DynamicHostService;
  111. use App\Service\CampaignApiService;
  112. use App\Entity\Workflow;
  113. class CampaignController extends AbstractController
  114. {
  115.     public function __construct(
  116.         private CampaignService $campaignService,
  117.         private MissionService $missionService,
  118.         private UtilsService $utilsService,
  119.         private ProductTextToObjectTransformer $productTextToObjectTransformer,
  120.         private ContractService $contractService,
  121.         private GoogleStorageService $googleStorageService,
  122.         private DynamicHostService $dynamicHostService,
  123.         private CampaignApiService $campaignApiService
  124.     ) {
  125.     }
  126.     /**
  127.      * @param UserRepository $userRepository
  128.      * @param Request $request
  129.      * @return JsonResponse
  130.      */
  131.     #[Route('/api/client-infos'name'get_client_info'methods: ['GET'])]
  132.     public function clientInfos(UserRepository $userRepositoryRequest $request): JsonResponse
  133.     {
  134.         $email base64_decode($request->get('emailCli'));
  135.         $user $userRepository->findOneByEmail($email);
  136.         $company =  $user->getCompany(); 
  137.         $response = new JsonResponse(
  138.             [
  139.                 'companyName' =>$company != null ?$company->getName() : '--',
  140.                 'cellPhone' => $user->getCellPhone(),
  141.                 'address'=> $company != null ?$company->getCompanyData()->getAddress() : '--',
  142.             ]
  143.         );
  144.         $response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
  145.         $response->headers->set('Access-Control-Allow-Origin''*');
  146.         $response->headers->set('Access-Control-Allow-Headers''Content-Type');
  147.         return $response;
  148.     }
  149.     /**
  150.      * @param CampaignRepository $campaignRepository
  151.      * @param Request $request
  152.      * @return JsonResponse
  153.      */
  154.     #[Route('/search'name'result_for_search_bar'methods: ['GET'])]
  155.     public function search(CampaignRepository $campaignRepositoryRequest $request): JsonResponse
  156.     {
  157.        
  158.         $data = [];
  159.         $query = ($request->get('query'));
  160.         $archived = ($request->get('archived'));
  161.         $deleted = ($request->get('deleted'));
  162.         $company null;
  163.         $subContractorAndAdmin = ($this->isGranted(Role::ROLE_ADMIN->value) or $this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) ? true false;
  164.         $isSubcontractor = ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) ? true false;
  165.         //determine who is connected and return result by user
  166.         if ($this->isGranted(Role::ROLE_ADMIN->value)) { //all campaing
  167.             $user null;
  168.         } elseif ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) { //only your campaing in all company
  169.             $user $this->getUser();
  170.         } else { //user only all campain in all company
  171.             $user $this->getUser();
  172.             $company $user->getCompany();
  173.         }
  174.         $campaigns $campaignRepository->querySearch($query$archived$user$company$subContractorAndAdmin$deleted,$isSubcontractor);
  175.         foreach ($campaigns as $campaign) {
  176.             $data[] = ['name' => str_pad($campaign['reference'], 50STR_PAD_LEFT) . " " $campaign['name'] . " (" $campaign['nameCompany'] . ") "'key' => $query'idCampaing' => $campaign['id']];
  177.         }
  178.         $response =  new JsonResponse(['data' => $data]);
  179.         $response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
  180.         $response->headers->set('Access-Control-Allow-Origin''*');
  181.         $response->headers->set('Access-Control-Allow-Headers''Content-Type');
  182.         return $response;
  183.     }
  184.     /**
  185.      * @param UserRepository $userRepository
  186.      * @param ProductRepository $productRepository
  187.      * @param Request $request
  188.      * @return JsonResponse
  189.      */
  190.     #[Route('/api/remise-product-credit'name'get_price_product_with_remise_when_credit'methods: ['GET'])]
  191.     public function remiseProduct(UserRepository $userRepositoryProductRepository $productRepositoryRequest $request): JsonResponse
  192.     {
  193.         $email base64_decode($request->get('emailCli'));
  194.         $credit 220;
  195.         $product $productRepository->findOneByFrontId($request->get('product_id'));
  196.         $user $userRepository->findOneByEmail($email);
  197.         $discount $user->getCompany()->getCustomerDiscount();
  198.         $response = new JsonResponse(
  199.             [
  200.                 'product_price' => $product->getPrice(),
  201.                 'discount' => $discount,
  202.                 'price_credit_with_remise' => ($credit - (($credit $discount) / 100))
  203.             ]
  204.         );
  205.         $response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
  206.         $response->headers->set('Access-Control-Allow-Origin''*');
  207.         $response->headers->set('Access-Control-Allow-Headers''Content-Type');
  208.         return $response;
  209.     }
  210.     /**
  211.      * @param CompanyRepository $companyRepository
  212.      * @param Request $request
  213.      * @return JsonResponse
  214.      */
  215.     #[Route('/api/premium-package'name'premium_package'methods: ['POST'])]
  216.     public function premiumPackage(UserRepository $userRepositoryEventDispatcherInterface $dispatcherRequest $request): JsonResponse
  217.     {
  218.         $email =  $request->request->get('email');
  219.         $otherEmail $request->request->get('otherEmail');
  220.         $user $userRepository->findOneByEmail($email);
  221.         try {
  222.             $event = new PremiumPackageEvent($user$otherEmail);
  223.             $dispatcher->dispatch($eventPremiumPackageEvent::NAME);
  224.             $response = new JsonResponse(['success']);
  225.         } catch (\Error $e) {
  226.             $response = new JsonResponse(['failed']);
  227.         }
  228.         $response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
  229.         $response->headers->set('Access-Control-Allow-Origin''*');
  230.         $response->headers->set('Access-Control-Allow-Headers''Content-Type');
  231.         return $response;
  232.     }
  233.     /**
  234.      * @param CompanyRepository $companyRepository
  235.      * @param Request $request
  236.      * @return JsonResponse
  237.      */
  238.     #[Route('/api/discount'name'company_discount'methods: ['POST'])]
  239.     public function discount(CompanyRepository $companyRepositoryRequest $request): JsonResponse
  240.     {
  241.         $id $request->request->get('id');
  242.         $company $companyRepository->findByFrontId((int)$id);
  243.         return new JsonResponse((int)$company[0]->getCustomerDiscount());
  244.     }
  245.      /**
  246.      * @param CompanyRepository $companyRepository
  247.      * @param Request $request
  248.      * @return JsonResponse
  249.      */
  250.     #[Route('/api/discountinBack/{id}'name'company_discount_in_back'methods: ['GET'])]
  251.     public function discountInBack($id,CompanyRepository $companyRepositoryRequest $request): JsonResponse
  252.     {
  253.         $company $companyRepository->findById($id);
  254.         return new JsonResponse($company[0]->getCustomerDiscount());
  255.     }
  256.     /**
  257.      * @param CompanyRepository $companyRepository
  258.      * @param Request $request
  259.      * @return JsonResponse
  260.      */
  261.     #[Route('/api/getAllUser/{id}/{idCampaing}'name'company_getAll_user_in_back'methods: ['GET'])]
  262.     public function allUsersCompany($id,$idCampaingCampaignApiService $campaignApiServiceUserRepository $userRepository,CampaignRepository $campaignRepositoryRequest $request,CompanyRepository $companyRepository): JsonResponse
  263.     {
  264.         /*
  265.         return sprintf('%s - %s (%s)', $user->getLastname(), $user->getFirstname(), $user->getEmail());
  266.          */
  267.         
  268.         $alldataUser = [];
  269.         $alldataUser[] = [
  270.             'id' => 0,
  271.             'text' => 'Choisir un utilisateur',
  272.         ];
  273.         $company $companyRepository->find($id);
  274.         if($this->getUser()!=null && in_array('ROLE_SUBCONTRACTOR'$this->getUser()->getRoles())){
  275.             $campaigns $campaignRepository->findAllInterlocutors($this->getUser(), 5);
  276.             $allClientParticipantsMail = [];
  277.             $allClientParticipants = [];
  278.             foreach ($campaigns as $campaign) {
  279.                 foreach ($campaign->getMissions() as $mission) {
  280.                     foreach ($mission->getParticipants() as $participant) {
  281.                         if ($participant->getRole() !== Role::ROLE_SUBCONTRACTOR && !in_array('ROLE_ADMIN',$participant->getUser()->getRoles()) ) {
  282.                             if (!in_array($participant->getUser()->getEmail(), $allClientParticipantsMail)) {
  283.                                 $allClientParticipantsMail[] = $participant->getUser()->getEmail();
  284.                                 $allClientParticipants[] = $participant->getUser();
  285.                             }
  286.                         }
  287.                     }
  288.                 }
  289.             }
  290.             $allUsers =  $allClientParticipants;
  291.         }
  292.         else{
  293.             $allUsers $userRepository->findByIdCompany($id,$company);
  294.         }
  295.         //get all user externaly
  296.         $ids = [];
  297.         
  298.         $campaign $campaignRepository->find($idCampaing);
  299.         
  300.         if (!is_null($campaign) and !empty($campaign)) {
  301.             $userExternal $campaign->getAllUserExternal();
  302.             $additionnal $campaignApiService->getAdditionalUserEmail($campaigntrue); 
  303.             
  304.             if (!is_null($userExternal) and !empty($userExternal)) {
  305.                 foreach($userExternal as $user) {
  306.                     if (!in_array($user->getId(), $ids)) {
  307.                         $alldataUser []= [
  308.                             'id' => $user->getId(),
  309.                             'text' => sprintf('%s - %s (%s)'$user->getLastname(), $user->getFirstname(), $user->getEmail())
  310.                         ];
  311.                     }
  312.                     $ids[] = $user->getId();
  313.                 }
  314.             }
  315.             foreach($additionnal as $user) {
  316.                 if (!in_array($user->getId(), $ids)) {
  317.                     $alldataUser []= [
  318.                         'id' => $user->getId(),
  319.                         'text' => sprintf('%s - %s (%s)'$user->getLastname(), $user->getFirstname(), $user->getEmail())
  320.                     ];
  321.                 }
  322.                 $ids[] = $user->getId();
  323.             }
  324.         }
  325.         foreach ($allUsers as $user) {
  326.                if (!in_array($user->getId(), $ids)) {
  327.                    $alldataUser[] = [
  328.                         'id' => $user->getId(),
  329.                         'text' => sprintf('%s - %s (%s)'$user->getLastname(), $user->getFirstname(), $user->getEmail())
  330.                    ];
  331.                }
  332.                $ids[] = $user->getId();
  333.            
  334.         }
  335.         return new JsonResponse(($alldataUser));
  336.     }
  337.      /**
  338.      * @param CompanyRepository $companyRepository
  339.      * @param Request $request
  340.      * @return JsonResponse
  341.      */
  342.     #[Route('/api/getAllJob/{id}'name'product_all_id_job'methods: ['GET'])]
  343.     public function allJobId($id,ProductRepository $productRepositoryRequest $request): JsonResponse
  344.     {
  345.         $idJob "";
  346.         $product $productRepository->findById((int) $id );
  347.         if (!empty($product)) {
  348.             foreach ($product[0]->getJobs() as $job) {
  349.                $idJob .= $job->getId().",";
  350.             }
  351.         }
  352.         return new JsonResponse($idJob);
  353.     }
  354.     /**
  355.      * @param CompanyRepository $companyRepository
  356.      * @param Request $request
  357.      * @return JsonResponse
  358.      */
  359.     #[Route('/api/creditHistory/company/{id}'name'company_get_credit_in_back'methods: ['GET'])]
  360.     public function creditHistoryForCompany($id,CreditHistoryRepository $creditHistoryRepositoryCompanyRepository $companyRepositoryRequest $request)
  361.     {
  362.         $company $companyRepository->findById($id);
  363.         $creditHistory $creditHistoryRepository->findAvailableServiceHistory($company[0],new \DateTime());
  364.         return $this->renderForm('credit_history/list.html.twig', [
  365.             'creditHistory' => $creditHistory,
  366.         ]);
  367.     }
  368.     /**
  369.      * @param CompanyRepository $companyRepository
  370.      * @param Request $request
  371.      * @return JsonResponse
  372.      */
  373.     #[Route('/api/imgCompany'name'company_img'methods: ['GET'])]
  374.     public function imgCompany(CompanyRepository $companyRepositoryRequest $requestParameterBagInterface $parameter): JsonResponse
  375.     {
  376.         $idCompany $request->get('companyId');
  377.         $urlDir $parameter->get('dir_logo_company');
  378.         if (empty($idCompany)) {
  379.             $response = new JsonResponse(['failed']);
  380.         }
  381.         $company $companyRepository->findById($idCompany);
  382.         if (is_null($company[0]?->getLogoName())) {
  383.             $response = new JsonResponse(['failed']);
  384.         } else {
  385.             $response = new JsonResponse([$urlDir $company[0]->getLogoName()]);
  386.         }
  387.         $response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
  388.         $response->headers->set('Access-Control-Allow-Origin''*');
  389.         $response->headers->set('Access-Control-Allow-Headers''Content-Type');
  390.         return $response;
  391.     }
  392.     /**
  393.      * Display the view/handle how to edit a campaign
  394.      *
  395.      * @param Request $request
  396.      * @param EntityManagerInterface $entityManager
  397.      * @return Json
  398.      */
  399.     #[Route('/api/preCommande'name'pre_commande'methods: ['POST'])]
  400.     public function preCommande(Request $requestEntityManagerInterface $entityManagerUserRepository $userRepositoryProductRepository $productRepositoryEventDispatcherInterface $dispatcher)
  401.     {
  402.         $campaignData $request->request->get('campaign');
  403.         $missionData $request->request->get('missions');
  404.         $type $request->request->get('type');
  405.         $user $userRepository->findOneBy(['email' => $campaignData['orderedBy']]);
  406.         $admins $this->dynamicHostService->getMailAdmin();
  407.         $campaign = new Campaign();
  408.         $campaign->setName($campaignData['name'])
  409.             ->setBrief($campaignData['brief']);
  410.         $entityManager->persist($campaign);
  411.         $campaign->setCompany($user->getCompany())
  412.             ->setOrderedBy($user);
  413.         foreach ($missionData as $missions) {
  414.             if (isset($missions['product'])) {
  415.                 $mission  = new Mission();
  416.                 $product  $productRepository->findByFrontId($missions['product']);
  417.                 if (!empty($product)) {
  418.                     $mission->setProduct($product[0])
  419.                         ->setPrice(floatval(str_replace(",""."$missions['price'])))
  420.                         ->setQuantity($missions['quantity']);
  421.                 }
  422.                 $campaign->addMission($mission);
  423.             }
  424.         }
  425.         if ($type === "devis") {
  426.             $event = new DevisCreatedNotFinished($campaign$user);
  427.             $dispatcher->dispatch($eventDevisCreatedNotFinished::NAME);
  428.         } else {
  429.             $event = new CampaignNotFinishedEvent($campaign$mission$user);
  430.             $dispatcher->dispatch($eventCampaignNotFinishedEvent::NAME);
  431.         }
  432.         $entityManager->remove($campaign);
  433.         $entityManager->flush();
  434.         return new JsonResponse([]);
  435.     }
  436.     #[Route('/campaigns/draft/edit/{id}'name'edit_draft'methods: ['GET','POST'])] 
  437.     public function editDraft(Campaign $campaign,CampaignWpEditService $campaignWpEditService,  EntityManagerInterface $entityManager,  Request $request,MissionParticipantService $missionParticipantService,EventDispatcherInterface $dispatcher,UserPasswordHasherInterface $passwordHasher,UserRepository $userRepositoryCompanyService $companyServiceCreditHistoryRepository $creditHistoryRepository){
  438.         
  439.         if($campaign->getState() == 'draft'){
  440.             $formWpEdit $this->createForm(CampaignEditWpType::class, $campaign);
  441.             $formWpEdit->handleRequest($request);
  442.     
  443.             if($formWpEdit->isSubmitted()){
  444.                 
  445.                 $campaignWpEditService->removeAllParticipantNotSubcontractor($campaign);
  446.     
  447.                 $participants $request->request->get('participants');
  448.                 $creditHistoryId $request->request->get('campaign_edit_wp')['contract'];
  449.                 $confidentiality = isset($request->request->get('campaign_edit_wp')['confidentiality']) ? true false;
  450.                 
  451.                 $attachements $request->files->get('attachements'); 
  452.     
  453.                 // dd($request->files->get('attachements'));
  454.                 if($creditHistoryId != null){
  455.                     $creditHistory $creditHistoryRepository->findOneById($creditHistoryId);
  456.                     $campaign->setCreditHistory($creditHistory);
  457.                 }
  458.            
  459.                 $campaign->setConfidentiality($confidentiality);
  460.                 $observerList = [];
  461.                 $defaultValidator = [];
  462.                 $defaultValidatorExternal = [];
  463.                 $defaultObserverExernal = [];
  464.                 
  465.     
  466.                 foreach ($campaign->getMissions() as $mission) {
  467.                     if($participants != null){
  468.     
  469.                         foreach ($participants as $participant) {
  470.     
  471.                                 $email $participant['email_de_participant'];
  472.                                 $role $participant['type_de_participant'];
  473.                                
  474.                                 $role =  $campaignWpEditService->formatToValidRole($role); 
  475.                                 $user $userRepository->findOneBy(['email' => $email]);
  476.                                 $role_client "ROLE_CLIENT";
  477.                                 
  478.                                 if (null === $user) {
  479.                                     $user = (new User())
  480.                                         ->setEmail($email)
  481.                                         ->setRoles([$role_client])
  482.                                         ->setEnabled(false)
  483.                                         ->setIsNewClient(true)
  484.                                         ;
  485.                                     $user->setPassword($passwordHasher->hashPassword($user$user->getPassword()));
  486.                                     $entityManager->persist($user);
  487.                                     $entityManager->flush();
  488.                                     $event = new ClientUpdatedEvent($usertrue);
  489.                                     $newUserCreateId[] = $user->getId();
  490.                                     $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  491.                                 }
  492.                                 if($this->campaignService->isMyCompany($campaign->getCompany(), $user) || $this->campaignService->isMyEmailSameExtensionOfCompanyExtension($campaign->getCompany(),$user)){
  493.                         
  494.                                      $user->setCompany($campaign->getCompany());
  495.                                      $role =  $this->campaignService->getRoleForInternalClient(Role::tryFrom($role ));
  496.                                   
  497.                                     switch ($role->value) {
  498.                                             case 'ROLE_OBSERVER':
  499.                                                 
  500.                                                 $observerList = [...$observerList$user->getEmail()];
  501.                                                 break;
  502.                                             case 'ROLE_VALIDATOR':
  503.                                                 $defaultValidator = [...$defaultValidator$user->getEmail()];
  504.                                                 break;
  505.                                     }
  506.                                 }else{
  507.                                     
  508.                                         $role =  $this->campaignService->getRoleForExternalClient(Role::from($role ));
  509.                                      
  510.                                         switch ($role->value) {
  511.                                             case 'ROLE_VALIDATOR_EXTERNAL':
  512.                                                 $defaultValidatorExternal = [...$defaultValidatorExternal$user->getEmail()];
  513.                                                 break;
  514.                                             case 'ROLE_OBSERVER_EXTERNAL':
  515.                                                 $defaultObserverExernal = [...$defaultObserverExernal$user->getEmail()];
  516.                                                 break;
  517.                                     }
  518.                                 }
  519.                                  $campaignWpEditService->addPartipant($mission$email$role->value );
  520.                             }                                       
  521.                         }
  522.                 }
  523.     
  524.                 
  525.                 $campaign->setDefautObserver($observerList);
  526.                 $campaign->setDefautObserverExternal($defaultObserverExernal);
  527.     
  528.                 $campaign->setDefaultValidator($defaultValidator);
  529.                 $campaign->setDefaultValidatorExternal($defaultValidatorExternal);
  530.                 $campaign->setLastStepWp(4);
  531.                 $entityManager->flush();
  532.     
  533.                 $pathCampaing 'file_campaing_directory';
  534.                 $pathMission 'file_mission_directory';
  535.                 foreach ($attachements as $file) {
  536.                     $destination $this->getParameter($pathCampaing) . '/' $campaign->getId();
  537.                     $originalFilename pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  538.                     $newFilename $originalFilename '-' uniqid() . '.' $file->guessExtension();
  539.                     $file->move(
  540.                         $destination,
  541.                         $newFilename
  542.                     );
  543.                     $fileMission = new FileMission();
  544.                     $fileMission->setName($newFilename);
  545.                     $campaign->addFileMission($fileMission);
  546.     
  547.                     //add to mission 
  548.                     foreach ($campaign->getMissions() as $mission) {
  549.                        
  550.                         $destinationFileMission $this->getParameter($pathMission) . '/' $mission->getId();
  551.                         if (!is_dir($destinationFileMission)) {
  552.                             mkdir($destinationFileMission0755true);
  553.                         }
  554.     
  555.                         copy($destination '/' $newFilename$destinationFileMission '/' $newFilename);
  556.                         $fileMission = new FileMission();
  557.                         $fileMission->setName($newFilename);
  558.                         $mission->addFileMission($fileMission);
  559.                     }
  560.                 }
  561.                 $entityManager->flush();
  562.                return  $this->redirectToRoute('campaign_recapitulatif',[
  563.                     'id'=>$campaign->getId(),
  564.                     'showStep'=> 'step'
  565.                 ]);
  566.             }
  567.             $creditHistories$companyService->getAvailableContract(creditHistories$creditHistoryRepository->findAvailableServiceHistory($campaign->getCompany(),new \DateTime()));
  568.             $creditHistoriesFormated array_reduce($creditHistories, function($carry$item){ return  [...$carry, ...$item];},[]);
  569.             $participants =  $missionParticipantService->getParticipants($campaign'user'false);
  570.     
  571.             return $this->render('/draft/edit.html.twig',[
  572.                 'campaign'=>$campaign
  573.                 'form_wp_edit'=> $formWpEdit->createView(),
  574.                 'credit_histories' => $creditHistoriesFormated
  575.                 'participants_client' => $missionParticipantService->getClient($campaign''false), 
  576.                 'participants_subcontractor' => $missionParticipantService->getSubcontractorWithMissing($campaign), 
  577.                 'step'=> $campaign->getLastStepWp() != null ? ($campaign->getLastStepWp() == $campaign->getLastStepWp()) : 1,
  578.                 'show_step'=>true
  579.             ]);
  580.         }
  581.         $this->addFlash('error','Cette commande n\'est pas un brouillon !');
  582.         return $this->redirectToRoute('mission_index');
  583.     }
  584.     #[Route('/campaigns/draft/validate/{id}/{fromRecap}'name'validate_draft'methods: ['GET'], defaults:['fromRecap'=>''])] 
  585.     public function validateDraft(Campaign $campaign,string $fromRecap,CampaignRecurrentService $campaignRecurrentServiceEventDispatcherInterface $dispatcherEntityManagerInterface $entityManagerRequest $request): RedirectResponse
  586.     {
  587.         
  588.         $isDevis sizeof($campaign->getMissions()) == 0  true false
  589.         $campaign->setState($isDevis 'provisional' 'waiting') ;
  590.         if ($campaign->getActiveFrequency()) {
  591.             $now = new \DateTime();
  592.             $startDate $campaign->getFrequency()->getStartDate();
  593.             $hours $now->format('G');
  594.             $minutes $now->format('i');
  595.             $second $now->format('s');
  596.             $newStartDate $startDate->setTime($hours$minutes$second);
  597.             $campaign->getFrequency()->setStartDate($newStartDate);
  598.             $campaign->setIsRecurrent(true);
  599.             $campaign->setRecurringState('in_progress');
  600.             $campaign->setState('recurred');
  601.             
  602.             //create a campaign in new start date
  603.             $eventRecurrent = new CampaignRecurrentEvent($campaigntrue);
  604.             $dispatcher->dispatch($eventRecurrentCampaignRecurrentEvent::NAME);
  605.             if($now->format('y/d/m G:i') >=  $startDate->format('y/d/m G:i')){
  606.                 $campaignRecurrentService->updateLaunchRecurringAt($campaign);
  607.                 $newCampaign =  $campaignRecurrentService->clone($campaign);
  608.                 $entityManager->persist($newCampaign);
  609.                 $campaign $newCampaign;
  610.             }else{
  611.                  $campaignRecurrentService->updateLaunchRecurringAt(campaign:$campaign,dateToLaunch:$newStartDate);
  612.             }
  613.             $entityManager->flush();
  614.      
  615.         }
  616.         
  617.         $event $isDevis ? new CampaignCreatedEvent($campaign'CREATION_DEVIS') :  new CampaignCreatedEvent($campaign);
  618.         $dispatcher->dispatch($eventCampaignCreatedEvent::NAME);
  619.         $this->addFlash('success','Commande enregistrée avec succès');
  620.         $entityManager->flush();
  621.         $fromRecap $fromRecap == "recap" true false
  622.         return  $fromRecap  $this->redirectToRoute('mission_index') : $this->redirect($request->headers->get('referer'));
  623.     }
  624.     #[Route('/api/campaigns'name'api_campaigns_create'methods: ['POST''GET'])]
  625.     public function create(Request $request,CampaignWpEditService $campaignWpEditService,  CampaignRecurrentService $campaignRecurrentServiceEntityManagerInterface $entityManagerSerializerInterface $serializerCreditHistoryRepository $creditHistoryRepository,  WorkflowRepository $workflowRepositoryUserRepository $userRepositoryEventDispatcherInterface $dispatcherUserPasswordHasherInterface $passwordHasherMissionService $missionServiceMailerInterface $mailerMissionRepository $missionRepository,GoogleStorageService $googleStorageService): JsonResponse
  626.     {
  627.         
  628.        
  629.         $campaign = new Campaign();
  630.         $form $this->createForm(CampaignType::class, $campaign);
  631.         $form->handleRequest($request);
  632.        
  633.         // $errors = $form->getErrors(true, true);
  634.         // foreach ($errors as $error) {
  635.         //     mail('r.rado@yopmail.com','name',$error->getOrigin()->getName());
  636.         //     mail('r.rado@yopmail.com','valeur',$error->getOrigin()->getData());
  637.         //     mail('r.rado@yopmail.com','message',$error->getMessage());
  638.         //     mail('r.rado@yopmail.com', 'Erreur : Fichier',$error->getCause() );
  639.         //     mail('r.rado@yopmail.com', 'Erreur : Ligne',$error->getMessageTemplate());
  640.         // }
  641.         
  642.         // mail('r.rado@yopmail.com','kmlkjmlkj',$campaign->getConfidentiality() ? "true": "false");
  643.         // mail('r.rado@yopmail.com','user',$campaign->getOrderedBy()!=null ? $campaign->getOrderedBy()->getFullName(): "false");
  644.         if ($form->isSubmitted() && $form->isValid()) {
  645.             $stateDraft"";
  646.           
  647.             if($campaign->getLastStepWp()!=null){
  648.                 $stateDraft 'draft';
  649.                 //$campaignWpEditService->deleteOldDraft($campaign);  
  650.             }
  651.             $newUserCreateId = [];
  652.             $launchJustOne true;
  653.             $isDevis false;
  654.             $observerList = [];
  655.             $defaultValidator = [];
  656.             $defaultValidatorExternal = [];
  657.             $defaultObserverExernal = [];
  658.             $company $campaign->getOrderedBy()->getCompany();
  659.             $creditHistoryId $form->get('creditserviceId')->getData();
  660.             $orderedByAdmin $request->query->get('ordered_by_admin'"false") == "true" true false;
  661.             $idAdmin = (!is_null($request->query->get('admin_id'))) ? $request->query->get('admin_id') : false;
  662.             $campaignTypeInitiation CampaignTypeInitiation::CAMPAIGN_FROM_TUNNEL_CLIENT->value;
  663.             $historyActionCampaignInitiation 'campaign_initiate_by_tunnel_client';
  664.             if (empty($creditHistoryId) or is_null($creditHistoryId)) {
  665.                 $creditHistory $creditHistoryRepository->findBy(['company'=>$company,'typePack' => '4']);
  666.                 if (empty($creditHistory)) {
  667.                     $creditHistory $creditHistoryRepository->findBy(['company'=>$company])[0];
  668.                 }else{
  669.                     $creditHistory $creditHistory[0];
  670.                 }
  671.             }else{
  672.                 $creditHistory $creditHistoryRepository->findOneById($creditHistoryId);
  673.             }
  674.             $campaign->setCompany($company);
  675.             $campaign->setCreditHistory($creditHistory);
  676.   
  677.             $campaign->setBrief(nl2br($this->utilsService->formatLinkToAnchor($campaign->getBrief())));
  678.             $campaign->setIsOrdoredByAdmin($orderedByAdmin);
  679.          
  680.             $attachments explode('|'$form->get('attachments')->getData());
  681.             $participants explode('|'$form->get('participants')->getData());
  682.             $verifOrderByIsHer false;
  683.             foreach ($participants as $p) {
  684.                 if (strpos($p$campaign->getOrderedBy()->getEmail()) !== false) {
  685.                     $verifOrderByIsHer true;
  686.                 }
  687.                
  688.             }
  689.             if (!$verifOrderByIsHer ) {
  690.                 $participants[] = "{$campaign->getOrderedBy()->getEmail()},ROLE_VALIDATOR";
  691.             } 
  692.             
  693.             $state 'waiting';
  694.             foreach ($campaign->getMissions() as $mission) {
  695.                 $mission->setInitialBriefing(nl2br($this->utilsService->formatLinkToAnchor($mission->getInitialBriefing())));
  696.                 if ($mission->getProduct()->getType() === ProductType::A_EVALUER) {
  697.                     $state 'waiting';
  698.                 }
  699.             }
  700.           
  701.             if ($campaign->getMissions()->count() === 0) {
  702.                 $state 'provisional';
  703.                 $isDevis true;
  704.                 $campaignTypeInitiation CampaignTypeInitiation::CAMPAIGN_FROM_DEVIS_CLIENT->value;
  705.                 //send mail new user in demande de devis
  706.               
  707.                 foreach ($participants as $participant) {
  708.                     if (!empty($participant)) {
  709.                         [$email$role] = explode(','$participant);
  710.                         $user $userRepository->findOneBy(['email' => $email]);
  711.                         $role_client "ROLE_CLIENT";
  712.                         if (null === $user) {
  713.                             $user = (new User())
  714.                                 ->setEmail($email)
  715.                                 ->setRoles([$role_client])
  716.                                 ->setEnabled(false)
  717.                                 ->setIsNewClient(true)
  718.                                 ;
  719.                             $user->setPassword($passwordHasher->hashPassword($user$user->getPassword()));
  720.                             $entityManager->persist($user);
  721.                             $entityManager->flush();
  722.                             $event = new ClientUpdatedEvent($usertrue);
  723.                             $newUserCreateId[] = $user->getId();
  724.                             $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  725.                         }
  726.                         if($this->campaignService->isMyCompany($campaign->getCompany(), $user) || $this->campaignService->isMyEmailSameExtensionOfCompanyExtension($campaign->getCompany(),$user)){
  727.                         
  728.                             $role =  $this->campaignService->getRoleForInternalClient(Role::from($role ));
  729.                             $user->setCompany($campaign->getCompany());
  730.             
  731.                             switch ($role->value) {
  732.                                     case 'ROLE_OBSERVER':
  733.                                         
  734.                                         $observerList = [...$observerList$user->getEmail()];
  735.                                         break;
  736.                                     case 'ROLE_VALIDATOR':
  737.                                         $defaultValidator = [...$defaultValidator$user->getEmail()];
  738.                                         break;
  739.                                 }
  740.                             }else{
  741.                 
  742.                                 $role =  $this->campaignService->getRoleForExternalClient(Role::from($role ));
  743.                                 switch ($role->value) {
  744.                                     case 'ROLE_VALIDATOR_EXTERNAL':
  745.                                         $defaultValidatorExternal = [...$defaultValidatorExternal$user->getEmail()];
  746.                                         break;
  747.                                     case 'ROLE_OBSERVER_EXTERNAL':
  748.                                         $defaultObserverExernal = [...$defaultObserverExernal$user->getEmail()];
  749.                                         break;
  750.                             }
  751.                         }
  752.                         
  753.                     }
  754.                 }
  755.               
  756.                 //creation piece jointe
  757.                 $filesystem = new Filesystem();
  758.                 foreach ($attachments as $attachment) {
  759.                     if (!empty($attachment)) {
  760.                        $fileContent file_get_contents($attachment);
  761.                         // Créez une instance de fichier téléchargé à partir du contenu téléchargé
  762.                         $tempFilePath tempnam(sys_get_temp_dir(), 'file');
  763.                         file_put_contents($tempFilePath$fileContent);
  764.                         $uploadedFile = new UploadedFile(
  765.                             $tempFilePath,
  766.                             basename($attachment), 
  767.                             mime_content_type($tempFilePath)
  768.                         );
  769.                         $originalFilename pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
  770.                         $extensionFile =  pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_EXTENSION);
  771.                         $newFilename $originalFilename '-' uniqid() . '.' $extensionFile;
  772.                          //upload file in google storage
  773.                         $nameUniqueCompany strtolower("company-".$campaign->getCompany()->getId());
  774.                         $this->googleStorageService->uploadFile($nameUniqueCompany,$uploadedFile,$newFilename,'Campaigns/'.$campaign->getId());
  775.                         $fileMission = new FileMission();
  776.                         $fileMission->setName($newFilename);
  777.                         $fileMission->setIsNew(1);
  778.                         $fileMission->setUser($campaign->getOrderedBy());
  779.                         $fileMission->setUser($campaign->getOrderedBy());
  780.                         $campaign->addFileMission($fileMission);
  781.                     }
  782.                 }
  783.                 $campaign->setDefautObserver($observerList);
  784.                 $campaign->setDefaultValidator($defaultValidator)
  785.                         ->setDefaultValidatorExternal($defaultValidatorExternal)
  786.                         ->setDefautObserverExternal($defaultObserverExernal);
  787.                       
  788.             }
  789.             
  790.             $state $stateDraft ==  'draft' $stateDraft  $state ;
  791.             
  792.             $campaign->setState($state);
  793.             foreach ($campaign->getMissions() as $mission) {
  794.                 if (empty($mission->getReference())) {
  795.                     $mission->setReference($missionService->generateReference());
  796.                 }
  797.                 if (
  798.                     $state === 'waiting' &&
  799.                     ($mission->getProduct()->getType() === ProductType::AU_FORFAIT) || ($mission->getProduct()->getType() === ProductType::AU_TEMPS_PASSE)
  800.                 ) {
  801.                     $mission->setState('provisional');
  802.                 } else {
  803.                     $mission->setState($state);
  804.                 }
  805.                 $mission->getState() === 'waiting' ?  $mission->setStateProvider('A évaluer') : $mission->setStateProvider('A activer');
  806.                 // recalculate the price of a mission from a product price not from a price of a mission
  807.                 $mission->setOriginalPrice($mission->getProduct()->getPrice());
  808.                 if ($mission->getProduct()->getType() != ProductType::AU_FORFAIT) {
  809.                     $mission->setPrice(null);
  810.                     $mission->setOriginalPrice(null);
  811.                 }
  812.                 $mission->setDiscountForCompany($campaign->getCompany()->getCustomerDiscount());
  813.                 $campaign->setPaymentMethod($campaign->getCompany()->getContract());
  814.                 $campaign->setDiscountForCompany($campaign->getCompany()->getCustomerDiscount());
  815.                 if ($campaign->getCompany()->getContract() == 0) {
  816.                     $DEFAULT_CREADIT_COST 220;
  817.                     $mission->setPrice(round($mission->getOriginalPrice() / $DEFAULT_CREADIT_COST2));
  818.                     $campaign->setIsPaidOnCredit(true);
  819.                 } else {
  820.                     $discountValueForOneCompany $campaign->getCompany()->getCustomerDiscount() / 100;
  821.                     $mission->setPrice($mission->getOriginalPrice() - $mission->getOriginalPrice() * $discountValueForOneCompany);
  822.                     $campaign->setIsPaidOnCredit(false);
  823.                 }
  824.                 $filesystem = new Filesystem();
  825.                 foreach ($attachments as $attachment) {
  826.                     if (!empty($attachment)) {
  827.                         $fileContent file_get_contents($attachment);
  828.                         // Créez une instance de fichier téléchargé à partir du contenu téléchargé
  829.                         $tempFilePath tempnam(sys_get_temp_dir(), 'file');
  830.                         file_put_contents($tempFilePath$fileContent);
  831.                         $uploadedFile = new UploadedFile(
  832.                             $tempFilePath,
  833.                             basename($attachment), 
  834.                             mime_content_type($tempFilePath)
  835.                         );
  836.                         $originalFilename pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
  837.                         $extensionFile =  pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_EXTENSION);
  838.                         $newFilename $originalFilename '-' uniqid() . '.' $extensionFile;
  839.                          //upload file in google storage
  840.                         $nameUniqueCompany strtolower("company-".$campaign->getCompany()->getId());
  841.                         $this->googleStorageService->uploadFile($nameUniqueCompany,$uploadedFile,$newFilename,'Campaigns/'.$campaign->getId());
  842.                         $fileMission = new FileMission();
  843.                         $fileMission->setName($newFilename);
  844.                         $fileMission->setIsNew(1);
  845.                         $fileMission->setUser($campaign->getOrderedBy());
  846.                         $fileMission->setUser($campaign->getOrderedBy());
  847.                         $campaign->addFileMission($fileMission);
  848.                     }
  849.                 }
  850.                 $workflow $workflowRepository->findOneBy(['template' => true'product' => $mission->getProduct(), 'company' => $campaign->getCompany(), 'active' => true]);
  851.                 if (null === $workflow) {
  852.                     $workflow $workflowRepository->findOneBy(['template' => true'product' => $mission->getProduct(), 'active' => true]);
  853.                     if (null === $workflow) {
  854.                         $mission->setWorkflow(null);
  855.                         $event = new MissionWithoutWorkflowEvent($mission);
  856.                         /*$dispatcher->dispatch($event, MissionWithoutWorkflowEvent::NAME);*/
  857.                         $this->onMissionWithoutWorkflow($event$userRepository$mailer);
  858.                     }
  859.                 }
  860.                 if (null !== $workflow) {
  861.                     $missionWorkflow = clone $workflow;
  862.                     $missionWorkflow->setTemplate(false);
  863.                     $mission->setWorkflow($missionWorkflow);
  864.                     $missionWorkflow->setMission($mission);
  865.                     foreach ($missionWorkflow->getSteps() as $step) {
  866.                         foreach ($step->getActions() as $action) {
  867.                             if ($action->getRecipient() == Role::ROLE_OBSERVER_EXTERNAL or $action->getRecipient() == Role::ROLE_VALIDATOR_EXTERNAL) {
  868.                                 //take user and integrating in external user
  869.                                 foreach ($action->getUser() as $user) {
  870.                                     $participant = (new MissionParticipant())
  871.                                         ->setUser($user)
  872.                                         ->setMission($mission)
  873.                                         ->setRole(Role::tryFrom($action->getRecipient()->value));
  874.                                     $mission->addParticipant($participant);
  875.                                     $event = new ContactAddedEvent($mission$user$participant);
  876.                                     $dispatcher->dispatch($eventContactAddedEvent::NAME);
  877.                                 }
  878.                             }
  879.                         }
  880.                     }
  881.                 }
  882.                 $filesystem = new Filesystem();
  883.                 $listIdUser = [];
  884.                 foreach ($participants as $participant) {
  885.                     if (!empty($participant)) {
  886.                         [$email$role] = explode(','$participant);
  887.                         $isExternal false
  888.                         $user $userRepository->findOneBy(['email' => $email]);
  889.                         if($this->campaignService->isMyCompany($campaign->getCompany(), $user) || $this->campaignService->isMyEmailSameExtensionOfCompanyExtension($campaign->getCompany(),$user)){
  890.                             $isExternal false
  891.                             $role =  $this->campaignService->getRoleForInternalClient(Role::tryFrom($role ));
  892.                             $user->setCompany($campaign->getCompany());
  893.             
  894.                             switch ($role->value) {
  895.                                     case 'ROLE_OBSERVER':
  896.                                         
  897.                                         $observerList = [...$observerList$user->getEmail()];
  898.                                         break;
  899.                                     case 'ROLE_VALIDATOR':
  900.                                         $defaultValidator = [...$defaultValidator$user->getEmail()];
  901.                                         break;
  902.                                 }
  903.                             }else{
  904.                                 $isExternal true;
  905.                                 $role =  $this->campaignService->getRoleForExternalClient(Role::tryFrom($role ));
  906.                                 switch ($role->value) {
  907.                                     case 'ROLE_VALIDATOR_EXTERNAL':
  908.                                         $defaultValidatorExternal = [...$defaultValidatorExternal$user->getEmail()];
  909.                                         break;
  910.                                     case 'ROLE_OBSERVER_EXTERNAL':
  911.                                         $defaultObserverExernal = [...$defaultObserverExernal$user->getEmail()];
  912.                                         break;
  913.                             }
  914.                         }
  915.                         if (null === $user) {
  916.                             //role external is just a client
  917.                             $role_client "ROLE_CLIENT";
  918.                             $user = (new User())
  919.                                 ->setEmail($email)
  920.                                 ->setRoles([$role_client])
  921.                                 ->setEnabled(false)
  922.                                 ->setIsNewClient(true)
  923.                                 ;
  924.                             if ($isExternal) {
  925.                                 $user->setExternal(true);
  926.                             }
  927.                             $user->setPassword($passwordHasher->hashPassword($user$user->getPassword()));
  928.                             $entityManager->persist($user);
  929.                             $entityManager->flush();
  930.                             $event = new ClientUpdatedEvent($usertrue);
  931.                             $newUserCreateId[] = $user->getId();
  932.                             $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  933.                         } else {
  934.                             if (!in_array($user->getId(), $newUserCreateId) && true === $launchJustOne) {
  935.                                 if ($user->getId() != $mission->getCampaign()->getOrderedBy()->getId()) {
  936.                                     $event = new MissionSendEvent($mission$user$role);
  937.                                     $dispatcher->dispatch($eventMissionSendEvent::NAME);
  938.                                 }
  939.                             }
  940.                         }
  941.                         $participant = (new MissionParticipant())
  942.                             ->setUser($user)
  943.                             ->setMission($mission)
  944.                             ->setRole$role);
  945.                         if (in_array($user->getId(), $listIdUser)) {
  946.                             $participant->setInitialTime(0)
  947.                                 ->setEstimatedIncome(0)
  948.                                 ->setAdminTime(0)
  949.                                 ->setEstimatedIncomeAdmin(0)
  950.                                 ->setActivated(1);
  951.                         }
  952.                         $listIdUser[] = $user->getId();
  953.                         $mission->addParticipant($participant);
  954.                         if ($role == "ROLE_OBSERVER") {
  955.                             $observerList = [...$observerList$email];
  956.                         }
  957.                     }
  958.                 }
  959.                 $launchJustOne false;
  960.             }
  961.             try {
  962.                 $campaign->setNumberInitialOfMissions(sizeof($campaign->getMissions()));
  963.                 $campaign->setDefautObserver($observerList);
  964.                 $campaign->setTypeInitiation($campaignTypeInitiation);
  965.                 $entityManager->persist($campaign);
  966.                 $entityManager->flush();
  967.                 foreach ($campaign->getMissions() as $mission) {
  968.                     $this->missionService->addHistorique(mission$missionuser:$campaign->getOrderedBy() , action$historyActionCampaignInitiation);
  969.                     $listOfUser = [];
  970.                     foreach ($mission->getParticipants() as $participant) {
  971.                         if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR) {
  972.                             if (in_array($participant->getUser()->getId(), $listOfUser)) {
  973.                                 $participant->setInitialTime(0)
  974.                                     ->setEstimatedIncome(0)
  975.                                     ->setInitialTimeAdmin(0)
  976.                                     ->setEstimatedIncomeAdmin(0)
  977.                                     ->setActivated(1);
  978.                                 $entityManager->persist($participant);
  979.                                 $entityManager->flush();
  980.                             }
  981.                             $listOfUser[] = $participant->getUser()->getId();
  982.                         }
  983.                     }
  984.                 }
  985.                 $missionsPersited $campaign->getMissions();
  986.                 foreach ($missionsPersited as $missionPersisted) {
  987.                     if ($missionPersisted->getWorkflow() !== null && count($missionPersisted->getWorkflow()->getSteps()) > 0) {
  988.                         $missionPersisted->getWorkflow()->getSteps()->first()->setActive(false);
  989.                     }
  990.                     $missionPersisted->setOldCommand("{$missionPersisted->getQuantity()}-{$missionPersisted->getPrice()}-{$missionPersisted->getProduct()->getId()}-{$mission->getDesiredDelivery()->getTimestamp()}");
  991.                 }
  992.                 $entityManager->flush();
  993.                
  994.                 if ($campaign->getActiveFrequency() && $campaign->getState() != "draft") {
  995.                     $now = new \DateTime();
  996.                     $startDate $campaign->getFrequency()->getStartDate();
  997.                     $campaignTypeInitiation CampaignTypeInitiation::CAMPAIGN_FROM_RECURRENT->value;
  998.                     $historyActionCampaignInitiation 'campaign_initiate_by_recurrent';
  999.                     $hours $now->format('G');
  1000.                     $minutes $now->format('i');
  1001.                     $second $now->format('s');
  1002.                     $newStartDate $startDate->setTime($hours$minutes$second);
  1003.                     $campaignTypeInitiation CampaignTypeInitiation::CAMPAIGN_FROM_RECURRENT->value;
  1004.                     $campaign->getFrequency()->setStartDate($newStartDate);
  1005.                     $campaign->setIsRecurrent(true);
  1006.                     if( !is_null($orderedByAdmin) && isset($orderedByAdmin) &&  $orderedByAdmin != false ){
  1007.                         $campaign->setRecurringState('waiting_validation');
  1008.                     }else{
  1009.                         $campaign->setRecurringState('in_progress');
  1010.                     }
  1011.                     $campaign->setState('recurred');
  1012.                     $campaign->setTypeInitiation($campaignTypeInitiation);
  1013.                     //create a campaign in new start date
  1014.                     if($campaign->getState() != "draft"){
  1015.                         $eventRecurrent = new CampaignRecurrentEvent($campaigntrue);
  1016.                         $dispatcher->dispatch($eventRecurrentCampaignRecurrentEvent::NAME);
  1017.                     }
  1018.                     if($now->format('y/d/m G:i') >=  $startDate->format('y/d/m G:i') &&  $campaign->getRecurringState()!='waiting_validation'){
  1019.                        
  1020.                         $campaign->getFrequency()->setStartDate(new \DateTime());
  1021.                         $campaignRecurrentService->updateLaunchRecurringAt($campaign);
  1022.                         $newCampaign =  $campaignRecurrentService->clone($campaign);
  1023.                         $entityManager->persist($newCampaign);
  1024.                         $campaign $newCampaign;
  1025.                         // $this->createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$campaign,$now,$entityManager);
  1026.                     }elseif($campaign->getRecurringState()!='waiting_validation'){
  1027.                          $campaignRecurrentService->updateLaunchRecurringAt(campaign:$campaign,dateToLaunch:$newStartDate);
  1028.                     }
  1029.                     $entityManager->flush();
  1030.              
  1031.                 }
  1032.                 if($campaign->getState()!='provisional'){
  1033.                     foreach($campaign->getMissions() as $mission) {
  1034.                         $this->missionService->addHistorique(mission$missionuser:$campaign->getOrderedBy() , action:$historyActionCampaignInitiation);
  1035.                     } 
  1036.                 }
  1037.                 
  1038.                 
  1039.                 if($campaign->getState() != "draft" && $campaign->getRecurringState()!='waiting_validation'){
  1040.                     $event $isDevis ? new CampaignCreatedEvent($campaign'CREATION_DEVIS') :  new CampaignCreatedEvent($campaign);
  1041.                     $dispatcher->dispatch($eventCampaignCreatedEvent::NAME);
  1042.                 }
  1043.                 
  1044.                 return new JsonResponse(
  1045.                     json_decode($serializer->serialize($campaign'json', [AbstractNormalizer::GROUPS => ['campaign']])),
  1046.                     Response::HTTP_CREATED
  1047.                 );
  1048.             } catch (\Exception $e) {
  1049.                 foreach (array_unique($newUserCreateId) as $id) {
  1050.                     $user $userRepository->findOneBy(['id' => $id]);
  1051.                     $entityManager->remove($user);
  1052.                     $entityManager->flush();
  1053.                 }
  1054.                 $campaign->setErrorCommand($e->getMessage());
  1055.                 $event = new AdminCommandErrorEvent($campaign);
  1056.                 $dispatcher->dispatch($eventAdminCommandErrorEvent::NAME);
  1057.             }
  1058.         }
  1059.         return new JsonResponse([], Response::HTTP_BAD_REQUEST);
  1060.     }
  1061.     private function createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign,$now,$entityManager){
  1062.        
  1063.         $campaignRecurrentService->updateLaunchRecurringAt($originalCampaign);
  1064.         $campaignFrequency $originalCampaign->getFrequency()->getLaunchRecurrenceAt();
  1065.         $newCampaign =  $campaignRecurrentService->clone($originalCampaign);
  1066.         $campaign $newCampaign;
  1067.         $entityManager->persist($campaign);
  1068.         $entityManager->flush();
  1069.         if($campaignFrequency<$now){
  1070.             $this->createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign$now,$entityManager);
  1071.         }
  1072.         return;
  1073.     }
  1074.     /**
  1075.      * Display the view/handle how to edit a campaign
  1076.      *
  1077.      * @param Campaign $campaign - the campaign to edit
  1078.      * @param Request $request
  1079.      * @param EntityManagerInterface $entityManager
  1080.      *
  1081.      * @return Response template /mission/handle_campaign.html.twig
  1082.      */
  1083.     #[Route('/campagnes/{id}'name'campaign_edit')]
  1084.     public function edit(Campaign $campaignRequest $requestEntityManagerInterface $entityManager): Response
  1085.     {
  1086.         $form $this->createForm(CampaignType::class, $campaign);
  1087.         $form->handleRequest($request);
  1088.         if ($form->isSubmitted() && $form->isValid()) {
  1089.             $this->addFlash('success''La campagne a bien été modifiée');
  1090.             $entityManager->flush();
  1091.             return $this->redirectToRoute('mission_index');
  1092.         }
  1093.         return $this->renderForm('campaign/edit.html.twig', [
  1094.             'form' => $form,
  1095.             'campaign' => $campaign,
  1096.         ]);
  1097.     }
  1098.     #[Route('/campaign/{id}/uncancelled'name"campaign_uncancelled")]
  1099.     public function campaignUncancelled(Campaign $campaignEntityManagerInterface $entityManagerInterface,EventDispatcherInterface $dispatcher,MissionService $missionService): Response
  1100.     {
  1101.         $campaign->setState($campaign->getLastState());
  1102.         foreach ($campaign->getMissions() as $mission) {
  1103.             $mission->setState($mission->getLastState());
  1104.         }
  1105.         $event = new CampaignResumeEvent($campaigntrue);
  1106.         $dispatcher->dispatch($eventCampaignResumeEvent::NAME);
  1107.         foreach ($campaign->getMissions() as $mission) {
  1108.             $missionService->addHistorique(mission$missionuser$this->getUser(), action"unpause");
  1109.         }
  1110.         $entityManagerInterface->flush();
  1111.         $this->addFlash(
  1112.             type'success',
  1113.             message"La campagne reprend avec succès ",
  1114.         );
  1115.         return $this->redirectToRoute('mission_index');
  1116.     }
  1117.     /**
  1118.      * If applicable, apply the workflow transition $transition on a campaign
  1119.      * and on all its missions.
  1120.      *
  1121.      * Only validate, pause, unpause, cancel and archived transitions are allowed
  1122.      *
  1123.      * @param Campaign $campaign - the campaign on whom to apply the transition
  1124.      * @param string $transition - the transition to apply
  1125.      * @param Registry $workflows
  1126.      * @param EntityManagerInterface $entityManager
  1127.      * @param EventDispatcherInterface $dispatcher
  1128.      *
  1129.      * @return Response Redirect to the mission's index
  1130.      */
  1131.     #[Route('/campagne/{id}/{transition<validate|pause|unpause|resend|cancel|archive|validation_by_client|activated|closed|delete|decline>}/{currentRouteName}/{firstClickedMissionId?}/{subcontractorId?}'name'campaign_transition'defaults: ['currentRouteName' => null'firstClickedMissionId' => null'subcontractorId' => null])]
  1132.     public function transition(Campaign $campaignMissionParticipantService $missionParticipantServiceClientSoldService $clientSoldServiceNumberFormatService $numberFormatServiceCampaignService $campaignServiceMissionService $missionServicestring $transitionRegistry $workflowsEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcherRequest $requestPriceService $priceServiceWorkflowStepRepository $workflowStepRepositoryBalanceTransactionsRepository $balanceTransactionsRepository$currentRouteName null$firstClickedMissionId null$subcontractorId null): Response
  1133.     {
  1134.         $workflow $workflows->get($campaign'classic');
  1135.         $redirect $this->redirectToRoute('mission_index');
  1136.         if (isset($currentRouteName) && $currentRouteName == 'mission_edit' && isset($firstClickedMissionId)) {
  1137.             $redirect =  $this->redirectToRoute('mission_edit', ['id' => $firstClickedMissionId]);
  1138.         } 
  1139.         // clone original campagne 
  1140.         $originalCampaign =  clone $campaign;
  1141.         $originalMissions $originalCampaign->getMissions();
  1142.         if ($transition === "delete") {
  1143.             if($campaign->getState()=="draft"){
  1144.                 $campaign->setDeleteReason('Brouillon');
  1145.             }
  1146.             else {
  1147.                 $formDeleteCampaign $this->createForm(CampaignDeleteType::class, $campaign);
  1148.                 $formDeleteCampaign->handleRequest($request);
  1149.             }
  1150.             $campaign->setLastState($originalCampaign->getState());
  1151.             $pack $campaign->getCreditHistory();
  1152.             $isDeteleCampaignRecurrend $request->query->get('recurred') == true ?  true false;
  1153.             if (!$isDeteleCampaignRecurrend) {
  1154.                 // remove all price in creditHistory and BalanceTransaction if $transition is delete
  1155.                 $dataCampainState = ['in_progress''closed''cancelled''archived'];
  1156.                 if (in_array($campaign->getState(), $dataCampainState)) {
  1157.                     $totalAmountInBalance 0;
  1158.                     $isNull false;
  1159.                     $isNull count($campaign->getMissions()) === true false;
  1160.                     foreach ($campaign->getMissions() as $mission) {
  1161.                         $balanceTransaction $balanceTransactionsRepository->soldeByMission($pack$mission);
  1162.                         if (is_null($balanceTransaction)) {
  1163.                             $isNull true;
  1164.                             break;
  1165.                         }
  1166.                         $creditHistory $balanceTransaction->getCreditHistory();
  1167.                         $totalAmountInBalance += $balanceTransaction->getAmount();
  1168.                         $entityManager->remove($balanceTransaction);
  1169.                         $this->missionService->addHistorique($mission$this->getUser(),'mission_deleted',$mission);
  1170.                     }
  1171.                     if (!$isNull) {
  1172.                         $oldTotalConsuption $creditHistory->getTotalConsumption();
  1173.                         $oldCurrentBalance $creditHistory->getCurrentBalance();
  1174.                         $creditHistory->setTotalConsumption($oldTotalConsuption $totalAmountInBalance);
  1175.                         $creditHistory->setCurrentBalance($oldCurrentBalance $totalAmountInBalance);
  1176.                     }
  1177.                 }
  1178.               
  1179.                 foreach ($originalCampaign->getMissions() as $mission) {
  1180.                     $mission->setLastState($mission->getState());
  1181.                     $mission->setState('deleted');
  1182.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"deleted");
  1183.                 }
  1184.                 if($campaign->getState() !== "deleted"){
  1185.                     $event = new CampaignDeletedEvent($campaign$this->getUser());
  1186.                     $dispatcher->dispatch($eventCampaignDeletedEvent::NAME);
  1187.                 }
  1188.                 $campaign->setState('deleted');
  1189.             }
  1190.             else{
  1191.                 $campaign->setRecurringState('deleted');
  1192.             }
  1193.             $entityManager->flush();
  1194.             $this->addFlash(
  1195.                 type'success',
  1196.                 message"La campagne {$campaign->getName()} a bien été supprimée"
  1197.             );
  1198.             if ($isDeteleCampaignRecurrend) {
  1199.                 return $this->redirectToRoute('recurring_service');
  1200.             } elseif (isset($currentRouteName) && $currentRouteName == 'mission_edit' && isset($firstClickedMissionId)) {
  1201.                 return $this->redirectToRoute('mission_edit', ['id' => $firstClickedMissionId]);
  1202.             } else {
  1203.                 return $this->redirectToRoute('mission_index');
  1204.             }
  1205.         }
  1206.         
  1207.         if ($transition === 'decline') {
  1208.             foreach ($campaign->getMissions() as $mission) {
  1209.                 foreach ($mission->getParticipants() as $participant) {
  1210.                     if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR && $participant->getUser()->getId() == $subcontractorId) {
  1211.                         $entityManager->remove($participant);
  1212.                         $entityManager->flush();
  1213.                         $this->missionService->addHistorique($mission$this->getUser(), 'decline_mission');
  1214.                         continue 2;
  1215.                     }
  1216.                 }
  1217.             }
  1218.             $event = new CampaignDeclineEvent($campaigntrue$this->getUser());
  1219.             $dispatcher->dispatch($eventCampaignDeclineEvent::NAME);
  1220.             foreach ($campaign->getMissions() as $mission) {
  1221.                 $missionService->addHistorique(mission$missionuser$this->getUser(), action"refus");
  1222.             }
  1223.             
  1224.             $this->addFlash(
  1225.                 type'success',
  1226.                 message"La mission {$campaign->getName()} a bien été supprimée"
  1227.             );
  1228.         }
  1229.         if ($workflow->can($campaign$transition)) {
  1230.             $workflow->apply($campaign$transition);
  1231.             if ($transition === 'unpause') {
  1232.                 $event = new CampaignResumeEvent($campaigntrue);
  1233.                 $dispatcher->dispatch($eventCampaignResumeEvent::NAME);
  1234.                 foreach ($campaign->getMissions() as $mission) {
  1235.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"unpause");
  1236.                 }
  1237.             }
  1238.             if ($transition === 'resend') {
  1239.                 foreach ($campaign->getMissions() as $mission) {
  1240.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"resend");
  1241.                 }
  1242.             }
  1243.             if ($transition === 'pause') {
  1244.                 $event = new CampaignWaitingEvent($campaigntrue);
  1245.                 $dispatcher->dispatch($eventCampaignWaitingEvent::NAME);
  1246.                 foreach ($campaign->getMissions() as $mission) {
  1247.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"pause");
  1248.                 }
  1249.             }
  1250.             if ($transition === 'cancel') {
  1251.                 $formCancelCampaign $this->createForm(CampaignCancelType::class, $campaign);
  1252.                 $formCancelCampaign->handleRequest($request);
  1253.                 $campaign->setLastState($originalCampaign->getState());
  1254.                 foreach ($originalCampaign->getMissions() as $mission) {
  1255.                     $mission->setLastState($mission->getState());
  1256.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"cancel");
  1257.                 }
  1258.                 $entityManager->flush();
  1259.                 $event = new CampaignCancelledEvent($campaign$this->getUser(),);
  1260.                 $dispatcher->dispatch($eventCampaignCancelledEvent::NAME);
  1261.             }
  1262.             if ($transition === "closed") {
  1263.                 foreach ($campaign->getMissions() as $mission) {
  1264.                     $mission->setState('finalized');
  1265.                     $campaign->setIsToBeinvoiced(true);
  1266.                     if(sizeof($this->campaignApiService->getSubcontractorNoEstimatedIncome($campaign)) != 0){
  1267.                         $campaign->setState('closing_in_progress');
  1268.                     }
  1269.                     // if ($mission->getProduct()->getType() == ProductType::AU_TEMPS_PASSE) {
  1270.                     $clientSoldService->decreaseCurrentBalanceByMissionCost(mission$mission);
  1271.                     // }
  1272.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"closed");
  1273.                 }
  1274.             }
  1275.             foreach ($campaign->getMissions() as $mission) {
  1276.                 $workflow $workflows->get($mission'classic');
  1277.                 if ($workflow->can($mission$transition)) {
  1278.                     $workflow->apply($mission$transition);
  1279.                 }
  1280.             }
  1281.             // If we validate the campaign, we dispatch the campaign.validated event
  1282.             if ($transition === 'validate') {
  1283.                 $flag true;
  1284.                 foreach ($campaign->getMissions() as $mission) {
  1285.                     $i 0;
  1286.                     foreach ($mission->getParticipants() as $participant) {
  1287.                         if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR) {
  1288.                             $i++;
  1289.                         }
  1290.                         if ($i || $participant->getMission()->getStateProvider() == 'A évaluer') {
  1291.                             $flag false;
  1292.                         }
  1293.                     }
  1294.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"validate");
  1295.                 }
  1296.                 if ($flag == true) {
  1297.                     $event = new CampaignValidatedEvent($campaign);
  1298.                     $dispatcher->dispatch($eventCampaignValidatedEvent::NAME);
  1299.                 } else {
  1300.                     return $this->redirectToRoute('handle_mission_campaign', ['id' => $campaign->getId(), 'erreur' => true]);
  1301.                 }
  1302.             }
  1303.             if ($transition === 'activated') {
  1304.                 $canStartCampaign true;
  1305.                 $error false;
  1306.                 $userConnected $this->getUser();
  1307.                
  1308.                 if (in_array("ROLE_SUBCONTRACTOR"$userConnected->getRoles())) {
  1309.                     $message = [];
  1310.                     foreach ($campaign->getMissions() as $mission) {
  1311.                         $missionService->setDefaultValueIfAnUserClickedAnActivationButtonWithoutADelaisAndTimeIsEmpty($mission$priceService);
  1312.                        
  1313.                         //////////////////// Check marge mission  
  1314.                         $getMargeMyFlow $priceService->marginExceeded(mission$mission);
  1315.                         if ($missionService->isMyMission(mission$mission) and $getMargeMyFlow['percentage'] <= and $mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
  1316.                             if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
  1317.                                 $this->addFlash(
  1318.                                     type'error',
  1319.                                     message"Une action de l'administrateur est attendue pour pouvoir valider cette mission.",
  1320.                                 );
  1321.                                 $event = new MissionCanActivateEvent(mission$missionmarge$getMargeMyFlow['percentage'] );
  1322.                                 $dispatcher->dispatch($eventMissionCanActivateEvent::NAME);
  1323.                             }
  1324.                             $campaign->setState($originalCampaign->getState());
  1325.                             $mission->setState($mission->getLastState());
  1326.                             $entityManager->flush();
  1327.                             $canStartCampaign false;
  1328.                             continue; 
  1329.                             //return  $redirect;
  1330.                         }
  1331.                         ////////////////////////
  1332.                         foreach ($mission->getParticipants() as $missionParticipation) {
  1333.                             if (!$missionParticipation->isEvaluate() && !$missionParticipation->isActivated() && !$missionParticipation->isRefused() && $this->getUser() == $missionParticipation->getUser()) {
  1334.                                 $missionParticipation->setActivated(true);
  1335.                                 $missionParticipation->setActivatedAt(new \DateTime());
  1336.                                 $entityManager->flush();
  1337.                                 $this->missionService->addHistorique($mission$this->getUser(), 'accept_mission');
  1338.                                 //break;
  1339.                             }
  1340.                         }
  1341.                         $listUserNotEvaluate "";
  1342.                         $listUserEvaluate "";
  1343.                         $message = [=> "- Mission lancée avec succès"];
  1344.                         foreach ($missionService->determineAllSubcontractorEvaluated(mission$mission) as $userEvaluate) {
  1345.                             if ($userEvaluate != $this->getUser()) {
  1346.                                 $listUserNotEvaluate .= "{$userEvaluate->getFullName()} ,";
  1347.                             }
  1348.                             if (strlen($listUserNotEvaluate) > && $campaign->getState() != "resend") {
  1349.                                 $listUserNotEvaluate rtrim($listUserNotEvaluate",");
  1350.                                 $message[1] = " - Merci pour votre validation. Les intervenants suivants ont réévalué la mission. Nous attendons donc la validation du client pour démarrer le travail :  $listUserNotEvaluate.";
  1351.                             }
  1352.                         }
  1353.                         $allSubcontractorEvaluated $missionService->getListSubcontractorNotActivate(mission$mission);
  1354.                         $msg count($allSubcontractorEvaluated) > "Les intervenants suivants ont réévalué la mission" "L'intervenant suivant a réévalué la mission";
  1355.                         foreach ($allSubcontractorEvaluated as $userNotEvaluate) {
  1356.                             if ($userNotEvaluate != $this->getUser()) {
  1357.                                 $listUserNotEvaluate .= "{$userNotEvaluate->getFullName()} ,";
  1358.                             }
  1359.                             if (strlen($listUserNotEvaluate) > && $campaign->getState() != "resend") {
  1360.                                 $listUserNotEvaluate rtrim($listUserNotEvaluate",");
  1361.                                 $message[2] = " - Vous venez d'accepter la mission, nous attendons maintenant l'activation de l'intervenant ci-dessous pour démarrer le travail :  $listUserNotEvaluate.";
  1362.                             }
  1363.                         }
  1364.                         if ($missionService->lackSubcontractorTest(mission$mission) && sizeof($missionService->getListSubcontractorNotActivate(mission$mission)) == && !$missionService->aSubcontractorBotIsInThisMission(mission$mission)) {
  1365.                             $mission->setState('in_progress');
  1366.                             $entityManager->flush();
  1367.                             foreach ($originalMissions as $missionOriginal) {
  1368.                                 if (in_array($missionOriginal->getState(), ["cancelled""archived""closed"]) && $missionOriginal->getId() == $mission->getId()) {
  1369.                                     $mission->setState($originalMissions->getState());
  1370.                                     $entityManager->flush();
  1371.                                 }
  1372.                             }
  1373.                         } else {
  1374.                             if ($missionService->lackSubcontractorTest(mission$mission) && !$missionService->aSubcontractorBotIsInThisMission(mission$mission)) {
  1375.                                 $message[3] = "- Vous venez d'accepter la mission, nous attendons maintenant l'intervention de l'administrateur pour poursuivre le processus";
  1376.                                 $event = new SubcontractorActivateOrThereIsABotEvent($mission);
  1377.                                 $dispatcher->dispatch($eventSubcontractorActivateOrThereIsABotEvent::NAME);
  1378.                             }
  1379.                             $campaign->setState($campaign->getLastState());
  1380.                             foreach ($originalCampaign->getMissions() as $missionOriginal) {
  1381.                                 if ($missionOriginal->getId() == $mission->getId()) {
  1382.                                     $mission->setState("provisional");
  1383.                                 }
  1384.                             }
  1385.                             $entityManager->flush();
  1386.                             $canStartCampaign false;
  1387.                         }
  1388.                         foreach ($missionService->determineAllSubcontractorEvaluated(mission$mission) as $userEvaluate) {
  1389.                             if ($userEvaluate != $this->getUser()) {
  1390.                                 $listUserEvaluate .= "{$userEvaluate->getFullName()} ,";
  1391.                             }
  1392.                             if (strlen($listUserEvaluate) > 3) {
  1393.                                 $listUserEvaluate rtrim($listUserEvaluate",");
  1394.                                 $message[4] = " - Merci pour votre validation. " $msg ". Nous attendons donc la validation du client pour démarrer le travail :  $listUserEvaluate.";
  1395.                             }
  1396.                         }
  1397.                     }
  1398.                     if ($this->campaignService->canResendOrderToClient(campaign$mission->getCampaign(), missionEvaluate$mission) && $originalCampaign->getState() == "waiting_resend") {
  1399.                         $this->campaignService->resendCampaignForValidation(campaign$mission->getCampaign(), user$this->getUser());
  1400.                         $canStartCampaign false;
  1401.                     }
  1402.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"activation_campaign");
  1403.                     $allMessage "";
  1404.                     foreach ($message as $msg) {
  1405.                         //$allMessage .= "{$msg} <br> <br>";
  1406.                         $this->addFlash(
  1407.                             type'success',
  1408.                             message$msg,
  1409.                         );
  1410.                     }
  1411.                 } elseif (in_array("ROLE_ADMIN"$userConnected->getRoles())) {
  1412.                    
  1413.                     foreach ($campaign->getMissions() as $mission) {
  1414.                         //////////////////// Check marge mission  
  1415.                         $getMargeMyFlow $priceService->marginExceeded(mission$mission);
  1416.                         if ($getMargeMyFlow['percentage'] <= && $mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE ) {
  1417.                           
  1418.                                 $this->addFlash(
  1419.                                     type'error',
  1420.                                     message"Nous avons rencontré un problème, une des missions a une marge de {$getMargeMyFlow['percentage']} % .",
  1421.                                 );  
  1422.                                 $campaign->setState($originalCampaign->getState());
  1423.                                 $entityManager->flush();
  1424.                                  $canStartCampaign false;
  1425.                                 continue; 
  1426.                                 //return  $redirect;
  1427.                             }
  1428.                         foreach ($mission->getParticipants() as $missionParticipation) {
  1429.                             if (!$missionParticipation->isActivated() && !$missionParticipation->isRefused()) {
  1430.                                 $missionParticipation->setActivated(true);
  1431.                                 $missionParticipation->setEvaluate(false);
  1432.                                 $missionParticipation->setActivatedAt(new \DateTime());
  1433.                                 $entityManager->flush();
  1434.                             }
  1435.                         }
  1436.                         if ($mission->isEvaluate()) {
  1437.                             $mission->setEvaluate(false);
  1438.                         }
  1439.                         $missionService->addHistorique(mission$missionuser$this->getUser(), action"activation_campaign");
  1440.                     }
  1441.                     $canStartCampaign true;
  1442.                 } else {
  1443.                     foreach ($campaign->getMissions() as $mission) {
  1444.                         //////////////////// Check marge mission  
  1445.                         $missionCanActive true;
  1446.                         $getMargeMyFlow $priceService->marginExceeded(mission$mission);
  1447.                         if ($getMargeMyFlow['percentage'] <= 0) {
  1448.                             if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
  1449.                                 $event = new MissionCanActivateEvent($mission$getMargeMyFlow['percentage']);
  1450.                                 $dispatcher->dispatch($eventMissionCanActivateEvent::NAME);
  1451.                                 $missionCanActive false;
  1452.                                 
  1453.                             }
  1454.                             $missionCanActive false;
  1455.                             continue; 
  1456.                         }
  1457.                         foreach ($mission->getParticipants() as $missionParticipation) {
  1458.                             if ($missionParticipation->isEvaluate() && !$missionParticipation->isRefused()) {
  1459.                                 $missionParticipation->setActivated(true);
  1460.                                 $missionParticipation->setEvaluate(false);
  1461.                                 $missionParticipation->setActivatedAt(new \DateTime());
  1462.                                 $entityManager->flush();
  1463.                             }
  1464.                         }
  1465.                         if ($mission->isEvaluate()) {
  1466.                             $mission->setEvaluate(false);
  1467.                         }
  1468.                         if ($missionCanActive && $missionService->lackSubcontractorTest(mission$mission)) {
  1469.                             if (in_array($mission->getState(), ["cancelled""archived""closed"])) {
  1470.                                 foreach ($originalCampaign->getMissions() as $missionOriginal) {
  1471.                                     if ($missionOriginal->getId() == $mission->getId()) {
  1472.                                         $mission->setState($originalCampaign->getState());
  1473.                                         $entityManager->flush();
  1474.                                     }
  1475.                                 }
  1476.                             }
  1477.                         } else {
  1478.                             foreach ($originalCampaign->getMissions() as $missionOriginal) {
  1479.                                 if ($missionOriginal->getId() == $mission->getId()) {
  1480.                                     $mission->setState("provisional");
  1481.                                     $entityManager->persist($mission);
  1482.                                     $entityManager->flush();
  1483.                                 }
  1484.                             }
  1485.                             $canStartCampaign false;
  1486.                         }
  1487.                     }
  1488.                 }
  1489.                 if (!$canStartCampaign) {
  1490.                     $campaign->setState($originalCampaign->getState());
  1491.                     $entityManager->flush();
  1492.                 }
  1493.                 //verification de BOT
  1494.                 if ($campaign->haveBot()) {
  1495.                     if (in_array("ROLE_SUBCONTRACTOR"$userConnected->getRoles())) {
  1496.                         $this->addFlash(
  1497.                             type'error',
  1498.                             message'l\'activation de la campagne nécessite encore l\'intevention de l\'administrateur.',
  1499.                         );
  1500.                     } else {
  1501.                         $this->addFlash(
  1502.                             type'error',
  1503.                             message'Activation impossible car certaines mission sont encore liées a des Bots.',
  1504.                         );
  1505.                     }
  1506.                     $campaign->setState($originalCampaign->getState());
  1507.                     $entityManager->flush();
  1508.                     return  $redirect;
  1509.                 }
  1510.                 if ($canStartCampaign && $campaignService->isCanStart(campaign$campaign)) {
  1511.                     // campaign and setState() in progress managed by symfony workflow in config/packages/workflow
  1512.                     $campaign->setReSendToClient(false);
  1513.                     $campaign->setClientStatus("");
  1514.                     foreach ($campaign->getMissions() as $mission) {
  1515.                         if (!empty($mission->getWorkflow())) {
  1516.                             $stepIsActive false;
  1517.                             //verifié si un step est active // si active alors ne plus faire de mise a jour.
  1518.                             foreach ($mission->getWorkflow()->getSteps() as $step) {
  1519.                                 if ($step->isActive()) {
  1520.                                     $stepIsActive true;
  1521.                                 }
  1522.                             }
  1523.                             $step $workflowStepRepository->getFirstStep($mission->getWorkflow());
  1524.                             if (empty($step) || $step === false) {
  1525.                                 if (in_array("ROLE_SUBCONTRACTOR"$userConnected->getRoles())) {
  1526.                                     $this->addFlash(
  1527.                                         type'error',
  1528.                                         message'l\'activation de la campagne nécessite encore l\'intevention de l\'administrateur.',
  1529.                                     );
  1530.                                 } else {
  1531.                                     $this->addFlash(
  1532.                                         type'error',
  1533.                                         message'Activation impossible car le workflow n\'as pas d\'étape prédéfinie.',
  1534.                                     );
  1535.                                 }
  1536.                                 $campaign->setState($originalCampaign->getState());
  1537.                                 $entityManager->flush();
  1538.                                 return $redirect;
  1539.                             }
  1540.                             if (!$stepIsActive) {
  1541.                                 $step->setActive(true);
  1542.                                 $now = new \DateTime();
  1543.                                 $timezone = new \DateTimeZone("UTC");
  1544.                                 $now->setTimezone($timezone);
  1545.                                 $step->setStartDate($now);
  1546.                                 $event = new WorkflowStepEnteredEvent($step);
  1547.                                 $dispatcher->dispatch($eventWorkflowStepEnteredEvent::NAME);
  1548.                             }
  1549.                         } else {
  1550.                             if (in_array("ROLE_SUBCONTRACTOR"$userConnected->getRoles())) {
  1551.                                 $this->addFlash(
  1552.                                     type'error',
  1553.                                     message'l\'activation de la campagne nécessite encore l\'intevention de l\'administrateur.',
  1554.                                 );
  1555.                             } else {
  1556.                                 $this->addFlash(
  1557.                                     type'error',
  1558.                                     message'Activation impossible car la campagne n\'a pas de workflow',
  1559.                                 );
  1560.                             }
  1561.                             $campaign->setState($originalCampaign->getState());
  1562.                             $entityManager->flush();
  1563.                             return $this->redirectToRoute('mission_index');
  1564.                         }
  1565.                         //fin vérification
  1566.                         if ($step->getManager() == 0) {
  1567.                             $mission->setStateClient('Déclenchement en attente');
  1568.                         } else {
  1569.                             $mission->setStateProvider($step->getName());
  1570.                         }
  1571.                         $mission->setCanInvoiced(true);
  1572.                         $entityManager->flush();
  1573.                         if ($mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
  1574.                              $missionService->setDefaultValueIfAnUserClickedAnActivationButtonWithoutADelaisAndTimeIsEmpty($mission$priceService);
  1575.                             $clientSoldService->decreaseCurrentBalanceByMissionCost($mission);
  1576.                         }
  1577.                         $missionParticipantService->markAsAllParticipantClickActivationButton(mission$mission);
  1578.                         $missionService->addHistorique(mission$missionuser$this->getUser(), action"start");
  1579.                     }
  1580.                     $event = new CampaignValidatedPerActivationEvent($campaign$this->getUser());
  1581.                     $dispatcher->dispatch($event,CampaignValidatedPerActivationEvent::NAME);
  1582.                 } else {
  1583.                     if ($campaign->getState() !== "waiting_validation") {
  1584.                         $campaign->setState($originalCampaign->getState());
  1585.                         $entityManager->flush();
  1586.                     }
  1587.                     return $redirect;
  1588.                 }
  1589.             }
  1590.             /* if(($transition == "activated" || $transition == "validate") && $currentRouteName == null ){
  1591.                 $campaign->setActivatedAt(new \DateTimeImmutable());
  1592.             } */
  1593.             
  1594.             $entityManager->flush();
  1595.             $message = match ($transition) {
  1596.                 'validate' => 'validée',
  1597.                 'pause' => 'mise en pause',
  1598.                 'unpause' => 'relancée',
  1599.                 'cancel' => 'annulée',
  1600.                 'closed' => 'clôturée',
  1601.                 'activated' => 'activée',
  1602.                 default => 'enregistrée',
  1603.             };
  1604.             $this->addFlash(
  1605.                 type'success',
  1606.                 message"La campagne {$campaign->getName()} a bien été " $message,
  1607.             );
  1608.             
  1609.         }
  1610.         return $redirect;
  1611.     }
  1612.     #[Route('/campagne/{id}/detail/check'name'handle_detail_campaing'methods: ['GET''POST'])]
  1613.     public function campaignDetail(Campaign $campaign,MissionService $missionService,EntityManagerInterface $entityManager,UserRepository $userRepository){
  1614.             if (count($campaign->getMissions()) != 0) {
  1615.                 return  $this->redirectToRoute('mission_edit',['id'=>$campaign->getMissions()->first()->getId()]) ; 
  1616.             }
  1617.             //count nb mission
  1618.             $product = new Product();
  1619.             $product->setName("Espace de discussion");
  1620.             $product->setFrontId(0);
  1621.             $product->setType(ProductType::AU_TEMPS_PASSE);
  1622.             $entityManager->persist($product);
  1623.             $today = new \DateTime();
  1624.             $mission  = new Mission();
  1625.             $campaignDefaultObserver $campaign->getDefautObserver();
  1626.             $campaignDefaultValidator $campaign->getDefaultValidator();
  1627.             $campaignDefaultValidatorExternal $campaign->getDefaultValidatorExternal();
  1628.             $campaignDefaultObserverExternal $campaign->getDefautObserverExternal();
  1629.             if(!empty($campaignDefaultValidator)){
  1630.                 foreach($campaignDefaultValidator as $validatorEmail){
  1631.                     $user $userRepository->findOneBy(['email'=>$validatorEmail]);
  1632.                     $userDefaultValidatorParticipant = (new MissionParticipant())
  1633.                                 ->setUser($user)
  1634.                                 ->setMission($mission)
  1635.                                 ->setRole(Role::ROLE_VALIDATOR);
  1636.                     $mission->addParticipant($userDefaultValidatorParticipant);
  1637.                 }
  1638.             }
  1639.             if(!empty($campaignDefaultObserver)){
  1640.                 foreach($campaignDefaultObserver as $observerEmail){
  1641.                     $user $userRepository->findOneBy(['email'=>$observerEmail]);
  1642.                     $userDefaultObserverParticipant = (new MissionParticipant())
  1643.                                 ->setUser($user)
  1644.                                 ->setMission($mission)
  1645.                                 ->setRole(Role::ROLE_OBSERVER);
  1646.                     $mission->addParticipant($userDefaultObserverParticipant);
  1647.                 }
  1648.             }
  1649.             if(!empty($campaignDefaultValidatorExternal)){
  1650.                 foreach($campaignDefaultValidatorExternal as $validatorExternalEmail){
  1651.                     $user $userRepository->findOneBy(['email'=>$validatorExternalEmail]);
  1652.                     $userDefaultValidatorExternalParticipant = (new MissionParticipant())
  1653.                             ->setUser($user)
  1654.                             ->setMission($mission)
  1655.                             ->setRole(Role::ROLE_VALIDATOR_EXTERNAL);
  1656.                     $mission->addParticipant($userDefaultValidatorExternalParticipant);
  1657.                 }
  1658.             }
  1659.             if(!empty($campaignDefaultObserverExternal)){
  1660.                 foreach($campaignDefaultObserverExternal as $observerExternalEmail){
  1661.                     $user $userRepository->findOneBy(['email'=>$observerExternalEmail]);
  1662.                     $userDefaultValidatorExternalParicipant = (new MissionParticipant())
  1663.                             ->setUser($user)
  1664.                             ->setMission($mission)
  1665.                             ->setRole(Role::ROLE_OBSERVER_EXTERNAL);
  1666.                     $mission->addParticipant($userDefaultValidatorExternalParicipant);
  1667.                 }
  1668.             }
  1669.             $workflow $entityManager->getRepository(Workflow::class)->findOneBy(['template'=>1,'name'=>'Discussion']);
  1670.             $newWorkflow = clone($workflow);
  1671.             $mission->setProduct($product)
  1672.                     ->setQuantity(1)
  1673.                     ->setDesiredDelivery($today->add(new \DateInterval('P1Y')))
  1674.                     ->setState('provisional')
  1675.                     ->setWorkflow($newWorkflow)
  1676.                     ->setCampaign($campaign)
  1677.                     //->setReference($this->missionService->generateReference());
  1678.                     ;
  1679.             $campaign->setState('provisional');
  1680.             $entityManager->persist($mission);
  1681.             $entityManager->persist($campaign);
  1682.             $entityManager->flush();
  1683.             return  $this->redirectToRoute('mission_edit',['id'=> $mission->getId()]) ; 
  1684.         
  1685.     }
  1686.    
  1687.     #[Route('/campagne/{id}/missions'name'handle_mission_campaign'methods: ['GET''POST'])]
  1688.     public function handleAllMission($id,Request $requestCreditHistoryRepository $creditHistoryRepositoryJobRepository $jobRepositoryEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcherMissionParticipant $missionParticipant nullMissionRepository $missionRepositoryMissionParticipantRepository $missionParticipantRepositoryMissionService $missionServiceUserRepository $userRepositoryParameterBagInterface $parameter,CampaignRepository $campaignRepository,CompanyRepository $companyRepository,FileMissionRepository $fileMissionRepository,CampaignRecurrentService $campaignRecurrentService,UserPasswordHasherInterface $passwordHasher,GoogleStorageService $googleStorageService): Response
  1689.     {
  1690.         
  1691.         $newUserCreateId = [];
  1692.         $launchJustOne true;
  1693.         $matriceFrequencyType = [0=>'hours',1=>'months',2=>'days',3=>'years'];
  1694.         $error false;
  1695.         $campaignBrief null;
  1696.         $allMissionsInCampaign = [];
  1697.         $isNewCampaing false;
  1698.         if ($id == "new") {
  1699.             $campaign = new Campaign();
  1700.             $campaign->setOrderedBy($this->getUser())
  1701.                     ->setIsNew(true)
  1702.                     ->setDisabled(true)
  1703.                     ->setTypeInitiation(CampaignTypeInitiation::CAMPAIGN_FROM_ADMIN->value);
  1704.             $isNewCampaing true;
  1705.             if(in_array('ROLE_ADMIN'$this->getUser()->getRoles())){
  1706.                 $campaign->setRecurringState('waiting_validation');
  1707.             }
  1708.             $entityManager->persist($campaign);
  1709.             $entityManager->flush();
  1710.             $missionAlreadyExist false;
  1711.             $campaignInitiator $this->getUser();
  1712.             $url $this->generateUrl('handle_mission_campaign', ["id" => $campaign->getId()]);
  1713.             return new RedirectResponse($url);
  1714.         }else{
  1715.             $campaign $campaignRepository->findOneBy(['id'=>$id]);
  1716.             $campaignInitiator $campaign->getOrderedBy();
  1717.             $campaignBeforeState $campaign->getState();
  1718.             $oldCampaign = clone $campaign;
  1719.             $missionAlreadyExist =  (count($oldCampaign->getMissions()) == 0) ? false true;
  1720.             $campaignBrief $campaign->getBrief();
  1721.             $allMissionsInCampaign $missionRepository->findBy(['campaign' => $campaign]);
  1722.         }
  1723.         $stateRecurred $campaign->getState() ;
  1724.         $oldCampaignStateActiveFrequency =  $campaign->getActiveFrequency();
  1725.         $oldFrequency $campaign->getFrequency() != null ?  clone $campaign->getFrequency() : null;
  1726.         $oldPack $campaign->getCreditHistory();
  1727.         $sendEmailDeliveryDateChange true;
  1728.         $missionsInCampaign = [];
  1729.         
  1730.         foreach ($allMissionsInCampaign as $missionInCampaign) {
  1731.             if (!isset($missionsInCampaign[$missionInCampaign->getId()])) {
  1732.                 $missionsInCampaign[$missionInCampaign->getId()] = [];
  1733.             }
  1734.             if (!empty($missionInCampaign->getDesiredDelivery())) {
  1735.                 $missionsInCampaign[$missionInCampaign->getId()] = clone $missionInCampaign->getDesiredDelivery();
  1736.             }
  1737.         }
  1738.         $oldMissionId = [];
  1739.         $oldMission   $campaign->getMissions();
  1740.         $oldParticipantMail= [];
  1741.         foreach ($oldMission as $key => $mission) {
  1742.             $oldMissionId[] = $mission->getId();
  1743.             foreach ($mission->getParticipants() as $participant) {
  1744.                 $oldParticipantMail [] = $participant->getUser()->getEmail();
  1745.             }
  1746.         }
  1747.         //list of user to link of all mission
  1748.         $user $userRepository->findAll();
  1749.         $isadminAgency false;
  1750.         $company null;
  1751.         if (in_array("ROLE_ADMIN_AGENCY"$this->getUser()->getRoles()) ) {
  1752.            
  1753.             $isadminAgency true;
  1754.             $company $this->getUser()->getCompany();
  1755.         }
  1756.         foreach ($campaign->getMissions() as $mission) {
  1757.             $mission->setPrice($this->getPrice$mission->getProduct(),$this->getUser()));
  1758.         }
  1759.         $formEditCampaign $this->createForm(ListMissionFormType::class, $campaign,['user'=>$user,'isadminAgency'=>$isadminAgency,'company'=> $company]);
  1760.         $formEditCampaign->handleRequest($request);
  1761.         $errors $formEditCampaign->getErrors(truetrue);
  1762.         
  1763.         $canResendToClient true;
  1764.         $nbrAU_FORFAIT 0;
  1765.         $nbrA_EVALUER 0;
  1766.         $nbrAU_TEMPS_PASSE 0;
  1767.         $nbrMission 0;
  1768.         $allMissionNewId = [];
  1769.         $pathCampaing 'file_campaing_directory';
  1770.         $pathMission 'file_mission_directory';
  1771.         $newCampaign false;
  1772.         
  1773.         $errors $formEditCampaign->getErrors(truetrue);
  1774.     
  1775.         if ($formEditCampaign->isSubmitted() && $formEditCampaign->isValid()) {
  1776.             $contactProjects = [];
  1777.             if ($campaign->getDisabled() == 1) {
  1778.                 $newCampaign true;
  1779.             }
  1780.             $state 'waiting';
  1781.             $missions $formEditCampaign->get('missions');
  1782.             $otherInformationThanDateChange false;
  1783.             $newMissionInCampaign false;
  1784.             //validateur external an user validator / observer----------------
  1785.             //first delete all user in mission
  1786.             foreach ($campaign->getMissions() as $mission) {
  1787.                 if($campaign->getTypeInitiation()==&& $campaignBeforeState == "provisional"){
  1788.                         $listHistoriqueMission $mission->getHistoriques();
  1789.                         $messageHistoryMissionForProvisional "Mission déposée à partir du tunnel de demande de devis";
  1790.                         $isAlreadyAMessageOfThis false;
  1791.                         foreach($listHistoriqueMission as $historique){
  1792.                             if($messageHistoryMissionForProvisional == $historique->getMessage()){
  1793.                                 $isAlreadyAMessageOfThis true;
  1794.                                 break;
  1795.                             }
  1796.                         }
  1797.                         if(!$isAlreadyAMessageOfThis){
  1798.                             $this->missionService->addHistorique(mission$missionuser:$campaignInitiatoraction'campaign_initiate_by_tunnel_devis');
  1799.                         }
  1800.                 }
  1801.                 if($campaign->getTypeInitiation()==5){            
  1802.                     $this->missionService->addHistorique(mission$missionuser$campaign->getOrderedBy(), action'campaign_initiate_by_mail');
  1803.                 
  1804.                 }
  1805.                 foreach ($mission->getParticipants() as $participant) {
  1806.                     if (in_array($participant->getRole()->value, ['ROLE_OBSERVER_EXTERNAL','ROLE_VALIDATOR_EXTERNAL','ROLE_OBSERVER','ROLE_VALIDATOR'])) {
  1807.                         $entityManager->remove($participant);
  1808.                         $entityManager->flush();
  1809.                     }
  1810.                 }
  1811.             }
  1812.             $userAlreadyAdd = [];
  1813.             $userToAdd $formEditCampaign->get('user')->getData();
  1814.             $files $formEditCampaign->get('fileMissions')->getData();
  1815.             // $files = $files != null ? $files : [];
  1816.             /* $droppedFilesMissions = $formEditCampaign->get('droppedFileMissions')->getData(); */
  1817.              //second add participant
  1818.             $defaultObserver = [];
  1819.             $defaultObserverExernal = [];
  1820.             $defaultValidator = [];
  1821.             $defaultValidatorExternal = [];
  1822.             foreach ($userToAdd as $element) {
  1823.                 $user $element['user'];
  1824.                 $role $element['role'];
  1825.                 if (is_null($user) || is_null$role)) {
  1826.                     continue;
  1827.                 }
  1828.                 $clientIntern=false
  1829.                 if($this->campaignService->isMyCompany($campaign->getCompany(), $user) || 
  1830.                     $this->campaignService->isMyEmailSameExtensionOfCompanyExtension($campaign->getCompany(),$user)){
  1831.                     $role =  $this->campaignService->getRoleForInternalClient($element['role']);
  1832.                     $clientIntern=true
  1833.                     switch ($role->value) {
  1834.                             case 'ROLE_OBSERVER':
  1835.                                 $defaultObserver = [...$defaultObserver$user->getEmail()];
  1836.                                 break;
  1837.                             case 'ROLE_VALIDATOR':
  1838.                                 $defaultValidator = [...$defaultValidator$user->getEmail()];
  1839.                                 break;
  1840.                     }
  1841.                 }else{
  1842.                     $clientIntern=false;
  1843.                     $role =  $this->campaignService->getRoleForExternalClient($element['role']);
  1844.                     switch ($role->value) {
  1845.                         case 'ROLE_VALIDATOR_EXTERNAL':
  1846.                             $defaultValidatorExternal = [...$defaultValidatorExternal$user->getEmail()];
  1847.                             break;
  1848.                         case 'ROLE_OBSERVER_EXTERNAL':
  1849.                             $defaultObserverExernal = [...$defaultObserverExernal$user->getEmail()];
  1850.                             break;
  1851.                     }
  1852.                 }
  1853.                 if ($user->getNewAdd()) {
  1854.                     //role external is just a client
  1855.             
  1856.                     $user->setRoles(['ROLE_CLIENT'])
  1857.                          ->setEnabled(false)
  1858.                          ->setNewAdd(false)
  1859.                          ;
  1860.                     //add company in user new add
  1861.                     $companyUser $formEditCampaign?->get('company')?->getData();
  1862.                     if ($companyUser !== null &&   $clientIntern==true) {
  1863.                         $user->setCompany($companyUser);
  1864.                     }
  1865.                     //end
  1866.                     if (in_array($role, ['ROLE_OBSERVER_EXTERNAL','ROLE_VALIDATOR_EXTERNAL'])) {
  1867.                         $user->setExternal(true);
  1868.                         $user->setCompany(null);
  1869.                     }
  1870.                     $user->setPassword($passwordHasher->hashPassword($user$user->getPassword()));
  1871.                     $entityManager->persist($user);
  1872.                     $entityManager->flush();
  1873.                     $event = new ClientUpdatedEvent($usertrue);
  1874.                     $newUserCreateId[] = $user->getId();
  1875.                     if (!in_array($user->getEmail(),$oldParticipantMail)) {
  1876.                         $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  1877.                     }
  1878.                 } else {
  1879.                     if (!in_array($user->getId(), $newUserCreateId) && true === $launchJustOne&& isset($mission) && !is_null($mission)) {
  1880.                         if ($user->getId() != $mission->getCampaign()->getOrderedBy()->getId()) {
  1881.                             $event = new MissionSendEvent($mission$user$role);
  1882.                             
  1883.                             if (!in_array($user->getEmail(),$oldParticipantMail)) {
  1884.                                 $dispatcher->dispatch($eventMissionSendEvent::NAME);
  1885.                             }
  1886.                         }
  1887.                     }
  1888.                 }
  1889.                 foreach ($campaign->getMissions() as $mission) {
  1890.                      $participantAlredyExiste false;
  1891.                      foreach ($mission->getParticipants() as $participant) {
  1892.                             if($participant->getUser()->getId() == $user->getId() && $participant->getRole()->value == $role && $role!="ROLE_SUBCONTRACTOR"){
  1893.                                 $participantAlredyExiste true ;
  1894.                             }
  1895.                      }
  1896.                     if (!is_null($user) and !empty($user) and !in_array($user->getId(),$userAlreadyAdd) && !$participantAlredyExiste) {
  1897.                        //add participant
  1898.                        
  1899.                         $participant = (new MissionParticipant())
  1900.                                 ->setUser($user)
  1901.                                 ->setMission($mission)
  1902.                                 ->setRole($role);
  1903.                        $mission->addParticipant($participant);
  1904.                     }
  1905.                 }
  1906.             }
  1907.             if (!empty($contactProjects)) {
  1908.                 //first remove all contact project
  1909.                 foreach ($campaign->getMissions() as $mission) {
  1910.                     foreach ($mission->getParticipants() as $participant) {
  1911.                         if ($participant->getRole() == Role::PROJECT_CONTACT) {
  1912.                             $entityManager->remove($participant);
  1913.                             $entityManager->flush();
  1914.                         }
  1915.                     }
  1916.                 }
  1917.                 //add contact project in all mission
  1918.                 foreach ($campaign->getMissions() as $mission) {
  1919.                     $contactProjects array_unique($contactProjects);
  1920.                     foreach ($contactProjects as $contact) {
  1921.                        $contactUser $userRepository->find($contact);
  1922.                        $participant = (new MissionParticipant())
  1923.                                 ->setUser($contactUser)
  1924.                                 ->setMission($mission)
  1925.                                 ->setRole(Role::PROJECT_CONTACT);
  1926.                        $mission->addParticipant($participant);
  1927.                     }
  1928.                 }
  1929.             }else{
  1930.                 //add contact project in all mission
  1931.                 foreach ($campaign->getMissions() as $mission) {
  1932.                     $contactProjectIsAvailable false;
  1933.                     foreach ($mission->getParticipants() as $participant) {
  1934.                         if ($participant->getRole() ==  Role::PROJECT_CONTACT) {
  1935.                             $contactProjectIsAvailable true;
  1936.                         }
  1937.                     }
  1938.                     
  1939.                     if (!$contactProjectIsAvailable) {
  1940.                         $contactProject array_column($userRepository->getContactProjectByCompany($campaign->getCompany()),'id');
  1941.                         $contactProject array_unique($contactProject);
  1942.                        foreach ($contactProject as $contact) {
  1943.                             $userContact $userRepository->find($contact);
  1944.                             $missionParticipantContactProject = (new MissionParticipant())
  1945.                                                     ->setUser($userContact)
  1946.                                                     ->setMission($mission)
  1947.                                                     ->setRole(Role::PROJECT_CONTACT);
  1948.                             $mission->addParticipant($missionParticipantContactProject);
  1949.                         }
  1950.                     }
  1951.                 }
  1952.             }
  1953.             
  1954.             $campaign->setDefautObserver($defaultObserver)
  1955.                     ->setDefaultValidator($defaultValidator)
  1956.                     ->setDefaultValidatorExternal($defaultValidatorExternal)
  1957.                     ->setDefautObserverExternal($defaultObserverExernal);
  1958.             $launchJustOne false;
  1959.             $fileToDeleted $formEditCampaign->get('listfileMissionsToDeleted')->getData();
  1960.             //delete files 
  1961.             if (!empty($fileToDeleted) and !is_null($fileToDeleted) ) {
  1962.                 $fileExplode explode(';',$fileToDeleted);
  1963.                 foreach ($fileExplode as $file) {
  1964.                     $fileMission $fileMissionRepository->findOneBy(['name'=>$file,'campaign'=>$campaign]);
  1965.                     if (!is_null($fileMission)) {
  1966.                         $fileName =   $fileName "Campaigns/".$campaign->getId()."/".$fileMission->getName();
  1967.                         $bucketName "company-".strtolower($campaign->getCompany()->getId());
  1968.                         $destination $this->getParameter($pathCampaing) . '/' $campaign->getId();
  1969.                         if (file_exists($destination."/".$fileMission->getName())) {
  1970.                             unlink($destination."/".$fileMission->getName());
  1971.                         }
  1972.                         //delete file in repertory
  1973.                         $campaign->removeFileMission($fileMission);
  1974.                         //remove in repertory
  1975.                         foreach ($campaign->getMissions() as $mission) {
  1976.                             $fileMission $fileMissionRepository->findOneBy(['name'=>$file,'mission'=>$mission]);
  1977.                             $destinationFileMission $this->getParameter($pathMission) . '/' $mission->getId();
  1978.                             if (!is_null($fileMission) && file_exists($destinationFileMission."/".$fileMission->getName())) {
  1979.                                 unlink($destinationFileMission."/".$fileMission->getName());
  1980.                             }
  1981.                             if (!is_null($fileMission)) {
  1982.                                 $mission->removeFileMission($fileMission);
  1983.                                 $entityManager->remove($fileMission);
  1984.                             }
  1985.                             //suppression file in storage
  1986.                         }
  1987.                         $googleStorageService->deleteFile($bucketName,$fileName);
  1988.                         $entityManager->flush();
  1989.                     }
  1990.                 }
  1991.             }
  1992.   
  1993.             foreach ($files as $file) {
  1994.                 $destination $this->getParameter($pathCampaing) . '/' $campaign->getId();
  1995.                 $originalFilename pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  1996.                 $extensionFile =  pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
  1997.                 $newFilename $originalFilename '-' uniqid() . '.' $extensionFile;
  1998.                  //upload file in google storage
  1999.                 $nameUniqueCompany strtolower("company-".$campaign->getCompany()->getId());
  2000.                 $this->googleStorageService->uploadFile($nameUniqueCompany,$file,$newFilename,'Campaigns/'.$campaign->getId());
  2001.                 $fileMission = new FileMission();
  2002.                 $fileMission->setName($newFilename);
  2003.                 $fileMission->setIsNew(1);
  2004.                 $fileMission->setUser($this->getUser());
  2005.                 $campaign->addFileMission($fileMission);
  2006.  
  2007.             }
  2008.             // dd( $campaign->getFileMissions());
  2009.             $jobSub $request->request->get('jobsub');
  2010.             $nbrMission sizeof($missions);
  2011.             
  2012.             if ($campaign->getNumberInitialOfMissions() != null && intval($campaign->getNumberInitialOfMissions()) != $nbrMission) {
  2013.                 $isCampaignContainsEvaluateProduct $this->checkIfCampaignContainsProductEvaluate($campaign);
  2014.                 $newStateOfThisCampaign 'resend';
  2015.                 $campaign->setReSendToClient(true);
  2016.                 if($isCampaignContainsEvaluateProduct){
  2017.                      $newStateOfThisCampaign 'waiting';
  2018.                 }
  2019.                 if(in_array('ROLE_ADMIN'$this->getUser()->getRoles())){
  2020.                     $campaign->setRecurringState('waiting_validation');
  2021.                 }
  2022.                 $campaign->setState($newStateOfThisCampaign);
  2023.                 $campaign->setNumberInitialOfMissions(sizeof($missions));
  2024.             }
  2025.             
  2026.             if ($campaign->getMissions()->count() === 0) {
  2027.                 $state 'provisional';
  2028.                 $campaignTypeInitiation CampaignTypeInitiation::CAMPAIGN_FROM_DEVIS_CLIENT->value;
  2029.                 $campaign->setTypeInitiation($campaignTypeInitiation);
  2030.             }
  2031.             if (count($campaign->getMissions()) == and $campaign->getMissions()->first()->getProduct()->getName()=="Espace de discussion") {
  2032.                 $campaign->setState('provisional');
  2033.             }
  2034.             
  2035.             $ids =[];
  2036.             foreach ($missions as $key => $mission) {
  2037.                 $serviceParticipant = new Service();
  2038.                
  2039.                 //determine if mission is new // add normal state
  2040.                 if ($newCampaign) {
  2041.                     if ($mission->getData()->getProduct()->getType() === ProductType::A_EVALUER) {
  2042.                         $state 'waiting';
  2043.                     }
  2044.                 }
  2045.                 //add brief 
  2046.                 $mission->getData()->setInitialBriefing($campaignBrieftrue);
  2047.                 if (!$missionService->haveAvalidator(mission$mission->getData())) {
  2048.                     $allMissionNewId[] = $missionService->setValidatorUserWhoOrder(mission$mission->getData());
  2049.                 }
  2050.                 if ($mission->getData()->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
  2051.                     $nbrAU_TEMPS_PASSE++;
  2052.                 }
  2053.                 if ($mission->getData()->getProduct()->getType() == ProductType::A_EVALUER) {
  2054.                     $nbrA_EVALUER++;
  2055.                 }
  2056.                 if ($mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT) {
  2057.                     $nbrAU_FORFAIT++;
  2058.                 }
  2059.              
  2060.                 if(sizeof(explode("-"$mission->getData()->getOldCommand()))==1){
  2061.                     $newMissionInCampaign true;
  2062.                 }
  2063.                 if ($mission->getData()->getOldCommand() != null && sizeof(explode("-"$mission->getData()->getOldCommand())) == 4) {
  2064.                     [$quatity$price$productId$timestamp] =  explode("-"$mission->getData()->getOldCommand());
  2065.    
  2066.                     // Check if timestamp an other information change; 
  2067.                     if ($mission->getData()->getQuantity() != $quatity || $mission->getData()->getProduct()->getId() != $productId) {
  2068.                         
  2069.                         $otherInformationThanDateChange true;
  2070.                         //add information to historique 
  2071.                         if(in_array('ROLE_ADMIN'$this->getUser()->getRoles())){
  2072.                             $campaign->setRecurringState('waiting_validation');
  2073.                         }
  2074.                         $historique = (new Historique())
  2075.                             ->setUser($this->getUser())
  2076.                             ->setMission($mission->getData())
  2077.                             ->setMessage('Le panier a été mis à jour par : ' $this->getUser());
  2078.                         $entityManager->persist($historique);
  2079.                         $entityManager->flush();
  2080.                     }
  2081.                       if ($mission->getData()->getDesiredDelivery()?->getTimestamp() && intval($timestamp) != intval($mission->getData()->getDesiredDelivery()->getTimestamp())) {
  2082.                         if (!$otherInformationThanDateChange) {
  2083.                             $missionService->addHistorique(mission$mission->getData(), user$this->getUser(), action"deadline_change");
  2084.                 
  2085.                         }
  2086.                     }
  2087.                     
  2088.                     if ($otherInformationThanDateChange and !$newCampaign) {
  2089.                         $campaign->setReSendToClient(true);
  2090.                         $campaign->setState("resend");
  2091.                         if(in_array('ROLE_ADMIN'$this->getUser()->getRoles())){
  2092.                             $campaign->setRecurringState('waiting_validation');
  2093.                         }
  2094.                         $canResendToClient false;
  2095.                     }
  2096.                 }
  2097.                 
  2098.                 if ($mission->getData()->getOldCommand() != null and !$newCampaign and $otherInformationThanDateChange) {
  2099.                     
  2100.                     $campaign->setReSendToClient(true);
  2101.                     $campaign->setState("resend");
  2102.                  
  2103.                     $entityManager->persist($campaign);
  2104.                     $entityManager->flush();
  2105.                 }
  2106.                 $originalMission =  $missionRepository->find($mission->getData()->getId());
  2107.                 if (!is_null($mission->getData()->getAdminIncome())) {
  2108.                     $mission->getData()->setPrice($mission->getData()->getAdminIncome());
  2109.                 }
  2110.                 //-----------------------add default observer if new mission-------------------
  2111.                 if (!is_null($originalMission) and empty($originalMission->getReference())  ) {
  2112.                 //   //add default observer
  2113.                    if($campaign->getDefautObserver() != null){
  2114.                         $missionService->addDefaultClient($mission->getData(), 'observer',$stateRecurred);
  2115.                    }
  2116.                   
  2117.                    // add default validator
  2118.                    if($campaign->getDefaultValidator() != null){
  2119.                         $missionService->addDefaultClient($mission->getData(), 'validator',$stateRecurred);
  2120.                    }
  2121.                    
  2122.                
  2123.                  //------------------------------------------------------------------------------
  2124.                 }
  2125.                 if (!is_null($originalMission)) {
  2126.                     if (!$isNewCampaing) {
  2127.                         $mission->getData()->setOldCommand("{$mission->getData()->getQuantity()}-{$originalMission->getPrice()}-{$mission->getData()->getProduct()->getId()}-{$mission->getData()->getDesiredDelivery()?->getTimestamp()}");
  2128.                     }
  2129.                 }
  2130.                 if (empty($mission->getData()->getReference())) {
  2131.                     foreach ($campaign->getMissions() as $mis) {
  2132.                         if (!empty($mis->getReference())) {
  2133.                             $mission->getData()->setReference($mis->getReference());
  2134.                             break;
  2135.                         }
  2136.                     }
  2137.                     if (empty($mission->getData()->getReference())) {
  2138.                         $mission->getData()->setReference($missionService->generateReference());
  2139.                     }
  2140.                 }
  2141.                 $missionId $missionRepository->findOneBy(['id' => $mission->get('missionId')->getData()]);
  2142.                 if ($sendEmailDeliveryDateChange and !$newCampaign) {
  2143.                     if (isset($missionsInCampaign[$mission->getData()->getId()]) && $mission->getData()->getDesiredDelivery() != $missionsInCampaign[$mission->getData()->getId()] && !in_array($mission->getData()->getState(), ['provisional''waiting'])) {
  2144.                         $event = new MissionDesiredDeliveryUpdatedAfterValidationEvent($missionId);
  2145.                         $dispatcher->dispatch($eventMissionDesiredDeliveryUpdatedAfterValidationEvent::NAME);
  2146.                         $sendEmailDeliveryDateChange false;
  2147.                     } elseif (isset($missionsInCampaign[$mission->getData()->getId()]) && $mission->getData()->getDesiredDelivery() != $missionsInCampaign[$mission->getData()->getId()] && ($mission->getData()->getState() == 'provisional' || $mission->getData()->getState() == 'waiting')) {
  2148.                         // $campaign->setState('provisional');
  2149.                         $event = new MissionDesiredDeliveryUpdatedBeforeValidationEvent($mission->getData());
  2150.                         $dispatcher->dispatch($eventMissionDesiredDeliveryUpdatedBeforeValidationEvent::NAME);
  2151.                         $sendEmailDeliveryDateChange false;
  2152.                     }
  2153.                 }
  2154.                 //--------------------------add New Subcontractor ------------------------------------------
  2155.                 $jobsubForThisMission $jobSub[$key];
  2156.                 $jobsubForThisMissionInArray explode(";"$jobsubForThisMission);
  2157.                 $newSubcontractorList = [];
  2158.                
  2159.                 foreach ($jobsubForThisMissionInArray as $newSubontractor) {
  2160.                     $newSubontractor explode("-:"$newSubontractor);
  2161.                     if (sizeof($newSubontractor) == or sizeof($newSubontractor) == or sizeof($newSubontractor) == 4) {
  2162.                         $newSubcontractorList = [
  2163.                             ...$newSubcontractorList,
  2164.                             [
  2165.                                 "job_id" => $newSubontractor[0],
  2166.                                 "email_user" => $newSubontractor[1],
  2167.                                 "income_suggested" => isset($newSubontractor[2]) ? $newSubontractor[2]: null,
  2168.                                 "priceForProduct" => isset($newSubontractor[3]) ? $newSubontractor[3]: null,
  2169.                             ]
  2170.                         ];
  2171.                     }
  2172.                 }
  2173.                
  2174.                 $alreadySent = [];
  2175.                 foreach ($newSubcontractorList as $key => $newSuboContractor) {
  2176.                     echo "début insertion sous traitant<br>";
  2177.                     $errorAddSub false;
  2178.                     $newUser $userRepository->findOneBy(['email' => $newSuboContractor['email_user']]);
  2179.                     $newjob $jobRepository->findOneBy(['id' => $newSuboContractor['job_id']]);
  2180.                     if ($newUser == null) {
  2181.                         $errorAddSub true;
  2182.                         $error true;
  2183.                         $this->addFlash(
  2184.                             type'error',
  2185.                             message"Veuillez vérifier le contact opérationnel suivant " $newSuboContractor['email_user']
  2186.                         );
  2187.                         return $this->redirectToRoute('handle_mission_campaign', ["id" => $campaign->getId()]);
  2188.                     }
  2189.                     $productMission $mission->getData()->getProduct();
  2190.                     foreach ($mission->getData()->getParticipants() as $participant) {
  2191.                         $fullName $newUser->getFullName();
  2192.                         if ($participant->getUser() == $newUser && $participant->getJob() == $newjob) {
  2193.                           
  2194.                             $this->addFlash(
  2195.                                 type'error',
  2196.                                 message"Le sous-traitant $fullName vous essayé d'ajouté est deja sur cette mission"
  2197.                             );
  2198.                             $errorAddSub true;
  2199.                             $error true;
  2200.                         }
  2201.                         $services $entityManager->getRepository(Service::class)->findBy(['user' => $newUser]);
  2202.                         $linkService false;
  2203.                         $matriceLink = [];
  2204.                         foreach ($services as $service) {
  2205.                             if ($service->getProduct()->getId() === $productMission->getId()) {
  2206.                                 $linkService true;
  2207.                             }
  2208.                         }
  2209.                         
  2210.                         
  2211.                         if (!$linkService and !in_array('ROLE_SUBCONTRACTOR'$this->getUser()->getRoles())) {
  2212.                             $serviceParticipant->setProduct($productMission)
  2213.                                            //->setPrice($productMission->getPrice())
  2214.                                            ->setUser($newUser);
  2215.                             if ($mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT and $newSuboContractor['priceForProduct'] != null) {
  2216.                               
  2217.                                  // mail("anthonyssdfsffffff@yopmail.com", "mission", $newSuboContractor['priceForProduct']);
  2218.                                 $serviceParticipant->setPrice($newSuboContractor['priceForProduct'])->setResale($productMission->getPrice());
  2219.                                 $entityManager->persist($serviceParticipant);
  2220.                             }
  2221.                         }else{
  2222.                             
  2223.                             if( in_array('ROLE_SUBCONTRACTOR'$this->getUser()->getRoles()) && 
  2224.                                 $mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT && 
  2225.                                 !$linkService &&  !in_array($mission->getData()->getId(),$ids)
  2226.                             ){
  2227.                               
  2228.                                 $dailyRate floatval($newUser->getDailyRate());
  2229.                                 $resaleRate floatval($newUser->getResaleRate());
  2230.                                 $missionPrice =  floatval($mission->getData()->getPrice()); 
  2231.                                
  2232.                                 $time =   $missionPrice 420 $dailyRate 
  2233.                                 $resalePrice $time*$resaleRate/420;
  2234.             
  2235.                                 $serviceParticipant->setProduct($productMission)
  2236.                                                     ->setUser($newUser)
  2237.                                                     ->setPrice($missionPrice)
  2238.                                                     ->setResale($resalePrice)
  2239.                                                     ;
  2240.                                 $ids = [...$ids,$mission->getData()->getId()];
  2241.                                 $mission->getData()->setPrice($resalePrice);
  2242.                                 $productMission->setPrice($resalePrice);
  2243.                                 $entityManager->persist($serviceParticipant);
  2244.                             }
  2245.                             elseif(!$linkService and $mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT and $newSuboContractor['priceForProduct'] == null) {
  2246.     
  2247.                                 $errorAddSub true;
  2248.                                 $error true;
  2249.                                 $this->addFlash('error'"Veuillez ajouter le produit et le prix pratique par  $fullName au niveau de sa fiche ou au niveau de l'ajout du sous traitant lors de la commande.");
  2250.                             }
  2251.                         }
  2252.                     }
  2253.                     if (!$errorAddSub) {
  2254.                        
  2255.                         $missionParticipant = new MissionParticipant();
  2256.                         if (empty($missionId)) {
  2257.                             $missionParticipant->setMission($mission->getData());
  2258.                         } else {
  2259.                             $missionParticipant->setMission($missionId);
  2260.                         }
  2261.                         $missionParticipant->setUser($newUser);
  2262.                         //$missionParticipant->setIncomeSuggested($newSuboContractor['income_suggested']);
  2263.                         $missionParticipant->setJob($newjob);
  2264.                         $missionParticipant->setRole(Role::ROLE_SUBCONTRACTOR);
  2265.                         if (!empty($newSuboContractor['income_suggested'])) {
  2266.                             $missionParticipant->setIncomeSuggested($newSuboContractor['income_suggested']);
  2267.                         }
  2268.                         $mission->getData()->addParticipant($missionParticipant);
  2269.                         $entityManager->persist($missionParticipant);
  2270.                         $entityManager->flush();
  2271.                         if (!in_array($missionParticipant->getUser(), $alreadySent) && !$newCampaign) {
  2272.                             $event = new SubContractorMissionAddedEvent($missionParticipant->getUser(), $mission->getData());
  2273.                             $dispatcher->dispatch($eventSubContractorMissionAddedEvent::NAME);
  2274.                             $alreadySent[] = $missionParticipant->getUser();
  2275.                         }
  2276.                     }
  2277.                 }
  2278.                 $searchParticipant $missionParticipantRepository->findOneBy(['mission' => $missionId'role' => 'ROLE_SUBCONTRACTOR']);
  2279.                 if (empty($searchParticipant)) {
  2280.                     $event = new MissionWithoutSubContractorCheckedEvent($mission->getData());
  2281.                     $dispatcher->dispatch($eventMissionWithoutSubContractorCheckedEvent::NAME);
  2282.                 }
  2283.                 if (!empty($mission->get('newWorkflow')->getData())) {
  2284.                     $newWorkflow = clone $mission->get('newWorkflow')->getData();
  2285.                     $newWorkflow->setTemplate(false);
  2286.                     $mission->getData()->setWorkflow($newWorkflow);
  2287.                     $entityManager->persist($newWorkflow);
  2288.                 }
  2289.                 
  2290.             }
  2291.             $entityManager->flush();
  2292.             
  2293.             if ($error) {
  2294.                 foreach ($allMissionNewId as $id) {
  2295.                     if (!in_array($id$oldMissionId) or empty($oldMissionId)) {
  2296.                         $missionToRemove $entityManager->getRepository(Mission::class)->find($id);
  2297.                         $missionToRemove->setWorkflow(null);
  2298.                         $entityManager->persist($missionToRemove);
  2299.                         $entityManager->flush();
  2300.                         $entityManager->remove($missionToRemove);
  2301.                         $entityManager->flush();
  2302.                     }
  2303.                 }
  2304.                 return $this->redirectToRoute('handle_mission_campaign', ["id" => $campaign->getId()]);
  2305.             }
  2306.             
  2307.             foreach ($campaign->getMissions() as $mission) {
  2308.                 //$mission->setState('provisional');
  2309.                 if ($newCampaign) {
  2310.                     if (
  2311.                         $state === 'waiting' &&
  2312.                         ($mission->getProduct()->getType() === ProductType::AU_FORFAIT) || ($mission->getProduct()->getType() === ProductType::AU_TEMPS_PASSE)
  2313.                     ) {
  2314.                         $mission->setState('provisional');
  2315.                     } else {
  2316.                         $mission->setState($state);
  2317.                     }
  2318.                     if ($mission->getState() === 'waiting') {
  2319.                         $mission->setStateProvider('A évaluer');
  2320.                     } else {
  2321.                         $mission->setStateProvider('A activer');
  2322.                     }
  2323.                 }
  2324.             }
  2325.             if ($campaign->getCreditHistory() == null) {
  2326.                 $creditHistory $creditHistoryRepository->findOneBy(['company' => $campaign->getCompany(), "typePack" => 4]);
  2327.                 $campaign->setCreditHistory($creditHistory);
  2328.             }
  2329.             if ($newCampaign) {
  2330.                 $campaign->setState($state);
  2331.                 if(!empty($campaign->getMissions())){
  2332.                     foreach($campaign->getMissions() as $mission)  {
  2333.                         $this->missionService->addHistorique(mission$missionuser:$campaignInitiatoraction'campaign_initiate_by_admin');
  2334.                     }
  2335.                 }
  2336.                 
  2337.             }
  2338.     
  2339.             if( ($otherInformationThanDateChange || $newMissionInCampaign) && ( in_array('ROLE_SUBCONTRACTOR'$this->getUser()->getRoles()))&& !$this->campaignService->isAllProductHaveA_EvaluerMission($campaign) ){
  2340.                 $this->campaignService->resendCampaignForValidation($campaign,$this->getUser());
  2341.             }
  2342.             $campaign->setDisabled(null);
  2343.             $entityManager->persist($campaign);
  2344.             $entityManager->flush();
  2345.  
  2346.             if (!$newCampaign) {
  2347.                 if ($otherInformationThanDateChange &&  $nbrAU_FORFAIT && $nbrAU_FORFAIT == $nbrMission && $this->campaignService->areAllRequiredSubcontractorsPresent(campaign$campaign)) {
  2348.                     $campaign->setReSendToClient(true);
  2349.                     
  2350.                     $entityManager->persist($campaign);
  2351.                     $entityManager->flush();
  2352.                 }
  2353.                 if ($formEditCampaign->getClickedButton() && 'editGlobalMssion' === $formEditCampaign->getClickedButton()->getName()) {
  2354.               
  2355.                     // Btn édit on envoie juste un email.
  2356.                     $event = new CampaignModifiedEvent($campaign);
  2357.                     $dispatcher->dispatch($eventCampaignModifiedEvent::NAME);
  2358.                 } else if ($formEditCampaign->getClickedButton() && 'saveGlobalMission' === $formEditCampaign->getClickedButton()->getName()) {
  2359.        
  2360.                     $nbMission = [];
  2361.                     $nbInitialNotEmpty = [];
  2362.                     foreach ($campaign->getMissions() as $mission) {
  2363.                         $nbMission[] = $mission;
  2364.                         $initialTime $mission->getInitialTime();
  2365.                         if (!empty($initialTime)) {
  2366.                             $nbInitialNotEmpty[] = $initialTime;
  2367.                         }
  2368.                     }
  2369.                     if (count($nbMission) === count($nbInitialNotEmpty)) {
  2370.                         return $this->redirectToRoute('campaign_transition', ['id' => $campaign->getId(), 'transition' => 'unpause']);
  2371.                     }
  2372.                 }
  2373.             }
  2374.             //recurrency
  2375.             if($stateRecurred == 'recurred'){
  2376.                 $campaign->setState('recurred');
  2377.                 $entityManager->flush();
  2378.                 $stateActiveFrequency $oldCampaignStateActiveFrequency == false && $campaign->getActiveFrequency() == true true false
  2379.                 $isActiveFrequency =  $campaign->getActiveFrequency()== true true false
  2380.                 $recurringState = !is_null($campaign->getRecurringState()) && $campaign->getRecurringState() == "waiting_validation" || (
  2381.                     in_array('ROLE_ADMIN',$this->getUser()->getRoles()) && $campaignRecurrentService->isAnElementFrequencyChange($campaign->getFrequency() ,$oldFrequency ) ) ?  'waiting_validation':  'in_progress';
  2382.                 $campaign->setRecurringState(recurringState$recurringState );
  2383.                 $campaignRecurrentService->toogleRecurrent($campaign,$isActiveFrequency$stateActiveFrequency);
  2384.                 
  2385.               
  2386.                 $now = new \DateTime();
  2387.                 $startDate $campaign->getFrequency()->getStartDate();
  2388.                 if($now->format('y/d/m G:i') >=  $startDate->format('y/d/m G:i') &&  $campaign->getRecurringState()!='waiting_validation'){
  2389.                                     
  2390.                     $campaign->getFrequency()->setStartDate(new \DateTime());
  2391.                     $campaignRecurrentService->updateLaunchRecurringAt($campaign);
  2392.                     $newCampaign =  $campaignRecurrentService->clone($campaign);
  2393.                     $entityManager->persist($newCampaign);
  2394.                     $campaign $newCampaign ;
  2395.                 }elseif($campaign->getRecurringState()!='waiting_validation'){
  2396.                     $campaignRecurrentService->updateLaunchRecurringAt(campaign:$campaign,dateToLaunch:$newStartDate);
  2397.                 }
  2398.                 $eventRecurrent = new CampaignRecurrentEvent($campaignfalsetrue);
  2399.                 $dispatcher->dispatch($eventRecurrentCampaignRecurrentEvent::NAME);
  2400.                 $this->addFlash(
  2401.                     type'success',
  2402.                     message'Votre commande réccurente a été modifier avec succès'
  2403.                 );
  2404.                 
  2405.                 return $this->redirectToRoute('recurring_service');
  2406.             }
  2407.             else{
  2408.                 if ($campaign->getActiveFrequency()) {
  2409.                         $now = new \DateTime();
  2410.                         $startDate $campaign->getFrequency()->getStartDate();
  2411.                         $hours $now->format('G');
  2412.                         $minutes $now->format('i');
  2413.                         $second $now->format('s');
  2414.                         $campaignTypeInitiation CampaignTypeInitiation::CAMPAIGN_FROM_RECURRENT->value;
  2415.                         $newStartDate $startDate->setTime($hours$minutes$second);
  2416.                         $campaign->getFrequency()->setStartDate($newStartDate);
  2417.                         $campaign->setIsRecurrent(true);
  2418.                         $recurringState = !is_null($campaign->getRecurringState()) && $campaign->getRecurringState() == "waiting_validation" ?  $campaign->getRecurringState() :  'in_progress';
  2419.                         $campaign->setRecurringState($recurringState );
  2420.                         $campaign->setState('recurred');
  2421.                         $campaign->setTypeInitiation($campaignTypeInitiation);
  2422.                         $eventRecurrent = new CampaignRecurrentEvent($campaigntrue);
  2423.                         $dispatcher->dispatch($eventRecurrentCampaignRecurrentEvent::NAME);
  2424.                         if($now->format('y/d/m G:i') >=  $startDate->format('y/d/m G:i') &&  $campaign->getRecurringState()!='waiting_validation'){
  2425.                             $this->updateCampaignFrequencyDateUntilNow($campaignRecurrentService,$campaign,$now,$entityManager,$dispatcher);
  2426.                         }else{
  2427.                             $campaignRecurrentService->updateLaunchRecurringAt(campaign:$campaign,dateToLaunch:$newStartDate);
  2428.                         }
  2429.                         $this->addFlash(
  2430.                             type'success',
  2431.                             message'Votre commande réccurente a été crée avec succès'
  2432.                         );
  2433.                         
  2434.                         return $this->redirectToRoute('recurring_service');
  2435.                 }
  2436.                 else{
  2437.                     
  2438.                     if ($newCampaign) {
  2439.                         $event = new CampaignCreatedEvent($campaign,'',$contactProjects,true);
  2440.                         $dispatcher->dispatch($eventCampaignCreatedEvent::NAME);
  2441.                         $this->addFlash('success''Votre commande a été enregistrée avec succès');
  2442.                     }else{
  2443.                         $this->addFlash('success''Modification enregistrée');
  2444.                     }
  2445.                     if (count($campaign->getMissions()) == and $campaign->getMissions()->first()->getProduct()->getName()=="Espace de discussion") {
  2446.                         $campaign->setState('provisional');
  2447.                         $entityManager->persist($campaign);
  2448.                         $entityManager->flush();
  2449.                     }
  2450.                 }
  2451.             }
  2452.         
  2453.             if (!is_null($oldPack) and $oldPack != $campaign->getCreditHistory() and isset($mission) and !is_null($mission)) {
  2454.                 $this->missionService->addHistorique(mission$missionuser$this->getUser(), action'credit_campagne_modified');
  2455.                 
  2456.                 $this->contractService->balanceAllocation($campaign$oldPack);
  2457.                 $entityManager $this->getDoctrine()->getManager();
  2458.                 $entityManager->persist($campaign);
  2459.                 $entityManager->flush();
  2460.             }
  2461.             if (count($campaign->getMissions()) == and $campaign->getMissions()->first()->getProduct()->getName()=="Espace de discussion") {
  2462.                 $campaign->setState('provisional');
  2463.                 $entityManager->persist($campaign);
  2464.                 $entityManager->flush();
  2465.             }
  2466.             return $this->redirectToRoute('mission_index');
  2467.         }
  2468.         $formEditSubcontractor $this->createForm(EditSubcontractorParticipantType::class);
  2469.         setcookie('missionIDs','',0,"/");
  2470.         return $this->renderForm('campaign/edit_mission.html.twig', [
  2471.             'campaign' => $campaign,
  2472.             'form' => $formEditCampaign,
  2473.             'formEditSubcontractor' => $formEditSubcontractor,
  2474.             'user' => $user
  2475.         ]);
  2476.     }
  2477.     private function updateCampaignFrequencyDateUntilNow($campaignRecurrentService,$originalCampaign$now,$entityManager,$dispatcher){
  2478.         $campaignRecurrentService->updateLaunchRecurringAt($originalCampaign);
  2479.         $campaignFrequency $originalCampaign->getFrequency()->getLaunchRecurrenceAt();
  2480.         $newCampaign =  $campaignRecurrentService->clone($originalCampaign);
  2481.         $campaign $newCampaign;
  2482.         $entityManager->persist($campaign);
  2483.         $entityManager->flush();
  2484.         $event = new CampaignCreatedEvent($campaign);
  2485.         $dispatcher->dispatch($eventCampaignCreatedEvent::NAME);
  2486.         foreach($newCampaign->getMissions() as $mission ){
  2487.             $this->missionService->addHistorique(mission$missionuser:$newCampaign->getOrderedBy() , action'campaign_initiate_by_recurrent');  
  2488.         }
  2489.         if($campaignFrequency<$now){
  2490.             $this->updateCampaignFrequencyDateUntilNow($campaignRecurrentService,$originalCampaign$now,$entityManager,$dispatcher);
  2491.         }
  2492.         return;
  2493.     }
  2494.     #[Route('/campagne/{id}/demande-evaluation'name'campaign_demande_evaluation')]
  2495.     public function evaluation(Request $requestCampaign $campaignMissionService $missionServiceEventDispatcherInterface $dispatcher): Response
  2496.     {
  2497.         $event = new CampaignEvaluationEvent($campaign);
  2498.         $dispatcher->dispatch($eventCampaignEvaluationEvent::NAME);
  2499.         foreach ($campaign->getMissions() as $mission) {
  2500.             $missionService->addHistorique(mission$missionuser$this->getUser(), action"evaluation_request");
  2501.         }
  2502.         $this->addFlash(
  2503.             type'success',
  2504.             message'La demande d\'évaluation a bien été envoyée'
  2505.         );
  2506.         return $this->redirect($request->headers->get('referer'));
  2507.     }
  2508.     #[Route('/campagne/{id}/recapitulatif/{showStep}'name'campaign_recapitulatif'defaults: ['showStep'=>""])]
  2509.     public function recapPanier(string $showStepPriceService $priceService,MissionParticipantService $missionParticipantServiceNumberFormatService $numberFormatServiceCampaignService $campaignService,  ConsumptionBalanceForCompanyService $consumptionBalanceForCompanyService,  Campaign $campaign): Response
  2510.     {
  2511.         $creditHistory $campaign->getCreditHistory();
  2512.         $typePack =  $creditHistory->getTypePack();
  2513.         $text = match ((int) $typePack) {
  2514.             => 'Votre solde actuel',
  2515.             => 'Solde sur ' $numberFormatService->format($creditHistory->getOrderPrice()) . ' € HT/mois',
  2516.             => 'Solde sur ' $numberFormatService->format($creditHistory->getOrderPrice()) . ' € HT/an',
  2517.             => 'Budget HT consommé depuis le 1er du mois',
  2518.             => '',
  2519.             default => '',
  2520.         };
  2521.         $currency = match ((int) $campaign->getCreditHistory()->getTypePack()) {
  2522.             => '€',
  2523.             default => '€',
  2524.         };
  2525.         $balance $campaign->getCreditHistory()->getTypePack() == $consumptionBalanceForCompanyService->consumptionOfTheMonth(company$campaign->getCompany()) : $campaign->getCreditHistory()->getCurrentBalance();
  2526.         return $this->renderForm('campaign/recapitulatif.html.twig', [
  2527.             'campaign' => $campaign,
  2528.             'participants_subcontractor' => $missionParticipantService->getSubcontractorWithMissing($campaign), 
  2529.             'text' => $text,
  2530.             'price_service' => $priceService,
  2531.             'currency' => $currency,
  2532.             'balance' =>  $balance,
  2533.             'show_step'=> $showStep == "step" true false,
  2534.             'step'=>4
  2535.         ]);
  2536.     }
  2537.     #[Route('/campagne/{id}/accepter/{currentRouteName?}/{firstClickedMissionId?}'name'campaign_accept_all'defaults: ['currentRouteName' => null'firstClickedMissionId' => null])]
  2538.     public function campaignAccept(CampaignService $campaignServiceMissionService $missionServiceCampaign $campaignEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcherClientSoldService $clientSoldService$currentRouteName null$firstClickedMissionId null): Response
  2539.     {
  2540.         $campaign->setState($campaignService->getStateCampaign(campaign$campaign));
  2541.         $campaign->setReSendToClient(false);
  2542.         $campaign->setClientStatus("");
  2543.         $entityManager->flush();
  2544.         $campaignService->setAllMissionAsNotEvaluate(campaign$campaign);
  2545.         $event = new CampaignValidatedEvent($campaign);
  2546.         $dispatcher->dispatch($eventCampaignValidatedEvent::NAME);
  2547.         foreach ($campaign->getMissions() as $mission) {
  2548.             $missionService->addHistorique(mission$missionuser$this->getUser(), action"accepter");
  2549.         }
  2550.         $this->addFlash(
  2551.             type'success',
  2552.             message"Le panier a bien été validé avec succès"
  2553.         );
  2554.         if (isset($currentRouteName) && $currentRouteName == 'mission_edit' && isset($firstClickedMissionId)) {
  2555.             return $this->redirectToRoute('campaign_transition', [
  2556.                 'id' => $campaign->getId(),
  2557.                 "transition" => "activated",
  2558.                 "currentRouteName" => $currentRouteName,
  2559.                 "firstClickedMissionId" => $firstClickedMissionId
  2560.             ]);
  2561.         } else {
  2562.             return $this->redirectToRoute('campaign_transition', ['id' => $campaign->getId(), "transition" => "activated"]);
  2563.         }
  2564.     }
  2565.     #[Route('/campagne/{id}/resoumission'name'campaign_resoumission')]
  2566.     public function campaignResoumission(Request $requestMissionService $missionService,  Campaign $campaignEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher): Response
  2567.     {
  2568.         
  2569.         $event = new CampaignWaitingEvent($campaignfalse$this->getUser());
  2570.         $dispatcher->dispatch($eventCampaignWaitingEvent::NAME);
  2571.         foreach ($campaign->getMissions() as $mission) {
  2572.             $missionService->addHistorique(mission$missionuser$this->getUser(), action"resoumission");
  2573.         }
  2574.         $campaign->setClientStatus('waiting_for_confirmation');
  2575.         $campaign->setState('waiting_validation');
  2576.         $entityManager->flush();
  2577.         $message "Le panier est bien soumis avec succès";
  2578.         if ($this->isGranted("ROLE_SUBCONTRACTOR")) {
  2579.             $listMissionNotEvaluate $this->campaignService->getMissionListNotEvaluate(user$this->getUser(), campaign$mission->getCampaign());
  2580.             $message "";
  2581.             if ($this->missionService->isMyMission(mission$mission) && $mission->getCampaign()->getState() != "in_progress" && $mission->isEvaluate()) {
  2582.                 $message "Vous avez évalué la mission. Nous attendons maintenant la validation du client {$mission->getCampaign()->getCompany()->getName()}";
  2583.             } elseif ($listMissionNotEvaluate && $this->campaignService->evaluateAllHerMission(campaign$mission->getCampaign(), user$this->getUser()) && $this->missionService->isMyMission(mission$mission)) {
  2584.                 $intervenants "";
  2585.                 foreach ($mission->getCampaign()->getMissions() as $mission) {
  2586.                     foreach ($mission->getParticipants() as $participant) {
  2587.                         if (!$participant->isEvaluate()) {
  2588.                             $intervenants .= "{$participant->getUser()->getFullName()} , ";
  2589.                         }
  2590.                     }
  2591.                 }
  2592.                 $intervenants rtrim($intervenants",");
  2593.                 $message "Vous avez évalué la mission. Nous attendons maintenant le retour de ces partenaires pour resoumettre la proposition au client ( { $intervenants})";
  2594.             }
  2595.             $this->addFlash(
  2596.                 type'success',
  2597.                 message$message
  2598.             );
  2599.         } else {
  2600.             $this->addFlash(
  2601.                 type'success',
  2602.                 message'La campagne à bien été resoumise'
  2603.             );
  2604.         }
  2605.         return $this->redirect($request->headers->get('referer'));
  2606.     }
  2607.    
  2608.     #[Route('/campagne/activated/{id}'name'order_reactivated')]
  2609.     public function orderReactivated(Request $request,OrderService $orderServiceCampaign $campaignEntityManagerInterface $entityManager,CampaignService $campaignServiceEventDispatcherInterface $dispatcher): Response
  2610.     {
  2611.         
  2612.         $orderService->reActive($campaign);
  2613.         $this->addFlash(
  2614.             type'success',
  2615.             message'La campagne a bien été réactiver'
  2616.         );
  2617.         return $this->redirect($request->headers->get('referer'));
  2618.     }
  2619.     #[Route('/campagne/{id}/relancer'name'campaign_relancer')]
  2620.     public function campaignRelancer(Request $requestCampaign $campaignEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher): Response
  2621.     {
  2622.         $event = new CampaignResendEvent($campaign);
  2623.         $dispatcher->dispatch($eventCampaignResendEvent::NAME);
  2624.         $this->addFlash(
  2625.             type'success',
  2626.             message'La campagne a bien été relancer'
  2627.         );
  2628.         return $this->redirect($request->headers->get('referer'));
  2629.     }
  2630.     public function onMissionWithoutWorkflow(MissionWithoutWorkflowEvent $event$userRepository$mailer)
  2631.     {
  2632.         $mission $event->getMission();
  2633.         if (!$mission instanceof Mission) {
  2634.             return;
  2635.         }
  2636.         $admins $this->dynamicHostService->getMailAdmin();
  2637.         foreach ($admins as $admin) {
  2638.             $notification = (new NotificationEmail())
  2639.                 ->to(new Address($admin->value))
  2640.                 ->subject('Une mission a été créée sans workflow')
  2641.                 ->content('
  2642.                 <p>Bonjour,</p>
  2643.                 <p>La mission ' $mission->getReference() . ' contient un produit "' $mission->getProduct()->getName() . '" qui n\'a pas de Workflow associé.</p>
  2644.                 <p>Merci d\'en créer un pour ce produit et d\'aller le relier à la mission.</p>
  2645.             ')
  2646.                 ->action('Modifier la mission'$this->generateUrl('handle_mission_campaign', ['id' => $mission->getCampaign()->getId()], UrlGeneratorInterface::ABSOLUTE_URL))
  2647.                 ->markAsPublic();
  2648.             $mailer->send($notification);
  2649.         }
  2650.     }
  2651.     #[Route('/campagne/cart/{id}/{type}'name'campaign_pdf_cart'defaults: ['type' => 'pdf'])]
  2652.     public function  getPdfCart(Campaign $campaignstring $typePriceService $priceService)
  2653.     {
  2654.         $update_ref true;
  2655.         foreach ($campaign->getMissionsWithoutEspaceDeDiscussion() as $mission) {
  2656.             $mission->additionnal $this->getAdditionalInformation($mission->getProduct()->getFrontId(), $update_ref);
  2657.             $update_ref false;
  2658.         }
  2659.         $twigRender = [
  2660.             'link' => "campaign/pdf_cart/index.html.twig",
  2661.             'param' => [
  2662.                 'campaign' => $campaign,
  2663.                 'price_service' => $priceService,
  2664.                 'currency' => "€",
  2665.                 'balance' =>  "0",
  2666.             ]
  2667.         ];
  2668.         if ($type == 'pdf') {
  2669.             $pdfOptions = new Options();
  2670.             $pdfOptions->set('defaultFont''Arial');
  2671.             $pdfOptions->set('enable_remote'true);
  2672.             $pdfOptions->setIsRemoteEnabled(true);
  2673.             $dompdf = new Dompdf($pdfOptions);
  2674.             $context stream_context_create([
  2675.                 'ssl' => [
  2676.                     'verify_peer' => FALSE,
  2677.                     'verify_peer_name' => FALSE,
  2678.                     'allow_self_signed' => TRUE
  2679.                 ]
  2680.             ]);
  2681.             $dompdf->setHttpContext($context);
  2682.             $html $this->renderView($twigRender['link'], $twigRender['param']);
  2683.             $dompdf->loadHtml($html);
  2684.             $dompdf->setPaper('A4''portrait');
  2685.             $dompdf->render();
  2686.             $fichier "commande_myflow_" date('dmY');
  2687.             $dompdf->stream($fichier, [
  2688.                 'attachement' => true
  2689.             ]);
  2690.             return new JsonResponse(['status' => "Ok"], Response::HTTP_CREATED, ["Content-type" => "application/pdf"]);
  2691.         } else {
  2692.             return $this->render($twigRender['link'], $twigRender['param']);
  2693.         }
  2694.     }
  2695.     private function getAdditionalInformation(string $productFrontIdbool $updateRef false)
  2696.     {
  2697.         $param $updateRef "$productFrontId&update_id=true" $productFrontId;
  2698.         $frontWebSiteUrl $this->getParameter('front_website_url');
  2699.         $client = new Client();
  2700.         $response $client->request('GET'"$frontWebSiteUrl/wp-json/my-flow/v1/product_info?product_id=$param", []);
  2701.         $responseDecode json_decode($response->getBody()->getContents());
  2702.         return [
  2703.             "ref" => $responseDecode->ref,
  2704.             "attachement" => gettype($responseDecode->attachement) == "array" && sizeof($responseDecode->attachement) > $responseDecode->attachement[0] : "",
  2705.             "link" =>  $responseDecode->link,
  2706.         ];
  2707.     }
  2708.     private function updateUserDataDateCertificate($userData){
  2709.         $dateAddCertificate = new \DateTime();
  2710.         //if(is_null($userData->getVigilanceCertificate())){
  2711.             $userData->setDateUpdateCertificate($dateAddCertificate);
  2712.         //}
  2713.    }
  2714.    #[Route('/campagne/modification/price'name'campaign_modif_price')]
  2715.     public function  modificationPrestation(Request $request,PriceService $priceService,EntityManagerInterface $entityManager,ClientSoldService $clientSoldService)
  2716.     {   
  2717.         $neddToReajustSold false;
  2718.         $allData $request->request->all();
  2719.         foreach ($allData as $missionId => $value) {
  2720.             $mission $entityManager->getRepository(Mission::class)->find($missionId);
  2721.             $campaign $mission->getCampaign();
  2722.             $firstIdMission $campaign->getMissions()->first()->getId();
  2723.             $creditHistory $campaign->getCreditHistory();
  2724.             $dateActidatedAt $campaign->getActivatedAt();
  2725.             //price mission after update price prestation
  2726.             $priceMissionNotTouch $priceService->priceAndTimeMissionBasedOnPriceSale($mission)['price'];
  2727.             if ($priceMissionNotTouch != $value) {
  2728.                 $neddToReajustSold true;
  2729.                 //update priceSales mission if price original <> de new price
  2730.                 //first update price sales mission
  2731.                 $mission->setPriceSale($value);
  2732.                 $entityManager->persist($mission);
  2733.                 $entityManager->flush();
  2734.                 //second need to delete all balance transaction
  2735.                 $balanceTransaction $entityManager->getRepository(BalanceTransactions::class)->soldeByMission($creditHistory,$mission);
  2736.                 if (is_null($balanceTransaction)) {
  2737.                     $oldTotalConsuption $creditHistory->getTotalConsumption();
  2738.                     $oldCurrentBalance $creditHistory->getCurrentBalance();
  2739.                     $creditHistory->setTotalConsumption($oldTotalConsuption $value );
  2740.                     $creditHistory->setCurrentBalance($oldCurrentBalance $value);
  2741.                     //remove balance transaction
  2742.                 }
  2743.                 //third decrease all value in balance transactions.
  2744.                 $clientSoldService->decreaseCurrentBalanceByMissionCost($mission,$dateActidatedAt);
  2745.             }
  2746.         }
  2747.         $entityManager->flush();
  2748.         $this->addFlash('success','Prix de la prestation changé avec succées');
  2749.         return $this->redirectToRoute('mission_edit', ['id' => $firstIdMission], Response::HTTP_SEE_OTHER);
  2750.     }
  2751.     //  private function createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign,$now,$entityManager){
  2752.     //     $campaignRecurrentService->updateLaunchRecurringAt($originalCampaign);
  2753.     //     $campaignFrequency = $originalCampaign->getFrequency()->getLaunchRecurrenceAt();
  2754.     //     $newCampaign =  $campaignRecurrentService->clone($originalCampaign);
  2755.     //     $campaign = $newCampaign;
  2756.     //     $entityManager->persist($campaign);
  2757.     //     $entityManager->flush();
  2758.     //     if($campaignFrequency<$now){
  2759.     //         $this->createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign, $now,$entityManager);
  2760.     //     }
  2761.     //     return;
  2762.     // }
  2763.     private function checkIfCampaignContainsProductEvaluate(Campaign $campaign){
  2764.         foreach($campaign->getMissions() as $mission){
  2765.             if($mission->getProduct()->getType()==ProductType::A_EVALUER){
  2766.                 return true;
  2767.             }
  2768.         }
  2769.         return false;
  2770.     }
  2771.     #[Route('/contact-project/html/add'name'campaing_contact_project_html_add'methods: ['GET''POST'])]
  2772.     public function modalContactProjectCampaing(Request $request): Response
  2773.     {
  2774.          $formAddMissionContactProject $this->createForm(AddMissionContactProjectType::class);
  2775.         return  $this->render('campaign/_contact_project.html.twig', [
  2776.             'formAddMissionContactProject' => $formAddMissionContactProject->createView()
  2777.         ]);
  2778.     }
  2779.      #[Route('/contact-project/take-info/{email}'name'campaing_contact_project_take_info'methods: ['GET''POST'])]
  2780.     public function contactTakeInfos(Request $request,EntityManagerInterface $entityManager,$email null): Response
  2781.     {
  2782.         $user null;
  2783.         if ($email !== null and !empty($email) ) {
  2784.             $user $entityManager->getRepository(User::class)->findOneByEmail($email);
  2785.         }
  2786.         return  $this->render('campaign/_contact_project_list.html.twig', [
  2787.             'user' => $user
  2788.         ]);
  2789.     }
  2790.     private function getProductList(?User $user=null){
  2791.         if($user ==null){
  2792.             return [];
  2793.         }
  2794.         $productList = []; 
  2795.         $services $user->getServices(); 
  2796.         foreach ($services as  $service) {
  2797.             $productList[$service->getProduct()->getId()] = $service->getPrice();
  2798.         }
  2799.         return  $productList
  2800.     }
  2801.     private function getPrice(Product $product$user){
  2802.         
  2803.         $productPrice $product->getPrice();
  2804.   
  2805.         if($user != null && in_array('ROLE_SUBCONTRACTOR'$user->getRoles())){
  2806.                 $listService $this->getProductList($user);
  2807.                 $productPrice $product->getId()!=null && array_key_exists($product->getId(),$listService) && $listService[$product->getId()]!=null floatval($listService[$product->getId()]) : 0;
  2808.         }
  2809.         return ($product->getType()->value != and  $product->getType()->value !=  3) ? $productPrice ;
  2810.     }
  2811. }