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