src/Controller/CampaignController.php line 737

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