src/Controller/CampaignController.php line 700

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