src/Controller/MissionController.php line 151

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Campaign;
  4. use App\Entity\FileMessage;
  5. use App\Entity\FileMission;
  6. use App\Entity\Historique;
  7. use App\Entity\InfoMission;
  8. use App\Entity\Message;
  9. use App\Entity\Mission;
  10. use App\Entity\MissionParticipant;
  11. use App\Enum\BillingMethod;
  12. use App\Enum\ProductType;
  13. use App\Enum\Role;
  14. use App\Entity\UserData;
  15. use App\Event\Mission\MissionClosedEvent;
  16. use App\Event\Admin\MissionInitialTimeAfterValidationUpdatedEvent;
  17. use App\Event\Admin\MissionNotificationActivatedEvent;
  18. use App\Event\Chat\MessageSentEvent;
  19. use App\Event\Client\NoticeOfInsufficientBudgetEvent;
  20. use App\Event\Mission\MissionAcceptedEvent;
  21. use App\Event\Mission\MissionActivatedEvent;
  22. use App\Event\Mission\MissionCancelledEvent;
  23. use App\Event\Mission\MissionDesiredDeliveryUpdatedAfterValidationEvent;
  24. use App\Event\Mission\MissionInitialTimeEvent;
  25. use App\Event\Mission\MissionRefusedEvent;
  26. use App\Event\Mission\MissionArchivedEvent;
  27. use App\Event\Mission\MissionCanActivateEvent;
  28. use App\Event\Mission\MissionDesiredDeliveryUpdatedBeforeValidationEvent;
  29. use App\Event\Workflow\Step\WorkflowStepEnteredEvent;
  30. use App\Form\AddMissionContactType;
  31. use App\Form\AddMissionContactProjectType;
  32. use App\Form\AddMissionContactExternalType;
  33. use App\Form\AddMissionSubContractorType;
  34. use App\Form\CampaignCancelType;
  35. use App\Form\CampaignDeleteType;
  36. use App\Form\ChangeInitialTimeType;
  37. use App\Form\ChangeRealTimeType;
  38. use App\Form\EditDesiredDeliveryType;
  39. use App\Form\EditSubcontractorParticipantType;
  40. use App\Form\FileMissionType;
  41. use App\Form\InfoMissionType;
  42. use App\Form\CampaignNameType;
  43. use App\Form\InitialBriefType;
  44. use App\Form\MessageType;
  45. use App\Form\MissionCancelType;
  46. use App\Form\MissionEditInitialTimeType;
  47. use App\Form\MissionParticipantDelaisType;
  48. use App\Form\MissionParticipantIncomeType;
  49. use App\Form\MissionParticipantType;
  50. use App\Form\MissionQuantityType;
  51. use App\Form\CampaignCreditHistoryType;
  52. use App\Repository\CampaignRepository;
  53. use App\Repository\HistoriqueRepository;
  54. use App\Repository\InfoMissionRepository;
  55. use App\Repository\MessageRepository;
  56. use App\Repository\MissionParticipantRepository;
  57. use App\Repository\CompanyRepository;
  58. use App\Repository\FileMissionRepository;
  59. use App\Repository\MissionRepository;
  60. use App\Repository\ServiceRepository;
  61. use App\Repository\UserRepository;
  62. use App\Service\CreditService;
  63. use App\Service\ResaleRateService;
  64. use Doctrine\ORM\EntityManagerInterface;
  65. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  66. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  67. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  68. use Symfony\Component\HttpFoundation\JsonResponse;
  69. use Symfony\Component\HttpFoundation\RedirectResponse;
  70. use Symfony\Component\HttpFoundation\Request;
  71. use Symfony\Component\HttpFoundation\Response;
  72. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  73. use Symfony\Component\Routing\Annotation\Route;
  74. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  75. use Symfony\Component\Routing\RouterInterface;
  76. use Symfony\Component\Workflow\Registry;
  77. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  78. use App\Event\Mission\MissionResendEvent;
  79. use App\Event\User\UserMentionnedEvent;
  80. use App\Form\MissionAddWorkflowType;
  81. use App\Form\FilterType;
  82. use App\Repository\WorkflowRepository;
  83. use App\Service\CampaignService;
  84. use App\Service\ClientSoldService;
  85. use App\Service\MessageService;
  86. use App\Service\MissionService;
  87. use App\Service\MyFlowMarginService;
  88. use App\Service\NumberFormatService;
  89. use Twig\Environment;
  90. use App\Service\PackService;
  91. use App\Service\PriceService;
  92. use Knp\Component\Pager\PaginatorInterface;
  93. use App\Repository\WorkflowStepRepository;
  94. use function PHPSTORM_META\type;
  95. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  96. use App\Service\ContractService;
  97. use App\Form\CampaignType;
  98. use App\Form\DesiredDeliveryType;
  99. use App\Form\StorageMissionType;
  100. use App\Repository\CommandeLoggingRepository;
  101. use App\Service\CampaignApiService;
  102. use DateTime;
  103. use Symfony\Component\Filesystem\Filesystem;
  104. use Symfony\Component\Mime\Address;
  105. use App\Service\GoogleStorageService;
  106. use App\Service\DynamicHostService;
  107. use App\Service\MissionParticipantService;
  108. use App\Service\SwitchConnexionService;
  109. class MissionController extends AbstractController
  110. {
  111.     const COST_OF_A_CREDIT 220;
  112.     public function __construct(
  113.         private EntityManagerInterface $entityManager,
  114.         private Environment $twig,
  115.         private CampaignService $campaignService,
  116.         private MissionService $missionService,
  117.         private NumberFormatService $numberFormatService,
  118.         private ContractService $contractService,
  119.         private  UserRepository $userRepository,
  120.         private EventDispatcherInterface $dispatcher,
  121.         private MessageService $messageService,
  122.         private GoogleStorageService $googleStorageService,
  123.         private PriceService $priceService,
  124.         private DynamicHostService $dynamicHostService,
  125.         private CampaignApiService $campaignApiService
  126.         private MissionParticipantService $missionParticipantService
  127.     ) {
  128.     }
  129.     /**
  130.      * Displays the missions index
  131.      *
  132.      * The admin views all the missions
  133.      * A company user view only his company's missions
  134.      * A subcontractor view only his missions
  135.      *
  136.      * @param CampaignRepository $campaignRepository
  137.      * @param CreditService $creditService
  138.      *
  139.      * @return Response template /mission/index.html.twig
  140.      */
  141.     #[Route('/mission'name'mission_index')]
  142.     #[Route('/mission/archived'name'mission_index_archived')]
  143.     #[Route('/mission/deleted'name'mission_index_deleted')]
  144.     public function index(Request $request,CampaignService $campaignServiceCommandeLoggingRepository $commandeLoggingRepositoryCampaignRepository $campaignRepositoryClientSoldService $clientSoldServiceCreditService $creditServiceMissionParticipantRepository $missionParticipantRepositoryUserRepository $userRepositoryParameterBagInterface $parameterBagInterfacePackService $packServicePriceService $priceServiceMissionRepository $missionRepositoryPaginatorInterface $paginatorSessionInterface $sessionCompanyRepository $companyRepository,SwitchConnexionService $switchConnexionService): Response
  145.     {
  146.         
  147.         
  148.         $routeName $request->attributes->get('_route');
  149.         $filterDownAndTop = !is_null($session->get('filterDownAndTop')) ? $session->get('filterDownAndTop') : [];
  150.         if (!is_null($request->query->get('nb_mission'))) {
  151.             $session->set('nbrMissionByPage'$request->query->get('nb_mission'));
  152.         }
  153.         $nbMissionByPage =  !is_null($session->get('nbrMissionByPage')) ? $session->get('nbrMissionByPage') : 10;
  154.         
  155.         //top down filter // ASC and DESC
  156.         if (
  157.             !is_null($request->query->get('companyFilter'))
  158.             or !is_null($request->query->get('campaingFilter'))
  159.             or !is_null($request->query->get('statusFilter'))
  160.             or !is_null($request->query->get('priceFilter'))
  161.             or !is_null($request->query->get('referenceFilter'))
  162.             or !is_null($request->query->get('referenceRandomFilter'))
  163.             or !is_null($request->query->get('companyRandomFilter'))
  164.             or !is_null($request->query->get('campaingRandomFilter'))
  165.             or !is_null($request->query->get('statusRandomFilter'))
  166.             or !is_null($request->query->get('priceRandomFilter'))
  167.         ) {
  168.             //random filter for reference
  169.             if (!is_null($request->query->get('referenceRandomFilter'))) {
  170.                 $ord = (isset($filterDownAndTop['referenceFilter']) && $filterDownAndTop['referenceFilter'] == "ASC") ? "DESC" "ASC";
  171.                 $request->query->set('referenceFilter'$ord);
  172.             }
  173.             //random for company
  174.             if (!is_null($request->query->get('companyRandomFilter'))) {
  175.                 $ord = (isset($filterDownAndTop['companyFilter']) && $filterDownAndTop['companyFilter'] == "ASC") ? "DESC" "ASC";
  176.                 $request->query->set('companyFilter'$ord);
  177.             }
  178.             //random for campaing
  179.             if (!is_null($request->query->get('campaingRandomFilter'))) {
  180.                 $ord = (isset($filterDownAndTop['campaingFilter']) && $filterDownAndTop['campaingFilter'] == "ASC") ? "DESC" "ASC";
  181.                 $request->query->set('campaingFilter'$ord);
  182.             }
  183.             //random for status
  184.             if (!is_null($request->query->get('statusRandomFilter'))) {
  185.                 $ord = (isset($filterDownAndTop['statusFilter']) && $filterDownAndTop['statusFilter'] == "ASC") ? "DESC" "ASC";
  186.                 $request->query->set('statusFilter'$ord);
  187.             }
  188.             //random for status
  189.             if (!is_null($request->query->get('priceRandomFilter'))) {
  190.                 $ord = (isset($filterDownAndTop['priceFilter']) && $filterDownAndTop['priceFilter'] == "ASC") ? "DESC" "ASC";
  191.                 $request->query->set('priceFilter'$ord);
  192.             }
  193.             $filterDownAndTop = [
  194.                 'companyFilter' => $request->query->get('companyFilter'),
  195.                 'campaingFilter' => $request->query->get('campaingFilter'),
  196.                 'statusFilter' => $request->query->get('statusFilter'),
  197.                 'priceFilter' => $request->query->get('priceFilter'),
  198.                 'referenceFilter' => $request->query->get('referenceFilter'),
  199.             ];
  200.             $session->set('filterDownAndTop'$filterDownAndTop);
  201.             return $this->redirectToRoute($routeName, [], Response::HTTP_SEE_OTHER);
  202.         }
  203.         //reset filter
  204.         if ($request->get('reset')) {
  205.             $session->set('criteriaFilter', []);
  206.             $session->set('filterDownAndTop', []);
  207.             $this->addFlash(
  208.                 type'success',
  209.                 message'Le filtre a été réinitialisé',
  210.             );
  211.             return $this->redirectToRoute($routeName, [], Response::HTTP_SEE_OTHER);
  212.         }
  213.         $criteriaFilter = !is_null($session->get('criteriaFilter')) ? $session->get('criteriaFilter') : [];
  214.         //creation formulaire 
  215.         $campaignCommand = [];
  216.         $campaignsPrice = [];
  217.         $totalHtPerMonth = [];
  218.         $creditConso = [];
  219.         $invoiced = [];
  220.         $nombreCampaignCommande 0;
  221.         $listSubContractorId = [];
  222.         if($this->isGranted(Role::ROLE_CLIENT->value) || $this->isGranted(Role::ROLE_CLIENT_ADMIN->value) ){
  223.             $listCampaignWithSubContractor $campaignRepository->findAllInterlocutors($this->getUser(), 3);
  224.             foreach ($listCampaignWithSubContractor as $campaign) {
  225.                 foreach ($campaign->getMissions() as $mission) {
  226.                     foreach ($mission->getParticipants() as $participant) {
  227.                         if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR) {
  228.                             if (!in_array($participant->getUser()->getEmail(), $listSubContractorId)) {
  229.                                 $listSubContractorId []= $participant->getUser()->getId(); 
  230.                             }
  231.                         }
  232.                     }
  233.                 }
  234.             }
  235.         }
  236.         $searchFilterForm $this->createForm(FilterType::class, null, ['user' => $this->getUser(), 'route' => $routeName,'listParticipantId'=>array_unique($listSubContractorId)]);
  237.         $formMissionQuantity $this->createForm(MissionQuantityType::class);
  238.         $formMissionInitialTime $this->createForm(MissionParticipantType::class);
  239.         $formMissionInitialTimeManually $this->createForm(MissionParticipantDelaisType::class);
  240.         $formMissionIncomeManually $this->createForm(MissionParticipantIncomeType::class);
  241.         $determineIfArchive $routeName == "mission_index_archived" true false;
  242.         $determineIfDelete $routeName == "mission_index_deleted" true false;
  243.         $querySearch $request->get('query'null) ??  null;
  244.         $typeSearch = ($request->get('typeSearch')) ??  null;
  245.         $subContractorAndAdmin = ($this->isGranted(Role::ROLE_ADMIN->value) or $this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) ? true false;
  246.         //for filter
  247.         $searchFilterForm->handleRequest($request);
  248.         if ($searchFilterForm->isSubmitted() && $searchFilterForm->isValid()) {
  249.             $criteriaFilter = [
  250.                 'company' => $searchFilterForm->get('company')->getData(),
  251.                 'campaign' => $searchFilterForm->get('campaign')->getData(),
  252.                 'state' => $searchFilterForm->get('state')->getData(),
  253.                 'max' => $searchFilterForm->get('max')->getData(),
  254.                 'min' => $searchFilterForm->get('min')->getData(),
  255.                 'user' => $searchFilterForm->get('user')->getData(),
  256.                 'client' => (in_array('ROLE_ADMIN',$this->getUser()->getRoles()) or in_array('ROLE_ADMIN_AGENCY',$this->getUser()->getRoles())  or in_array('ROLE_MANAGER',$this->getUser()->getRoles())  ) ? $searchFilterForm->get('client')->getData() : null,
  257.             ];
  258.             $session->set('criteriaFilter'$criteriaFilter);
  259.             return $this->redirectToRoute($routeName);
  260.         }
  261.         if (!is_null($request->query->get('query'))) {
  262.             $session->set('filterDownAndTop', []);
  263.             $criteriaFilter = [];
  264.         }
  265.         // $company = ;
  266.         // $isAgency = $this->dynamicHostService->isAgency();
  267.         
  268.         if ($this->isGranted(Role::ROLE_ADMIN->value) or $this->isGranted(Role::ROLE_ADMIN_AGENCY->value)) {
  269.       
  270.             $adminCompany =$this->isGranted(Role::ROLE_ADMIN_AGENCY->value) ?  $this->getUser()->getCompany() : null;   
  271.             
  272.             $campaigns $campaignRepository->orderedByDesiredDelivery($this->dynamicHostService->getCompany(), $determineIfArchive$querySearch$determineIfDelete$criteriaFilter$filterDownAndTop);
  273.             
  274.             $priceCampaign $missionParticipantRepository->findByInitialTime();
  275.             $estimatedIncome = [];
  276.             $initialTime = [];
  277.             $price = [];
  278.             foreach ($priceCampaign as $value) {
  279.                 if (!isset($estimatedIncome[$value->getMission()->getId()])) {
  280.                     $estimatedIncome[$value->getMission()->getId()] = [];
  281.                 }
  282.                 $initialTime[$value->getMission()->getId()][] = $value->getInitialTime();
  283.                 $price[$value->getMission()->getId()][] = $value->getEstimatedIncome();
  284.             }
  285.         } elseif ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
  286.            
  287.             $campaigns $campaignRepository->findForSubcontractor($this->getUser(), null$determineIfArchive$querySearch$subContractorAndAdmin$determineIfDelete$filterDownAndTop);
  288.             $estimatedIncome $missionParticipantRepository->getMissionForUserGroupById($this->getUser());
  289.         } else {
  290.             
  291.             $clientCompany =$this->isGranted(Role::ROLE_CLIENT_ADMIN->value) ?  $this->getUser()->getCompany() : null
  292.             $campaigns $campaignRepository->findForSubcontractor($this->getUser(),  $clientCompany $determineIfArchive$querySearchfalse$determineIfDelete$filterDownAndTop$criteriaFilter);
  293.             
  294.             if ($this->isGranted(Role::ROLE_CLIENT->value) || $this->isGranted(Role::ROLE_CLIENT_ADMIN->value)) {
  295.                 $estimatedIncome null;
  296.             } else {
  297.                 $estimatedIncome $missionParticipantRepository->getMissionForUserGroupById($this->getUser());
  298.             }
  299.         }
  300.         $company $this->getUser()->getCompany();
  301.         $creditAvailable $creditService->CreditAvailable($company);
  302.         $allCredit 0;
  303.         foreach ($creditAvailable as $credit) {
  304.             $allCredit += $credit->getCredit();
  305.         }
  306.         $formCancelCampaign $this->createForm(CampaignCancelType::class);
  307.         $formDeleteCampaign $this->createForm(CampaignDeleteType::class);
  308.         $formCancelMission $this->createForm(MissionCancelType::class);
  309.         $urlToConnectWp $parameterBagInterface->get('front_website_url') . "?tsso=" hash('sha256'$this->getUser()->getEmail() . $this->getUser()->getEmail());
  310.         if(empty($filterDownAndTop)){
  311.             $campaigns $campaignService->reOrderByNumberMessageUnreadAndState($campaigns);
  312.         }
  313.         $pagination $paginator->paginate(
  314.             $campaigns,
  315.             $request->query->getInt('page'1),
  316.             $nbMissionByPage
  317.         );
  318.         $totalIndividualBilling $campaignRepository->getTotalIndividualBilling($this->getUser(), $company);
  319.         $totalOtherCommande$company!=null $commandeLoggingRepository->getTotalOtherCommande(type:4,user$this->getUser(),company $company ): ['sum'=>0];
  320.         $isFilterMissionOpen false;
  321.         if($session->has('is_filter_open')){
  322.             $isFilterMissionOpen $session->get('is_filter_open') == "true" true false;
  323.         }
  324.         return $this->renderForm('mission/index.html.twig', [
  325.             'campaigns' => $pagination,
  326.             'isEmpty' => empty($campaigns) ? true false,
  327.             'creditConso' => $creditConso,
  328.             'searchFilterForm' => $searchFilterForm,
  329.             'invoiced' => $invoiced,
  330.             'formMissionQuantity' => $formMissionQuantity,
  331.             'formMissionInitialTime' => $formMissionInitialTime,
  332.             'formMissionInitialTimeManually' => $formMissionInitialTimeManually,
  333.             'formMissionIncomeManually' => $formMissionIncomeManually,
  334.             'formCancelCampaign' => $formCancelCampaign,
  335.             'formDeleteCampaign' => $formDeleteCampaign,
  336.             'formCancelMission' => $formCancelMission,
  337.             'estimatedIncome' => $estimatedIncome,
  338.             // 'formFf' => $estimatedIncome,
  339.             'urlToConnectWp' => $urlToConnectWp,
  340.             'user' => $this->getUser(),
  341.             'archive' => $determineIfArchive,
  342.             'delete' => $determineIfDelete,
  343.             'querySearch' => $querySearch,
  344.             'typeSearch' => $typeSearch,
  345.             'nombreOfresults' => count($campaigns),
  346.             'balanceHistories' => $clientSoldService->groupByTypeOfContractNotDeleted(company$company),
  347.             'totalIndividualBilling' => ($totalIndividualBilling != null $totalIndividualBilling['sum'] : 0)+  $totalOtherCommande['sum'],
  348.             'criteriaFilter' => $criteriaFilter,
  349.             'routeName' => $routeName,
  350.             'nbMissionByPage' => $nbMissionByPage,
  351.             'isFilterMissionOpen' => $isFilterMissionOpen,
  352.         ]);
  353.     }
  354.     #[Route('/mission/history'name'mission_index_history')]
  355.     public function historyCommande(CampaignRepository $campaignRepository,PriceService $priceService,  ParameterBagInterface $parameterBagInterface)
  356.     {   
  357.         
  358.         $groupedData = [];
  359.         if ($this->isGranted('ROLE_ADMIN')) {
  360.             $company null;
  361.             if ($this->isGranted('ROLE_ADMIN_AGENCY') or $this->isGranted('ROLE_MANAGER')) {
  362.                 $company $this->getUser()->getCompany();
  363.             }
  364.             $history $campaignRepository->findAllCampaignByMonth($company);
  365.         
  366.             foreach ($history as $element) {
  367.                 //dateClosed
  368.                 $date $element['dateClosed'] != null $element['dateClosed']->format('m:Y') : $element['dateActivation']->format('m:Y');
  369.                 $info $element;
  370.                 if (!isset($groupedData[$date])) {
  371.                     $groupedData[$date] = [];
  372.                 }
  373.                 $groupedData[$date][] = $info;
  374.             }
  375.         }
  376.         elseif($this->isGranted('ROLE_SUBCONTRACTOR')){
  377.             $campaigns $campaignRepository->findAllForSubonconctractotCampaignByMonth($this->getUser());
  378.             foreach ($campaigns as $campaign) {
  379.                 $date $campaign->getDateClosed() != null $campaign->getDateClosed()->format('m:Y') : $campaign->getActivatedAt()->format('m:Y');
  380.                 if (!isset($groupedData[$date])) {
  381.                     $groupedData[$date] = [
  382.                         'total'=>0,
  383.                         'missions'=>[]
  384.                     ];
  385.                 }
  386.                 $groupedData[$date]['total'] += $priceService->getTotalPriceAndTimeMissionSubcontractorById($campaign$this->getUser())['price'] ;
  387.                 $groupedData[$date]['missions']=[...$groupedData[$date]['missions'],...$campaign->getMissions()];
  388.             }
  389.         }
  390.         $urlToConnectWp $parameterBagInterface->get('front_website_url') . "?tsso=" hash('sha256'$this->getUser()->getEmail() . $this->getUser()->getEmail());
  391.         uksort($groupedData, function($a$b) {
  392.             $dateA DateTime::createFromFormat('m:Y'$a);
  393.             $dateB DateTime::createFromFormat('m:Y'$b);
  394.             return $dateA <=> $dateB;
  395.         });
  396.         
  397.         return $this->renderForm('mission/history.html.twig', [
  398.             'histories' => $groupedData,
  399.             'urlToConnectWp' => $urlToConnectWp,
  400.             'archive' => 0,
  401.             'delete' => 0,
  402.             'querySearch' => "",
  403.             'typeSearch' => "",
  404.         ]);
  405.     }
  406.     #[Route('/mission/{missionId}/{id}/delete'name'mission_info_delete'methods: ['GET'])]
  407.     public function deleteInfoMission(EntityManagerInterface $emInfoMissionRepository $infoMissionRepository$id$missionId): Response
  408.     {
  409.         $infoMission $infoMissionRepository->find($id);
  410.         $em->remove($infoMission);
  411.         $em->flush();
  412.                  
  413.         $this->addFlash(
  414.             type'success',
  415.             message'Info supprimeé avec succés.'
  416.         );
  417.         return $this->redirectToRoute('mission_edit', ['id' => $missionId]);
  418.     }
  419.     #[Route('/mission/ajaxEditInfoMission'name'mission_info_ajax_edit'methods: ['POST'])]
  420.     public function ajaxEditInfoMission(Request $requestEntityManagerInterface $emInfoMissionRepository $infoMissionRepository): JsonResponse
  421.     {
  422.         $data json_decode($request->getContent());
  423.         $infoMission $infoMissionRepository->find($data[0]);
  424.         $infoMission->setContent($data[1]);
  425.         $em->persist($infoMission);
  426.         try {
  427.             $em->flush();
  428.             return new JsonResponse(['status' => 'OK']);
  429.         } catch (\Exception $e) {
  430.             return new JsonResponse([
  431.                 'status' => 'KO',
  432.                 'message' => $e->getMessage(),
  433.             ]);
  434.         }
  435.     }
  436.     #[Route('/mission/edit/{missionId}/{id}'name'mission_info_edit'methods: ['POST'])]
  437.     public function editInfoMission(Request $requestEntityManagerInterface $entityManagerInfoMissionRepository $infoMissionRepository$id$missionId): Response
  438.     {
  439.         $newContent $request->request->get('info_mission_edit')['content'];
  440.         $infoMission $infoMissionRepository->find($id);
  441.         $infoMission->setContent($newContent);
  442.         
  443.         $entityManager->persist($infoMission);
  444.         $entityManager->flush();
  445.         
  446.         $this->addFlash(
  447.             type'success',
  448.             message'Info enregistré avec succés.'
  449.         );
  450.         return $this->redirectToRoute('mission_edit', ['id' => $missionId], Response::HTTP_SEE_OTHER);
  451.     }
  452.     #[Route('/missionParticipant/{id}/changeInitialTime'name'mission_change_manually_time'methods: ['GET''POST'])]
  453.     public function changeManuallyTime(Request $requestMissionParticipant $missionParticipantEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcherPriceService $priceService): JsonResponse
  454.     {
  455.         $mission $missionParticipant->getMission();
  456.         $MANS_DAY_FROM_7_HOURS_TO_MINUTES 420;
  457.         $this->campaignService->changeStateCampaignToRESEND($mission->getCampaign(), $mission$missionParticipant);
  458.         $mission->setAdminTime($request->query->get('delais'));
  459.         $mission->setAdminIncome($missionParticipant->getUser()->getResaleRate() * $request->query->get('delais') /  $MANS_DAY_FROM_7_HOURS_TO_MINUTES);
  460.         if ($missionParticipant->getUser()->getBillingMethod() == && $missionParticipant->getMission()->getState() == 'in_progress') {
  461.             $missionParticipant->setInitialTime($request->query->get('delais'));
  462.             $entityManager->persist($missionParticipant);
  463.             $entityManager->flush();
  464.             $event = new MissionInitialTimeAfterValidationUpdatedEvent($mission $missionParticipant->getMission());
  465.             $dispatcher->dispatch($eventMissionInitialTimeAfterValidationUpdatedEvent::NAME);
  466.             $this->addFlash(
  467.                 type'success',
  468.                 message'Le délais client a bien été mis à jour',
  469.             );
  470.             return new JsonResponse(['redirect' => $this->generateUrl('mission_index', [], UrlGeneratorInterface::ABSOLUTE_URL)]);
  471.         }
  472.         $ratio null;
  473.         if (!empty($missionParticipant->getEstimatedIncome()) && !empty($missionParticipant->getInitialTime())) {
  474.             $ratio $missionParticipant->getEstimatedIncome() / $missionParticipant->getInitialTime();
  475.         }
  476.         $formMissionInitialTimeManually $this->createForm(MissionParticipantDelaisType::class, $missionParticipant);
  477.         $formMissionInitialTimeManually->handleRequest($request);
  478.         $missionParticipant->setInitialTime($request->query->get('delais'));
  479.         if (empty($ratio)) {
  480.             $missionParticipant->setEstimatedIncome($missionParticipant->getInitialTime() * $missionParticipant->getUser()->getDailyRate() / $MANS_DAY_FROM_7_HOURS_TO_MINUTES);
  481.         } else {
  482.             $missionParticipant->setEstimatedIncome($missionParticipant->getInitialTime() * $ratio);
  483.         }
  484.         $entityManager->persist($missionParticipant);
  485.         $entityManager->flush();
  486.         $this->addFlash(
  487.             type'success',
  488.             message'Le délais client a bien été mis à jour',
  489.         );
  490.         return new JsonResponse(['redirect' => $this->generateUrl('mission_index', [], UrlGeneratorInterface::ABSOLUTE_URL)]);
  491.     }
  492.      #[Route('/missionParticipant/changeInitialTimeModal'name'mission_change_manually_modal_all'methods: ['GET''POST'])]
  493.      public function changeManuallyTimeModalAll(Request $requestEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcherPriceService $priceService): JsonResponse
  494.     {
  495.        $formData $request->request->all();
  496.        $currentUser $this->getUser();
  497.        $filteredValues array_filter($formData, function($key) {
  498.             return strpos($key'Mission_') === 0;
  499.        }, ARRAY_FILTER_USE_KEY);
  500.         $idMissions array_values($filteredValues);
  501.         foreach ($idMissions as $idMission) {
  502.             $mission $entityManager->getRepository(Mission::class)->find($idMission);
  503.             $timeSubcontractor $request->request->get('mission_initial_time_'.$idMission);
  504.             $priceSubcontractor $request->request->get('mission_initial_price_'.$idMission);
  505.             //search participant
  506.             $missionParticipant null;
  507.             foreach ($mission->getParticipants() as $participant) {
  508.                 if ($currentUser->getId() == $participant->getUser()->getId()) {
  509.                     $missionParticipant $participant;
  510.                     break;
  511.                 }
  512.             }
  513.             //upldate subcontractor information price and time
  514.             $missionParticipant->setInitialTime($timeSubcontractor);
  515.             $priceFoSubcontractor $priceService->tarifSubcontractor($missionParticipant->getUser()->getDailyRate(), $timeSubcontractor);
  516.             $missionParticipant->setEstimatedIncome($priceFoSubcontractor);
  517.             $missionParticipant->setInitialTimeAdmin($timeSubcontractor);
  518.             //prive for admin / client
  519.             $priceForAdmin =  $priceService->tarifAdminAndClient($missionParticipant->getUser()->getResaleRate(), $timeSubcontractor);
  520.             $missionParticipant->setEstimatedIncomeAdmin($priceForAdmin);
  521.             $entityManager->persist($missionParticipant);
  522.             $entityManager->flush();
  523.             //update information mission based in price and time for admin
  524.             $priceAndTimeMission $priceService->priceAndTimeMission($mission);
  525.             
  526.             $mission->setAdminIncome($priceAndTimeMission['price']);
  527.             $mission->setPrice($priceAndTimeMission['price']);
  528.             $mission->setAdminTime($priceAndTimeMission['time']);
  529.             $entityManager->persist($mission);
  530.            
  531.              //with marge if agency
  532.             $margeMyFlow =  $this->dynamicHostService->getMargeMyFlow();
  533.             if ($margeMyFlow != 0) {
  534.                 $mission->setPriceWithMargeMyFlow($priceService->getPriceMissionWithMargeMyFlow($margeMyFlow,$priceAndTimeMission['price']))->setMargeMyFlow($margeMyFlow);
  535.             }
  536.             $entityManager->flush();
  537.             $this->missionService->addHistorique(mission$missionuser$this->getUser(), action"mission_evaluate"option$missionParticipant);
  538.             $this->campaignService->changeStateEvaluateForParticipant($mission$missionParticipant);
  539.             if ($this->campaignService->canResendOrderToClient(campaign$mission->getCampaign(), missionEvaluate$mission)) {
  540.                 $this->campaignService->resendCampaignForValidation(campaign$mission->getCampaign(), user$this->getUser());
  541.             }
  542.         }
  543.         return new JsonResponse('ok');
  544.     }
  545.     #[Route('/missionParticipant/{id}/changeIncome'name'mission_change_manually_income'methods: ['GET''POST'])]
  546.     public function changeManuallyIncome(Request $requestMissionParticipant $missionParticipantEntityManagerInterface $entityManager)
  547.     {
  548.         $formMissionIncomeManually $this->createForm(MissionParticipantIncomeType::class, $missionParticipant);
  549.         $formMissionIncomeManually->handleRequest($request);
  550.         $missionParticipant->setEstimatedIncome($request->query->get('income'));
  551.         $entityManager->persist($missionParticipant);
  552.         $entityManager->flush();
  553.         $this->addFlash(
  554.             type'success',
  555.             message'Le revenu client a bien été mis à jour',
  556.         );
  557.         return $this->redirect($request->headers->get('referer'), Response::HTTP_SEE_OTHER);
  558.     }
  559.     #[Route('/mission/{id}/relancer'name'mission_relancer')]
  560.     public function campaignRelancer(Request $requestMission $missionMissionService $missionServiceEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher): Response
  561.     {
  562.         $event = new MissionResendEvent($mission);
  563.         $dispatcher->dispatch($eventMissionResendEvent::NAME);
  564.         $this->addFlash(
  565.             type'success',
  566.             message'La Mission a bien été relancer'
  567.         );
  568.         return $this->redirectToRoute('mission_index');
  569.     }
  570.     #[Route('/mission/{id}/changeQuantity'name'mission_change_quantity'methods: ['GET''POST'])]
  571.     public function changeQuantity(Request $requestMission $missionEntityManagerInterface $entityManagerMissionService $missionServicePriceService $priceService): JsonResponse
  572.     {
  573.         $formMissionQuantity $this->createForm(MissionQuantityType::class, $mission);
  574.         $formMissionQuantity->handleRequest($request);
  575.         $mission->getCampaign()->setReSendToClient(true);
  576.         $mission->setQuantity($request->query->get('quantity'));
  577.         $this->missionService->addHistorique(mission$missionuser$this->getUser(), action"quantity_update");
  578.         $entityManager->flush();
  579.         if ($this->campaignService->canResendOrderToClient(campaign$mission->getCampaign(), missionEvaluate$mission)) {
  580.             $this->campaignService->resendCampaignForValidation(campaign$mission->getCampaign(), user$this->getUser());
  581.         }
  582.         return new JsonResponse($this->getMissionDetailArray(mission$missionmissionService$missionServiceprice$priceService));
  583.     }
  584.     #[Route('/mission/{id}/changeInitialTime'name'mission_change_initial_time'methods: ['GET''POST'])]
  585.     public function changeInitialTime(Request $requestMissionParticipant $missionParticipantMissionService $missionServiceEntityManagerInterface $entityManagerPriceService $priceService): JsonResponse
  586.     {
  587.         $mission $missionParticipant->getMission();
  588.         $formMissionInitialTime $this->createForm(MissionParticipantType::class, $missionParticipant);
  589.         $formMissionInitialTime->handleRequest($request);
  590.         //upldate subcontractor information price and time
  591.         $missionParticipant->setInitialTime($formMissionInitialTime->getData()->getInitialTime());
  592.         $priceFoSubcontractor $priceService->tarifSubcontractor($missionParticipant->getUser()->getDailyRate(), $formMissionInitialTime->getData()->getInitialTime());
  593.         $missionParticipant->setEstimatedIncome($priceFoSubcontractor);
  594.         $missionParticipant->setInitialTimeAdmin($formMissionInitialTime->getData()->getInitialTime());
  595.         //add price suggered
  596.         $missionParticipant->setIncomeSuggested($formMissionInitialTime->getData()->getIncomeSuggested());
  597.         //end price suggered
  598.         //prive for admin / client
  599.         $priceForAdmin =  $priceService->tarifAdminAndClient($missionParticipant->getUser()->getResaleRate(), $formMissionInitialTime->getData()->getInitialTime());
  600.         $missionParticipant->setEstimatedIncomeAdmin($priceForAdmin);
  601.         $entityManager->persist($missionParticipant);
  602.         $entityManager->flush();
  603.         //update information mission based in price and time for admin
  604.         $priceAndTimeMission $priceService->priceAndTimeMission($mission);
  605.         //dd($priceAndTimeMission['price']);
  606.         $mission->setAdminIncome($priceAndTimeMission['price']);
  607.         $mission->setPrice($priceAndTimeMission['price']);
  608.         $mission->setAdminTime($priceAndTimeMission['time']);
  609.         $entityManager->persist($mission);
  610.        
  611.          //with marge if agency
  612.         $margeMyFlow =  $this->dynamicHostService->getMargeMyFlow();
  613.         if ($margeMyFlow != 0) {
  614.             $mission->setPriceWithMargeMyFlow($priceService->getPriceMissionWithMargeMyFlow($margeMyFlow,$priceAndTimeMission['price']))->setMargeMyFlow($margeMyFlow);
  615.         }
  616.        
  617.         $entityManager->flush();
  618.         $this->missionService->addHistorique(mission$missionuser$this->getUser(), action"mission_evaluate"option$missionParticipant);
  619.         $this->campaignService->changeStateEvaluateForParticipant($mission$missionParticipant);
  620.         if ($this->campaignService->canResendOrderToClient(campaign$mission->getCampaign(), missionEvaluate$mission)) {
  621.             $this->campaignService->resendCampaignForValidation(campaign$mission->getCampaign(), user$this->getUser());
  622.         }
  623.         return new JsonResponse($this->getMissionDetailArray(mission$missionmissionService$missionServiceprice$priceService));
  624.     }
  625.     #[Route('/mission/{id}/adminSetTime'name'mission_admin_set_initial_time'methods: ['POST'])]
  626.     #[IsGranted('ROLE_ADMIN')]
  627.     public function adminSetTime(Request $requestMission $missionEntityManagerInterface $entityManagerMissionService $missionServicePriceService $priceService): JsonResponse
  628.     {
  629.         $formMissionInitialTime $this->createForm(MissionParticipantType::class);
  630.         $formMissionInitialTime->handleRequest($request);
  631.         $isAlreadySendMailResoumissionPanierAdmin false;
  632.         foreach ($mission->getParticipants() as $participant) {
  633.             if ($participant->getRole() === Role::ROLE_SUBCONTRACTOR) {
  634.                 $participant->setInitialTime($formMissionInitialTime->getData()->getInitialTime());
  635.                 $participant->setIncomeSuggested($formMissionInitialTime->getData()->getIncomeSuggested());
  636.                 $priceFoSubcontractor $priceService->tarifSubcontractor($participant->getUser()->getDailyRate(), $formMissionInitialTime->getData()->getInitialTime());
  637.                 $participant->setEstimatedIncome($priceFoSubcontractor);
  638.                 $participant->setInitialTimeAdmin($formMissionInitialTime->getData()->getInitialTime());
  639.                 $participant->setEstimatedIncomeAdmin($formMissionInitialTime->getData()->getEstimatedIncome());
  640.                 $entityManager->flush();
  641.                if($isAlreadySendMailResoumissionPanierAdmin == false) {
  642.                     $isAlreadySendMailResoumissionPanierAdmin $this->campaignService->changeStateEvaluateForParticipant($mission$participant);
  643.                 } 
  644.             }
  645.             $missionService->addHistorique(mission$missionuser$this->getUser(), action"mission_evaluate"option$participant);
  646.         }
  647.         $priceAndTimeMission $priceService->priceAndTimeMission($mission);
  648.         $mission->setAdminIncome($priceAndTimeMission['price']);
  649.         $mission->setPrice($priceAndTimeMission['price']);
  650.         $mission->setAdminTime($priceAndTimeMission['time']);
  651.         //with marge if agency
  652.         $margeMyFlow =  $this->dynamicHostService->getMargeMyFlow();
  653.         if ($margeMyFlow != 0) {
  654.             $mission->setPriceWithMargeMyFlow($priceService->getPriceMissionWithMargeMyFlow($margeMyFlow,$priceAndTimeMission['price']))->setMargeMyFlow($margeMyFlow);
  655.         }
  656.        
  657.         //reflush
  658.         $entityManager->persist($mission);
  659.         $entityManager->flush();
  660.         
  661.         if ($this->campaignService->canResendOrderToClient(campaign$mission->getCampaign(), missionEvaluate$mission)) {
  662.            
  663.             if(!$isAlreadySendMailResoumissionPanierAdmin){
  664.                 
  665.                 $this->campaignService->resendCampaignForValidation(campaign$mission->getCampaign(), user$this->getUser());
  666.                 $isAlreadySendMailResoumissionPanierAdmin true;
  667.             }
  668.         }
  669.         return new JsonResponse($this->getMissionDetailArray(mission$missionmissionService$missionServiceprice$priceService));
  670.     }
  671.     private function getMissionDetailArray(Mission $missionMissionService $missionServicePriceService $price): array
  672.     {
  673.         $isSubContractor in_array("ROLE_SUBCONTRACTOR"$this->getUser()->getRoles()) ? $this->getUser()->getId() : false;
  674.         $total $price->totalPriceCampaign($mission->getCampaign(), $isSubContractor);
  675.         $currency $price->currency($mission->getCampaign());
  676.         if($mission->getCampaign()->getState()=='closing_in_progress' &&  sizeof($this->campaignApiService->getSubcontractorNoEstimatedIncome($mission->getCampaign())) == 0){
  677.             $this->campaignApiService->closedCampaign($mission->getCampaign());
  678.         }
  679.         $priceAndTime $this->getPriceAndTimeForTwig(mission$missionmissionService$missionServicepriceService$price);
  680.         // dd((float) $priceAndTime['price']);
  681.         $price $this->numberFormatService->format((float) $priceAndTime['price']);
  682.         $time =  $this->numberFormatService->format((float) $priceAndTime['time']);
  683.         // //credit or euros
  684.         return [
  685.             'incomeSuggested' => $mission?->onlySubcontractorInMission()?->getIncomeSuggested(),
  686.             // 'total' =>  $this->campaignService->getTotalCost(campaign: $mission->getcampaign(), withCurrency: true),
  687.             'total' =>  $this->numberFormatService->format($total) . $currency,
  688.             'price' => $price,
  689.             'time' => $time,
  690.             'id' => $mission->getId(),
  691.             'campaign_id' => $mission->getCampaign()->getId(),
  692.             'campaign_status' => $this->twig->render('services/status_campaign.html.twig', [
  693.                 'campaign' => $mission->getCampaign(),
  694.             ]),
  695.             'subcontractor_status' => $this->twig->render('services/subcontractor_status.html.twig', [
  696.                 'campaign' => $mission->getCampaign(),
  697.                 'mission' => $mission
  698.             ]),
  699.             'campaign_action_button' => $this->twig->render('services/_button_campaign.html.twig', [
  700.                 'campaign' => $mission->getCampaign(),
  701.                 'campaign_service' => $this->campaignService,
  702.             ]),
  703.             'mission_action_button' => $this->twig->render('services/action_button_mission.html.twig', [
  704.                 'campaign' => $mission->getCampaign(),
  705.                 'mission' => $mission
  706.             ]),
  707.             'subcontractor_list' => $this->twig->render('services/subcontractor_list.html.twig', [
  708.                 'campaign' => $mission->getCampaign(),
  709.                 'mission' => $mission
  710.             ]),
  711.             'marge' => $this->twig->render('services/_marge_get_to_ajax.html.twig', [
  712.                 'mission' => $mission
  713.             ]),
  714.             'isAdmin' => in_array("ROLE_ADMIN"$this->getUser()->getRoles()) ? true false,
  715.             'product_type' => $mission->getProduct()->getType()->value
  716.         ];
  717.     }
  718.     private function getPriceAndTimeForTwig(Mission $missionMissionService $missionServicePriceService $priceService)
  719.     {
  720.         $estimatedIncomeAndTime $this->missionService->getEstimatedIncomeAndTime(mission$missionuser$this->getUser());
  721.         $priceOrTimeAdmin $priceService->priceAndTimeMission($mission);
  722.         $price "";
  723.         $time "";
  724.         $validAllAdmin false;
  725.         if (in_array("ROLE_ADMIN"$this->getUser()->getRoles()) 
  726.             or in_array("ROLE_MANAGER"$this->getUser()->getRoles()) 
  727.             or in_array("ROLE_ADMIN_AGENCY"$this->getUser()->getRoles()) 
  728.         ) { 
  729.             $validAllAdmin true;
  730.         }
  731.         if ($mission->getProduct()->getType() == ProductType::A_EVALUER) {
  732.             // if (!$missionService->isAllSubcontractorEvaluate(mission: $mission)) {
  733.             //     $price = $validAllAdmin ? "not-evaluate" : $estimatedIncomeAndTime["income"];
  734.             //     $time = in_array("ROLE_ADMIN", $this->getUser()->getRoles()) ? "not-evaluate" : $estimatedIncomeAndTime["time"];
  735.             // } else {
  736.                 $price $validAllAdmin $priceOrTimeAdmin['price'] : $estimatedIncomeAndTime["income"];
  737.                 $time $validAllAdmin $priceOrTimeAdmin['time'] : $estimatedIncomeAndTime["time"];
  738.            // }
  739.         } else {
  740.             $price $validAllAdmin $priceOrTimeAdmin['price'] : $estimatedIncomeAndTime["income"];
  741.             $time $validAllAdmin $priceOrTimeAdmin['time'] : $estimatedIncomeAndTime["time"];
  742.         }
  743.         return [
  744.             'price' => $price,
  745.             'time' => $time
  746.         ];
  747.     }
  748.     #[Route('/subcontractor/html'name'mission_subcontractor_html'methods: ['GET''POST'])]
  749.     public function getMissionSubcontractorHtml(Request $requestUserRepository $userRepository): Response
  750.     {
  751.         $formEditSubcontractor  $this->createForm(EditSubcontractorParticipantType::class);
  752.         return  $this->render('services/subcontractror_edit_form.html.twig', [
  753.             'formEditSubcontractor' => $formEditSubcontractor->createView(),
  754.             'urlAction' => $request->getContent()
  755.         ]);
  756.     }
  757.     #[Route('/subcontractor/html/add'name'mission_subcontractor_html_add'methods: ['GET''POST'])]
  758.     public function getMissionSubcontractorHtmlAdd(Request $request): Response
  759.     {
  760.         return  $this->render('services/subcontractror_add_form.html.twig', [
  761.             'formAddMissionSubContractor' => $this->createForm(AddMissionSubContractorType::class)->createView(),
  762.             'name' => $request->getContent()
  763.         ]);
  764.     }
  765.     
  766.     /**
  767.      * @param Mission $mission
  768.      * @param FileMission|null $fileMission
  769.      * @param Request $request
  770.      * @param MessageRepository $messageRepository
  771.      * @param InfoMissionRepository $infoMissionRepository
  772.      * @param HistoriqueRepository $historiqueRepository
  773.      * @return Response
  774.      */
  775.     #[Route('/mission/ajouter'name'mission_new'methods: ['GET''POST'])]
  776.     #[Route('/mission/{id}'name'mission_edit'methods: ['GET''POST'])]
  777.     public function handle(Mission $missionWorkflowRepository $workflowRepositoryMessageService $messageService,  FileMission $fileMission nullRequest $requestMessageRepository $messageRepositoryInfoMissionRepository $infoMissionRepositoryHistoriqueRepository $historiqueRepositoryEventDispatcherInterface $dispatcherEntityManagerInterface $entityManagerMissionParticipantRepository $missionParticipantRepositoryServiceRepository $serviceRepositoryMissionRepository $missionRepositoryUserRepository $userRepository,CampaignRepository $campaignRepository,FileMissionRepository $fileMissionRepository,ParameterBagInterface $parameterBagInterface): Response
  778.     {   
  779.         if ("Espace de discussion" == $mission?->getProduct()?->getName() && count($mission->getCampaign()?->getMissionsWithoutEspaceDeDiscussion()) > 0) {
  780.             return $this->redirectToRoute('mission_edit', ['id' => $mission->getCampaign()->getMissionsWithoutEspaceDeDiscussion()?->first()?->getId()], Response::HTTP_SEE_OTHER);
  781.         }
  782.        //dd($this->missionParticipantService->getUniqByFutureActions($mission->getCampaign()->getId(), $this->getUser()->getId()));
  783.         ini_set("memory_limit""-1");
  784.         $routeName $request->attributes->get('_route');
  785.         $confirmation $request->query->get('confirmation');
  786.         $isMine false;
  787.         $companyId $this->getUser()?->getCompany()?->getId();
  788.         foreach ($mission->getParticipants() as $participant) {
  789.             if ($participant->getUser()->getId() == $this->getUser()->getId() ||  $mission->getCampaign()?->getOrderedBy()->getId()== $this->getUser()->getId()) {
  790.                $isMine true;
  791.             }
  792.         }
  793.           if (
  794.             $this->isGranted(Role::ROLE_ADMIN->value
  795.             || 
  796.             ($this->isGranted(Role::ROLE_CLIENT_ADMIN->value) && $companyId == $mission->getCampaign()?->getCompany()?->getId())
  797.         )
  798.          {
  799.             $isMine true;
  800.         }
  801.         if (!$isMine and $routeName == 'mission_edit') {
  802.             $this->addFlash(
  803.                 type'error',
  804.                 message"Vous n'etes plus sur cette missions",
  805.             ); 
  806.             return $this->redirectToRoute('mission_index');
  807.         }
  808.         
  809.  
  810.         
  811.         $message = new Message();
  812.         $messages $messageRepository->findBy(['campaign' => $mission->getCampaign()->getId()], ['createdAt' => 'ASC']);
  813.         $informations $infoMissionRepository->findBy(['mission' => $mission->getId()], ['createdAt' => 'ASC']);
  814.         $campaign $mission->getCampaign();
  815.         $oldPack $campaign->getCreditHistory();
  816.         $formEditCampaignCredit $this->createForm(CampaignCreditHistoryType::class, $campaign);
  817.         $formEditCampaignCredit->handleRequest($request);
  818.         if ($formEditCampaignCredit->isSubmitted() && $formEditCampaignCredit->isValid()) {
  819.             $this->missionService->addHistorique(mission$missionuser$this->getUser(), action'credit_campagne_modified');
  820.             $this->contractService->balanceAllocation($campaign$oldPack);
  821.             $entityManager $this->getDoctrine()->getManager();
  822.             $entityManager->persist($campaign);
  823.             $entityManager->flush();
  824.             $creditHistory $campaign->getCreditHistory(); 
  825.             $currentBlance $creditHistory->getCurrentBalance();
  826.             $totalPrice $this->priceService->totalPriceCampaign($campaignfalse);
  827.     
  828.             if($currentBlance $totalPrice 0) {
  829.                 $event = new  NoticeOfInsufficientBudgetEvent($campaign->getCompany(), $mission->getCampaign());
  830.                 $this->dispatcher->dispatch($eventNoticeOfInsufficientBudgetEvent::NAME);
  831.             }
  832.             
  833.             $this->addFlash('success''La contrat de la campagne a bien été modifiée');
  834.             return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
  835.         }
  836.         /*
  837.          * Form handle Campaign name
  838.          */
  839.         $form1 $this->createForm(CampaignNameType::class, $campaign);
  840.         $form1->handleRequest($request);
  841.         if ($form1->isSubmitted() && $form1->isValid()) {
  842.             $this->missionService->addHistorique(mission$missionuser$this->getUser(), action'title_campagne_modified');
  843.             $entityManager $this->getDoctrine()->getManager();
  844.             $entityManager->persist($campaign);
  845.             $entityManager->flush();
  846.             $this->addFlash('success''La campagne a bien été modifiée');
  847.             return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
  848.         }
  849.         if ($this->isGranted(Role::ROLE_ADMIN->value)) {
  850.             $priceCampaign $missionParticipantRepository->findByInitialTime();
  851.             $estimatedIncome = [];
  852.             $initialTime = [];
  853.             $price = [];
  854.             foreach ($priceCampaign as $value) {
  855.                 if (!isset($estimatedIncome[$value->getMission()->getId()])) {
  856.                     $estimatedIncome[$value->getMission()->getId()] = [];
  857.                 }
  858.                 $initialTime[$value->getMission()->getId()][] = $value->getInitialTime();
  859.                 $price[$value->getMission()->getId()][] = $value->getEstimatedIncome();
  860.             }
  861.         } elseif ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
  862.             $visibleCampaign = ['orderedBy' => $this->getUser()];
  863.             $estimatedIncome $missionParticipantRepository->getSubcontractorForUserAndMission($this->getUser());
  864.         } else {
  865.             $estimatedIncome null;
  866.         }
  867.         $formMissionInitialTime $this->createForm(MissionParticipantType::class);
  868.         $formMissionInitialTimeManually $this->createForm(MissionParticipantDelaisType::class);
  869.         $formMissionIncomeManually $this->createForm(MissionParticipantIncomeType::class);
  870.         /**
  871.          * Form handle chatbox
  872.          */
  873.         $form $this->createForm(MessageType::class, $message);
  874.         $form->handleRequest($request);
  875.         $formAddFileStorage $this->createForm(StorageMissionType::class,$message);
  876.         /*
  877.          * Form form add worflow
  878.          */
  879.         $formAddWorkflow $this->createForm(MissionAddWorkflowType::class, $mission);
  880.         $formAddWorkflow->handleRequest($request);
  881.         if ($formAddWorkflow->isSubmitted() && $formAddWorkflow->isValid()) {
  882.             $worklowdId $request->request->get('mission_add_workflow');
  883.             if ($worklowdId != null) {
  884.                 $worklowdId $worklowdId['workflow'];
  885.                 $workflow $workflowRepository->findOneBy(['id' => $worklowdId]);
  886.                 $workflowClone = clone $workflow;
  887.                 $workflowClone->setTemplate(false);
  888.                 $mission->setWorkflow($workflowClone);
  889.                 $this->entityManager->persist($workflowClone);
  890.                 //if campaing is in progress so active first steps
  891.                 if ($mission->getState() == 'in_progress') {
  892.                     $step $mission->getWorkflow()->getSteps()->first();
  893.                     $step->setActive(true);
  894.                     if ($step->getManager() == 0) {
  895.                         $mission->setStateClient('Déclenchement en attente');
  896.                     } else {
  897.                         $mission->setStateProvider($step->getName());
  898.                     }
  899.                     $this->entityManager->flush();
  900.                     // $event = new WorkflowStepEnteredEvent($step);
  901.                     // $dispatcher->dispatch($event, WorkflowStepEnteredEvent::NAME);
  902.                 }
  903.                 $this->entityManager->flush();
  904.                 $this->addFlash('success''Le workflow a bien été modifié');
  905.             }
  906.             return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
  907.         }
  908.         
  909.         /*
  910.          * Form handle information général
  911.          */
  912.         $infoMission = new InfoMission();
  913.         $form2 $this->createForm(InfoMissionType::class, $infoMission);
  914.         $form2->handleRequest($request);
  915.         if ($form2->isSubmitted() && $form2->isValid()) {
  916.             $entityManager $this->getDoctrine()->getManager();
  917.             $infoMission->setMission($mission)
  918.                 ->setUser($this->getUser());
  919.             $mission->addInfoMission($infoMission);
  920.             $entityManager->persist($infoMission);
  921.             $entityManager->flush();
  922.             $this->addFlash(
  923.                 type'success',
  924.                 message'Message enregistré avec succés.'
  925.             );
  926.             return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
  927.         }
  928.         
  929.         
  930.         /*
  931.          * Form handle edit single line in information général
  932.          */
  933.         $infoFormArr = [];
  934.         $infoEditForm = [];
  935.         foreach ($informations as $information) {
  936.             $key $information->getId();
  937.             $infoEditForm[$key] = $this->createform(InfoMissionType::class, $information);
  938.             $infoFormArr[$key] = $infoEditForm[$key]->createView();
  939.         }
  940.         
  941.         $actualDesiredDelivery null;
  942.         if (null !== $mission->getDesiredDelivery()) {
  943.             $actualDesiredDelivery = clone $mission->getDesiredDelivery();
  944.         }
  945.         $formChangeDateDelivery $this->createForm(EditDesiredDeliveryType::class, $mission);
  946.         $formChangeDateDelivery->handleRequest($request);
  947.         if ($formChangeDateDelivery->isSubmitted() && $formChangeDateDelivery->isValid()) {
  948.             if (null !== $actualDesiredDelivery && $actualDesiredDelivery->format('Y-m-d') !== $formChangeDateDelivery->getData()->getDesiredDelivery()->format('Y-m-d')) {
  949.                 $entityManager $this->getDoctrine()->getManager();
  950.                 $entityManager->persist($mission);
  951.                 $entityManager->flush();
  952.                 if ($mission->getState() != 'provisionnal') {
  953.                     $event = new MissionDesiredDeliveryUpdatedAfterValidationEvent($mission);
  954.                     $dispatcher->dispatch($eventMissionDesiredDeliveryUpdatedAfterValidationEvent::NAME);
  955.                 }
  956.                 $this->addFlash(
  957.                     type'success',
  958.                     message'La date de livraison souhaitée à bien été modifiée'
  959.                 );
  960.             }
  961.             return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
  962.         }
  963.         $formInitialTime $this->createForm(ChangeInitialTimeType::class, $mission);
  964.         $formInitialTime->handleRequest($request);
  965.         if ($formInitialTime->isSubmitted() && $formInitialTime->isValid()) {
  966.             $initialTime $formInitialTime->getData()->getInitialTime();
  967.             $product $mission->getProduct()->getId();
  968.             $participant $missionParticipantRepository->findOneBy(['mission' => $mission]);
  969.             $service $serviceRepository->findOneBy(['user' => $participant->getUser(), 'product' => $product]);
  970.             $calculPrice $initialTime 60 $service->getResale() * $mission->getQuantity();
  971.             $mission->setPrice($calculPrice);
  972.             $entityManager->persist($mission);
  973.             $entityManager->flush();
  974.             $event = new MissionInitialTimeEvent($mission);
  975.             $dispatcher->dispatch($eventMissionInitialTimeEvent::NAME);
  976.             $this->addFlash(
  977.                 type'success',
  978.                 message'Le temps initial a bien été ajouté'
  979.             );
  980.             return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
  981.         }
  982.         $formRealTime $this->createForm(ChangeRealTimeType::class, $mission);
  983.         $formRealTime->handleRequest($request);
  984.         if ($formRealTime->isSubmitted() && $formRealTime->isValid()) {
  985.             $entityManager->persist($mission);
  986.             $entityManager->flush();
  987.             $this->addFlash(
  988.                 type'success',
  989.                 message'Le temps réel passé a bien été ajouté'
  990.             );
  991.             return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
  992.         }
  993.         /**
  994.          * Form handle fichier demande initial
  995.          */
  996.         $form3 $this->createForm(FileMissionType::class, $fileMission);
  997.         $form3->handleRequest($request);
  998.         if ($form3->isSubmitted() && $form3->isValid()) {
  999.             $path 'file_mission_directory';
  1000.             $entityManager $this->getDoctrine()->getManager();
  1001.             $files $form3->get('fileMissions')->getData();
  1002.             $filesystem = new Filesystem();
  1003.             foreach ($files as $file) {
  1004.                 $destination $this->getParameter($path) . '/' $mission->getId();
  1005.               
  1006.                 $campaignDestination $this->getParameter("file_campaing_directory") . '/' $mission->getCampaign()->getId();
  1007.                 if (!$filesystem->exists($destination)) {
  1008.                     $filesystem->mkdir($destination);
  1009.                 }
  1010.                 
  1011.                 if (!$filesystem->exists($campaignDestination)) {
  1012.                     $filesystem->mkdir($campaignDestination);
  1013.                 }
  1014.                 $originalFilename pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  1015.                 $newFilename $originalFilename '-' uniqid() . '.' $file->guessExtension();
  1016.                 // $file->move(
  1017.                 //     $destination,
  1018.                 //     $newFilename
  1019.                 // );
  1020.                 // $fileMission = $destination."/".$newFilename;
  1021.                 // copy($fileMission,$campaignDestination."/".$newFilename);
  1022.                 $originalFilename pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
  1023.                 $extensionFile =  pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
  1024.                 $newFilename $originalFilename '-' uniqid() . '.' $extensionFile;
  1025.                  //upload file in google storage
  1026.                 $nameUniqueCompany strtolower("company-".$mission->getCampaign()->getCompany()->getId());
  1027.                 $this->googleStorageService->uploadFile($nameUniqueCompany,$file,$newFilename,'Campaigns/'.$campaign->getId());
  1028.                 $fileMission = new FileMission();
  1029.                 $fileMission->setName($newFilename);
  1030.                 
  1031.                 $mission->getCampaign()->addFileMission($fileMission);
  1032.                 $fileMission->setIsNew(1);
  1033.                 $fileMission->setUser($this->getUser());
  1034.                 $entityManager->persist($fileMission);
  1035.           
  1036.                 
  1037.             }
  1038.             $entityManager->flush();
  1039.             $this->addFlash(
  1040.                 type'success',
  1041.                 message'Le fichier a bien été ajouté à la demande'
  1042.             );
  1043.             return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
  1044.         }
  1045.         $mission $mission->getInitialBriefing() == null $mission->setInitialBriefing($mission->getCampaign()->getBrief()) : $mission;
  1046.         $formInitialBrief $this->createForm(InitialBriefType::class, $mission);
  1047.         $formInitialBrief->handleRequest($request);
  1048.         if ($formInitialBrief->isSubmitted() && $formInitialBrief->isValid()) {
  1049.             $mission->getCampaign()->setBrief($mission->getInitialBriefing());
  1050.             $entityManager->persist($mission);
  1051.             // $historique = (new Historique())
  1052.             //     ->setUser($this->getUser())
  1053.             //     ->setMission($mission)
  1054.             //     ->setMessage('Modification de la demande initiale');
  1055.             // $entityManager->persist($historique);
  1056.             $this->missionService->addHistorique(mission$missionuser$this->getUser(), action"initial_time");
  1057.             $campaign->setBrief($mission->getInitialBriefing());
  1058.             //all initial brief is impact of all mission
  1059.             foreach ($mission->getCampaign()->getMissions() as $otherMission) {
  1060.                 if ($otherMission->getId() !== $mission->getId()) {
  1061.                     $otherMission->setInitialBriefing($mission->getInitialBriefing(), false);
  1062.                     $entityManager->persist($otherMission);
  1063.                 }
  1064.             }
  1065.             $entityManager->flush();
  1066.             $this->addFlash(
  1067.                 type'success',
  1068.                 message'Demande initiale modifiée avec succès.'
  1069.             );
  1070.             return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
  1071.         }
  1072.         $formAddMissionContact $this->createForm(AddMissionContactType::class, null, ['action' => $this->generateUrl('mission_participant_add', ['mission' => $mission->getId()])]);
  1073.          $formAddMissionContactProject $this->createForm(AddMissionContactProjectType::class, null, ['action' => $this->generateUrl('mission_participant_add', ['mission' => $mission->getId()])]);
  1074.         $formAddMissionContactExternal $this->createForm(AddMissionContactExternalType::class, null, ['action' => $this->generateUrl('mission_participant_add', ['mission' => $mission->getId()])]);
  1075.         $formAddMissionSubContractor $this->createForm(AddMissionSubContractorType::class, null, ['action' => $this->generateUrl('mission_participant_add', ['mission' => $mission->getId()])]);
  1076.         $formEditSubcontractor $this->createForm(EditSubcontractorParticipantType::class);
  1077.         $formCancelMission $this->createForm(MissionCancelType::class);
  1078.         $formDeleteCampaign $this->createForm(CampaignDeleteType::class);
  1079.         $formCancelCampaign $this->createForm(CampaignCancelType::class);
  1080.         //now participant in this mission if edit mission
  1081.         $missionParticipant null;
  1082.         foreach ($mission->getParticipants() as $participant) {
  1083.             if ($participant->getUser()->getId() == $this->getUser()->getId()) {
  1084.                 $missionParticipant $participant;
  1085.             }
  1086.         }
  1087.        $allClientParticipantsMail = [];
  1088.        $allClientParticipants = [];
  1089.         foreach ($mission->getCampaign()->getMissions() as $m) {
  1090.             foreach ($m->getParticipants() as $participant) {
  1091.                 if ($participant->getRole() !== Role::ROLE_SUBCONTRACTOR) {
  1092.                     if (!in_array($participant->getUser()->getEmail(), $allClientParticipantsMail)) {
  1093.                         $allClientParticipantsMail[] = $participant->getUser()->getEmail();
  1094.                         $allClientParticipants[] = $participant;
  1095.                     }
  1096.                 }
  1097.             }
  1098.         }
  1099.         $formDesiredDelivery $this->createForm(DesiredDeliveryType::class,$mission);
  1100.         $formDesiredDelivery->handleRequest($request);
  1101.         $allMission $missionRepository->findBy(['campaign'=>$campaign],['positionOrder'=>'ASC']);
  1102.         //all files in storage
  1103.         $allMissionId = [];
  1104.         
  1105.         foreach ($campaign->getMissions() as $m) {
  1106.             $allMissionId[] = $m->getId();
  1107.         }
  1108.        
  1109.         $allMessageContent $messageRepository->findMessagesContent($campaign);
  1110.         $allMessageWithLink = [];
  1111.         $links = [];
  1112.         //get all link in message
  1113.         foreach ($allMessageContent as $message) {
  1114.             $dom = new \DOMDocument();
  1115.             if (!empty($message['content']) and $message['content'] != null) {
  1116.                 @$dom->loadHTML($message['content']);
  1117.                 $anchors $dom->getElementsByTagName('a');
  1118.                 foreach ($anchors as $anchor) {
  1119.                     $links $anchor->getAttribute('href');
  1120.                     $message['linkInMessage'] = $links;
  1121.                     $message['linkInMessageShort'] = mb_substr($links040)."...";
  1122.                     $allMessageWithLink = [...$allMessageWithLink,$message];
  1123.                 }
  1124.             }
  1125.         }
  1126.         $allMessages $messageRepository->allMessageHaveFile($campaign);
  1127.         $allJointes  $fileMissionRepository->allFile($campaign,$allMissionId);
  1128.         $allFiles array_merge($allMessageWithLink,$allMessages$allJointes) ;
  1129.         usort($allFiles, function($a,$b){
  1130.             return $b['createdAt'] <=> $a['createdAt'];
  1131.         });
  1132.         $url $parameterBagInterface->get('back_website_url');
  1133.         //end
  1134.         $initialDemande $mission?->getCampaign()?->getBrief();
  1135.         $joinFilesMessage $mission->getCampaign()?->getFileMissions();
  1136.         
  1137.         $futurActions $this->missionParticipantService->getUniqByFutureActions($mission->getCampaign()->getId(),$this->getUser()->getId());
  1138.        
  1139.  
  1140.         $thisUserData$this->getUser()->getUserData();
  1141.         $activeMissionTab = [];
  1142.         if($thisUserData != null){
  1143.             $userActiveMissionTab $thisUserData->getMissionTabActive();
  1144.             if(!is_null($userActiveMissionTab)) {
  1145.                 $arrayActiveTabUser explode('#',$userActiveMissionTab);
  1146.                 if(isset($arrayActiveTabUser[0])){
  1147.                     $activeMissionTab['mission'] = $arrayActiveTabUser[0];
  1148.                 }
  1149.                 if(isset($arrayActiveTabUser[1])){
  1150.                     $activeMissionTab['tab_actif'] = $arrayActiveTabUser[1];
  1151.                 }
  1152.             }        
  1153.         }
  1154.         if ($confirmation) {
  1155.             $this->addFlash(
  1156.                 type'success',
  1157.                 message"Les délais ont été  bien mis à jour",
  1158.             ); 
  1159.         }
  1160.         return $this->renderForm('mission/handle_ux.html.twig', [
  1161.             'allMessages' => $allFiles,
  1162.             'price_service' => $this->priceService,
  1163.             'futurActions' => $futurActions,
  1164.             'urlDomaine' => $url,
  1165.             'initialDemande' => $initialDemande,
  1166.             'joinFilesMessage' => $joinFilesMessage,
  1167.             'mission' => $mission,
  1168.             'allMission' => $allMission,
  1169.             'form' => $form,
  1170.             'form1' => $form1,
  1171.             'form2' => $form2,
  1172.             'form3' => $form3,
  1173.             'infoFormArr' => $infoFormArr,
  1174.             'messages' => $messages,
  1175.             'informations' => $informations,
  1176.             'formDesiredDelivery'=> $formDesiredDelivery,
  1177.             'formAddMissionContact' => $formAddMissionContact,
  1178.             'formAddMissionContactExternal' => $formAddMissionContactExternal,
  1179.             'formAddMissionContactProject' => $formAddMissionContactProject,
  1180.             'formEditSubcontractor' => $formEditSubcontractor,
  1181.             'formChangeDateDelivery' => $formChangeDateDelivery,
  1182.             'formAddMissionSubContractor' => $formAddMissionSubContractor,
  1183.             'formMissionInitialTime' => $formMissionInitialTime,
  1184.             'formMissionInitialTimeManually' => $formMissionInitialTimeManually,
  1185.             'formMissionIncomeManually' => $formMissionIncomeManually,
  1186.             'formInitialTime' => $formInitialTime,
  1187.             'formRealTime' => $formRealTime,
  1188.             'formInitialBrief' => $formInitialBrief,
  1189.             'campaign' => $campaign,
  1190.             'estimatedIncome' => $estimatedIncome,
  1191.             'formCancelMission' => $formCancelMission,
  1192.             'formDeleteCampaign' => $formDeleteCampaign,
  1193.             'formCancelCampaign' => $formCancelCampaign,
  1194.             'formAddWorkflow' =>  $formAddWorkflow,
  1195.             'formEditCampaignCredit' => $formEditCampaignCredit,
  1196.             'userConnected' => $this->getUser(),
  1197.             'missionParticipant' => $missionParticipant,
  1198.             'allClientParticipants' => $allClientParticipants,
  1199.             'formAddFileStorage' =>$formAddFileStorage,
  1200.             'userActiveTab' => $activeMissionTab,
  1201.         ]);
  1202.     }
  1203.     
  1204.     #[Route('/mission/{id}/refus'name'mission_refus'methods: ['GET'])]
  1205.     public function refuse(Mission $missionUserRepository $userRepositoryRequest $requestMissionParticipantRepository $missionParticipantRepositoryEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher)
  1206.     {
  1207.         $intervenant $userRepository->find($request->query->get('intervenant'));
  1208.         if (null === $intervenant) {
  1209.             throw new NotFoundHttpException();
  1210.         }
  1211.         $event = new MissionRefusedEvent($mission$intervenant);
  1212.         $dispatcher->dispatch($eventMissionRefusedEvent::NAME);
  1213.         $this->addFlash(
  1214.             type'success',
  1215.             message'La mission a bien été refusée',
  1216.         );
  1217.         $this->missionService->addHistorique(mission$missionuser$this->getUser(), action"refus");
  1218.         return $this->redirectToRoute('mission_index');
  1219.     }
  1220.     #[Route('/mission/{id}/accepter'name'mission_accept'methods: ['GET'])]
  1221.     public function accept(Mission $missionClientSoldService $clientSoldServiceUserRepository $userRepositoryRequest $requestEntityManagerInterface $entityManagerEventDispatcherInterface $dispatcher)
  1222.     {
  1223.         if (empty($request->query->get('intervenant'))) {
  1224.             $intervenant $this->getUser();
  1225.         } else {
  1226.             $intervenant $userRepository->find($request->query->get('intervenant'));
  1227.         }
  1228.         if (null === $intervenant) {
  1229.             throw new NotFoundHttpException();
  1230.         }
  1231.         if ($mission->getWorkflow()) {
  1232.             $step $mission->getWorkflow()->getSteps()->first();
  1233.             $step->setActive(true);
  1234.             if ($step->getManager() == 0) {
  1235.                 $mission->setStateClient('Déclenchement en attente');
  1236.             } else {
  1237.                 $mission->setStateProvider($step->getName());
  1238.             }
  1239.             $event = new WorkflowStepEnteredEvent($step);
  1240.             $dispatcher->dispatch($eventWorkflowStepEnteredEvent::NAME);
  1241.         }
  1242.         $campaign $mission->getCampaign();
  1243.         $campaign->setState('in_progress');
  1244.         $mission->setState('in_progress');
  1245.         $entityManager->flush();
  1246.         $event = new MissionAcceptedEvent($mission$intervenant);
  1247.         $dispatcher->dispatch($eventMissionAcceptedEvent::NAME);
  1248.         $this->addFlash(
  1249.             type'success',
  1250.             message'La mission a bien été acceptée',
  1251.         );
  1252.         return $this->redirectToRoute('mission_index');
  1253.     }
  1254.     #[Route('/mission/{id}/{transition<pause|unpause|cancel|archive>}'name'mission_transition')]
  1255.     public function transition(Mission $missionstring $transitionClientSoldService $clientSoldServiceEventDispatcherInterface $dispatcherRequest $requestRegistry $workflowsEntityManagerInterface $entityManager): RedirectResponse
  1256.     {
  1257.         $workflow $workflows->get($mission'classic');
  1258.         $originalMission = clone $mission;
  1259.         $originalCampaign = clone $mission->getCampaign();
  1260.         if ($workflow->can($mission$transition)) {
  1261.             $workflow->apply($mission$transition);
  1262.             $applyToCampaign true;
  1263.             foreach ($mission->getCampaign()->getMissions() as $otherMission) {
  1264.                 if ($otherMission->getState() !== $mission->getState()) {
  1265.                     $applyToCampaign false;
  1266.                     break;
  1267.                 }
  1268.             }
  1269.             if ($applyToCampaign) {
  1270.                 $campaign $mission->getCampaign();
  1271.                 $workflow $workflows->get($campaign'classic');
  1272.                 if ($workflow->can($campaign$transition)) {
  1273.                     $workflow->apply($campaign$transition);
  1274.                 }
  1275.                 $entityManager->persist($campaign);
  1276.             }
  1277.             if ($transition === 'cancel') {
  1278.                 $formCancelMission $this->createForm(MissionCancelType::class, $mission);
  1279.                 $formCancelMission->handleRequest($request);
  1280.                 $mission->setLastState($originalMission->getState());
  1281.                 $this->missionService->addHistorique(mission$missionuser$this->getUser(), action"cancel");
  1282.                 //when all mission is canceled change status campaing
  1283.                 $allmissionIsCanceled true;
  1284.                 foreach ($originalCampaign->getMissions() as $missionP) {
  1285.                     if ($missionP->getState() != "cancelled") {
  1286.                         $allmissionIsCanceled false;
  1287.                     }
  1288.                 }
  1289.                 if ($allmissionIsCanceled) {
  1290.                     $mission->getCampaign()->setLastState($originalCampaign->getState());
  1291.                     $mission->getCampaign()->setState("cancelled");
  1292.                 }
  1293.                 $event = new MissionCancelledEvent($mission);
  1294.                 $dispatcher->dispatch($eventMissionCancelledEvent::NAME);
  1295.             }
  1296.         }
  1297.         if ($transition === 'archive') {
  1298.             $event1 = new MissionClosedEvent($mission);
  1299.             $dispatcher->dispatch($event1MissionClosedEvent::NAME);
  1300.             $mission->setState('finalized');            
  1301.             $mission->setLastState($originalMission->getLastState());
  1302.             $event = new MissionArchivedEvent($mission);
  1303.             $dispatcher->dispatch($eventMissionArchivedEvent::NAME);
  1304.             $numberOfMissionFinalized 0;
  1305.             $campaign $mission->getCampaign();
  1306.             if ($mission->getProduct()->getType() != ProductType::AU_FORFAIT) {
  1307.                 $clientSoldService->decreaseCurrentBalanceByMissionCost(mission$mission);
  1308.             }
  1309.             foreach ($campaign->getMissions() as $missionPersited) {
  1310.                 if ($missionPersited->getProduct()->getName() == "Espace de discussion") {
  1311.                     $numberOfMissionFinalized++;
  1312.                 }
  1313.                 if ($missionPersited->getid() == $mission->getId()) {
  1314.                     $numberOfMissionFinalized++;
  1315.                 } elseif ($missionPersited->getState() ==  "finalized" or $missionPersited->getState() == "cancelled") {
  1316.                     $numberOfMissionFinalized++;
  1317.                 }
  1318.             }
  1319.             if ($numberOfMissionFinalized == sizeof($campaign->getMissions())) {
  1320.                 $campaign->setState('closed');
  1321.                 $entityManager->persist($campaign);
  1322.                 $this->addFlash(
  1323.                     type'success',
  1324.                     message'La campagne a bien été clôturée',
  1325.                 );
  1326.             }
  1327.         }
  1328.         $entityManager->flush();
  1329.         $message = match ($transition) {
  1330.             'archive' => 'archivée',
  1331.             'pause' => 'mise en pause',
  1332.             'unpause' => 'relancée',
  1333.             'cancel' => 'annulée',
  1334.             default => 'enregistrée',
  1335.         };
  1336.         $this->missionService->addHistorique(mission$missionuser$this->getUser(), action$transition);
  1337.         $this->addFlash(
  1338.             type'success',
  1339.             message'La mission a bien été ' $message,
  1340.         );
  1341.         return $this->redirectToRoute('mission_index');
  1342.     }
  1343.     #[Route('/mission/{id}/list/participant'name'mission_list_participant'methods: ['GET'])]
  1344.     public function ListParticipant($idRequest $requestMissionRepository $missionRepositoryMissionParticipantRepository $missionParticipantRepositoryServiceRepository $serviceRepositoryPriceService $priceService)
  1345.     {
  1346.         $mission $missionRepository->find($id);
  1347.         $formMissionInitialTimeManually $this->createForm(MissionParticipantDelaisType::class);
  1348.         return $this->renderForm(
  1349.             'mission/_modal_list_all_participant.html.twig',
  1350.             [
  1351.                 'mission' => $mission,
  1352.                 'campaign' => $mission->getCampaign(),
  1353.                 'formMissionInitialTimeManually' => $formMissionInitialTimeManually
  1354.             ]
  1355.         );
  1356.     }
  1357.     #[Route('/mission/{id}/activation'name'mission_activate'methods: ['GET''POST'])]
  1358.     public function Activate(NumberFormatService $numberFormatServiceMyFlowMarginService $myFlowMarginServiceMissionService $missionService,  ClientSoldService $clientSoldServiceMission $missionEventDispatcherInterface $dispatcherEntityManagerInterface $entityManagerMissionParticipantRepository $missionParticipantRepositoryRouterInterface $routerPriceService $priceServiceWorkflowStepRepository $workflowStepRepository): RedirectResponse
  1359.     {
  1360.         $error false;
  1361.         if (!$this->missionService->canActivateMission(mission$mission)) {
  1362.             $error true;
  1363.             $this->addFlash(
  1364.                 type'error',
  1365.                 message'La mission n\'est pas activable pour le moment'
  1366.             );
  1367.             return $this->redirectToRoute('mission_index');
  1368.         }
  1369.         if (null === $mission->getWorkflow()) {
  1370.             $error true;
  1371.             $this->addFlash(
  1372.                 type'error',
  1373.                 message'La mission n\'a pas de workflow, merci de contacter l\'administrateur',
  1374.             );
  1375.             return $this->redirectToRoute('mission_index');
  1376.         }
  1377.         $campaign $mission->getCampaign();
  1378.         if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value) or $this->isGranted(Role::ROLE_ADMIN->value)) {
  1379.             $missionService->setDefaultValueIfAnUserClickedAnActivationButtonWithoutADelaisAndTimeIsEmpty($mission$priceService);
  1380.             if (empty($mission->getPreActivatedAt())) {
  1381.                 $mission->setPreActivatedAt(new \DateTime());
  1382.             }
  1383.             //////////////////// Check marge mission  
  1384.             $getMargeMyFlow $priceService->marginExceeded(mission$mission);
  1385.             if ($getMargeMyFlow['marginExceeded'] == true and $mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
  1386.                 if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
  1387.                     $error true;
  1388.                     $this->addFlash(
  1389.                         type'error',
  1390.                         message"Nous avons rencontré un problème, l'administrateur vient d'être informé pour activer la mission",
  1391.                     );
  1392.                     $event = new MissionCanActivateEvent(mission$mission);
  1393.                     $dispatcher->dispatch($eventMissionCanActivateEvent::NAME);
  1394.                     return $this->redirectToRoute('mission_index');
  1395.                 }
  1396.                 if ($this->isGranted(Role::ROLE_ADMIN->value)) {
  1397.                     $this->addFlash(
  1398.                         type'success',
  1399.                         message"La mission {$mission->getReference()} a bien activée",
  1400.                     );
  1401.                 }
  1402.             }
  1403.             ////////////////////////
  1404.             foreach ($mission->getParticipants() as $missionParticipation) {
  1405.                 if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
  1406.                     if ($this->getUser() == $missionParticipation->getUser()) {
  1407.                         // check marge Myflow
  1408.                         $missionParticipation->setActivated(true);
  1409.                         $missionParticipation->setActivatedAt(new \DateTime());
  1410.                         $this->missionService->addHistorique(mission$missionuser$this->getUser(), action"activation");
  1411.                         $entityManager->persist($missionParticipation);
  1412.                         $entityManager->flush();
  1413.                         break;
  1414.                     }
  1415.                 } elseif ($this->isGranted(Role::ROLE_ADMIN->value)) {
  1416.                     $missionParticipation->setActivated(true);
  1417.                     $missionParticipation->setActivatedAt(new \DateTime());
  1418.                     $entityManager->persist($missionParticipation);
  1419.                     $entityManager->flush();
  1420.                 }
  1421.             }
  1422.             if (sizeof($this->missionService->getListSubcontractorNotActivate(mission$mission)) == 0) {
  1423.                 if ($mission->getProduct()->getType() === ProductType::A_EVALUER) {
  1424.                     $client $mission->getCampaign()->getOrderedBy();
  1425.                     $event = new MissionActivatedEvent($mission$client);
  1426.                     $dispatcher->dispatch($eventMissionActivatedEvent::NAME);
  1427.                 }
  1428.                 if ($this->missionService->lackSubcontractorTest(mission$mission)) {
  1429.                     $event = new MissionNotificationActivatedEvent($mission);
  1430.                     $dispatcher->dispatch($eventMissionNotificationActivatedEvent::NAME);
  1431.                     $this->addFlash(
  1432.                         type'success',
  1433.                         message"La mission {$mission->getReference()} a bien activée",
  1434.                     );
  1435.                 } else {
  1436.                     $this->addFlash(
  1437.                         type'success',
  1438.                         message"Votre activation a bien été prise en compte.Nous devons toutefois attendre d'autres intervenants pour démarrer la mission. Vous serez prochainement notifié par Email.",
  1439.                     );
  1440.                 }
  1441.                 if ($mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
  1442.                     $clientSoldService->decreaseCurrentBalanceByMissionCost(mission$mission);
  1443.                 }
  1444.                 if ($error === false) {
  1445.                     $mission->setState('in_progress');
  1446.                     ////////////////////////////////
  1447.                     //////////////////////
  1448.                     $entityManager->flush();
  1449.                 }
  1450.             } else {
  1451.                 $this->addFlash(
  1452.                     type'success',
  1453.                     message"Votre activation a bien été prise en compte.Nous devons toutefois attendre la validation des autres intervenants pour démarrer la mission. Vous serez prochainement notifié par Email.",
  1454.                 );
  1455.             }
  1456.             //new validation for all subcontractor not activate 
  1457.             foreach ($this->campaignService->getListSubcontractorNotActivate(campaign$campaign) as $participant) {
  1458.                 $event = new MissionAcceptedEvent($mission$participant);
  1459.                 $dispatcher->dispatch($eventMissionAcceptedEvent::NAME);
  1460.             }
  1461.             if ($this->campaignService->isCanStart(campaign$campaign)) {
  1462.                 $campaign->setState('in_progress');
  1463.                 $campaign->setReSendToClient(false);
  1464.                 $campaign->setClientStatus("");
  1465.                 // --------------------------
  1466.                 $campaign->setReSendToClient(false);
  1467.                 foreach ($campaign->getMissions() as $mission) {
  1468.                     if (!empty($mission->getWorkflow())) {
  1469.                         //take a step first by position
  1470.                         $step $workflowStepRepository->getFirstStep($mission->getWorkflow());
  1471.                         $step->setActive(true);
  1472.                     } else {
  1473.                         $this->addFlash(
  1474.                             type'error',
  1475.                             message'Activation impossible car la campagne n\'a pas de workflow',
  1476.                         );
  1477.                         return $this->redirectToRoute('mission_index');
  1478.                     }
  1479.                     if ($step->getManager() == 0) {
  1480.                         $mission->setStateClient('Déclenchement en attente');
  1481.                     } else {
  1482.                         $mission->setStateProvider($step->getName());
  1483.                     }
  1484.                     $event = new WorkflowStepEnteredEvent($step);
  1485.                     $dispatcher->dispatch($eventWorkflowStepEnteredEvent::NAME);
  1486.                 }
  1487.                 // ---------------------------
  1488.                 $this->addFlash(
  1489.                     type'success',
  1490.                     message"La  campagne {$campaign->getName()} à démarrer  ",
  1491.                 );
  1492.                 $this->missionService->addHistorique(mission$missionuser$this->getUser(), action"activation");
  1493.             }
  1494.             //if error not persist
  1495.             if ($error === false) {
  1496.                 $entityManager->flush();
  1497.             }
  1498.         }
  1499.         return $this->redirectToRoute('mission_index');
  1500.     }
  1501.     #[Route('/mission/{id}/uncancelled'name"mission_uncancelled")]
  1502.     public function missionUncancelled(Mission $missionEntityManagerInterface $entityManagerInterface): Response
  1503.     {
  1504.         $mission->setState($mission->getLastState());
  1505.         $entityManagerInterface->flush();
  1506.         $this->addFlash(
  1507.             type'success',
  1508.             message"La mission reprend avec succès ",
  1509.         );
  1510.         return $this->redirectToRoute('mission_index');
  1511.     }
  1512.     #[Route('/mission/desired-delivery/{id}'name"mission_desired_delivery_change")]
  1513.     public function changeDesiredDelivery(Mission $mission,EventDispatcherInterface $dispatcherRequest $requestEntityManagerInterface $entityManager){
  1514.         
  1515.         $date $request->request->get('desired-delivery');
  1516.         $datetime = new DateTime($date);
  1517.         $mission->setDesiredDelivery($datetime);
  1518.         $entityManager->persist($mission);
  1519.         $entityManager->flush();
  1520.      
  1521.         $event = new MissionDesiredDeliveryUpdatedAfterValidationEvent($mission);
  1522.         $dispatcher->dispatch($eventMissionDesiredDeliveryUpdatedAfterValidationEvent::NAME);
  1523.         $this->missionService->addHistorique(mission$missionuser$this->getUser(), action"deadline_change");
  1524.         $this->addFlash('success','Nouvelle échéance enregistrée avec succès');
  1525.         return  $this->redirectToRoute('mission_edit',['id'=>$mission->getId()]) ; 
  1526.     }
  1527.    
  1528.     #[Route('/mission/file-history/{id}/{type}/{fileName}'name"file_history")]
  1529.     public function addFileHistory(Mission $mission,MissionService $missionService,string $type,  string $fileName){
  1530.         
  1531.         if($type=='save'){
  1532.             $bucket strtolower("company-".$mission->getCampaign()->getCompany()->getId());
  1533.             $missionService->addHistorique($mission$this->getUser(), 'save_file'$fileName) ;
  1534.         }
  1535.         elseif($type=="delete"){
  1536.             $missionService->addHistorique($mission$this->getUser(), 'delete_file'$fileName) ;
  1537.         }
  1538.         return  new JsonResponse([
  1539.             'status'=>'ok'
  1540.         ]) ;
  1541.     }
  1542.     #[Route('/mission/file-save/{id}/all'name"file_history_save_all")]
  1543.     public function saveFileHistory(Mission $mission,MissionService $missionService,){
  1544.         // $company = $mission->getCampaign()->getCompany();
  1545.         // $campaign = $mission->getCampaign();
  1546.         // $nameOfBucket = strtolower("company-".$company->getId());
  1547.         
  1548.         // $path = 'file_campaing_directory';
  1549.         // $pathMessage = "file_message_directory";
  1550.         // $backurl = 'back_website_url';
  1551.         // $destZip = $this->getParameter($path) . '/' . $mission->getCampaign()->getId()."/zip/";
  1552.         // $dest = $this->getParameter($path) . '/' . $mission->getCampaign()->getId().'/';
  1553.         // $destMessage = $this->getParameter($pathMessage)."/";
  1554.         // $destinationPath = $this->getParameter($path) . '/' . $mission->getCampaign()->getId()."/zip/";
  1555.         // $url = $this->getParameter($backurl) . '/uploads/campaign/' . $mission->getCampaign()->getId()."/zip/";
  1556.         // $zip = new \ZipArchive();
  1557.       
  1558.         // if (!is_dir($destinationPath)) {
  1559.         //     mkdir($destinationPath, 0777, true);
  1560.         // }
  1561.         // $cheminDestination = '/uploads/campaign/'.$mission->getCampaign()->getId()."/";
  1562.         // $cheminFichierZip = $destZip.$mission->getCampaign()->getId().".zip";
  1563.         //  //supprimer le fichier zip en premier
  1564.         // if(is_file($cheminFichierZip)){
  1565.         //     unlink($cheminFichierZip);
  1566.         // }
  1567.         // if ($zip->open($cheminFichierZip, \ZipArchive::CREATE) === true) {
  1568.         //     $listOfFiles = [];
  1569.         //     //list of file in campaing
  1570.         //     foreach ($campaign->getMessages() as $message) {
  1571.         //        foreach ($message->getFileMessages() as $file) {
  1572.         //             if ($file->isIsNew()) {
  1573.         //                 $year = $message->getCreatedAt()->format('Y');
  1574.         //                 $month = $message->getCreatedAt()->format('m');
  1575.         //                 $listOfFiles[] = "Campaigns/{$campaign->getId()}/{$file->getName()}";
  1576.         //             }
  1577.         //        }
  1578.         //     }
  1579.         //     foreach ($campaign->getFileMissions() as $file) {
  1580.         //         if ($file->isIsNew()) {
  1581.         //             $year = $file->getCreatedAt()->format('Y');
  1582.         //             $month = $file->getCreatedAt()->format('m');
  1583.         //              $listOfFiles[] = "Campaigns/{$campaign->getId()}/{$file->getName()}";
  1584.         //         }
  1585.         //     } 
  1586.         //    //end 
  1587.         //     $objects = $this->googleStorageService->getAllObject($nameOfBucket,$listOfFiles);
  1588.         //     foreach ($objects as $object) {
  1589.         //         $objectName = $object->name();
  1590.         //         if (in_array($objectName, $listOfFiles)) {
  1591.         //             $fileContent = $object->downloadAsString();
  1592.         //             $nameOfFile = explode("/", $object->name());
  1593.         //             $zip->addFromString($nameOfFile[2], $fileContent);
  1594.         //         }
  1595.         //     }
  1596.         //     //for the file of campaing
  1597.         //     foreach ($mission->getCampaign()->getFileMissions() as $file) {
  1598.         //         if (is_file($dest.$file->getName())) {
  1599.         //             $zip->addFile($dest.$file->getName(), $file->getName());
  1600.         //         }
  1601.         //     }
  1602.         //     //for the file of all messages
  1603.         //     $filesystem = new Filesystem();
  1604.         //     $fileAlredyZip = [];
  1605.         //     foreach ($campaign->getMessages() as $message) {
  1606.         //        foreach ($message->getFileMessages() as $file) {
  1607.         //             foreach ($mission->getCampaign()->getMissions() as $mission) {
  1608.         //                 $destination = "{$destMessage}{$mission->getId()}/message/{$file->getName()}";
  1609.         //                 if($filesystem->exists($destination) && !in_array($file->getName(), $fileAlredyZip)){
  1610.         //                     $zip->addFile($destination, $file->getName());
  1611.         //                     $fileAlredyZip[] = $file->getName();
  1612.         //                 }
  1613.         //             }
  1614.         //        }
  1615.         //     }
  1616.         //     $zip->close();
  1617.         // }
  1618.         return  new JsonResponse([
  1619.             'file'=> $this->googleStorageService->saveFileHistory($mission$missionService)
  1620.         ]) ;
  1621.     }
  1622.     #[Route('/mission/file-save-one/{id}'name"file_save")]
  1623.     public function donwloadFile(Mission $missionMissionService $missionService,GoogleStorageService $googleStorageService,Request $request){
  1624.         $url $request->request->get('url');
  1625.         $company $mission->getCampaign()->getCompany();
  1626.         $nameOfBucket strtolower("company-".$company->getId());
  1627.         return new JsonResponse($this->googleStorageService->getUrl($nameOfBucket,$url));
  1628.     }
  1629.     private function addLeadingSlashToImagePath($htmlContent) {
  1630.         // Use preg_replace to find image tags and modify the src attribute
  1631.         $pattern '/<img([^>]+)src="([^"]+)"([^>]+)>/';
  1632.         $replacement '<img$1src="/$2"$3>'// Add a slash at the beginning of the captured src attribute
  1633.         $newHtmlContent preg_replace($pattern$replacement$htmlContent);
  1634.         return $newHtmlContent;
  1635.     }
  1636.     #[Route('/update-active-tab'name"update_active_tab")]
  1637.     public function UpdateActiveTab(Request $request,EntityManagerInterface $entityManager) : JsonResponse
  1638.     {
  1639.         $missionActiveTab $request->request->get('mission-active-tab');
  1640.         $connectedUser $this->getUser();
  1641.         if($connectedUser->getUserData() == null) {
  1642.             $userData = new UserData();
  1643.             $userData->setMissionTabActive($missionActiveTab);           
  1644.         }else{
  1645.             $userData $connectedUser->getUserData();
  1646.             $userData->setMissionTabActive($missionActiveTab);
  1647.         }
  1648.         $entityManager->persist($userData);
  1649.         $connectedUser->setUserData($userData);
  1650.         $entityManager->persist($connectedUser);
  1651.         $entityManager->flush();
  1652.         return new JsonResponse('ok');
  1653.     }
  1654. }