src/Controller/CampaignController.php line 140

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->getOriginalMailUser()];
  513.                                                 break;
  514.                                             case 'ROLE_OBSERVER_EXTERNAL':
  515.                                                 $defaultObserverExernal = [...$defaultObserverExernal$user->getOriginalMailUser()];
  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->getOriginalMailUser()];
  746.                                         break;
  747.                                     case 'ROLE_OBSERVER_EXTERNAL':
  748.                                         $defaultObserverExernal = [...$defaultObserverExernal$user->getOriginalMailUser()];
  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->getOriginalMailUser()];
  909.                                         break;
  910.                                     case 'ROLE_OBSERVER_EXTERNAL':
  911.                                         $defaultObserverExernal = [...$defaultObserverExernal$user->getOriginalMailUser()];
  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: $mission, user:$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.          
  1033.                 foreach($campaign->getMissions() as $mission) {
  1034.                     $this->missionService->addHistorique(mission$missionuser:$campaign->getOrderedBy() , action:$historyActionCampaignInitiation);
  1035.                     break; 
  1036.                 } 
  1037.                 
  1038.                 
  1039.                 
  1040.                 if($campaign->getState() != "draft" && $campaign->getRecurringState()!='waiting_validation'){
  1041.                     $event $isDevis ? new CampaignCreatedEvent($campaign'CREATION_DEVIS') :  new CampaignCreatedEvent($campaign'TUNNEL_COMMANDE');
  1042.                     $dispatcher->dispatch($eventCampaignCreatedEvent::NAME);
  1043.                 }
  1044.                 
  1045.                 return new JsonResponse(
  1046.                     json_decode($serializer->serialize($campaign'json', [AbstractNormalizer::GROUPS => ['campaign']])),
  1047.                     Response::HTTP_CREATED
  1048.                 );
  1049.             } catch (\Exception $e) {
  1050.                 foreach (array_unique($newUserCreateId) as $id) {
  1051.                     $user $userRepository->findOneBy(['id' => $id]);
  1052.                     $entityManager->remove($user);
  1053.                     $entityManager->flush();
  1054.                 }
  1055.                 $campaign->setErrorCommand($e->getMessage());
  1056.                 $event = new AdminCommandErrorEvent($campaign);
  1057.                 $dispatcher->dispatch($eventAdminCommandErrorEvent::NAME);
  1058.             }
  1059.         }
  1060.         return new JsonResponse([], Response::HTTP_BAD_REQUEST);
  1061.     }
  1062.     private function createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign,$now,$entityManager){
  1063.        
  1064.         $campaignRecurrentService->updateLaunchRecurringAt($originalCampaign);
  1065.         $campaignFrequency $originalCampaign->getFrequency()->getLaunchRecurrenceAt();
  1066.         $newCampaign =  $campaignRecurrentService->clone($originalCampaign);
  1067.         $campaign $newCampaign;
  1068.         $entityManager->persist($campaign);
  1069.         $entityManager->flush();
  1070.         if($campaignFrequency<$now){
  1071.             $this->createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign$now,$entityManager);
  1072.         }
  1073.         return;
  1074.     }
  1075.     /**
  1076.      * Display the view/handle how to edit a campaign
  1077.      *
  1078.      * @param Campaign $campaign - the campaign to edit
  1079.      * @param Request $request
  1080.      * @param EntityManagerInterface $entityManager
  1081.      *
  1082.      * @return Response template /mission/handle_campaign.html.twig
  1083.      */
  1084.     #[Route('/campagnes/{id}'name'campaign_edit')]
  1085.     public function edit(Campaign $campaignRequest $requestEntityManagerInterface $entityManager): Response
  1086.     {
  1087.         $form $this->createForm(CampaignType::class, $campaign);
  1088.         $form->handleRequest($request);
  1089.         if ($form->isSubmitted() && $form->isValid()) {
  1090.             $this->addFlash('success''La campagne a bien été modifiée');
  1091.             $entityManager->flush();
  1092.             return $this->redirectToRoute('mission_index');
  1093.         }
  1094.         return $this->renderForm('campaign/edit.html.twig', [
  1095.             'form' => $form,
  1096.             'campaign' => $campaign,
  1097.         ]);
  1098.     }
  1099.     #[Route('/campaign/{id}/uncancelled'name"campaign_uncancelled")]
  1100.     public function campaignUncancelled(Campaign $campaignEntityManagerInterface $entityManagerInterface,EventDispatcherInterface $dispatcher,MissionService $missionService): Response
  1101.     {
  1102.         $campaign->setState($campaign->getLastState());
  1103.         foreach ($campaign->getMissions() as $mission) {
  1104.             $mission->setState($mission->getLastState());
  1105.         }
  1106.         $event = new CampaignResumeEvent($campaigntrue);
  1107.         $dispatcher->dispatch($eventCampaignResumeEvent::NAME);
  1108.         foreach ($campaign->getMissions() as $mission) {
  1109.             $missionService->addHistorique(mission$missionuser$this->getUser(), action"unpause");
  1110.         }
  1111.         $entityManagerInterface->flush();
  1112.         $this->addFlash(
  1113.             type'success',
  1114.             message"La campagne reprend avec succès ",
  1115.         );
  1116.         return $this->redirectToRoute('mission_index');
  1117.     }
  1118.     /**
  1119.      * If applicable, apply the workflow transition $transition on a campaign
  1120.      * and on all its missions.
  1121.      *
  1122.      * Only validate, pause, unpause, cancel and archived transitions are allowed
  1123.      *
  1124.      * @param Campaign $campaign - the campaign on whom to apply the transition
  1125.      * @param string $transition - the transition to apply
  1126.      * @param Registry $workflows
  1127.      * @param EntityManagerInterface $entityManager
  1128.      * @param EventDispatcherInterface $dispatcher
  1129.      *
  1130.      * @return Response Redirect to the mission's index
  1131.      */
  1132.     #[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])]
  1133.     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
  1134.     {
  1135.         $workflow $workflows->get($campaign'classic');
  1136.         $redirect $this->redirectToRoute('mission_index');
  1137.         if (isset($currentRouteName) && $currentRouteName == 'mission_edit' && isset($firstClickedMissionId)) {
  1138.             $redirect =  $this->redirectToRoute('mission_edit', ['id' => $firstClickedMissionId]);
  1139.         } 
  1140.         // clone original campagne 
  1141.         $originalCampaign =  clone $campaign;
  1142.         $originalMissions $originalCampaign->getMissions();
  1143.         if ($transition === "delete") {
  1144.             if($campaign->getState()=="draft"){
  1145.                 $campaign->setDeleteReason('Brouillon');
  1146.             }
  1147.             else {
  1148.                 $formDeleteCampaign $this->createForm(CampaignDeleteType::class, $campaign);
  1149.                 $formDeleteCampaign->handleRequest($request);
  1150.             }
  1151.             $campaign->setLastState($originalCampaign->getState());
  1152.             $pack $campaign->getCreditHistory();
  1153.             $isDeteleCampaignRecurrend $request->query->get('recurred') == true ?  true false;
  1154.             if (!$isDeteleCampaignRecurrend) {
  1155.                 // remove all price in creditHistory and BalanceTransaction if $transition is delete
  1156.                 $dataCampainState = ['in_progress''closed''cancelled''archived'];
  1157.                 if (in_array($campaign->getState(), $dataCampainState)) {
  1158.                     $totalAmountInBalance 0;
  1159.                     $isNull false;
  1160.                     $isNull count($campaign->getMissions()) === true false;
  1161.                     foreach ($campaign->getMissions() as $mission) {
  1162.                         $balanceTransaction $balanceTransactionsRepository->soldeByMission($pack$mission);
  1163.                         if (is_null($balanceTransaction)) {
  1164.                             $isNull true;
  1165.                             break;
  1166.                         }
  1167.                         $creditHistory $balanceTransaction->getCreditHistory();
  1168.                         $totalAmountInBalance += $balanceTransaction->getAmount();
  1169.                         $entityManager->remove($balanceTransaction);
  1170.                         $this->missionService->addHistorique($mission$this->getUser(),'mission_deleted',$mission);
  1171.                     }
  1172.                     if (!$isNull) {
  1173.                         $oldTotalConsuption $creditHistory->getTotalConsumption();
  1174.                         $oldCurrentBalance $creditHistory->getCurrentBalance();
  1175.                         $creditHistory->setTotalConsumption($oldTotalConsuption $totalAmountInBalance);
  1176.                         $creditHistory->setCurrentBalance($oldCurrentBalance $totalAmountInBalance);
  1177.                     }
  1178.                 }
  1179.               
  1180.                 foreach ($originalCampaign->getMissions() as $mission) {
  1181.                     $mission->setLastState($mission->getState());
  1182.                     $mission->setState('deleted');
  1183.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"deleted");
  1184.                 }
  1185.                 if($campaign->getState() !== "deleted"){
  1186.                     $event = new CampaignDeletedEvent($campaign$this->getUser());
  1187.                     $dispatcher->dispatch($eventCampaignDeletedEvent::NAME);
  1188.                 }
  1189.                 $campaign->setState('deleted');
  1190.             }
  1191.             else{
  1192.                 $campaign->setRecurringState('deleted');
  1193.             }
  1194.             $entityManager->flush();
  1195.             $this->addFlash(
  1196.                 type'success',
  1197.                 message"La campagne {$campaign->getName()} a bien été supprimée"
  1198.             );
  1199.             if ($isDeteleCampaignRecurrend) {
  1200.                 return $this->redirectToRoute('recurring_service');
  1201.             } elseif (isset($currentRouteName) && $currentRouteName == 'mission_edit' && isset($firstClickedMissionId)) {
  1202.                 return $this->redirectToRoute('mission_edit', ['id' => $firstClickedMissionId]);
  1203.             } else {
  1204.                 return $this->redirectToRoute('mission_index');
  1205.             }
  1206.         }
  1207.         
  1208.         if ($transition === 'decline') {
  1209.             foreach ($campaign->getMissions() as $mission) {
  1210.                 foreach ($mission->getParticipants() as $participant) {
  1211.                     if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR && $participant->getUser()->getId() == $subcontractorId) {
  1212.                         $entityManager->remove($participant);
  1213.                         $entityManager->flush();
  1214.                         $this->missionService->addHistorique($mission$this->getUser(), 'decline_mission');
  1215.                         continue 2;
  1216.                     }
  1217.                 }
  1218.             }
  1219.             $event = new CampaignDeclineEvent($campaigntrue$this->getUser());
  1220.             $dispatcher->dispatch($eventCampaignDeclineEvent::NAME);
  1221.             foreach ($campaign->getMissions() as $mission) {
  1222.                 $missionService->addHistorique(mission$missionuser$this->getUser(), action"refus");
  1223.             }
  1224.             
  1225.             $this->addFlash(
  1226.                 type'success',
  1227.                 message"La mission {$campaign->getName()} a bien été supprimée"
  1228.             );
  1229.         }
  1230.         if ($workflow->can($campaign$transition)) {
  1231.             $workflow->apply($campaign$transition);
  1232.             if ($transition === 'unpause') {
  1233.                 $event = new CampaignResumeEvent($campaigntrue);
  1234.                 $dispatcher->dispatch($eventCampaignResumeEvent::NAME);
  1235.                 foreach ($campaign->getMissions() as $mission) {
  1236.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"unpause");
  1237.                 }
  1238.             }
  1239.             if ($transition === 'resend') {
  1240.                 foreach ($campaign->getMissions() as $mission) {
  1241.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"resend");
  1242.                 }
  1243.             }
  1244.             if ($transition === 'pause') {
  1245.                 $event = new CampaignWaitingEvent($campaigntrue);
  1246.                 $dispatcher->dispatch($eventCampaignWaitingEvent::NAME);
  1247.                 foreach ($campaign->getMissions() as $mission) {
  1248.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"pause");
  1249.                 }
  1250.             }
  1251.             if ($transition === 'cancel') {
  1252.                 $formCancelCampaign $this->createForm(CampaignCancelType::class, $campaign);
  1253.                 $formCancelCampaign->handleRequest($request);
  1254.                 $campaign->setLastState($originalCampaign->getState());
  1255.                 foreach ($originalCampaign->getMissions() as $mission) {
  1256.                     $mission->setLastState($mission->getState());
  1257.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"cancel");
  1258.                 }
  1259.                 $entityManager->flush();
  1260.                 $event = new CampaignCancelledEvent($campaign$this->getUser(),);
  1261.                 $dispatcher->dispatch($eventCampaignCancelledEvent::NAME);
  1262.             }
  1263.             if ($transition === "closed") {
  1264.                 foreach ($campaign->getMissions() as $mission) {
  1265.                     $mission->setState('finalized');
  1266.                     $campaign->setIsToBeinvoiced(true);
  1267.                     if(sizeof($this->campaignApiService->getSubcontractorNoEstimatedIncome($campaign)) != 0){
  1268.                         $campaign->setState('closing_in_progress');
  1269.                     }
  1270.                     // if ($mission->getProduct()->getType() == ProductType::AU_TEMPS_PASSE) {
  1271.                     $clientSoldService->decreaseCurrentBalanceByMissionCost(mission$mission);
  1272.                     // }
  1273.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"closed");
  1274.                 }
  1275.             }
  1276.             foreach ($campaign->getMissions() as $mission) {
  1277.                 $workflow $workflows->get($mission'classic');
  1278.                 if ($workflow->can($mission$transition)) {
  1279.                     $workflow->apply($mission$transition);
  1280.                 }
  1281.             }
  1282.             // If we validate the campaign, we dispatch the campaign.validated event
  1283.             if ($transition === 'validate') {
  1284.                 $flag true;
  1285.                 foreach ($campaign->getMissions() as $mission) {
  1286.                     $i 0;
  1287.                     foreach ($mission->getParticipants() as $participant) {
  1288.                         if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR) {
  1289.                             $i++;
  1290.                         }
  1291.                         if ($i || $participant->getMission()->getStateProvider() == 'A évaluer') {
  1292.                             $flag false;
  1293.                         }
  1294.                     }
  1295.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"validate");
  1296.                 }
  1297.                 if ($flag == true) {
  1298.                     $event = new CampaignValidatedEvent($campaign);
  1299.                     $dispatcher->dispatch($eventCampaignValidatedEvent::NAME);
  1300.                 } else {
  1301.                     return $this->redirectToRoute('handle_mission_campaign', ['id' => $campaign->getId(), 'erreur' => true]);
  1302.                 }
  1303.             }
  1304.             if ($transition === 'activated') {
  1305.                 $canStartCampaign true;
  1306.                 $error false;
  1307.                 $userConnected $this->getUser();
  1308.                
  1309.                 if (in_array("ROLE_SUBCONTRACTOR"$userConnected->getRoles())) {
  1310.                     $message = [];
  1311.                     foreach ($campaign->getMissions() as $mission) {
  1312.                         $missionService->setDefaultValueIfAnUserClickedAnActivationButtonWithoutADelaisAndTimeIsEmpty($mission$priceService);
  1313.                        
  1314.                         //////////////////// Check marge mission  
  1315.                         $getMargeMyFlow $priceService->marginExceeded(mission$mission);
  1316.                         if ($missionService->isMyMission(mission$mission) and $getMargeMyFlow['percentage'] <= and $mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
  1317.                             if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
  1318.                                 $this->addFlash(
  1319.                                     type'error',
  1320.                                     message"Une action de l'administrateur est attendue pour pouvoir valider cette mission.",
  1321.                                 );
  1322.                                 $event = new MissionCanActivateEvent(mission$missionmarge$getMargeMyFlow['percentage'] );
  1323.                                 $dispatcher->dispatch($eventMissionCanActivateEvent::NAME);
  1324.                             }
  1325.                             $campaign->setState($originalCampaign->getState());
  1326.                             $mission->setState($mission->getLastState());
  1327.                             $entityManager->flush();
  1328.                             $canStartCampaign false;
  1329.                             continue; 
  1330.                             //return  $redirect;
  1331.                         }
  1332.                         ////////////////////////
  1333.                         foreach ($mission->getParticipants() as $missionParticipation) {
  1334.                             if (!$missionParticipation->isEvaluate() && !$missionParticipation->isActivated() && !$missionParticipation->isRefused() && $this->getUser() == $missionParticipation->getUser()) {
  1335.                                 $missionParticipation->setActivated(true);
  1336.                                 $missionParticipation->setActivatedAt(new \DateTime());
  1337.                                 $entityManager->flush();
  1338.                                 $this->missionService->addHistorique($mission$this->getUser(), 'accept_mission');
  1339.                                 //break;
  1340.                             }
  1341.                         }
  1342.                         $listUserNotEvaluate "";
  1343.                         $listUserEvaluate "";
  1344.                         $message = [=> "- Mission lancée avec succès"];
  1345.                         foreach ($missionService->determineAllSubcontractorEvaluated(mission$mission) as $userEvaluate) {
  1346.                             if ($userEvaluate != $this->getUser()) {
  1347.                                 $listUserNotEvaluate .= "{$userEvaluate->getFullName()} ,";
  1348.                             }
  1349.                             if (strlen($listUserNotEvaluate) > && $campaign->getState() != "resend") {
  1350.                                 $listUserNotEvaluate rtrim($listUserNotEvaluate",");
  1351.                                 $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.";
  1352.                             }
  1353.                         }
  1354.                         $allSubcontractorEvaluated $missionService->getListSubcontractorNotActivate(mission$mission);
  1355.                         $msg count($allSubcontractorEvaluated) > "Les intervenants suivants ont réévalué la mission" "L'intervenant suivant a réévalué la mission";
  1356.                         foreach ($allSubcontractorEvaluated as $userNotEvaluate) {
  1357.                             if ($userNotEvaluate != $this->getUser()) {
  1358.                                 $listUserNotEvaluate .= "{$userNotEvaluate->getFullName()} ,";
  1359.                             }
  1360.                             if (strlen($listUserNotEvaluate) > && $campaign->getState() != "resend") {
  1361.                                 $listUserNotEvaluate rtrim($listUserNotEvaluate",");
  1362.                                 $message[2] = " - Vous venez d'accepter la mission, nous attendons maintenant l'activation de l'intervenant ci-dessous pour démarrer le travail :  $listUserNotEvaluate.";
  1363.                             }
  1364.                         }
  1365.                         if ($missionService->lackSubcontractorTest(mission$mission) && sizeof($missionService->getListSubcontractorNotActivate(mission$mission)) == && !$missionService->aSubcontractorBotIsInThisMission(mission$mission)) {
  1366.                             $mission->setState('in_progress');
  1367.                             $entityManager->flush();
  1368.                             foreach ($originalMissions as $missionOriginal) {
  1369.                                 if (in_array($missionOriginal->getState(), ["cancelled""archived""closed"]) && $missionOriginal->getId() == $mission->getId()) {
  1370.                                     $mission->setState($originalMissions->getState());
  1371.                                     $entityManager->flush();
  1372.                                 }
  1373.                             }
  1374.                         } else {
  1375.                             if ($missionService->lackSubcontractorTest(mission$mission) && !$missionService->aSubcontractorBotIsInThisMission(mission$mission)) {
  1376.                                 $message[3] = "- Vous venez d'accepter la mission, nous attendons maintenant l'intervention de l'administrateur pour poursuivre le processus";
  1377.                                 $event = new SubcontractorActivateOrThereIsABotEvent($mission);
  1378.                                 $dispatcher->dispatch($eventSubcontractorActivateOrThereIsABotEvent::NAME);
  1379.                             }
  1380.                             $campaign->setState($campaign->getLastState());
  1381.                             foreach ($originalCampaign->getMissions() as $missionOriginal) {
  1382.                                 if ($missionOriginal->getId() == $mission->getId()) {
  1383.                                     $mission->setState("provisional");
  1384.                                 }
  1385.                             }
  1386.                             $entityManager->flush();
  1387.                             $canStartCampaign false;
  1388.                         }
  1389.                         foreach ($missionService->determineAllSubcontractorEvaluated(mission$mission) as $userEvaluate) {
  1390.                             if ($userEvaluate != $this->getUser()) {
  1391.                                 $listUserEvaluate .= "{$userEvaluate->getFullName()} ,";
  1392.                             }
  1393.                             if (strlen($listUserEvaluate) > 3) {
  1394.                                 $listUserEvaluate rtrim($listUserEvaluate",");
  1395.                                 $message[4] = " - Merci pour votre validation. " $msg ". Nous attendons donc la validation du client pour démarrer le travail :  $listUserEvaluate.";
  1396.                             }
  1397.                         }
  1398.                     }
  1399.                     if ($this->campaignService->canResendOrderToClient(campaign$mission->getCampaign(), missionEvaluate$mission) && $originalCampaign->getState() == "waiting_resend") {
  1400.                         $this->campaignService->resendCampaignForValidation(campaign$mission->getCampaign(), user$this->getUser());
  1401.                         $canStartCampaign false;
  1402.                     }
  1403.                     $missionService->addHistorique(mission$missionuser$this->getUser(), action"activation_campaign");
  1404.                     $allMessage "";
  1405.                     foreach ($message as $msg) {
  1406.                         //$allMessage .= "{$msg} <br> <br>";
  1407.                         $this->addFlash(
  1408.                             type'success',
  1409.                             message$msg,
  1410.                         );
  1411.                     }
  1412.                 } elseif (in_array("ROLE_ADMIN"$userConnected->getRoles())) {
  1413.                    
  1414.                     foreach ($campaign->getMissions() as $mission) {
  1415.                         //////////////////// Check marge mission  
  1416.                         $getMargeMyFlow $priceService->marginExceeded(mission$mission);
  1417.                         if ($getMargeMyFlow['percentage'] <= && $mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE ) {
  1418.                           
  1419.                                 $this->addFlash(
  1420.                                     type'error',
  1421.                                     message"Nous avons rencontré un problème, une des missions a une marge de {$getMargeMyFlow['percentage']} % .",
  1422.                                 );  
  1423.                                 $campaign->setState($originalCampaign->getState());
  1424.                                 $entityManager->flush();
  1425.                                  $canStartCampaign false;
  1426.                                 continue; 
  1427.                                 //return  $redirect;
  1428.                             }
  1429.                         foreach ($mission->getParticipants() as $missionParticipation) {
  1430.                             if (!$missionParticipation->isActivated() && !$missionParticipation->isRefused()) {
  1431.                                 $missionParticipation->setActivated(true);
  1432.                                 $missionParticipation->setEvaluate(false);
  1433.                                 $missionParticipation->setActivatedAt(new \DateTime());
  1434.                                 $entityManager->flush();
  1435.                             }
  1436.                         }
  1437.                         if ($mission->isEvaluate()) {
  1438.                             $mission->setEvaluate(false);
  1439.                         }
  1440.                         $missionService->addHistorique(mission$missionuser$this->getUser(), action"activation_campaign");
  1441.                     }
  1442.                     $canStartCampaign true;
  1443.                 } else {
  1444.                     foreach ($campaign->getMissions() as $mission) {
  1445.                         //////////////////// Check marge mission  
  1446.                         $missionCanActive true;
  1447.                         $getMargeMyFlow $priceService->marginExceeded(mission$mission);
  1448.                         if ($getMargeMyFlow['percentage'] <= 0) {
  1449.                             if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
  1450.                                 $event = new MissionCanActivateEvent($mission$getMargeMyFlow['percentage']);
  1451.                                 $dispatcher->dispatch($eventMissionCanActivateEvent::NAME);
  1452.                                 $missionCanActive false;
  1453.                                 
  1454.                             }
  1455.                             $missionCanActive false;
  1456.                             continue; 
  1457.                         }
  1458.                         foreach ($mission->getParticipants() as $missionParticipation) {
  1459.                             if ($missionParticipation->isEvaluate() && !$missionParticipation->isRefused()) {
  1460.                                 $missionParticipation->setActivated(true);
  1461.                                 $missionParticipation->setEvaluate(false);
  1462.                                 $missionParticipation->setActivatedAt(new \DateTime());
  1463.                                 $entityManager->flush();
  1464.                             }
  1465.                         }
  1466.                         if ($mission->isEvaluate()) {
  1467.                             $mission->setEvaluate(false);
  1468.                         }
  1469.                         if ($missionCanActive && $missionService->lackSubcontractorTest(mission$mission)) {
  1470.                             if (in_array($mission->getState(), ["cancelled""archived""closed"])) {
  1471.                                 foreach ($originalCampaign->getMissions() as $missionOriginal) {
  1472.                                     if ($missionOriginal->getId() == $mission->getId()) {
  1473.                                         $mission->setState($originalCampaign->getState());
  1474.                                         $entityManager->flush();
  1475.                                     }
  1476.                                 }
  1477.                             }
  1478.                         } else {
  1479.                             foreach ($originalCampaign->getMissions() as $missionOriginal) {
  1480.                                 if ($missionOriginal->getId() == $mission->getId()) {
  1481.                                     $mission->setState("provisional");
  1482.                                     $entityManager->persist($mission);
  1483.                                     $entityManager->flush();
  1484.                                 }
  1485.                             }
  1486.                             $canStartCampaign false;
  1487.                         }
  1488.                     }
  1489.                 }
  1490.                 if (!$canStartCampaign) {
  1491.                     $campaign->setState($originalCampaign->getState());
  1492.                     $entityManager->flush();
  1493.                 }
  1494.                 //verification de BOT
  1495.                 if ($campaign->haveBot()) {
  1496.                     if (in_array("ROLE_SUBCONTRACTOR"$userConnected->getRoles())) {
  1497.                         $this->addFlash(
  1498.                             type'error',
  1499.                             message'l\'activation de la campagne nécessite encore l\'intevention de l\'administrateur.',
  1500.                         );
  1501.                     } else {
  1502.                         $this->addFlash(
  1503.                             type'error',
  1504.                             message'Activation impossible car certaines mission sont encore liées a des Bots.',
  1505.                         );
  1506.                     }
  1507.                     $campaign->setState($originalCampaign->getState());
  1508.                     $entityManager->flush();
  1509.                     return  $redirect;
  1510.                 }
  1511.                 if ($canStartCampaign && $campaignService->isCanStart(campaign$campaign)) {
  1512.                     // campaign and setState() in progress managed by symfony workflow in config/packages/workflow
  1513.                     $campaign->setReSendToClient(false);
  1514.                     $campaign->setClientStatus("");
  1515.                     foreach ($campaign->getMissions() as $mission) {
  1516.                         if (!empty($mission->getWorkflow())) {
  1517.                             $stepIsActive false;
  1518.                             //verifié si un step est active // si active alors ne plus faire de mise a jour.
  1519.                             foreach ($mission->getWorkflow()->getSteps() as $step) {
  1520.                                 if ($step->isActive()) {
  1521.                                     $stepIsActive true;
  1522.                                 }
  1523.                             }
  1524.                             $step $workflowStepRepository->getFirstStep($mission->getWorkflow());
  1525.                             if (empty($step) || $step === false) {
  1526.                                 if (in_array("ROLE_SUBCONTRACTOR"$userConnected->getRoles())) {
  1527.                                     $this->addFlash(
  1528.                                         type'error',
  1529.                                         message'l\'activation de la campagne nécessite encore l\'intevention de l\'administrateur.',
  1530.                                     );
  1531.                                 } else {
  1532.                                     $this->addFlash(
  1533.                                         type'error',
  1534.                                         message'Activation impossible car le workflow n\'as pas d\'étape prédéfinie.',
  1535.                                     );
  1536.                                 }
  1537.                                 $campaign->setState($originalCampaign->getState());
  1538.                                 $entityManager->flush();
  1539.                                 return $redirect;
  1540.                             }
  1541.                             if (!$stepIsActive) {
  1542.                                 $step->setActive(true);
  1543.                                 $now = new \DateTime();
  1544.                                 $timezone = new \DateTimeZone("UTC");
  1545.                                 $now->setTimezone($timezone);
  1546.                                 $step->setStartDate($now);
  1547.                                 $event = new WorkflowStepEnteredEvent($step);
  1548.                                 $dispatcher->dispatch($eventWorkflowStepEnteredEvent::NAME);
  1549.                             }
  1550.                         } else {
  1551.                             if (in_array("ROLE_SUBCONTRACTOR"$userConnected->getRoles())) {
  1552.                                 $this->addFlash(
  1553.                                     type'error',
  1554.                                     message'l\'activation de la campagne nécessite encore l\'intevention de l\'administrateur.',
  1555.                                 );
  1556.                             } else {
  1557.                                 $this->addFlash(
  1558.                                     type'error',
  1559.                                     message'Activation impossible car la campagne n\'a pas de workflow',
  1560.                                 );
  1561.                             }
  1562.                             $campaign->setState($originalCampaign->getState());
  1563.                             $entityManager->flush();
  1564.                             return $this->redirectToRoute('mission_index');
  1565.                         }
  1566.                         //fin vérification
  1567.                         if ($step->getManager() == 0) {
  1568.                             $mission->setStateClient('Déclenchement en attente');
  1569.                         } else {
  1570.                             $mission->setStateProvider($step->getName());
  1571.                         }
  1572.                         $mission->setCanInvoiced(true);
  1573.                         $entityManager->flush();
  1574.                         if ($mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
  1575.                              $missionService->setDefaultValueIfAnUserClickedAnActivationButtonWithoutADelaisAndTimeIsEmpty($mission$priceService);
  1576.                             $clientSoldService->decreaseCurrentBalanceByMissionCost($mission);
  1577.                         }
  1578.                         $missionParticipantService->markAsAllParticipantClickActivationButton(mission$mission);
  1579.                         $missionService->addHistorique(mission$missionuser$this->getUser(), action"start");
  1580.                     }
  1581.                     $event = new CampaignValidatedPerActivationEvent($campaign$this->getUser());
  1582.                     $dispatcher->dispatch($event,CampaignValidatedPerActivationEvent::NAME);
  1583.                 } else {
  1584.                     if ($campaign->getState() !== "waiting_validation") {
  1585.                         $campaign->setState($originalCampaign->getState());
  1586.                         $entityManager->flush();
  1587.                     }
  1588.                     return $redirect;
  1589.                 }
  1590.             }
  1591.             /* if(($transition == "activated" || $transition == "validate") && $currentRouteName == null ){
  1592.                 $campaign->setActivatedAt(new \DateTimeImmutable());
  1593.             } */
  1594.             
  1595.             $entityManager->flush();
  1596.             $message = match ($transition) {
  1597.                 'validate' => 'validée',
  1598.                 'pause' => 'mise en pause',
  1599.                 'unpause' => 'relancée',
  1600.                 'cancel' => 'annulée',
  1601.                 'closed' => 'clôturée',
  1602.                 'activated' => 'activée',
  1603.                 default => 'enregistrée',
  1604.             };
  1605.             $this->addFlash(
  1606.                 type'success',
  1607.                 message"La campagne {$campaign->getName()} a bien été " $message,
  1608.             );
  1609.             
  1610.         }
  1611.         return $redirect;
  1612.     }
  1613.     #[Route('/campagne/{id}/detail/check'name'handle_detail_campaing'methods: ['GET''POST'])]
  1614.     public function campaignDetail(Campaign $campaign,MissionService $missionService,EntityManagerInterface $entityManager,UserRepository $userRepository){
  1615.             if (count($campaign->getMissions()) != 0) {
  1616.                 return  $this->redirectToRoute('mission_edit',['id'=>$campaign->getMissions()->first()->getId()]) ; 
  1617.             }
  1618.             //count nb mission
  1619.             $product = new Product();
  1620.             $product->setName("Espace de discussion");
  1621.             $product->setFrontId(0);
  1622.             $product->setType(ProductType::AU_TEMPS_PASSE);
  1623.             $entityManager->persist($product);
  1624.             $today = new \DateTime();
  1625.             $mission  = new Mission();
  1626.             $campaignDefaultObserver $campaign->getDefautObserver();
  1627.             $campaignDefaultValidator $campaign->getDefaultValidator();
  1628.             $campaignDefaultValidatorExternal $campaign->getDefaultValidatorExternal();
  1629.             $campaignDefaultObserverExternal $campaign->getDefautObserverExternal();
  1630.             if(!empty($campaignDefaultValidator)){
  1631.                 foreach($campaignDefaultValidator as $validatorEmail){
  1632.                     $user $userRepository->findOneBy(['email'=>$validatorEmail]);
  1633.                     $userDefaultValidatorParticipant = (new MissionParticipant())
  1634.                                 ->setUser($user)
  1635.                                 ->setMission($mission)
  1636.                                 ->setRole(Role::ROLE_VALIDATOR);
  1637.                     $mission->addParticipant($userDefaultValidatorParticipant);
  1638.                 }
  1639.             }
  1640.             if(!empty($campaignDefaultObserver)){
  1641.                 foreach($campaignDefaultObserver as $observerEmail){
  1642.                     $user $userRepository->findOneBy(['email'=>$observerEmail]);
  1643.                     $userDefaultObserverParticipant = (new MissionParticipant())
  1644.                                 ->setUser($user)
  1645.                                 ->setMission($mission)
  1646.                                 ->setRole(Role::ROLE_OBSERVER);
  1647.                     $mission->addParticipant($userDefaultObserverParticipant);
  1648.                 }
  1649.             }
  1650.             if(!empty($campaignDefaultValidatorExternal)){
  1651.                 foreach($campaignDefaultValidatorExternal as $validatorExternalEmail){
  1652.                     $user $userRepository->findOneBy(['email'=>$validatorExternalEmail]);
  1653.                     $userDefaultValidatorExternalParticipant = (new MissionParticipant())
  1654.                             ->setUser($user)
  1655.                             ->setMission($mission)
  1656.                             ->setRole(Role::ROLE_VALIDATOR_EXTERNAL);
  1657.                     $mission->addParticipant($userDefaultValidatorExternalParticipant);
  1658.                 }
  1659.             }
  1660.             if(!empty($campaignDefaultObserverExternal)){
  1661.                 foreach($campaignDefaultObserverExternal as $observerExternalEmail){
  1662.                     $user $userRepository->findOneBy(['email'=>$observerExternalEmail]);
  1663.                     $userDefaultValidatorExternalParicipant = (new MissionParticipant())
  1664.                             ->setUser($user)
  1665.                             ->setMission($mission)
  1666.                             ->setRole(Role::ROLE_OBSERVER_EXTERNAL);
  1667.                     $mission->addParticipant($userDefaultValidatorExternalParicipant);
  1668.                 }
  1669.             }
  1670.             $workflow $entityManager->getRepository(Workflow::class)->findOneBy(['template'=>1,'name'=>'Discussion']);
  1671.             $newWorkflow = clone($workflow);
  1672.             $mission->setProduct($product)
  1673.                     ->setQuantity(1)
  1674.                     ->setDesiredDelivery($today->add(new \DateInterval('P1Y')))
  1675.                     ->setState('provisional')
  1676.                     ->setWorkflow($newWorkflow)
  1677.                     ->setCampaign($campaign)
  1678.                     //->setReference($this->missionService->generateReference());
  1679.                     ;
  1680.             $campaign->setState('provisional');
  1681.             $entityManager->persist($mission);
  1682.             $entityManager->persist($campaign);
  1683.             $entityManager->flush();
  1684.             return  $this->redirectToRoute('mission_edit',['id'=> $mission->getId()]) ; 
  1685.         
  1686.     }
  1687.    
  1688.     #[Route('/campagne/{id}/missions'name'handle_mission_campaign'methods: ['GET''POST'])]
  1689.     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
  1690.     {
  1691.         
  1692.         $newUserCreateId = [];
  1693.         $launchJustOne true;
  1694.         $matriceFrequencyType = [0=>'hours',1=>'months',2=>'days',3=>'years'];
  1695.         $error false;
  1696.         $campaignBrief null;
  1697.         $allMissionsInCampaign = [];
  1698.         $isNewCampaing false;
  1699.         if ($id == "new") {
  1700.             $campaign = new Campaign();
  1701.             $campaign->setOrderedBy($this->getUser())
  1702.                     ->setIsNew(true)
  1703.                     ->setDisabled(true)
  1704.                     ->setTypeInitiation(CampaignTypeInitiation::CAMPAIGN_FROM_ADMIN->value);
  1705.             $isNewCampaing true;
  1706.             if(in_array('ROLE_ADMIN'$this->getUser()->getRoles())){
  1707.                 $campaign->setRecurringState('waiting_validation');
  1708.             }
  1709.             $entityManager->persist($campaign);
  1710.             $entityManager->flush();
  1711.             $missionAlreadyExist false;
  1712.             $campaignInitiator $this->getUser();
  1713.             $url $this->generateUrl('handle_mission_campaign', ["id" => $campaign->getId()]);
  1714.             return new RedirectResponse($url);
  1715.         }else{
  1716.             $campaign $campaignRepository->findOneBy(['id'=>$id]);
  1717.             $campaignInitiator $campaign->getOrderedBy();
  1718.             $campaignBeforeState $campaign->getState();
  1719.             $oldCampaign = clone $campaign;
  1720.             $missionAlreadyExist =  (count($oldCampaign->getMissions()) == 0) ? false true;
  1721.             $campaignBrief $campaign->getBrief();
  1722.             $allMissionsInCampaign $missionRepository->findBy(['campaign' => $campaign]);
  1723.         }
  1724.         $stateRecurred $campaign->getState() ;
  1725.         $oldCampaignStateActiveFrequency =  $campaign->getActiveFrequency();
  1726.         $oldFrequency $campaign->getFrequency() != null ?  clone $campaign->getFrequency() : null;
  1727.         $oldPack $campaign->getCreditHistory();
  1728.         $sendEmailDeliveryDateChange true;
  1729.         $missionsInCampaign = [];
  1730.         
  1731.         foreach ($allMissionsInCampaign as $missionInCampaign) {
  1732.             if (!isset($missionsInCampaign[$missionInCampaign->getId()])) {
  1733.                 $missionsInCampaign[$missionInCampaign->getId()] = [];
  1734.             }
  1735.             if (!empty($missionInCampaign->getDesiredDelivery())) {
  1736.                 $missionsInCampaign[$missionInCampaign->getId()] = clone $missionInCampaign->getDesiredDelivery();
  1737.             }
  1738.         }
  1739.         $oldMissionId = [];
  1740.         $oldMission   $campaign->getMissions();
  1741.         $oldParticipantMail= [];
  1742.         foreach ($oldMission as $key => $mission) {
  1743.             $oldMissionId[] = $mission->getId();
  1744.             foreach ($mission->getParticipants() as $participant) {
  1745.                 $oldParticipantMail [] = $participant->getUser()->getEmail();
  1746.             }
  1747.         }
  1748.         //list of user to link of all mission
  1749.         $user $userRepository->findAll();
  1750.         $isadminAgency false;
  1751.         $company null;
  1752.         if (in_array("ROLE_ADMIN_AGENCY"$this->getUser()->getRoles()) ) {
  1753.            
  1754.             $isadminAgency true;
  1755.             $company $this->getUser()->getCompany();
  1756.         }
  1757.         foreach ($campaign->getMissions() as $mission) {
  1758.             $mission->setPrice($this->getPrice$mission->getProduct(),$this->getUser()));
  1759.         }
  1760.         $formEditCampaign $this->createForm(ListMissionFormType::class, $campaign,['user'=>$user,'isadminAgency'=>$isadminAgency,'company'=> $company]);
  1761.         $formEditCampaign->handleRequest($request);
  1762.         $errors $formEditCampaign->getErrors(truetrue);
  1763.         
  1764.         $canResendToClient true;
  1765.         $nbrAU_FORFAIT 0;
  1766.         $nbrA_EVALUER 0;
  1767.         $nbrAU_TEMPS_PASSE 0;
  1768.         $nbrMission 0;
  1769.         $allMissionNewId = [];
  1770.         $pathCampaing 'file_campaing_directory';
  1771.         $pathMission 'file_mission_directory';
  1772.         $newCampaign false;
  1773.         
  1774.        
  1775.         
  1776.         
  1777.     
  1778.         if ($formEditCampaign->isSubmitted() && $formEditCampaign->isValid()) {
  1779.             
  1780.             $contactProjects = [];
  1781.             if ($campaign->getDisabled() == 1) {
  1782.                 $newCampaign true;
  1783.             }
  1784.             $state 'waiting';
  1785.             $missions $formEditCampaign->get('missions');
  1786.             $otherInformationThanDateChange false;
  1787.             $newMissionInCampaign false;
  1788.             //validateur external an user validator / observer----------------
  1789.             //first delete all user in mission
  1790.             foreach ($campaign->getMissions() as $mission) {
  1791.                
  1792.                 foreach ($mission->getParticipants() as $participant) {
  1793.                     if (in_array($participant->getRole()->value, ['ROLE_OBSERVER_EXTERNAL','ROLE_VALIDATOR_EXTERNAL','ROLE_OBSERVER','ROLE_VALIDATOR'])) {
  1794.                         $entityManager->remove($participant);
  1795.                         $entityManager->flush();
  1796.                     }
  1797.                 }
  1798.             }
  1799.             $userAlreadyAdd = [];
  1800.             $userToAdd $formEditCampaign->get('user')->getData();
  1801.             $files $formEditCampaign->get('fileMissions')->getData();
  1802.             //dd($userToAdd);
  1803.             // $files = $files != null ? $files : [];
  1804.             /* $droppedFilesMissions = $formEditCampaign->get('droppedFileMissions')->getData(); */
  1805.              //second add participant
  1806.             $defaultObserver = [];
  1807.             $defaultObserverExernal = [];
  1808.             $defaultValidator = [];
  1809.             $defaultValidatorExternal = [];
  1810.             foreach ($userToAdd as $element) {
  1811.                 $user $element['user'];
  1812.                 $role $element['role'];
  1813.                 if (is_null($user) || is_null$role)) {
  1814.                     continue;
  1815.                 }
  1816.                 $clientIntern=false
  1817.                 if($this->campaignService->isMyCompany($campaign->getCompany(), $user) || 
  1818.                     $this->campaignService->isMyEmailSameExtensionOfCompanyExtension($campaign->getCompany(),$user)){
  1819.                     $role =  $this->campaignService->getRoleForInternalClient($element['role']);
  1820.                     $clientIntern=true
  1821.                     switch ($role->value) {
  1822.                             case 'ROLE_OBSERVER':
  1823.                                 $defaultObserver = [...$defaultObserver$user->getOriginalMailUser()];
  1824.                                 break;
  1825.                             case 'ROLE_VALIDATOR':
  1826.                                 $defaultValidator = [...$defaultValidator$user->getOriginalMailUser()];
  1827.                                 break;
  1828.                     }
  1829.                 }else{
  1830.                     $clientIntern=false;
  1831.                     $roleList = ['ROLE_VALIDATOR_EXTERNAL','ROLE_OBSERVER_EXTERNAL'];
  1832.                     if (!in_array($role,$roleList)) {
  1833.                         $role =  $this->campaignService->getRoleForExternalClient($element['role']);
  1834.                     }
  1835.                     switch ($role->value) {
  1836.                         case 'ROLE_VALIDATOR_EXTERNAL':
  1837.                             $defaultValidatorExternal = [...$defaultValidatorExternal$user->getOriginalMailUser()];
  1838.                             break;
  1839.                         case 'ROLE_OBSERVER_EXTERNAL':
  1840.                             $defaultObserverExernal = [...$defaultObserverExernal$user->getOriginalMailUser()];
  1841.                             break;
  1842.                     }
  1843.                 }
  1844.                 if ($user->getNewAdd()) {
  1845.                     //role external is just a client
  1846.             
  1847.                     $user->setRoles(['ROLE_CLIENT'])
  1848.                          ->setEnabled(false)
  1849.                          ->setNewAdd(false)
  1850.                          ;
  1851.                     //add company in user new add
  1852.                     $companyUser $formEditCampaign?->get('company')?->getData();
  1853.                     if ($companyUser !== null &&   $clientIntern==true) {
  1854.                         $user->setCompany($companyUser);
  1855.                     }
  1856.                     //end
  1857.                     if (in_array($role, ['ROLE_OBSERVER_EXTERNAL','ROLE_VALIDATOR_EXTERNAL'])) {
  1858.                         $user->setExternal(true);
  1859.                         $user->setCompany(null);
  1860.                     }
  1861.                     $user->setPassword($passwordHasher->hashPassword($user$user->getPassword()));
  1862.                     $entityManager->persist($user);
  1863.                     $entityManager->flush();
  1864.                     $event = new ClientUpdatedEvent($usertrue);
  1865.                     $newUserCreateId[] = $user->getId();
  1866.                     if (!in_array($user->getEmail(),$oldParticipantMail)) {
  1867.                         $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  1868.                     }
  1869.                 } else {
  1870.                     if (!in_array($user->getId(), $newUserCreateId) && true === $launchJustOne&& isset($mission) && !is_null($mission)) {
  1871.                         if ($user->getId() != $mission->getCampaign()->getOrderedBy()->getId()) {
  1872.                             $event = new MissionSendEvent($mission$user$role);
  1873.                             
  1874.                             if (!in_array($user->getEmail(),$oldParticipantMail)) {
  1875.                                 $dispatcher->dispatch($eventMissionSendEvent::NAME);
  1876.                             }
  1877.                         }
  1878.                     }
  1879.                 }
  1880.                 foreach ($campaign->getMissions() as $mission) {
  1881.                      $participantAlredyExiste false;
  1882.                      foreach ($mission->getParticipants() as $participant) {
  1883.                             if($participant->getUser()->getId() == $user->getId() && $participant->getRole()->value == $role && $role!="ROLE_SUBCONTRACTOR"){
  1884.                                 $participantAlredyExiste true ;
  1885.                             }
  1886.                      }
  1887.                     if (!is_null($user) and !empty($user) and !in_array($user->getId(),$userAlreadyAdd) && !$participantAlredyExiste) {
  1888.                        //add participant
  1889.                        
  1890.                         $participant = (new MissionParticipant())
  1891.                                 ->setUser($user)
  1892.                                 ->setMission($mission)
  1893.                                 ->setRole($role);
  1894.                        $mission->addParticipant($participant);
  1895.                     }
  1896.                 }
  1897.             }
  1898.             //prendre les contact projet sur une des mission
  1899.             foreach ($campaign->getMissions() as $miss) {
  1900.                 foreach ($miss->getParticipants() as $p) {
  1901.                     if ($p->getRole() == Role::PROJECT_CONTACT ) {
  1902.                         $contactProjects[] = $p->getUser();
  1903.                     }
  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.                 $contactProjectIsAvailable false;
  1931.                 foreach ($campaign->getMissions() as $mission) {
  1932.                      foreach ($mission->getParticipants() as $participant) {
  1933.                         if ($participant->getRole() ==  Role::PROJECT_CONTACT) {
  1934.                             $contactProjectIsAvailable true;
  1935.                         }
  1936.                     }
  1937.                 }
  1938.                 //add contact project in all mission
  1939.                 foreach ($campaign->getMissions() as $mission) {
  1940.                     if (!$contactProjectIsAvailable) {
  1941.                         $contactProject array_column($userRepository->getContactProjectByCompany($campaign->getCompany()),'id');
  1942.                         $contactProject array_unique($contactProject);
  1943.                        foreach ($contactProject as $contact) {
  1944.                             $userContact $userRepository->find($contact);
  1945.                             $missionParticipantContactProject = (new MissionParticipant())
  1946.                                                     ->setUser($userContact)
  1947.                                                     ->setMission($mission)
  1948.                                                     ->setRole(Role::PROJECT_CONTACT);
  1949.                             $mission->addParticipant($missionParticipantContactProject);
  1950.                         }
  1951.                     }
  1952.                 }
  1953.             }
  1954.             
  1955.             $campaign->setDefautObserver($defaultObserver)
  1956.                     ->setDefaultValidator($defaultValidator)
  1957.                     ->setDefaultValidatorExternal($defaultValidatorExternal)
  1958.                     ->setDefautObserverExternal($defaultObserverExernal);
  1959.             
  1960.             $launchJustOne false;
  1961.             $fileToDeleted $formEditCampaign->get('listfileMissionsToDeleted')->getData();
  1962.             //delete files 
  1963.             if (!empty($fileToDeleted) and !is_null($fileToDeleted) ) {
  1964.                 $fileExplode explode(';',$fileToDeleted);
  1965.                 foreach ($fileExplode as $file) {
  1966.                     $fileMission $fileMissionRepository->findOneBy(['name'=>$file,'campaign'=>$campaign]);
  1967.                     if (!is_null($fileMission)) {
  1968.                         $fileName =   $fileName "Campaigns/".$campaign->getId()."/".$fileMission->getName();
  1969.                         $bucketName "company-".strtolower($campaign->getCompany()->getId());
  1970.                         $destination $this->getParameter($pathCampaing) . '/' $campaign->getId();
  1971.                         if (file_exists($destination."/".$fileMission->getName())) {
  1972.                             unlink($destination."/".$fileMission->getName());
  1973.                         }
  1974.                         //delete file in repertory
  1975.                         $campaign->removeFileMission($fileMission);
  1976.                         //remove in repertory
  1977.                         foreach ($campaign->getMissions() as $mission) {
  1978.                             $fileMission $fileMissionRepository->findOneBy(['name'=>$file,'mission'=>$mission]);
  1979.                             $destinationFileMission $this->getParameter($pathMission) . '/' $mission->getId();
  1980.                             if (!is_null($fileMission) && file_exists($destinationFileMission."/".$fileMission->getName())) {
  1981.                                 unlink($destinationFileMission."/".$fileMission->getName());
  1982.                             }
  1983.                             if (!is_null($fileMission)) {
  1984.                                 $mission->removeFileMission($fileMission);
  1985.                                 $entityManager->remove($fileMission);
  1986.                             }
  1987.                             //suppression file in storage
  1988.                         }
  1989.                         $googleStorageService->deleteFile($bucketName,$fileName);
  1990.                         $entityManager->flush();
  1991.                     }
  1992.                 }
  1993.             }
  1994.   
  1995.             foreach ($files as $file) {
  1996.                 $destination $this->getParameter($pathCampaing) . '/' $campaign->getId();
  1997.                 $originalFilename pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  1998.                 $extensionFile =  pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
  1999.                 $newFilename $originalFilename '-' uniqid() . '.' $extensionFile;
  2000.                  //upload file in google storage
  2001.                 $nameUniqueCompany strtolower("company-".$campaign->getCompany()->getId());
  2002.                 $this->googleStorageService->uploadFile($nameUniqueCompany,$file,$newFilename,'Campaigns/'.$campaign->getId());
  2003.                 $fileMission = new FileMission();
  2004.                 $fileMission->setName($newFilename);
  2005.                 $fileMission->setIsNew(1);
  2006.                 $fileMission->setUser($this->getUser());
  2007.                 $campaign->addFileMission($fileMission);
  2008.  
  2009.             }
  2010.             // dd( $campaign->getFileMissions());
  2011.             $jobSub $request->request->get('jobsub');
  2012.             $nbrMission sizeof($missions);
  2013.             
  2014.             if ($campaign->getNumberInitialOfMissions() != null && intval($campaign->getNumberInitialOfMissions()) != $nbrMission) {
  2015.                 $isCampaignContainsEvaluateProduct $this->checkIfCampaignContainsProductEvaluate($campaign);
  2016.                 $newStateOfThisCampaign 'resend';
  2017.                 $campaign->setReSendToClient(true);
  2018.                 if($isCampaignContainsEvaluateProduct){
  2019.                      $newStateOfThisCampaign 'waiting';
  2020.                 }
  2021.                 if(in_array('ROLE_ADMIN'$this->getUser()->getRoles())){
  2022.                     $campaign->setRecurringState('waiting_validation');
  2023.                 }
  2024.                 $campaign->setState($newStateOfThisCampaign);
  2025.                 $campaign->setNumberInitialOfMissions(sizeof($missions));
  2026.             }
  2027.             
  2028.             if ($campaign->getMissions()->count() === 0) {
  2029.                 $state 'provisional';
  2030.                 //$campaignTypeInitiation = CampaignTypeInitiation::CAMPAIGN_FROM_DEVIS_CLIENT->value;
  2031.                 //$campaign->setTypeInitiation($campaignTypeInitiation);
  2032.             }
  2033.             if (count($campaign->getMissions()) == and $campaign->getMissions()->first()->getProduct()->getName()=="Espace de discussion") {
  2034.                 $campaign->setState('provisional');
  2035.             }
  2036.             
  2037.             $ids =[];
  2038.             foreach ($missions as $key => $mission) {
  2039.                 $serviceParticipant = new Service();
  2040.                
  2041.                 //determine if mission is new // add normal state
  2042.                 if ($newCampaign) {
  2043.                     if ($mission->getData()->getProduct()->getType() === ProductType::A_EVALUER) {
  2044.                         $state 'waiting';
  2045.                     }
  2046.                 }
  2047.                 //add brief 
  2048.                 $mission->getData()->setInitialBriefing($campaignBrieftrue);
  2049.                 if (!$missionService->haveAvalidator(mission$mission->getData())) {
  2050.                     $id $missionService->setValidatorUserWhoOrder(mission$mission->getData());
  2051.                     if (null !== $id) {
  2052.                         $allMissionNewId[] = $id;
  2053.                     }
  2054.                 }
  2055.                 if ($mission->getData()->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
  2056.                     $nbrAU_TEMPS_PASSE++;
  2057.                 }
  2058.                 if ($mission->getData()->getProduct()->getType() == ProductType::A_EVALUER) {
  2059.                     $nbrA_EVALUER++;
  2060.                 }
  2061.                 if ($mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT) {
  2062.                     $nbrAU_FORFAIT++;
  2063.                 }
  2064.              
  2065.                 if(sizeof(explode("-"$mission->getData()->getOldCommand()))==1){
  2066.                     $newMissionInCampaign true;
  2067.                 }
  2068.                 if ($mission->getData()->getOldCommand() != null && sizeof(explode("-"$mission->getData()->getOldCommand())) == 4) {
  2069.                     [$quatity$price$productId$timestamp] =  explode("-"$mission->getData()->getOldCommand());
  2070.    
  2071.                     // Check if timestamp an other information change; 
  2072.                     if ($mission->getData()->getQuantity() != $quatity || $mission->getData()->getProduct()->getId() != $productId) {
  2073.                         
  2074.                         $otherInformationThanDateChange true;
  2075.                         //add information to historique 
  2076.                         if(in_array('ROLE_ADMIN'$this->getUser()->getRoles())){
  2077.                             $campaign->setRecurringState('waiting_validation');
  2078.                         }
  2079.                         $historique = (new Historique())
  2080.                             ->setUser($this->getUser())
  2081.                             ->setMission($mission->getData())
  2082.                             ->setMessage('Le panier a été mis à jour par : ' $this->getUser());
  2083.                         $entityManager->persist($historique);
  2084.                         $entityManager->flush();
  2085.                     }
  2086.                       if ($mission->getData()->getDesiredDelivery()?->getTimestamp() && intval($timestamp) != intval($mission->getData()->getDesiredDelivery()->getTimestamp())) {
  2087.                         if (!$otherInformationThanDateChange) {
  2088.                             $missionService->addHistorique(mission$mission->getData(), user$this->getUser(), action"deadline_change");
  2089.                 
  2090.                         }
  2091.                     }
  2092.                     
  2093.                     if ($otherInformationThanDateChange and !$newCampaign) {
  2094.                         $campaign->setReSendToClient(true);
  2095.                         $campaign->setState("resend");
  2096.                         if(in_array('ROLE_ADMIN'$this->getUser()->getRoles())){
  2097.                             $campaign->setRecurringState('waiting_validation');
  2098.                         }
  2099.                         $canResendToClient false;
  2100.                     }
  2101.                 }
  2102.                 
  2103.                 if ($mission->getData()->getOldCommand() != null and !$newCampaign and $otherInformationThanDateChange) {
  2104.                     
  2105.                     $campaign->setReSendToClient(true);
  2106.                     $campaign->setState("resend");
  2107.                  
  2108.                     $entityManager->persist($campaign);
  2109.                     $entityManager->flush();
  2110.                 }
  2111.                 $originalMission =  $missionRepository->find($mission->getData()->getId());
  2112.                 if (!is_null($mission->getData()->getAdminIncome())) {
  2113.                     $mission->getData()->setPrice($mission->getData()->getAdminIncome());
  2114.                 }
  2115.                 //-----------------------add default observer if new mission-------------------
  2116.                 if (!is_null($originalMission) and empty($originalMission->getReference())  ) {
  2117.                 //   //add default observer
  2118.                    if($campaign->getDefautObserver() != null){
  2119.                         $missionService->addDefaultClient($mission->getData(), 'observer',$stateRecurred);
  2120.                    }
  2121.                   
  2122.                    // add default validator
  2123.                    if($campaign->getDefaultValidator() != null){
  2124.                         $missionService->addDefaultClient($mission->getData(), 'validator',$stateRecurred);
  2125.                    }
  2126.                    
  2127.                
  2128.                  //------------------------------------------------------------------------------
  2129.                 }
  2130.                 if (!is_null($originalMission)) {
  2131.                     if (!$isNewCampaing) {
  2132.                         $mission->getData()->setOldCommand("{$mission->getData()->getQuantity()}-{$originalMission->getPrice()}-{$mission->getData()->getProduct()->getId()}-{$mission->getData()->getDesiredDelivery()?->getTimestamp()}");
  2133.                     }
  2134.                 }
  2135.                 if (empty($mission->getData()->getReference())) {
  2136.                     foreach ($campaign->getMissions() as $mis) {
  2137.                         if (!empty($mis->getReference())) {
  2138.                             $mission->getData()->setReference($mis->getReference());
  2139.                             break;
  2140.                         }
  2141.                     }
  2142.                     if (empty($mission->getData()->getReference())) {
  2143.                         $mission->getData()->setReference($missionService->generateReference());
  2144.                     }
  2145.                 }
  2146.                 $missionId $missionRepository->findOneBy(['id' => $mission->get('missionId')->getData()]);
  2147.                 if ($sendEmailDeliveryDateChange and !$newCampaign) {
  2148.                     if (isset($missionsInCampaign[$mission->getData()->getId()]) && $mission->getData()->getDesiredDelivery() != $missionsInCampaign[$mission->getData()->getId()] && !in_array($mission->getData()->getState(), ['provisional''waiting'])) {
  2149.                         $event = new MissionDesiredDeliveryUpdatedAfterValidationEvent($missionId);
  2150.                         $dispatcher->dispatch($eventMissionDesiredDeliveryUpdatedAfterValidationEvent::NAME);
  2151.                         $sendEmailDeliveryDateChange false;
  2152.                     } elseif (isset($missionsInCampaign[$mission->getData()->getId()]) && $mission->getData()->getDesiredDelivery() != $missionsInCampaign[$mission->getData()->getId()] && ($mission->getData()->getState() == 'provisional' || $mission->getData()->getState() == 'waiting')) {
  2153.                         // $campaign->setState('provisional');
  2154.                         $event = new MissionDesiredDeliveryUpdatedBeforeValidationEvent($mission->getData());
  2155.                         $dispatcher->dispatch($eventMissionDesiredDeliveryUpdatedBeforeValidationEvent::NAME);
  2156.                         $sendEmailDeliveryDateChange false;
  2157.                     }
  2158.                 }
  2159.                 //--------------------------add New Subcontractor ------------------------------------------
  2160.                 $jobsubForThisMission $jobSub[$key];
  2161.                 $jobsubForThisMissionInArray explode(";"$jobsubForThisMission);
  2162.                 $newSubcontractorList = [];
  2163.                
  2164.                 foreach ($jobsubForThisMissionInArray as $newSubontractor) {
  2165.                     $newSubontractor explode("-:"$newSubontractor);
  2166.                     if (sizeof($newSubontractor) == or sizeof($newSubontractor) == or sizeof($newSubontractor) == 4) {
  2167.                         $newSubcontractorList = [
  2168.                             ...$newSubcontractorList,
  2169.                             [
  2170.                                 "job_id" => $newSubontractor[0],
  2171.                                 "email_user" => $newSubontractor[1],
  2172.                                 "income_suggested" => isset($newSubontractor[2]) ? $newSubontractor[2]: null,
  2173.                                 "priceForProduct" => isset($newSubontractor[3]) ? $newSubontractor[3]: null,
  2174.                             ]
  2175.                         ];
  2176.                     }
  2177.                 }
  2178.                
  2179.                 $alreadySent = [];
  2180.                 foreach ($newSubcontractorList as $key => $newSuboContractor) {
  2181.                     echo "début insertion sous traitant<br>";
  2182.                     $errorAddSub false;
  2183.                     $newUser $userRepository->findOneBy(['email' => $newSuboContractor['email_user']]);
  2184.                     $newjob $jobRepository->findOneBy(['id' => $newSuboContractor['job_id']]);
  2185.                     if ($newUser == null) {
  2186.                         $errorAddSub true;
  2187.                         $error true;
  2188.                         $this->addFlash(
  2189.                             type'error',
  2190.                             message"Veuillez vérifier le contact opérationnel suivant " $newSuboContractor['email_user']
  2191.                         );
  2192.                         return $this->redirectToRoute('handle_mission_campaign', ["id" => $campaign->getId()]);
  2193.                     }
  2194.                     $productMission $mission->getData()->getProduct();
  2195.                     foreach ($mission->getData()->getParticipants() as $participant) {
  2196.                         $fullName $newUser->getFullName();
  2197.                         if ($participant->getUser() == $newUser && $participant->getJob() == $newjob) {
  2198.                           
  2199.                             $this->addFlash(
  2200.                                 type'error',
  2201.                                 message"Le sous-traitant $fullName vous essayé d'ajouté est deja sur cette mission"
  2202.                             );
  2203.                             $errorAddSub true;
  2204.                             $error true;
  2205.                         }
  2206.                         $services $entityManager->getRepository(Service::class)->findBy(['user' => $newUser]);
  2207.                         $linkService false;
  2208.                         $matriceLink = [];
  2209.                         foreach ($services as $service) {
  2210.                             if ($service->getProduct()->getId() === $productMission->getId()) {
  2211.                                 $linkService true;
  2212.                             }
  2213.                         }
  2214.                         
  2215.                         
  2216.                         if (!$linkService and !in_array('ROLE_SUBCONTRACTOR'$this->getUser()->getRoles())) {
  2217.                             $serviceParticipant->setProduct($productMission)
  2218.                                            //->setPrice($productMission->getPrice())
  2219.                                            ->setUser($newUser);
  2220.                             if ($mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT and $newSuboContractor['priceForProduct'] != null) {
  2221.                               
  2222.                                  // mail("anthonyssdfsffffff@yopmail.com", "mission", $newSuboContractor['priceForProduct']);
  2223.                                 $serviceParticipant->setPrice($newSuboContractor['priceForProduct'])->setResale($productMission->getPrice());
  2224.                                 $entityManager->persist($serviceParticipant);
  2225.                             }
  2226.                         }else{
  2227.                             
  2228.                             if( in_array('ROLE_SUBCONTRACTOR'$this->getUser()->getRoles()) && 
  2229.                                 $mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT && 
  2230.                                 !$linkService &&  !in_array($mission->getData()->getId(),$ids)
  2231.                             ){
  2232.                               
  2233.                                 $dailyRate floatval($newUser->getDailyRate());
  2234.                                 $resaleRate floatval($newUser->getResaleRate());
  2235.                                 $missionPrice =  floatval($mission->getData()->getPrice()); 
  2236.                                
  2237.                                 $time =   $missionPrice 420 $dailyRate 
  2238.                                 $resalePrice $time*$resaleRate/420;
  2239.             
  2240.                                 $serviceParticipant->setProduct($productMission)
  2241.                                                     ->setUser($newUser)
  2242.                                                     ->setPrice($missionPrice)
  2243.                                                     ->setResale($resalePrice)
  2244.                                                     ;
  2245.                                 $ids = [...$ids,$mission->getData()->getId()];
  2246.                                 $mission->getData()->setPrice($resalePrice);
  2247.                                 $productMission->setPrice($resalePrice);
  2248.                                 $entityManager->persist($serviceParticipant);
  2249.                             }
  2250.                             elseif(!$linkService and $mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT and $newSuboContractor['priceForProduct'] == null) {
  2251.     
  2252.                                 $errorAddSub true;
  2253.                                 $error true;
  2254.                                 $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.");
  2255.                             }
  2256.                         }
  2257.                     }
  2258.                     if (!$errorAddSub) {
  2259.                        
  2260.                         $missionParticipant = new MissionParticipant();
  2261.                         if (empty($missionId)) {
  2262.                             $missionParticipant->setMission($mission->getData());
  2263.                         } else {
  2264.                             $missionParticipant->setMission($missionId);
  2265.                         }
  2266.                         $missionParticipant->setUser($newUser);
  2267.                         //$missionParticipant->setIncomeSuggested($newSuboContractor['income_suggested']);
  2268.                         $missionParticipant->setJob($newjob);
  2269.                         $missionParticipant->setRole(Role::ROLE_SUBCONTRACTOR);
  2270.                         if (!empty($newSuboContractor['income_suggested'])) {
  2271.                             $missionParticipant->setIncomeSuggested($newSuboContractor['income_suggested']);
  2272.                         }
  2273.                         $mission->getData()->addParticipant($missionParticipant);
  2274.                         $entityManager->persist($missionParticipant);
  2275.                         $entityManager->flush();
  2276.                         if (!in_array($missionParticipant->getUser(), $alreadySent) && !$newCampaign) {
  2277.                             $event = new SubContractorMissionAddedEvent($missionParticipant->getUser(), $mission->getData());
  2278.                             $dispatcher->dispatch($eventSubContractorMissionAddedEvent::NAME);
  2279.                             $alreadySent[] = $missionParticipant->getUser();
  2280.                         }
  2281.                     }
  2282.                 }
  2283.                 $searchParticipant $missionParticipantRepository->findOneBy(['mission' => $missionId'role' => 'ROLE_SUBCONTRACTOR']);
  2284.                 if (empty($searchParticipant)) {
  2285.                     $event = new MissionWithoutSubContractorCheckedEvent($mission->getData());
  2286.                     $dispatcher->dispatch($eventMissionWithoutSubContractorCheckedEvent::NAME);
  2287.                 }
  2288.                 if (!empty($mission->get('newWorkflow')->getData())) {
  2289.                     $newWorkflow = clone $mission->get('newWorkflow')->getData();
  2290.                     $newWorkflow->setTemplate(false);
  2291.                     $mission->getData()->setWorkflow($newWorkflow);
  2292.                     $entityManager->persist($newWorkflow);
  2293.                 }
  2294.                 
  2295.             }
  2296.             $entityManager->flush();
  2297.             
  2298.             if ($error) {
  2299.                 foreach ($allMissionNewId as $id) {
  2300.                     if (!in_array($id$oldMissionId) or empty($oldMissionId)) {
  2301.                         $missionToRemove $entityManager->getRepository(Mission::class)->find($id);
  2302.                         $missionToRemove->setWorkflow(null);
  2303.                         $entityManager->persist($missionToRemove);
  2304.                         $entityManager->flush();
  2305.                         $entityManager->remove($missionToRemove);
  2306.                         $entityManager->flush();
  2307.                     }
  2308.                 }
  2309.                 return $this->redirectToRoute('handle_mission_campaign', ["id" => $campaign->getId()]);
  2310.             }
  2311.             
  2312.             foreach ($campaign->getMissions() as $mission) {
  2313.                 //$mission->setState('provisional');
  2314.                 if ($newCampaign) {
  2315.                     if (
  2316.                         $state === 'waiting' &&
  2317.                         ($mission->getProduct()->getType() === ProductType::AU_FORFAIT) || ($mission->getProduct()->getType() === ProductType::AU_TEMPS_PASSE)
  2318.                     ) {
  2319.                         $mission->setState('provisional');
  2320.                     } else {
  2321.                         $mission->setState($state);
  2322.                     }
  2323.                     if ($mission->getState() === 'waiting') {
  2324.                         $mission->setStateProvider('A évaluer');
  2325.                     } else {
  2326.                         $mission->setStateProvider('A activer');
  2327.                     }
  2328.                 }
  2329.             }
  2330.             if ($campaign->getCreditHistory() == null) {
  2331.                 $creditHistory $creditHistoryRepository->findOneBy(['company' => $campaign->getCompany(), "typePack" => 4]);
  2332.                 $campaign->setCreditHistory($creditHistory);
  2333.             }
  2334.             if ($newCampaign) {
  2335.                 $campaign->setState($state);
  2336.                 //if(!empty($campaign->getMissions())){
  2337.                     foreach($campaign->getMissions() as $mission)  {
  2338.                         $this->missionService->addHistorique(mission$missionuser:$campaignInitiatoraction'campaign_initiate_by_admin');
  2339.                         break; 
  2340.                     }
  2341.                 //}
  2342.                 
  2343.             }
  2344.     
  2345.             if( ($otherInformationThanDateChange || $newMissionInCampaign) && ( in_array('ROLE_SUBCONTRACTOR'$this->getUser()->getRoles()))&& !$this->campaignService->isAllProductHaveA_EvaluerMission($campaign) ){
  2346.                 $this->campaignService->resendCampaignForValidation($campaign,$this->getUser());
  2347.             }
  2348.             $campaign->setDisabled(null);
  2349.             $entityManager->persist($campaign);
  2350.             $entityManager->flush();
  2351.  
  2352.             if (!$newCampaign) {
  2353.                 if ($otherInformationThanDateChange &&  $nbrAU_FORFAIT && $nbrAU_FORFAIT == $nbrMission && $this->campaignService->areAllRequiredSubcontractorsPresent(campaign$campaign)) {
  2354.                     $campaign->setReSendToClient(true);
  2355.                     
  2356.                     $entityManager->persist($campaign);
  2357.                     $entityManager->flush();
  2358.                 }
  2359.                 if ($formEditCampaign->getClickedButton() && 'editGlobalMssion' === $formEditCampaign->getClickedButton()->getName()) {
  2360.               
  2361.                     // Btn édit on envoie juste un email.
  2362.                     $event = new CampaignModifiedEvent($campaign);
  2363.                     $dispatcher->dispatch($eventCampaignModifiedEvent::NAME);
  2364.                 } else if ($formEditCampaign->getClickedButton() && 'saveGlobalMission' === $formEditCampaign->getClickedButton()->getName()) {
  2365.        
  2366.                     $nbMission = [];
  2367.                     $nbInitialNotEmpty = [];
  2368.                     foreach ($campaign->getMissions() as $mission) {
  2369.                         $nbMission[] = $mission;
  2370.                         $initialTime $mission->getInitialTime();
  2371.                         if (!empty($initialTime)) {
  2372.                             $nbInitialNotEmpty[] = $initialTime;
  2373.                         }
  2374.                     }
  2375.                     if (count($nbMission) === count($nbInitialNotEmpty)) {
  2376.                         return $this->redirectToRoute('campaign_transition', ['id' => $campaign->getId(), 'transition' => 'unpause']);
  2377.                     }
  2378.                 }
  2379.             }
  2380.             //recurrency
  2381.             if($stateRecurred == 'recurred'){
  2382.                 $campaign->setState('recurred');
  2383.                 $entityManager->flush();
  2384.                 $stateActiveFrequency $oldCampaignStateActiveFrequency == false && $campaign->getActiveFrequency() == true true false
  2385.                 $isActiveFrequency =  $campaign->getActiveFrequency()== true true false
  2386.                 $recurringState = !is_null($campaign->getRecurringState()) && $campaign->getRecurringState() == "waiting_validation" || (
  2387.                     in_array('ROLE_ADMIN',$this->getUser()->getRoles()) && $campaignRecurrentService->isAnElementFrequencyChange($campaign->getFrequency() ,$oldFrequency ) ) ?  'waiting_validation':  'in_progress';
  2388.                 $campaign->setRecurringState(recurringState$recurringState );
  2389.                 $campaignRecurrentService->toogleRecurrent($campaign,$isActiveFrequency$stateActiveFrequency);
  2390.                 
  2391.               
  2392.                 $now = new \DateTime();
  2393.                 $startDate $campaign->getFrequency()->getStartDate();
  2394.                 if($now->format('y/d/m G:i') >=  $startDate->format('y/d/m G:i') &&  $campaign->getRecurringState()!='waiting_validation'){
  2395.                                     
  2396.                     $campaign->getFrequency()->setStartDate(new \DateTime());
  2397.                     $campaignRecurrentService->updateLaunchRecurringAt($campaign);
  2398.                     $newCampaign =  $campaignRecurrentService->clone($campaign);
  2399.                     $entityManager->persist($newCampaign);
  2400.                     $campaign $newCampaign ;
  2401.                 }elseif($campaign->getRecurringState()!='waiting_validation'){
  2402.                     $campaignRecurrentService->updateLaunchRecurringAt(campaign:$campaign,dateToLaunch:$newStartDate);
  2403.                 }
  2404.                 $eventRecurrent = new CampaignRecurrentEvent($campaignfalsetrue);
  2405.                 $dispatcher->dispatch($eventRecurrentCampaignRecurrentEvent::NAME);
  2406.                 $this->addFlash(
  2407.                     type'success',
  2408.                     message'Votre commande réccurente a été modifier avec succès'
  2409.                 );
  2410.                 
  2411.                 return $this->redirectToRoute('recurring_service');
  2412.             }
  2413.             else{
  2414.                 if ($campaign->getActiveFrequency()) {
  2415.                         $now = new \DateTime();
  2416.                         $startDate $campaign->getFrequency()->getStartDate();
  2417.                         $hours $now->format('G');
  2418.                         $minutes $now->format('i');
  2419.                         $second $now->format('s');
  2420.                         $campaignTypeInitiation CampaignTypeInitiation::CAMPAIGN_FROM_RECURRENT->value;
  2421.                         $newStartDate $startDate->setTime($hours$minutes$second);
  2422.                         $campaign->getFrequency()->setStartDate($newStartDate);
  2423.                         $campaign->setIsRecurrent(true);
  2424.                         $recurringState = !is_null($campaign->getRecurringState()) && $campaign->getRecurringState() == "waiting_validation" ?  $campaign->getRecurringState() :  'in_progress';
  2425.                         $campaign->setRecurringState($recurringState );
  2426.                         $campaign->setState('recurred');
  2427.                         $campaign->setTypeInitiation($campaignTypeInitiation);
  2428.                         $eventRecurrent = new CampaignRecurrentEvent($campaigntrue);
  2429.                         $dispatcher->dispatch($eventRecurrentCampaignRecurrentEvent::NAME);
  2430.                         if($now->format('y/d/m G:i') >=  $startDate->format('y/d/m G:i') &&  $campaign->getRecurringState()!='waiting_validation'){
  2431.                             $this->updateCampaignFrequencyDateUntilNow($campaignRecurrentService,$campaign,$now,$entityManager,$dispatcher);
  2432.                         }else{
  2433.                             $campaignRecurrentService->updateLaunchRecurringAt(campaign:$campaign,dateToLaunch:$newStartDate);
  2434.                         }
  2435.                         $this->addFlash(
  2436.                             type'success',
  2437.                             message'Votre commande réccurente a été crée avec succès'
  2438.                         );
  2439.                         
  2440.                         return $this->redirectToRoute('recurring_service');
  2441.                 }
  2442.                 else{
  2443.                     
  2444.                     if ($newCampaign) {
  2445.                         $event = new CampaignCreatedEvent($campaign,'CREER_PAR_ADMIN',$contactProjects,true);
  2446.                         $dispatcher->dispatch($eventCampaignCreatedEvent::NAME);
  2447.                         $this->addFlash('success''Votre commande a été enregistrée avec succès');
  2448.                     }else{
  2449.                         $this->addFlash('success''Modification enregistrée');
  2450.                     }
  2451.                     if (count($campaign->getMissions()) == and $campaign->getMissions()->first()->getProduct()->getName()=="Espace de discussion") {
  2452.                         $campaign->setState('provisional');
  2453.                         $entityManager->persist($campaign);
  2454.                         $entityManager->flush();
  2455.                     }
  2456.                 }
  2457.             }
  2458.         
  2459.             if (!is_null($oldPack) and $oldPack != $campaign->getCreditHistory() and isset($mission) and !is_null($mission)) {
  2460.                 $this->missionService->addHistorique(mission$missionuser$this->getUser(), action'credit_campagne_modified');
  2461.                 
  2462.                 $this->contractService->balanceAllocation($campaign$oldPack);
  2463.                 $entityManager $this->getDoctrine()->getManager();
  2464.                 $entityManager->persist($campaign);
  2465.                 $entityManager->flush();
  2466.             }
  2467.             if (count($campaign->getMissions()) == and $campaign->getMissions()->first()->getProduct()->getName()=="Espace de discussion") {
  2468.                 $campaign->setState('provisional');
  2469.                 $entityManager->persist($campaign);
  2470.                 $entityManager->flush();
  2471.             }
  2472.             $hitoryExist null;
  2473.             foreach ($campaign->getMissions() as $m) {
  2474.                 if (!$m->getHistoriques()->isEmpty()) {
  2475.                      $hitoryExist $m->getHistoriques();
  2476.                      break;
  2477.                 }
  2478.             }
  2479.             ;
  2480.           
  2481.             if ($hitoryExist !== null) {
  2482.                 foreach ($campaign->getMissions() as $m) {
  2483.                    if ($m->getHistoriques()->isEmpty()) {
  2484.                         foreach ($hitoryExist as $h) {
  2485.                             $historyNew = clone $h;
  2486.                             $m->addHistorique($historyNew);
  2487.                             $entityManager->persist($historyNew);
  2488.                         }
  2489.                         $entityManager->persist($m);
  2490.                         $entityManager->flush();
  2491.                     }
  2492.                 }
  2493.             }
  2494.             return $this->redirectToRoute('mission_index');
  2495.         }
  2496.         $formEditSubcontractor $this->createForm(EditSubcontractorParticipantType::class);
  2497.         setcookie('missionIDs','',0,"/");
  2498.         return $this->renderForm('campaign/edit_mission.html.twig', [
  2499.             'campaign' => $campaign,
  2500.             'form' => $formEditCampaign,
  2501.             'formEditSubcontractor' => $formEditSubcontractor,
  2502.             'user' => $user
  2503.         ]);
  2504.     }
  2505.     private function updateCampaignFrequencyDateUntilNow($campaignRecurrentService,$originalCampaign$now,$entityManager,$dispatcher){
  2506.         $campaignRecurrentService->updateLaunchRecurringAt($originalCampaign);
  2507.         $campaignFrequency $originalCampaign->getFrequency()->getLaunchRecurrenceAt();
  2508.         $newCampaign =  $campaignRecurrentService->clone($originalCampaign);
  2509.         $campaign $newCampaign;
  2510.         $entityManager->persist($campaign);
  2511.         $entityManager->flush();
  2512.         $event = new CampaignCreatedEvent($campaign);
  2513.         $dispatcher->dispatch($eventCampaignCreatedEvent::NAME);
  2514.         foreach($newCampaign->getMissions() as $mission ){
  2515.             $this->missionService->addHistorique(mission$missionuser:$newCampaign->getOrderedBy() , action'campaign_initiate_by_recurrent');  
  2516.         }
  2517.         if($campaignFrequency<$now){
  2518.             $this->updateCampaignFrequencyDateUntilNow($campaignRecurrentService,$originalCampaign$now,$entityManager,$dispatcher);
  2519.         }
  2520.         return;
  2521.     }
  2522.     #[Route('/campagne/{id}/demande-evaluation'name'campaign_demande_evaluation')]
  2523.     public function evaluation(Request $requestCampaign $campaignMissionService $missionServiceEventDispatcherInterface $dispatcher): Response
  2524.     {
  2525.         $event = new CampaignEvaluationEvent($campaign);
  2526.         $dispatcher->dispatch($eventCampaignEvaluationEvent::NAME);
  2527.         foreach ($campaign->getMissions() as $mission) {
  2528.             $missionService->addHistorique(mission$missionuser$this->getUser(), action"evaluation_request");
  2529.         }
  2530.         $this->addFlash(
  2531.             type'success',
  2532.             message'La demande d\'évaluation a bien été envoyée'
  2533.         );
  2534.         return $this->redirect($request->headers->get('referer'));
  2535.     }
  2536.     #[Route('/campagne/{id}/recapitulatif/{showStep}'name'campaign_recapitulatif'defaults: ['showStep'=>""])]
  2537.     public function recapPanier(string $showStepPriceService $priceService,MissionParticipantService $missionParticipantServiceNumberFormatService $numberFormatServiceCampaignService $campaignService,  ConsumptionBalanceForCompanyService $consumptionBalanceForCompanyService,  Campaign $campaign): Response
  2538.     {
  2539.         $creditHistory $campaign->getCreditHistory();
  2540.         $typePack =  $creditHistory->getTypePack();
  2541.         $text = match ((int) $typePack) {
  2542.             => 'Votre solde actuel',
  2543.             => 'Solde sur ' $numberFormatService->format($creditHistory->getOrderPrice()) . ' € HT/mois',
  2544.             => 'Solde sur ' $numberFormatService->format($creditHistory->getOrderPrice()) . ' € HT/an',
  2545.             => 'Budget HT consommé depuis le 1er du mois',
  2546.             => '',
  2547.             default => '',
  2548.         };
  2549.         $currency = match ((int) $campaign->getCreditHistory()->getTypePack()) {
  2550.             => '€',
  2551.             default => '€',
  2552.         };
  2553.         $balance $campaign->getCreditHistory()->getTypePack() == $consumptionBalanceForCompanyService->consumptionOfTheMonth(company$campaign->getCompany()) : $campaign->getCreditHistory()->getCurrentBalance();
  2554.         return $this->renderForm('campaign/recapitulatif.html.twig', [
  2555.             'campaign' => $campaign,
  2556.             'participants_subcontractor' => $missionParticipantService->getSubcontractorWithMissing($campaign), 
  2557.             'text' => $text,
  2558.             'price_service' => $priceService,
  2559.             'currency' => $currency,
  2560.             'balance' =>  $balance,
  2561.             'show_step'=> $showStep == "step" true false,
  2562.             'step'=>4
  2563.         ]);
  2564.     }
  2565.     #[Route('/campagne/{id}/accepter/{currentRouteName?}/{firstClickedMissionId?}'name'campaign_accept_all'defaults: ['currentRouteName' => null'firstClickedMissionId' => null])]
  2566.     public function campaignAccept(CampaignService $campaignServiceMissionService $missionServiceCampaign $campaignEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcherClientSoldService $clientSoldService$currentRouteName null$firstClickedMissionId null): Response
  2567.     {
  2568.         $campaign->setState($campaignService->getStateCampaign(campaign$campaign));
  2569.         $campaign->setReSendToClient(false);
  2570.         $campaign->setClientStatus("");
  2571.         $entityManager->flush();
  2572.         $campaignService->setAllMissionAsNotEvaluate(campaign$campaign);
  2573.         $event = new CampaignValidatedEvent($campaign);
  2574.         $dispatcher->dispatch($eventCampaignValidatedEvent::NAME);
  2575.         foreach ($campaign->getMissions() as $mission) {
  2576.             $missionService->addHistorique(mission$missionuser$this->getUser(), action"accepter");
  2577.         }
  2578.         $this->addFlash(
  2579.             type'success',
  2580.             message"Le panier a bien été validé avec succès"
  2581.         );
  2582.         if (isset($currentRouteName) && $currentRouteName == 'mission_edit' && isset($firstClickedMissionId)) {
  2583.             return $this->redirectToRoute('campaign_transition', [
  2584.                 'id' => $campaign->getId(),
  2585.                 "transition" => "activated",
  2586.                 "currentRouteName" => $currentRouteName,
  2587.                 "firstClickedMissionId" => $firstClickedMissionId
  2588.             ]);
  2589.         } else {
  2590.             return $this->redirectToRoute('campaign_transition', ['id' => $campaign->getId(), "transition" => "activated"]);
  2591.         }
  2592.     }
  2593.     #[Route('/campagne/{id}/resoumission'name'campaign_resoumission')]
  2594.     public function campaignResoumission(Request $requestMissionService $missionService,  Campaign $campaignEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher): Response
  2595.     {
  2596.         
  2597.         $event = new CampaignWaitingEvent($campaignfalse$this->getUser());
  2598.         $dispatcher->dispatch($eventCampaignWaitingEvent::NAME);
  2599.         foreach ($campaign->getMissions() as $mission) {
  2600.             $missionService->addHistorique(mission$missionuser$this->getUser(), action"resoumission");
  2601.         }
  2602.         $campaign->setClientStatus('waiting_for_confirmation');
  2603.         $campaign->setState('waiting_validation');
  2604.         $entityManager->flush();
  2605.         $message "Le panier est bien soumis avec succès";
  2606.         if ($this->isGranted("ROLE_SUBCONTRACTOR")) {
  2607.             $listMissionNotEvaluate $this->campaignService->getMissionListNotEvaluate(user$this->getUser(), campaign$mission->getCampaign());
  2608.             $message "";
  2609.             if ($this->missionService->isMyMission(mission$mission) && $mission->getCampaign()->getState() != "in_progress" && $mission->isEvaluate()) {
  2610.                 $message "Vous avez évalué la mission. Nous attendons maintenant la validation du client {$mission->getCampaign()->getCompany()->getName()}";
  2611.             } elseif ($listMissionNotEvaluate && $this->campaignService->evaluateAllHerMission(campaign$mission->getCampaign(), user$this->getUser()) && $this->missionService->isMyMission(mission$mission)) {
  2612.                 $intervenants "";
  2613.                 foreach ($mission->getCampaign()->getMissions() as $mission) {
  2614.                     foreach ($mission->getParticipants() as $participant) {
  2615.                         if (!$participant->isEvaluate()) {
  2616.                             $intervenants .= "{$participant->getUser()->getFullName()} , ";
  2617.                         }
  2618.                     }
  2619.                 }
  2620.                 $intervenants rtrim($intervenants",");
  2621.                 $message "Vous avez évalué la mission. Nous attendons maintenant le retour de ces partenaires pour resoumettre la proposition au client ( { $intervenants})";
  2622.             }
  2623.             $this->addFlash(
  2624.                 type'success',
  2625.                 message$message
  2626.             );
  2627.         } else {
  2628.             $this->addFlash(
  2629.                 type'success',
  2630.                 message'La campagne à bien été resoumise'
  2631.             );
  2632.         }
  2633.         return $this->redirect($request->headers->get('referer'));
  2634.     }
  2635.    
  2636.     #[Route('/campagne/activated/{id}'name'order_reactivated')]
  2637.     public function orderReactivated(Request $request,OrderService $orderServiceCampaign $campaignEntityManagerInterface $entityManager,CampaignService $campaignServiceEventDispatcherInterface $dispatcher): Response
  2638.     {
  2639.         
  2640.         $orderService->reActive($campaign);
  2641.         $this->addFlash(
  2642.             type'success',
  2643.             message'La campagne a bien été réactiver'
  2644.         );
  2645.         return $this->redirect($request->headers->get('referer'));
  2646.     }
  2647.     #[Route('/campagne/{id}/relancer'name'campaign_relancer')]
  2648.     public function campaignRelancer(Request $requestCampaign $campaignEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher): Response
  2649.     {
  2650.         $event = new CampaignResendEvent($campaign);
  2651.         $dispatcher->dispatch($eventCampaignResendEvent::NAME);
  2652.         $this->addFlash(
  2653.             type'success',
  2654.             message'La campagne a bien été relancer'
  2655.         );
  2656.         return $this->redirect($request->headers->get('referer'));
  2657.     }
  2658.     public function onMissionWithoutWorkflow(MissionWithoutWorkflowEvent $event$userRepository$mailer)
  2659.     {
  2660.         $mission $event->getMission();
  2661.         if (!$mission instanceof Mission) {
  2662.             return;
  2663.         }
  2664.         $admins $this->dynamicHostService->getMailAdmin();
  2665.         foreach ($admins as $admin) {
  2666.             $notification = (new NotificationEmail())
  2667.                 ->to(new Address($admin->value))
  2668.                 ->subject('Une mission a été créée sans workflow')
  2669.                 ->content('
  2670.                 <p>Bonjour,</p>
  2671.                 <p>La mission ' $mission->getReference() . ' contient un produit "' $mission->getProduct()->getName() . '" qui n\'a pas de Workflow associé.</p>
  2672.                 <p>Merci d\'en créer un pour ce produit et d\'aller le relier à la mission.</p>
  2673.             ')
  2674.                 ->action('Modifier la mission'$this->generateUrl('handle_mission_campaign', ['id' => $mission->getCampaign()->getId()], UrlGeneratorInterface::ABSOLUTE_URL))
  2675.                 ->markAsPublic();
  2676.             $mailer->send($notification);
  2677.         }
  2678.     }
  2679.     #[Route('/campagne/cart/{id}/{type}'name'campaign_pdf_cart'defaults: ['type' => 'pdf'])]
  2680.     public function  getPdfCart(Campaign $campaignstring $typePriceService $priceService)
  2681.     {
  2682.         $update_ref true;
  2683.         foreach ($campaign->getMissionsWithoutEspaceDeDiscussion() as $mission) {
  2684.             $mission->additionnal $this->getAdditionalInformation($mission->getProduct()->getFrontId(), $update_ref);
  2685.             $update_ref false;
  2686.         }
  2687.         $twigRender = [
  2688.             'link' => "campaign/pdf_cart/index.html.twig",
  2689.             'param' => [
  2690.                 'campaign' => $campaign,
  2691.                 'price_service' => $priceService,
  2692.                 'currency' => "€",
  2693.                 'balance' =>  "0",
  2694.             ]
  2695.         ];
  2696.         if ($type == 'pdf') {
  2697.             $pdfOptions = new Options();
  2698.             $pdfOptions->set('defaultFont''Arial');
  2699.             $pdfOptions->set('enable_remote'true);
  2700.             $pdfOptions->setIsRemoteEnabled(true);
  2701.             $dompdf = new Dompdf($pdfOptions);
  2702.             $context stream_context_create([
  2703.                 'ssl' => [
  2704.                     'verify_peer' => FALSE,
  2705.                     'verify_peer_name' => FALSE,
  2706.                     'allow_self_signed' => TRUE
  2707.                 ]
  2708.             ]);
  2709.             $dompdf->setHttpContext($context);
  2710.             $html $this->renderView($twigRender['link'], $twigRender['param']);
  2711.             $dompdf->loadHtml($html);
  2712.             $dompdf->setPaper('A4''portrait');
  2713.             $dompdf->render();
  2714.             $fichier "commande_myflow_" date('dmY');
  2715.             $dompdf->stream($fichier, [
  2716.                 'attachement' => true
  2717.             ]);
  2718.             return new JsonResponse(['status' => "Ok"], Response::HTTP_CREATED, ["Content-type" => "application/pdf"]);
  2719.         } else {
  2720.             return $this->render($twigRender['link'], $twigRender['param']);
  2721.         }
  2722.     }
  2723.     private function getAdditionalInformation(string $productFrontIdbool $updateRef false)
  2724.     {
  2725.         $param $updateRef "$productFrontId&update_id=true" $productFrontId;
  2726.         $frontWebSiteUrl $this->getParameter('front_website_url');
  2727.         $client = new Client();
  2728.         $response $client->request('GET'"$frontWebSiteUrl/wp-json/my-flow/v1/product_info?product_id=$param", []);
  2729.         $responseDecode json_decode($response->getBody()->getContents());
  2730.         return [
  2731.             "ref" => $responseDecode->ref,
  2732.             "attachement" => gettype($responseDecode->attachement) == "array" && sizeof($responseDecode->attachement) > $responseDecode->attachement[0] : "",
  2733.             "link" =>  $responseDecode->link,
  2734.         ];
  2735.     }
  2736.     private function updateUserDataDateCertificate($userData){
  2737.         $dateAddCertificate = new \DateTime();
  2738.         //if(is_null($userData->getVigilanceCertificate())){
  2739.             $userData->setDateUpdateCertificate($dateAddCertificate);
  2740.         //}
  2741.    }
  2742.    #[Route('/campagne/modification/price'name'campaign_modif_price')]
  2743.     public function  modificationPrestation(Request $request,PriceService $priceService,EntityManagerInterface $entityManager,ClientSoldService $clientSoldService)
  2744.     {   
  2745.         $neddToReajustSold false;
  2746.         $allData $request->request->all();
  2747.         foreach ($allData as $missionId => $value) {
  2748.             $mission $entityManager->getRepository(Mission::class)->find($missionId);
  2749.             $campaign $mission->getCampaign();
  2750.             $firstIdMission $campaign->getMissions()->first()->getId();
  2751.             $creditHistory $campaign->getCreditHistory();
  2752.             $dateActidatedAt $campaign->getActivatedAt();
  2753.             //price mission after update price prestation
  2754.             $priceMissionNotTouch $priceService->priceAndTimeMissionBasedOnPriceSale($mission)['price'];
  2755.             if ($priceMissionNotTouch != $value) {
  2756.                 $neddToReajustSold true;
  2757.                 //update priceSales mission if price original <> de new price
  2758.                 //first update price sales mission
  2759.                 $mission->setPriceSale($value);
  2760.                 $entityManager->persist($mission);
  2761.                 $entityManager->flush();
  2762.                 //second need to delete all balance transaction
  2763.                 $balanceTransaction $entityManager->getRepository(BalanceTransactions::class)->soldeByMission($creditHistory,$mission);
  2764.                 if (is_null($balanceTransaction)) {
  2765.                     $oldTotalConsuption $creditHistory->getTotalConsumption();
  2766.                     $oldCurrentBalance $creditHistory->getCurrentBalance();
  2767.                     $creditHistory->setTotalConsumption($oldTotalConsuption $value );
  2768.                     $creditHistory->setCurrentBalance($oldCurrentBalance $value);
  2769.                     //remove balance transaction
  2770.                 }
  2771.                 //third decrease all value in balance transactions.
  2772.                 $clientSoldService->decreaseCurrentBalanceByMissionCost($mission,$dateActidatedAt);
  2773.             }
  2774.         }
  2775.         $entityManager->flush();
  2776.         $this->addFlash('success','Prix de la prestation changé avec succées');
  2777.         return $this->redirectToRoute('mission_edit', ['id' => $firstIdMission], Response::HTTP_SEE_OTHER);
  2778.     }
  2779.     //  private function createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign,$now,$entityManager){
  2780.     //     $campaignRecurrentService->updateLaunchRecurringAt($originalCampaign);
  2781.     //     $campaignFrequency = $originalCampaign->getFrequency()->getLaunchRecurrenceAt();
  2782.     //     $newCampaign =  $campaignRecurrentService->clone($originalCampaign);
  2783.     //     $campaign = $newCampaign;
  2784.     //     $entityManager->persist($campaign);
  2785.     //     $entityManager->flush();
  2786.     //     if($campaignFrequency<$now){
  2787.     //         $this->createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign, $now,$entityManager);
  2788.     //     }
  2789.     //     return;
  2790.     // }
  2791.     private function checkIfCampaignContainsProductEvaluate(Campaign $campaign){
  2792.         foreach($campaign->getMissions() as $mission){
  2793.             if($mission->getProduct()->getType()==ProductType::A_EVALUER){
  2794.                 return true;
  2795.             }
  2796.         }
  2797.         return false;
  2798.     }
  2799.     #[Route('/contact-project/html/add'name'campaing_contact_project_html_add'methods: ['GET''POST'])]
  2800.     public function modalContactProjectCampaing(Request $request): Response
  2801.     {
  2802.          $formAddMissionContactProject $this->createForm(AddMissionContactProjectType::class);
  2803.         return  $this->render('campaign/_contact_project.html.twig', [
  2804.             'formAddMissionContactProject' => $formAddMissionContactProject->createView()
  2805.         ]);
  2806.     }
  2807.      #[Route('/contact-project/take-info/{email}'name'campaing_contact_project_take_info'methods: ['GET''POST'])]
  2808.     public function contactTakeInfos(Request $request,EntityManagerInterface $entityManager,$email null): Response
  2809.     {
  2810.         $user null;
  2811.         if ($email !== null and !empty($email) ) {
  2812.             $user $entityManager->getRepository(User::class)->findOneByEmail($email);
  2813.         }
  2814.         return  $this->render('campaign/_contact_project_list.html.twig', [
  2815.             'user' => $user
  2816.         ]);
  2817.     }
  2818.     private function getProductList(?User $user=null){
  2819.         if($user ==null){
  2820.             return [];
  2821.         }
  2822.         $productList = []; 
  2823.         $services $user->getServices(); 
  2824.         foreach ($services as  $service) {
  2825.             $productList[$service->getProduct()->getId()] = $service->getPrice();
  2826.         }
  2827.         return  $productList
  2828.     }
  2829.     private function getPrice(Product $product$user){
  2830.         
  2831.         $productPrice $product->getPrice();
  2832.   
  2833.         if($user != null && in_array('ROLE_SUBCONTRACTOR'$user->getRoles())){
  2834.                 $listService $this->getProductList($user);
  2835.                 $productPrice $product->getId()!=null && array_key_exists($product->getId(),$listService) && $listService[$product->getId()]!=null floatval($listService[$product->getId()]) : 0;
  2836.         }
  2837.         return ($product->getType()->value != and  $product->getType()->value !=  3) ? $productPrice ;
  2838.     }
  2839. }