src/Controller/API/MissionController.php line 52

Open in your IDE?
  1. <?php
  2. namespace App\Controller\API;
  3. use App\Entity\FileMessage;
  4. use App\Entity\FileMission;
  5. use App\Entity\Mission;
  6. use App\Entity\User;
  7. use App\Entity\MissionParticipant;
  8. use App\Enum\AdminMail;
  9. use App\Enum\Role;
  10. use App\Repository\MissionRepository;
  11. use App\Repository\UserRepository;
  12. use App\Service\CampaignApiService;
  13. use App\Service\DateService;
  14. use App\Service\MessageService;
  15. use FOS\RestBundle\Controller\Annotations as Rest;
  16. use FOS\RestBundle\Request\ParamFetcherInterface;
  17. use Nelmio\ApiDocBundle\Annotation\Model;
  18. use OpenApi\Attributes as OA;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use App\Event\SubContractor\SubContractorRequestEvaluateMissionEvent;
  21. use App\Repository\CampaignRepository;
  22. use App\Repository\FileMissionRepository;
  23. use App\Repository\MessageRepository;
  24. use App\Repository\MissionParticipantRepository;
  25. use App\Service\CampaignService;
  26. use App\Service\ConfidentialityService;
  27. use App\Service\MissionApiService;
  28. use App\Service\MissionParticipantService;
  29. use App\Service\MissionService;
  30. use App\Service\NotificationService;
  31. use App\Service\NumberFormatService;
  32. use App\Service\PriceService;
  33. use Doctrine\ORM\EntityManagerInterface;
  34. use App\Service\StepsService;
  35. use App\Service\UpcomingActionService;
  36. use App\Service\WorkflowStepService;
  37. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  38. use Symfony\Component\HttpFoundation\JsonResponse;
  39. use Symfony\Component\HttpFoundation\Request;
  40. use Symfony\Component\HttpFoundation\Response;
  41. use Symfony\Component\Mime\Address;
  42. use App\Service\WpMissionService;
  43. use App\Service\GoogleStorageService;
  44. use App\Service\DynamicHostService;
  45. use Twig\Environment;
  46. use Symfony\Component\HttpClient\HttpClient;
  47. #[OA\Tag(name'Missions')]
  48. class MissionController extends AbstractController
  49. {
  50.     
  51.     
  52.     public function __construct(
  53.         private WorkflowStepService $workflowStepService,
  54.         private GoogleStorageService $googleStorageService
  55.         private MissionParticipantService $missionParticipantService
  56.         private MessageRepository $messageRepository
  57.         private MissionService $missionService
  58.         private PriceService $priceService,
  59.         private MessageService $messageService
  60.         private MissionRepository $missionRepository
  61.         private CampaignApiService $campaignApiService
  62.         private DynamicHostService $dynamicHostService,
  63.         private FileMissionRepository $fileMissionRepository
  64.     ){
  65.     }
  66.         /**
  67.      * Get all the details about a mission
  68.      */
  69.     #[Rest\Get('/api/v2/missions/{id}/{numberPage}')]
  70.     #[Rest\View(serializerGroups: ['mission_read'])]
  71.     #[OA\Response(
  72.         response200,
  73.         description'Get all the details about a mission',
  74.         content: new OA\JsonContent(
  75.             type'array',
  76.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  77.         )
  78.     )]
  79.     #[OA\Response(
  80.         response401,
  81.         description'Unauthorized - the user isn\'t logged in',
  82.         content: new OA\JsonContent(
  83.             type'array',
  84.             items: new OA\Items(properties: [
  85.                 new OA\Property(property'code'type'integer'),
  86.                 new OA\Property(property'message'type'string'),
  87.             ], type'object')
  88.         )
  89.     )]
  90.     #[OA\Response(
  91.         response404,
  92.         description'The mission with id doesn\'t exists',
  93.     )]
  94.     public function getOne(Mission $mission,UpcomingActionService $upcomingActions,NumberFormatService $numberFormatServicePriceService $priceServiceMessageService $messageServiceDateService $dateService)
  95.     {   
  96.         $userSetPicture=[];
  97.  
  98.         $mission->setRemainDays($dateService->getDaysRemaining($mission->getDesiredDelivery()));
  99.         $mission->setPlanningAdditionalInformation($mission->canStart());
  100.         $mission->setCampaignAmountApi($numberFormatService->format($priceService->totalPriceCampaign($mission->getCampaign())));
  101.         $mission->setResponsable($this->workflowStepService->getResponsableStepByMission($mission));
  102.       
  103.         foreach ($mission->getCampaign()->getMessages() as $message) {
  104.                 
  105.                 foreach ($message->getFileMessages() as $fileMessage) {
  106.                     if($fileMessage->isIsNew()){
  107.                         $nameOfFileinBucket "Campaigns/{$mission->getCampaign()->getId()}/{$fileMessage->getName()}";
  108.                         $nameOfBucket "company-{$mission->getCampaign()->getCompany()->getId()}";
  109.                         $link $this->googleStorageService->getUrlBucketForApi(strtolower($nameOfBucket),$nameOfFileinBucket);
  110.                     }
  111.                     else{
  112.                         $link "{$this->getParameter('back_website_url')}/{$messageService->getFileMissionUrl($mission$fileMessage->getName())}";
  113.                     } 
  114.                     $fileMessage->setName("$link;=;{$fileMessage->getName()}");
  115.                 }
  116.         }
  117.         
  118.         return [ 
  119.                     'missions'=>$mission,
  120.                     'all_mission_of_campaign'=> $mission->getCampaign()->getMissionsWithoutEspaceDeDiscussion(),
  121.                     'upcoming_actions'=> $upcomingActions->get(mission$missionuser$this->getUser()),
  122.                     'step_active_responsable' => $this->workflowStepService->getIdResponsableStepActive($mission),
  123.                ];
  124.     }
  125.     #[Rest\GET('/api/v2/missions/confidentiality/{id}/{userId}'name'api_confidentialityContract')]
  126.     #[Rest\View(statusCodeResponse::HTTP_OK)]
  127.     public function getConfidentialityContract(Mission $mission,Environment $twigstring $userIdUserRepository $userRepository )
  128.     {  
  129.             $user $userRepository->findOneBy(['id'=>$userId]); 
  130.            
  131.             return new JsonResponse([
  132.                 'status'=>'success',
  133.                 'confidentiality'=> $twig->render('confidentiality/termApi.html.twig',[
  134.                     'company'=>$mission->getCampaign()->getCompany(), 
  135.                     'user'=>$user
  136.                     'prenom_nom_validateur'=> $this->getPrenomNomNalidateur($mission) , 
  137.                 ])
  138.             ]) ;
  139.     }
  140.     #[Rest\GET('/api/v2/link-file/{id}'name'api_link_file_message')]
  141.     #[Rest\View(statusCodeResponse::HTTP_OK)]
  142.     public function getFileLink(FileMessage $fileMessage){
  143.         
  144.         $campaign $fileMessage->getMessages()->getCampaign(); 
  145.         $campaignId $campaign->getId(); 
  146.         $companyId $campaign->getCompany()->getId(); 
  147.         if($fileMessage->isIsNew()){
  148.             $nameOfFileinBucket "Campaigns/$campaignId/{$fileMessage->getName()}";
  149.             $nameOfBucket "company-$companyId";
  150.             $link $this->googleStorageService->getUrlBucket(strtolower($nameOfBucket),$nameOfFileinBucket);;
  151.         }
  152.         else{
  153.             $link "{$this->getParameter('back_website_url')}/{$this->messageService->getFileMissionUrlByCampaign$campaign$fileMessage->getName())}";
  154.         } 
  155.      
  156.         return  new JsonResponse($link);
  157.     }
  158.             /**
  159.      * Get all the details about a mission
  160.      */
  161.     #[Rest\Get('/api/v2/mission/initialbrief/{id}')]
  162.     #[Rest\View(serializerGroups: ['mission_read'])]
  163.     #[OA\Response(
  164.         response200,
  165.         description'Get all the details about a mission',
  166.         content: new OA\JsonContent(
  167.             type'array',
  168.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  169.         )
  170.     )]
  171.     #[OA\Response(
  172.         response401,
  173.         description'Unauthorized - the user isn\'t logged in',
  174.         content: new OA\JsonContent(
  175.             type'array',
  176.         )
  177.     )]
  178.     #[OA\Response(
  179.         response404,
  180.         description'The mission with id doesn\'t exists',
  181.     )]
  182.     public function getInitialBrief(Mission $mission)
  183.     {   
  184.         $fileList = []; 
  185.         $incomesAndTimes = []; 
  186.         foreach ( $mission->getCampaign()->getFileMissions() as $file ) {
  187.             $nameOfFileinBucket "Campaigns/{$mission->getCampaign()->getId()}/{$file->getName()}";
  188.             $nameOfBucket "company-{$mission->getCampaign()->getCompany()->getId()}";
  189.             $fileList = [ ...$fileList
  190.                                 [
  191.                                     'link' => $this->googleStorageService->getUrlBucketForApi(strtolower($nameOfBucket),$nameOfFileinBucket), 
  192.                                     'name'=>$file->getName()
  193.                                 ]
  194.                         ] ;
  195.         }
  196.         
  197.         foreach ($mission->getCampaign()->getMissions() as $key => $mission) {
  198.             if(in_array('ROLE_SUBCONTRACTOR'$this->getUser()->getRoles()) && $this->missionService->isMyMission($mission)){
  199.                 $product =  $mission->getProduct(); 
  200.                 $priceAndTime =  $this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_CLIENT') ? 
  201.                                  $this->priceService->priceAndTimeMissionBasedOnPriceSale($mission) :
  202.                                  $this->priceService->priceAndTimeMissionSubcontractorById($mission,$this->getUser()->getId());
  203.     
  204.                 $price =   floatval($priceAndTime['price']);
  205.                 $time floatval($priceAndTime['time']);
  206.                 $participant $this->missionParticipantService->getParticipantByUser($mission$this->getUser()); 
  207.                 $incomesAndTimes = [
  208.                     ...$incomesAndTimes,
  209.                     [
  210.                         'mission_id'=>  $mission->getId(),
  211.                         'product'=> [
  212.                             'name' => $product->getName(),
  213.                             'type' => $product->getType()->value,
  214.                         ],
  215.                         'income'=> $price,
  216.                         'time' => $time
  217.                         'participant'=> $participant,
  218.                     ]
  219.                 ]; 
  220.             }
  221.         }
  222.         return [
  223.                     'initial_brief' => $mission->getCampaign()->getBrief(),
  224.                     'missions' => $incomesAndTimes
  225.                     'file_list'=>$fileList
  226.             ];
  227.     }
  228.     #[Rest\Get('/api/v2/mission/google-storage/{id}')]
  229.     #[Rest\View(serializerGroups: ['mission_read'])]
  230.     #[OA\Response(
  231.         response200,
  232.         description'Get all the details about a mission',
  233.         content: new OA\JsonContent(
  234.             type'array',
  235.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  236.         )
  237.     )]
  238.     #[OA\Response(
  239.         response401,
  240.         description'Unauthorized - the user isn\'t logged in',
  241.         content: new OA\JsonContent(
  242.             type'array',
  243.         )
  244.     )]
  245.     #[OA\Response(
  246.         response404,
  247.         description'The mission with id doesn\'t exists',
  248.     )]
  249.     public function getFileInGoogleStorage(Mission $mission)
  250.     {   
  251.         $allMissionId = [];
  252.         $campaign $mission->getCampaign(); 
  253.         foreach ($campaign->getMissions() as $key => $mission) {
  254.             $allMissionId[] = $mission->getId();
  255.         }
  256.         $allMessageContent $this->messageRepository->findMessagesContent($campaign$this->getUser());
  257.         $allMessageContentGroup $this->messageRepository->findMessagesContentGroup($campaign,$this->getUser());
  258.         $allMessageWithLink = [];
  259.         $allMessageWithLinkGroup = [];
  260.         $links = [];
  261.         //get all link in message
  262.         foreach ($allMessageContent as $message) {
  263.             $dom = new \DOMDocument();
  264.             @$dom->loadHTML($message['content']);
  265.             $anchors $dom->getElementsByTagName('a');
  266.             foreach ($anchors as $anchor) {
  267.                 $links $anchor->getAttribute('href');
  268.                 $message['linkInMessage'] = $links;
  269.                 $message['linkInMessageShort'] = mb_substr($links040)."...";
  270.                 $allMessageWithLink = [...$allMessageWithLink,$message];
  271.             }
  272.            
  273.         }
  274.         //get all link in message Group
  275.         foreach ($allMessageContentGroup as $messageGroup) {
  276.             $dom = new \DOMDocument();
  277.             if (!empty($messageGroup['content']) and $messageGroup['content'] != null) {
  278.                 @$dom->loadHTML($messageGroup['content']);
  279.                 $anchors $dom->getElementsByTagName('a');
  280.                 foreach ($anchors as $anchor) {
  281.                     $links $anchor->getAttribute('href');
  282.                     $messageGroup['linkInMessage'] = $links;
  283.                     $messageGroup['linkInMessageShort'] = mb_substr($links040)."...";
  284.                     $allMessageWithLinkGroup = [...$allMessageWithLinkGroup,$messageGroup];
  285.                 }
  286.             }
  287.         }
  288.         $allMessages $this->messageRepository->allMessageHaveFile($campaign$this->getUser());
  289.         $allMessagesGroup $this->messageRepository->allMessageHaveFileGroup($campaign,$this->getUser());
  290.         $allJointes  $this->fileMissionRepository->allFile($campaign,$allMissionId);
  291.         $allFiles $this->addLinkStorage(array_merge($allMessageWithLinkGroup,$allMessageWithLink,$allMessages,$allMessagesGroup$allJointes)) ;
  292.         usort($allFiles, function($a,$b){
  293.             return $b['createdAt'] <=> $a['createdAt'];
  294.         });
  295.         return [ 'all_file' => $allFiles ];
  296.                     
  297.     }
  298.     #[Rest\Get('/api/v6/mission/google-storage/download-all-file/{id}')]
  299.     #[Rest\View(serializerGroups: ['mission_read'])]
  300.     #[OA\Response(
  301.         response200,
  302.         description'Get all the details about a mission',
  303.         content: new OA\JsonContent(
  304.             type'array',
  305.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  306.         )
  307.     )]
  308.     #[OA\Response(
  309.         response401,
  310.         description'Unauthorized - the user isn\'t logged in',
  311.         content: new OA\JsonContent(
  312.             type'array',
  313.         )
  314.     )]
  315.     #[OA\Response(
  316.         response404,
  317.         description'The mission with id doesn\'t exists',
  318.     )]
  319.     public function getAllFileAsZip(Mission $mission)
  320.     {   
  321.        
  322.         $fileUrl =  $this->googleStorageService->saveFileHistory($mission$this->missionService);
  323.         $client HttpClient::create();
  324.         $response $client->request('GET'$fileUrl);
  325.         // Vérifier le statut de la réponse
  326.         if ($response->getStatusCode() !== 200) {
  327.             throw $this->createNotFoundException('L\'image n\'a pas pu être téléchargée.');
  328.         }
  329.        
  330.         // Obtenir le contenu de l'image
  331.         $imageContent $response->getContent();
  332.         // Déterminer le type de contenu
  333.         $contentType $response->getHeaders()['content-type'][0] ?? 'application/octet-stream';
  334.         // Déterminer le nom du fichier
  335.         $filename basename(parse_url($fileUrlPHP_URL_PATH));
  336.         // Créer la réponse pour le téléchargement
  337.         return new Response(
  338.             $imageContent,
  339.             Response::HTTP_OK,
  340.             [
  341.                 'Content-Description' => 'File Transfer',
  342.                 'Content-Type' => $contentType,
  343.                 'Content-Disposition' => 'attachment; filename="' $filename '"',
  344.                 'Content-Length' => strlen($imageContent),
  345.             ]
  346.         );              
  347.     }
  348.     
  349.     #[Rest\Get('/api/v6/mission/_google-storage/download-one-file')]
  350.     #[Rest\View(serializerGroups: ['mission_read'])]
  351.     #[OA\Response(
  352.         response200,
  353.         description'Get all the details about a mission',
  354.         content: new OA\JsonContent(
  355.             type'array',
  356.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  357.         )
  358.     )]
  359.     #[OA\Response(
  360.         response401,
  361.         description'Unauthorized - the user isn\'t logged in',
  362.         content: new OA\JsonContent(
  363.             type'array',
  364.         )
  365.     )]
  366.     #[OA\Response(
  367.         response404,
  368.         description'The mission with id doesn\'t exists',
  369.     )]
  370.     public function downloadOneFile(Request $request)
  371.     {  
  372.         $url $request->query->get('url');
  373.         $Expires urlencode($request->query->get('Expires'));
  374.         $Signature urlencode($request->query->get('Signature'));
  375.         
  376.         // dd( $url);
  377.         $fileUrl =  "$url&Expires=$Expires&Signature=$Signature"
  378.   
  379.         // Vérifier que l'URL est présente
  380.         if (!$fileUrl) {
  381.             throw $this->createNotFoundException('URL de fichier non fournie.');
  382.         }
  383.         // Utiliser HttpClient pour obtenir l'image
  384.         $client HttpClient::create();
  385.         $response $client->request('GET'$fileUrl);
  386.         // Vérifier le statut de la réponse
  387.         if ($response->getStatusCode() !== 200) {
  388.             throw $this->createNotFoundException('L\'image n\'a pas pu être téléchargée.');
  389.         }
  390.         // Obtenir le contenu de l'image
  391.         $imageContent $response->getContent();
  392.         // Déterminer le type de contenu
  393.         $contentType $response->getHeaders()['content-type'][0] ?? 'application/octet-stream';
  394.         // Déterminer le nom du fichier
  395.         $filename basename(parse_url($fileUrlPHP_URL_PATH));
  396.         // Créer la réponse pour le téléchargement
  397.         return new Response(
  398.             $imageContent,
  399.             Response::HTTP_OK,
  400.             [
  401.                 'Content-Description' => 'File Transfer',
  402.                 'Content-Type' => $contentType,
  403.                 'Content-Disposition' => 'attachment; filename="' $filename '"',
  404.                 'Content-Length' => strlen($imageContent),
  405.             ]
  406.         );
  407.     }
  408.     #[Rest\Get('/api/v6/mission/_google-storage/download-one-file-custom')]
  409.     #[Rest\View(serializerGroups: ['mission_read'])]
  410.     #[OA\Response(
  411.         response200,
  412.         description'Get all the details about a mission',
  413.         content: new OA\JsonContent(
  414.             type'array',
  415.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  416.         )
  417.     )]
  418.     #[OA\Response(
  419.         response401,
  420.         description'Unauthorized - the user isn\'t logged in',
  421.         content: new OA\JsonContent(
  422.             type'array',
  423.         )
  424.     )]
  425.     #[OA\Response(
  426.         response404,
  427.         description'The mission with id doesn\'t exists',
  428.     )]
  429.     public function downloadOneFileCustom(Request $request): Response|JsonResponse
  430.     {  
  431.         $url $request->query->get('url');
  432.         $Expires urlencode($request->query->get('Expires'));
  433.         $Signature urlencode($request->query->get('Signature'));
  434.  
  435.         $fileUrl "$url&Expires=$Expires&Signature=$Signature"
  436.         
  437.         // Vérifier que l'URL est présente
  438.         if (!$fileUrl) {
  439.             throw $this->createNotFoundException('URL de fichier non fournie.');
  440.         }
  441.         // Utiliser HttpClient pour obtenir l'image
  442.         $client HttpClient::create();
  443.         $response $client->request('GET'$fileUrl);
  444.         // Vérifier le statut de la réponse
  445.         if ($response->getStatusCode() !== 200) {
  446.             throw $this->createNotFoundException('L\'image n\'a pas pu être téléchargée.');
  447.         }
  448.         // Obtenir le contenu de l'image
  449.         $imageContent $response->getContent();
  450.         // Déterminer le type de contenu
  451.         $contentType $response->getHeaders()['content-type'][0] ?? 'application/octet-stream';
  452.         // Déterminer le nom du fichier
  453.         $filename basename(parse_url($fileUrlPHP_URL_PATH));
  454.         // Créer la réponse pour le téléchargement
  455.         return new Response(
  456.             $imageContent,
  457.             Response::HTTP_OK,
  458.             [
  459.                 'Content-Description' => 'File Transfer',
  460.                 'Content-Type' => $contentType,
  461.                 'Content-Disposition' => 'attachment; filename="' $filename '"',
  462.                 'Content-Length' => strlen($imageContent),
  463.             ]
  464.         );
  465.     }
  466.     #[Rest\Post('/api/v2/mission/fileHistory/{id}/{fileName}/{fileId}/{action}')]
  467.     #[Rest\View(serializerGroups: ['mission_read'])]
  468.     #[OA\Response(
  469.         response200,
  470.         description'Get all the details about a mission',
  471.         content: new OA\JsonContent(
  472.             type'array',
  473.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  474.         )
  475.     )]
  476.     #[OA\Response(
  477.         response401,
  478.         description'Unauthorized - the user isn\'t logged in',
  479.         content: new OA\JsonContent(
  480.             type'array',
  481.         )
  482.     )]
  483.     #[OA\Response(
  484.         response404,
  485.         description'The mission with id doesn\'t exists',
  486.     )]
  487.     public function addFileHistory(Mission $mission$fileName,$fileId$action)
  488.     {   
  489.         
  490.         $this->missionService->addHistorique($mission$this->getUser(), $action$fileName) ;
  491.         return [ 'status' => 'ok'];
  492.     }
  493.     /**
  494.      * List all the missions for the authenticated user
  495.      *
  496.      * @param MissionRepository $missionRepository
  497.      * @param ParamFetcherInterface $paramFetcher
  498.      * @return \App\Entity\Mission[]|float|int|mixed|string
  499.      */
  500.     #[Rest\Get('/api/v2/missions/{page}/{loadMore}/{query}')]
  501.     #[Rest\View(serializerGroups: ['mission_list'])]
  502.     #[Rest\QueryParam(
  503.         name'archived',
  504.         requirements'\d',
  505.         default: 0,
  506.         description'Filter the results to show only the archived or cancelled missions. Only accepts 0 (shows missions in progress) or 1 (shows archived missions).'
  507.     )]
  508.     #[OA\Response(
  509.         response200,
  510.         description'Returns all the missions for the authenticated user',
  511.         content: new OA\JsonContent(
  512.             type'array',
  513.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_list']))
  514.         )
  515.     )]
  516.     #[OA\Response(
  517.         response401,
  518.         description'Unauthorized - the user isn\'t logged in',
  519.         content: new OA\JsonContent(
  520.             type'array',
  521.             items: new OA\Items(properties: [
  522.                 new OA\Property(property'code'type'integer'),
  523.                 new OA\Property(property'message'type'string'),
  524.             ], type'object')
  525.         )
  526.     )]
  527.     public function getMissions(MissionRepository $missionRepository,ConfidentialityService $confidentialityService,  MissionApiService $missionApiService,  EntityManagerInterface $entityManagerWpMissionService $wpMissionServiceNumberFormatService $numberFormatServicePriceService $priceServiceCampaignService $campaignService,CampaignRepository $campaignRepository,  MessageService $messageService,  ParamFetcherInterface $paramFetcher,string $loadMore="0"string $page "1"string $query ="")
  528.     {
  529.         if ($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_ADMIN_AGENCY') ||  $this->isGranted('ROLE_MANAGER')) {
  530.             
  531.              $company =  $this->dynamicHostService->getCompany() ; 
  532.              $curentUser $this->getUser();
  533.              if (!is_null($curentUser) and !is_null($curentUser?->getRoles()) and in_array('ROLE_MANAGER'$curentUser?->getRoles())) {
  534.                 $company $curentUser?->getCompany();
  535.              }
  536.              $missions $missionRepository->findMissionsFor(Role::ROLE_ADMIN$this->getUser(), $paramFetcher->get('archived') == 0$query,  $company);
  537.         } elseif ($this->isGranted('ROLE_CLIENT')) {
  538.             $missions $missionRepository->findMissionsFor(Role::ROLE_CLIENT$this->getUser(), $paramFetcher->get('archived') == 0,$query);
  539.         }
  540.         else{
  541.             $missions $missionRepository->findMissionsFor(Role::ROLE_SUBCONTRACTOR$this->getUser(), $paramFetcher->get('archived') == 0,$query);
  542.         }
  543.         // $limit = 10; 
  544.         // $offset = $loadMore == "0" ? 0 : ($page - 1) * $limit;
  545.         $page $page == $page
  546.         $offset 0
  547.         $limit $page*10
  548.         $totalItems count($missions);
  549.         $totalPages ceil($totalItems $limit);
  550.         $paginatedMission array_slice($missions$offset$limit);
  551.         foreach ($paginatedMission as $key => $mission) {
  552.             $mission->setMessageUnreadApi($messageService->getNumberAllMessageUnread($mission));
  553.             $mission->setCanActivateApi($this->isGranted('ROLE_SUBCONTRACTOR') && $campaignService->canActivateCampaign($mission->getCampaign())&& !in_array($mission->getCampaign()->getState(),["resend","waiting_validation","closed""archived""deleted","finalized"]));
  554.             $mission->setCanValidateApi($mission->getCampaign()->getState() == "waiting_validation" && ($this->isGranted('ROLE_ADMIN') || ($this->isGranted('ROLE_CLIENT') && !$campaignService->isExternalParticipant($mission->getCampaign(), $this->getUser()) )));
  555.             $mission->setCampaignAmountApi($numberFormatService->format($priceService->totalPriceCampaign($mission->getCampaign())));
  556.             if($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_CLIENT')){
  557.                 $priceAndTime $priceService->priceAndTimeMissionBasedOnPriceSale($mission);
  558.                 $price =  floatval($priceAndTime['price']) ; 
  559.                 $time floatval($priceAndTime['time']);
  560.             }else{
  561.                 $priceAndTime =  $priceService->priceAndTimeMissionSubcontractorById($mission,$this->getUser()->getId());
  562.                 $price =   floatval($priceAndTime['price']);
  563.                 $time floatval($priceAndTime['time']);
  564.             }
  565.             $mission->setPriceApi($price);
  566.             $stepActive $this->workflowStepService->getStepActive($mission);
  567.             $mission->setResponsable($this->workflowStepService->getResponsableStepByMission($missionfalse$stepActive ));
  568.             $mission->setTimeApi($time);
  569.             $mission->setConfidential($mission->getCampaign()->getConfidentiality()!=null $mission->getCampaign()->getConfidentiality() : false); 
  570.             $mission->setAlreadyAcceptConfidentialityContract($confidentialityService->canShowConfidentialCampaign($this->getUser(), $mission->getCampaign())); 
  571.             $mission->setCampaignStateApi([
  572.                     ...$missionApiService->getCampaignState($mission->getCampaign()),
  573.                     ...[
  574.                             'isAlreadyStart'=> $mission->getCampaign()->isAlreadyStart(),
  575.                             'state'=> $mission->getCampaign()->getState()
  576.                     ]
  577.         ]);
  578.         }
  579.         
  580.         
  581.         return [
  582.             'success' => true
  583.             'totalPage'=> $totalPages,
  584.             'data'=>$paginatedMission
  585.         ];
  586.     }
  587.     /**
  588.      * Send email for subcontractor not evaluate a mission
  589.      */
  590.     #[Rest\POST('/api/v2/mission/subcontrator/notify/{id}')]
  591.     #[Rest\View(serializerGroups: ['mission_read'])]
  592.     #[OA\Response(
  593.         response200,
  594.         description'Send email for subcontractor not evaluate a mission',
  595.         content: new OA\JsonContent(
  596.             type'array',
  597.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  598.         )
  599.     )]
  600.     #[OA\Response(
  601.         response401,
  602.         description'Unauthorized - the user isn\'t logged in',
  603.         content: new OA\JsonContent(
  604.             type'array',
  605.             items: new OA\Items(properties: [
  606.                 new OA\Property(property'code'type'integer'),
  607.                 new OA\Property(property'message'type'string'),
  608.             ], type'object')
  609.         )
  610.     )]
  611.     #[OA\Response(
  612.         response404,
  613.         description'The mission with id doesn\'t exists',
  614.     )]
  615.     public function sendEmailForSubcontractor(Mission $mission,EventDispatcherInterface $dispatcher)
  616.     {   
  617.         $event = new SubContractorRequestEvaluateMissionEvent($mission);
  618.         $dispatcher->dispatch($eventSubContractorRequestEvaluateMissionEvent::NAME);
  619.         return new JsonResponse([
  620.             'status'=>'ok'
  621.         ]);
  622.     }
  623.     #[Rest\Post('/api/v2/mission/subcontractor-cancelled-evaluation/{id}'name'subcontractor_cancelled_evaluation')]
  624.     #[Rest\View(statusCodeResponse::HTTP_OK)]
  625.     public function sendEmailSubcontractorEvaluateByNotValidate(NotificationService $notificationServiceMission $mission){
  626.         $emails $this->dynamicHostService->getMailAdmin();
  627.         foreach ($emails as  $email) {
  628.             $notificationService->sendEmail(
  629.                 new Address('caroline.b@my-flow.fr','myFlow'),
  630.                 new Address($email->value),
  631.                 'mission  évaluée mais pas resoumise',
  632.                 "La mission ref: {$mission->getReference()} - {$mission->getProduct()->getName()} a été évaluée mais n 'a pas été resoumise au client par {$this->getUser()->getFullName()}"
  633.             ) ;
  634.         }
  635.         
  636.         return new JsonResponse([
  637.             'status'=>'ok'
  638.         ]);
  639.     }
  640.     #[Rest\Post('/api/v2/mission/subcontractor-validated-evaluation'name'estimated_income_subcontractor')]
  641.     #[Rest\View(statusCodeResponse::HTTP_OK)]
  642.     public function estimatedIncomeSubcontractor(MissionParticipantRepository $missionParticipantRepositoryCampaignService $campaignService,MissionApiService $missionApiServiceMissionService $missionServicePriceService $priceServiceMissionParticipantService $missionParticipantServiceRequest $request){
  643.         $request$request->request->All();
  644.         
  645.         $datas =  $request['data'] ;
  646.         foreach ($datas as $key => $data) {
  647.             $missionParticipant $missionParticipantRepository->findOneBy(['id'=>$data['participant']['id']]);
  648.             $mission $missionParticipant->getMission();
  649.             $income $data['income'];
  650.             $time $data['time'];
  651.             $missionParticipantService->setEstimatedIncomeSubcontractor($campaignService,$missionService,$priceService,$missionParticipant,$income$time);
  652.             
  653.         }
  654.         if($mission){
  655.             if($mission->getCampaign()->getState()=='closing_in_progress' &&  sizeof($this->campaignApiService->getSubcontractorNoEstimatedIncome($mission->getCampaign())) == 0){
  656.                 $this->campaignApiService->closedCampaign($mission->getCampaign());
  657.             }
  658.         }
  659.         return new JsonResponse([
  660.             'status'=>'ok',
  661.              'datas'=> $datas
  662.             // 'state'=>$missionApiService->getCampaignStateHtml($mission->getCampaign())
  663.         ]);
  664.     }
  665.     #[Rest\Get('/api/v2/mission/actions/{id}'name'actions')]
  666.     #[Rest\View(serializerGroups: ['mission_read'], statusCodeResponse::HTTP_OK)]
  667.     public function actions(Mission $mission){
  668.        
  669.         $fileList = []; 
  670.         $incomesAndTimes = []; 
  671.        
  672.         if(in_array('ROLE_SUBCONTRACTOR'$this->getUser()->getRoles())) {
  673.             foreach ($mission->getCampaign()->getMissions() as $key => $mission) {
  674.                 if($this->missionService->isMyMission($mission) && $this->missionService->subcontractorCanEvaluate($mission$this->getUser())){
  675.                     $evaluationInformation null
  676.                     $product =  $mission->getProduct(); 
  677.                     $priceAndTime =  $this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_CLIENT') ? 
  678.                                      $this->priceService->priceAndTimeMissionBasedOnPriceSale($mission) :
  679.                                      $this->priceService->priceAndTimeMissionSubcontractorById($mission,$this->getUser()->getId());
  680.         
  681.                     $price =   floatval($priceAndTime['price']);
  682.                     $time floatval($priceAndTime['time']);
  683.     
  684.                     $participants $this->missionParticipantService->getParticipantByUser($mission$this->getUser(), true);
  685.                     $jobsForParticipant $this->missionParticipantService->getJobsForParticipant($mission$this->getUser());
  686.                     $sizeofParticipant $participants!= null sizeof($participants) : ;  
  687.                     $sizeofjobsForParticipant $jobsForParticipant!= null sizeof($jobsForParticipant) : ;  
  688.                     
  689.                     $roles $sizeofjobsForParticipant ?  implode(','$jobsForParticipant) : '';
  690.                     $evaluationInformation =  $sizeofjobsForParticipant "Vous avez plusieurs rôles sur cette mission. Veuillez renseigner un temps ou un budget pour les rôle de [{$roles}]." null
  691.                     $participant $sizeofParticipant ?  $participants[0] : null 
  692.                    
  693.                     $incomesAndTimes = [
  694.                         ...$incomesAndTimes,
  695.                         [
  696.                             'mission_id'=>  $mission->getId(),
  697.                             'product'=> [
  698.                                 'name' => $product->getName(),
  699.                                 'type' => $product->getType()->value,
  700.                             ],
  701.                             'income'=> $price,
  702.                             'time' => $time
  703.                             'participant'=> [
  704.                                 'id'=> $participant!=null ?  $participant->getId() : null
  705.                             ],
  706.                             'evaluationInformation'=> $evaluationInformation
  707.                         ]
  708.                     ]; 
  709.                 }
  710.             }
  711.         }
  712.  
  713.        return new JsonResponse([
  714.             'status'=>'ok',
  715.             'incomesAndTimes'=> $incomesAndTimes
  716.             // 'state'=>$missionApiService->getCampaignStateHtml($mission->getCampaign())
  717.         ]);
  718.     }
  719.     #[Rest\Post('/api/v2/mission/delete-file-mission/{id}'name'delete-file-mission')]
  720.     #[Rest\View(statusCodeResponse::HTTP_OK)]
  721.     #[Route('/mission/delete-file-mission/{id}'name'delete-file-mission-desktop')]
  722.     public function deleteFileMission(FileMission $fileMissionEntityManagerInterface $entityManagerInterface,FileMissionRepository $fileMissionRepository,Request $request,GoogleStorageService $googleStorageService)
  723.     {  
  724.         $campaign $fileMission->getCampaign();
  725.         $fileMissionCampain $fileMissionRepository->findOneBy(['name'=>$fileMission->getName(),'campaign'=>$campaign]);
  726.         $bucketName "company-".strtolower($campaign->getCompany()->getId());
  727.         $fileName "Campaigns/".$campaign->getId()."/".$fileMissionCampain->getName();
  728.     
  729.              try {
  730.                 unlink('uploads/campaign/'.$fileMission->getMission()->getCampaign()->getId().'/'.$fileMission->getName());
  731.              } catch (\Throwable $th) {
  732.              }
  733.             if (!is_null($fileMissionCampain)) {
  734.                 $campaign->removeFileMission($fileMissionCampain);
  735.                 $entityManagerInterface->remove($fileMissionCampain);
  736.             }
  737.             $entityManagerInterface->remove($fileMission);
  738.             $entityManagerInterface->flush();
  739.              $this->addFlash(
  740.                  type'success',
  741.                  message'le fichier joint au message est supprimée'
  742.             );
  743.             $googleStorageService->deleteFile($bucketName,$fileName);
  744.         
  745.             return new JsonResponse([
  746.                 'status'=>'success'
  747.             ]) ;
  748.     }
  749.     private function getPrenomNomNalidateur(Mission $mission){
  750.           foreach ($mission->getParticipants() as $participant) {
  751.                 if($participant->getRole()->value=='ROLE_VALIDATOR'){
  752.                     return $participant->getUser()->getFullName();
  753.                 }
  754.           }
  755.           
  756.           return '--'
  757.     }
  758.     private function getParticipantByUser(Mission $mission,User $user){
  759.         $participant null;
  760.         
  761.         foreach ($mission->getParticipants() as $key => $participant) {
  762.              if($participant->getUser() == $user){
  763.                 return $participant;
  764.              }
  765.         }
  766.         return $participant;
  767.     }
  768.     private function addLinkStorage(array $files){
  769.         $urlDomaine  ""
  770.         $fileWithLink = [];
  771.        
  772.         foreach ($files as $key => $file) {
  773.             $link "" ;
  774.             if($file['linkInMessage'] == 0){
  775.                 if($file['isNew'] == 1){
  776.                     $nameOfFileinBucket "Campaigns/{$file['idCampaing']}/{$file['name']}";
  777.                     $nameOfBucket "company-{$file['idCompany']}";
  778.                     $link $this->googleStorageService->getUrlBucketForApi(strtolower($nameOfBucket),$nameOfFileinBucket) ;
  779.                 }else{
  780.                      if ( $file['isBrief'] == ){
  781.                             $mission =$this->missionRepository->find($file['idMission']);
  782.                             $fileUrl $this->messageService->getFileMissionUrl($mission$file['name']); 
  783.                             $link "$urlDomaine$fileUrl";
  784.                         }
  785.                     else{
  786.                         $link "$urlDomaine/uploads/campaign/{$file['idCampaing']}/{$file['name']};
  787.                     }
  788.                 }
  789.             }else{
  790.                 $link $file['linkInMessage'];
  791.             }
  792.             $fileWithLink = [...$fileWithLink,[...$file'linkStorage'=> $link]];
  793.         }
  794.         return $fileWithLink
  795.     }
  796.     
  797. }