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.                     $messageGroup['size'] = 
  285.                     $allMessageWithLinkGroup = [...$allMessageWithLinkGroup,$messageGroup];
  286.                 }
  287.             }
  288.         }
  289.         $allMessages $this->messageRepository->allMessageHaveFile($campaign$this->getUser());
  290.         $allMessagesGroup $this->messageRepository->allMessageHaveFileGroup($campaign,$this->getUser());
  291.         $allJointes  $this->fileMissionRepository->allFile($campaign,$allMissionId);
  292.         $allFiles $this->addLinkStorage(array_merge($allMessageWithLinkGroup,$allMessageWithLink,$allMessages,$allMessagesGroup$allJointes)) ;
  293.         usort($allFiles, function($a,$b){
  294.             return $b['createdAt'] <=> $a['createdAt'];
  295.         });
  296.         return [ 'all_file' => $allFiles ];
  297.                     
  298.     }
  299.     #[Rest\Get('/api/v6/mission/google-storage/download-all-file/{id}')]
  300.     #[Rest\View(serializerGroups: ['mission_read'])]
  301.     #[OA\Response(
  302.         response200,
  303.         description'Get all the details about a mission',
  304.         content: new OA\JsonContent(
  305.             type'array',
  306.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  307.         )
  308.     )]
  309.     #[OA\Response(
  310.         response401,
  311.         description'Unauthorized - the user isn\'t logged in',
  312.         content: new OA\JsonContent(
  313.             type'array',
  314.         )
  315.     )]
  316.     #[OA\Response(
  317.         response404,
  318.         description'The mission with id doesn\'t exists',
  319.     )]
  320.     public function getAllFileAsZip(Mission $mission)
  321.     {   
  322.        
  323.         $fileUrl =  $this->googleStorageService->saveFileHistory($mission$this->missionService);
  324.         $client HttpClient::create();
  325.         $response $client->request('GET'$fileUrl);
  326.         // Vérifier le statut de la réponse
  327.         if ($response->getStatusCode() !== 200) {
  328.             throw $this->createNotFoundException('L\'image n\'a pas pu être téléchargée.');
  329.         }
  330.        
  331.         // Obtenir le contenu de l'image
  332.         $imageContent $response->getContent();
  333.         // Déterminer le type de contenu
  334.         $contentType $response->getHeaders()['content-type'][0] ?? 'application/octet-stream';
  335.         // Déterminer le nom du fichier
  336.         $filename basename(parse_url($fileUrlPHP_URL_PATH));
  337.         // Créer la réponse pour le téléchargement
  338.         return new Response(
  339.             $imageContent,
  340.             Response::HTTP_OK,
  341.             [
  342.                 'Content-Description' => 'File Transfer',
  343.                 'Content-Type' => $contentType,
  344.                 'Content-Disposition' => 'attachment; filename="' $filename '"',
  345.                 'Content-Length' => strlen($imageContent),
  346.             ]
  347.         );              
  348.     }
  349.     
  350.     #[Rest\Get('/api/v6/mission/_google-storage/download-one-file')]
  351.     #[Rest\View(serializerGroups: ['mission_read'])]
  352.     #[OA\Response(
  353.         response200,
  354.         description'Get all the details about a mission',
  355.         content: new OA\JsonContent(
  356.             type'array',
  357.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  358.         )
  359.     )]
  360.     #[OA\Response(
  361.         response401,
  362.         description'Unauthorized - the user isn\'t logged in',
  363.         content: new OA\JsonContent(
  364.             type'array',
  365.         )
  366.     )]
  367.     #[OA\Response(
  368.         response404,
  369.         description'The mission with id doesn\'t exists',
  370.     )]
  371.     public function downloadOneFile(Request $request)
  372.     {  
  373.         $url $request->query->get('url');
  374.         $Expires urlencode($request->query->get('Expires'));
  375.         $Signature urlencode($request->query->get('Signature'));
  376.         
  377.         // dd( $url);
  378.         $fileUrl =  "$url&Expires=$Expires&Signature=$Signature"
  379.   
  380.         // Vérifier que l'URL est présente
  381.         if (!$fileUrl) {
  382.             throw $this->createNotFoundException('URL de fichier non fournie.');
  383.         }
  384.         // Utiliser HttpClient pour obtenir l'image
  385.         $client HttpClient::create();
  386.         $response $client->request('GET'$fileUrl);
  387.         // Vérifier le statut de la réponse
  388.         if ($response->getStatusCode() !== 200) {
  389.             throw $this->createNotFoundException('L\'image n\'a pas pu être téléchargée.');
  390.         }
  391.         // Obtenir le contenu de l'image
  392.         $imageContent $response->getContent();
  393.         // Déterminer le type de contenu
  394.         $contentType $response->getHeaders()['content-type'][0] ?? 'application/octet-stream';
  395.         // Déterminer le nom du fichier
  396.         $filename basename(parse_url($fileUrlPHP_URL_PATH));
  397.         // Créer la réponse pour le téléchargement
  398.         return new Response(
  399.             $imageContent,
  400.             Response::HTTP_OK,
  401.             [
  402.                 'Content-Description' => 'File Transfer',
  403.                 'Content-Type' => $contentType,
  404.                 'Content-Disposition' => 'attachment; filename="' $filename '"',
  405.                 'Content-Length' => strlen($imageContent),
  406.             ]
  407.         );
  408.     }
  409.     #[Rest\Get('/api/v6/mission/_google-storage/download-one-file-custom')]
  410.     #[Rest\View(serializerGroups: ['mission_read'])]
  411.     #[OA\Response(
  412.         response200,
  413.         description'Get all the details about a mission',
  414.         content: new OA\JsonContent(
  415.             type'array',
  416.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  417.         )
  418.     )]
  419.     #[OA\Response(
  420.         response401,
  421.         description'Unauthorized - the user isn\'t logged in',
  422.         content: new OA\JsonContent(
  423.             type'array',
  424.         )
  425.     )]
  426.     #[OA\Response(
  427.         response404,
  428.         description'The mission with id doesn\'t exists',
  429.     )]
  430.     public function downloadOneFileCustom(Request $request): Response|JsonResponse
  431.     {  
  432.         $url $request->query->get('url');
  433.         $Expires urlencode($request->query->get('Expires'));
  434.         $Signature urlencode($request->query->get('Signature'));
  435.  
  436.         $fileUrl "$url&Expires=$Expires&Signature=$Signature"
  437.         
  438.         // Vérifier que l'URL est présente
  439.         if (!$fileUrl) {
  440.             throw $this->createNotFoundException('URL de fichier non fournie.');
  441.         }
  442.         // Utiliser HttpClient pour obtenir l'image
  443.         $client HttpClient::create();
  444.         $response $client->request('GET'$fileUrl);
  445.         // Vérifier le statut de la réponse
  446.         if ($response->getStatusCode() !== 200) {
  447.             throw $this->createNotFoundException('L\'image n\'a pas pu être téléchargée.');
  448.         }
  449.         // Obtenir le contenu de l'image
  450.         $imageContent $response->getContent();
  451.         // Déterminer le type de contenu
  452.         $contentType $response->getHeaders()['content-type'][0] ?? 'application/octet-stream';
  453.         // Déterminer le nom du fichier
  454.         $filename basename(parse_url($fileUrlPHP_URL_PATH));
  455.         // Créer la réponse pour le téléchargement
  456.         return new Response(
  457.             $imageContent,
  458.             Response::HTTP_OK,
  459.             [
  460.                 'Content-Description' => 'File Transfer',
  461.                 'Content-Type' => $contentType,
  462.                 'Content-Disposition' => 'attachment; filename="' $filename '"',
  463.                 'Content-Length' => strlen($imageContent),
  464.             ]
  465.         );
  466.     }
  467.     #[Rest\Post('/api/v2/mission/fileHistory/{id}/{fileName}/{fileId}/{action}')]
  468.     #[Rest\View(serializerGroups: ['mission_read'])]
  469.     #[OA\Response(
  470.         response200,
  471.         description'Get all the details about a mission',
  472.         content: new OA\JsonContent(
  473.             type'array',
  474.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  475.         )
  476.     )]
  477.     #[OA\Response(
  478.         response401,
  479.         description'Unauthorized - the user isn\'t logged in',
  480.         content: new OA\JsonContent(
  481.             type'array',
  482.         )
  483.     )]
  484.     #[OA\Response(
  485.         response404,
  486.         description'The mission with id doesn\'t exists',
  487.     )]
  488.     public function addFileHistory(Mission $mission$fileName,$fileId$action)
  489.     {   
  490.         
  491.         $this->missionService->addHistorique($mission$this->getUser(), $action$fileName) ;
  492.         return [ 'status' => 'ok'];
  493.     }
  494.     /**
  495.      * List all the missions for the authenticated user
  496.      *
  497.      * @param MissionRepository $missionRepository
  498.      * @param ParamFetcherInterface $paramFetcher
  499.      * @return \App\Entity\Mission[]|float|int|mixed|string
  500.      */
  501.     #[Rest\Get('/api/v2/missions/{page}/{loadMore}/{query}')]
  502.     #[Rest\View(serializerGroups: ['mission_list'])]
  503.     #[Rest\QueryParam(
  504.         name'archived',
  505.         requirements'\d',
  506.         default: 0,
  507.         description'Filter the results to show only the archived or cancelled missions. Only accepts 0 (shows missions in progress) or 1 (shows archived missions).'
  508.     )]
  509.     #[OA\Response(
  510.         response200,
  511.         description'Returns all the missions for the authenticated user',
  512.         content: new OA\JsonContent(
  513.             type'array',
  514.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_list']))
  515.         )
  516.     )]
  517.     #[OA\Response(
  518.         response401,
  519.         description'Unauthorized - the user isn\'t logged in',
  520.         content: new OA\JsonContent(
  521.             type'array',
  522.             items: new OA\Items(properties: [
  523.                 new OA\Property(property'code'type'integer'),
  524.                 new OA\Property(property'message'type'string'),
  525.             ], type'object')
  526.         )
  527.     )]
  528.     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 ="")
  529.     {
  530.         if ($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_ADMIN_AGENCY') ||  $this->isGranted('ROLE_MANAGER')) {
  531.             
  532.              $company =  $this->dynamicHostService->getCompany() ; 
  533.              $curentUser $this->getUser();
  534.              if (!is_null($curentUser) and !is_null($curentUser?->getRoles()) and in_array('ROLE_MANAGER'$curentUser?->getRoles())) {
  535.                 $company $curentUser?->getCompany();
  536.              }
  537.              $missions $missionRepository->findMissionsFor(Role::ROLE_ADMIN$this->getUser(), $paramFetcher->get('archived') == 0$query,  $company);
  538.         } elseif ($this->isGranted('ROLE_CLIENT')) {
  539.             $missions $missionRepository->findMissionsFor(Role::ROLE_CLIENT$this->getUser(), $paramFetcher->get('archived') == 0,$query);
  540.         }
  541.         else{
  542.             $missions $missionRepository->findMissionsFor(Role::ROLE_SUBCONTRACTOR$this->getUser(), $paramFetcher->get('archived') == 0,$query);
  543.         }
  544.         // $limit = 10; 
  545.         // $offset = $loadMore == "0" ? 0 : ($page - 1) * $limit;
  546.         $page $page == $page
  547.         $offset 0
  548.         $limit $page*10
  549.         $totalItems count($missions);
  550.         $totalPages ceil($totalItems $limit);
  551.         $paginatedMission array_slice($missions$offset$limit);
  552.         foreach ($paginatedMission as $key => $mission) {
  553.             $mission->setMessageUnreadApi($messageService->getNumberAllMessageUnread($mission));
  554.             $mission->setCanActivateApi($this->isGranted('ROLE_SUBCONTRACTOR') && $campaignService->canActivateCampaign($mission->getCampaign())&& !in_array($mission->getCampaign()->getState(),["resend","waiting_validation","closed""archived""deleted","finalized"]));
  555.             $mission->setCanValidateApi($mission->getCampaign()->getState() == "waiting_validation" && ($this->isGranted('ROLE_ADMIN') || ($this->isGranted('ROLE_CLIENT') && !$campaignService->isExternalParticipant($mission->getCampaign(), $this->getUser()) )));
  556.             $mission->setCampaignAmountApi($numberFormatService->format($priceService->totalPriceCampaign($mission->getCampaign())));
  557.             if($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_CLIENT')){
  558.                 $priceAndTime $priceService->priceAndTimeMissionBasedOnPriceSale($mission);
  559.                 $price =  floatval($priceAndTime['price']) ; 
  560.                 $time floatval($priceAndTime['time']);
  561.             }else{
  562.                 $priceAndTime =  $priceService->priceAndTimeMissionSubcontractorById($mission,$this->getUser()->getId());
  563.                 $price =   floatval($priceAndTime['price']);
  564.                 $time floatval($priceAndTime['time']);
  565.             }
  566.             $mission->setPriceApi($price);
  567.             $stepActive $this->workflowStepService->getStepActive($mission);
  568.             $mission->setResponsable($this->workflowStepService->getResponsableStepByMission($missionfalse$stepActive ));
  569.             $mission->setTimeApi($time);
  570.             $mission->setConfidential($mission->getCampaign()->getConfidentiality()!=null $mission->getCampaign()->getConfidentiality() : false); 
  571.             $mission->setAlreadyAcceptConfidentialityContract($confidentialityService->canShowConfidentialCampaign($this->getUser(), $mission->getCampaign())); 
  572.             $mission->setCampaignStateApi([
  573.                     ...$missionApiService->getCampaignState($mission->getCampaign()),
  574.                     ...[
  575.                             'isAlreadyStart'=> $mission->getCampaign()->isAlreadyStart(),
  576.                             'state'=> $mission->getCampaign()->getState()
  577.                     ]
  578.         ]);
  579.         }
  580.         
  581.         
  582.         return [
  583.             'success' => true
  584.             'totalPage'=> $totalPages,
  585.             'data'=>$paginatedMission
  586.         ];
  587.     }
  588.     /**
  589.      * Send email for subcontractor not evaluate a mission
  590.      */
  591.     #[Rest\POST('/api/v2/mission/subcontrator/notify/{id}')]
  592.     #[Rest\View(serializerGroups: ['mission_read'])]
  593.     #[OA\Response(
  594.         response200,
  595.         description'Send email for subcontractor not evaluate a mission',
  596.         content: new OA\JsonContent(
  597.             type'array',
  598.             items: new OA\Items(ref: new Model(typeMission::class, groups: ['mission_read']))
  599.         )
  600.     )]
  601.     #[OA\Response(
  602.         response401,
  603.         description'Unauthorized - the user isn\'t logged in',
  604.         content: new OA\JsonContent(
  605.             type'array',
  606.             items: new OA\Items(properties: [
  607.                 new OA\Property(property'code'type'integer'),
  608.                 new OA\Property(property'message'type'string'),
  609.             ], type'object')
  610.         )
  611.     )]
  612.     #[OA\Response(
  613.         response404,
  614.         description'The mission with id doesn\'t exists',
  615.     )]
  616.     public function sendEmailForSubcontractor(Mission $mission,EventDispatcherInterface $dispatcher)
  617.     {   
  618.         $event = new SubContractorRequestEvaluateMissionEvent($mission);
  619.         $dispatcher->dispatch($eventSubContractorRequestEvaluateMissionEvent::NAME);
  620.         return new JsonResponse([
  621.             'status'=>'ok'
  622.         ]);
  623.     }
  624.     #[Rest\Post('/api/v2/mission/subcontractor-cancelled-evaluation/{id}'name'subcontractor_cancelled_evaluation')]
  625.     #[Rest\View(statusCodeResponse::HTTP_OK)]
  626.     public function sendEmailSubcontractorEvaluateByNotValidate(NotificationService $notificationServiceMission $mission){
  627.         $emails $this->dynamicHostService->getMailAdmin();
  628.         foreach ($emails as  $email) {
  629.             $notificationService->sendEmail(
  630.                 new Address('caroline.b@my-flow.fr','myFlow'),
  631.                 new Address($email->value),
  632.                 'mission  évaluée mais pas resoumise',
  633.                 "La mission ref: {$mission->getReference()} - {$mission->getProduct()->getName()} a été évaluée mais n 'a pas été resoumise au client par {$this->getUser()->getFullName()}"
  634.             ) ;
  635.         }
  636.         
  637.         return new JsonResponse([
  638.             'status'=>'ok'
  639.         ]);
  640.     }
  641.     #[Rest\Post('/api/v2/mission/subcontractor-validated-evaluation'name'estimated_income_subcontractor')]
  642.     #[Rest\View(statusCodeResponse::HTTP_OK)]
  643.     public function estimatedIncomeSubcontractor(MissionParticipantRepository $missionParticipantRepositoryCampaignService $campaignService,MissionApiService $missionApiServiceMissionService $missionServicePriceService $priceServiceMissionParticipantService $missionParticipantServiceRequest $request){
  644.         $request$request->request->All();
  645.         
  646.         $datas =  $request['data'] ;
  647.         foreach ($datas as $key => $data) {
  648.             $missionParticipant $missionParticipantRepository->findOneBy(['id'=>$data['participant']['id']]);
  649.             $mission $missionParticipant->getMission();
  650.             $income $data['income'];
  651.             $time $data['time'];
  652.             $missionParticipantService->setEstimatedIncomeSubcontractor($campaignService,$missionService,$priceService,$missionParticipant,$income$time);
  653.             
  654.         }
  655.         if($mission){
  656.             if($mission->getCampaign()->getState()=='closing_in_progress' &&  sizeof($this->campaignApiService->getSubcontractorNoEstimatedIncome($mission->getCampaign())) == 0){
  657.                 $this->campaignApiService->closedCampaign($mission->getCampaign());
  658.             }
  659.         }
  660.         return new JsonResponse([
  661.             'status'=>'ok',
  662.              'datas'=> $datas
  663.             // 'state'=>$missionApiService->getCampaignStateHtml($mission->getCampaign())
  664.         ]);
  665.     }
  666.     #[Rest\Get('/api/v2/mission/actions/{id}'name'actions')]
  667.     #[Rest\View(serializerGroups: ['mission_read'], statusCodeResponse::HTTP_OK)]
  668.     public function actions(Mission $mission){
  669.        
  670.         $fileList = []; 
  671.         $incomesAndTimes = []; 
  672.        
  673.         if(in_array('ROLE_SUBCONTRACTOR'$this->getUser()->getRoles())) {
  674.             foreach ($mission->getCampaign()->getMissions() as $key => $mission) {
  675.                 if($this->missionService->isMyMission($mission) && $this->missionService->subcontractorCanEvaluate($mission$this->getUser())){
  676.                     $evaluationInformation null
  677.                     $product =  $mission->getProduct(); 
  678.                     $priceAndTime =  $this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_CLIENT') ? 
  679.                                      $this->priceService->priceAndTimeMissionBasedOnPriceSale($mission) :
  680.                                      $this->priceService->priceAndTimeMissionSubcontractorById($mission,$this->getUser()->getId());
  681.         
  682.                     $price =   floatval($priceAndTime['price']);
  683.                     $time floatval($priceAndTime['time']);
  684.     
  685.                     $participants $this->missionParticipantService->getParticipantByUser($mission$this->getUser(), true);
  686.                     $jobsForParticipant $this->missionParticipantService->getJobsForParticipant($mission$this->getUser());
  687.                     $sizeofParticipant $participants!= null sizeof($participants) : ;  
  688.                     $sizeofjobsForParticipant $jobsForParticipant!= null sizeof($jobsForParticipant) : ;  
  689.                     
  690.                     $roles $sizeofjobsForParticipant ?  implode(','$jobsForParticipant) : '';
  691.                     $evaluationInformation =  $sizeofjobsForParticipant "Vous avez plusieurs rôles sur cette mission. Veuillez renseigner un temps ou un budget pour les rôle de [{$roles}]." null
  692.                     $participant $sizeofParticipant ?  $participants[0] : null 
  693.                    
  694.                     $incomesAndTimes = [
  695.                         ...$incomesAndTimes,
  696.                         [
  697.                             'mission_id'=>  $mission->getId(),
  698.                             'product'=> [
  699.                                 'name' => $product->getName(),
  700.                                 'type' => $product->getType()->value,
  701.                             ],
  702.                             'income'=> $price,
  703.                             'time' => $time
  704.                             'participant'=> [
  705.                                 'id'=> $participant!=null ?  $participant->getId() : null
  706.                             ],
  707.                             'evaluationInformation'=> $evaluationInformation
  708.                         ]
  709.                     ]; 
  710.                 }
  711.             }
  712.         }
  713.  
  714.        return new JsonResponse([
  715.             'status'=>'ok',
  716.             'incomesAndTimes'=> $incomesAndTimes
  717.             // 'state'=>$missionApiService->getCampaignStateHtml($mission->getCampaign())
  718.         ]);
  719.     }
  720.     #[Rest\Post('/api/v2/mission/delete-file-mission/{id}'name'delete-file-mission')]
  721.     #[Rest\View(statusCodeResponse::HTTP_OK)]
  722.     #[Route('/mission/delete-file-mission/{id}'name'delete-file-mission-desktop')]
  723.     public function deleteFileMission(FileMission $fileMissionEntityManagerInterface $entityManagerInterface,FileMissionRepository $fileMissionRepository,Request $request,GoogleStorageService $googleStorageService)
  724.     {  
  725.         $campaign $fileMission->getCampaign();
  726.         $fileMissionCampain $fileMissionRepository->findOneBy(['name'=>$fileMission->getName(),'campaign'=>$campaign]);
  727.         $bucketName "company-".strtolower($campaign->getCompany()->getId());
  728.         $fileName "Campaigns/".$campaign->getId()."/".$fileMissionCampain->getName();
  729.     
  730.              try {
  731.                 unlink('uploads/campaign/'.$fileMission->getMission()->getCampaign()->getId().'/'.$fileMission->getName());
  732.              } catch (\Throwable $th) {
  733.              }
  734.             if (!is_null($fileMissionCampain)) {
  735.                 $campaign->removeFileMission($fileMissionCampain);
  736.                 $entityManagerInterface->remove($fileMissionCampain);
  737.             }
  738.             $entityManagerInterface->remove($fileMission);
  739.             $entityManagerInterface->flush();
  740.              $this->addFlash(
  741.                  type'success',
  742.                  message'le fichier joint au message est supprimée'
  743.             );
  744.             $googleStorageService->deleteFile($bucketName,$fileName);
  745.         
  746.             return new JsonResponse([
  747.                 'status'=>'success'
  748.             ]) ;
  749.     }
  750.     private function getPrenomNomNalidateur(Mission $mission){
  751.           foreach ($mission->getParticipants() as $participant) {
  752.                 if($participant->getRole()->value=='ROLE_VALIDATOR'){
  753.                     return $participant->getUser()->getFullName();
  754.                 }
  755.           }
  756.           
  757.           return '--'
  758.     }
  759.     private function getParticipantByUser(Mission $mission,User $user){
  760.         $participant null;
  761.         
  762.         foreach ($mission->getParticipants() as $key => $participant) {
  763.              if($participant->getUser() == $user){
  764.                 return $participant;
  765.              }
  766.         }
  767.         return $participant;
  768.     }
  769.     private function addLinkStorage(array $files){
  770.         $urlDomaine  ""
  771.         $fileWithLink = [];
  772.        
  773.         foreach ($files as $key => $file) {
  774.             $link "" ;
  775.             $size '-a';
  776.             if($file['linkInMessage'] == 0){
  777.                 if($file['isNew'] == 1){
  778.                     $nameOfFileinBucket "Campaigns/{$file['idCampaing']}/{$file['name']}";
  779.                     $nameOfBucket "company-{$file['idCompany']}";
  780.                     $link $this->googleStorageService->getUrlBucketForApi(strtolower($nameOfBucket),$nameOfFileinBucket) ;
  781.                     $size $this->googleStorageService->sizeFile(strtolower($nameOfBucket), $nameOfFileinBucket); 
  782.                 }else{
  783.                      if ( $file['isBrief'] == ){
  784.                             $mission =$this->missionRepository->find($file['idMission']);
  785.                             $fileUrl $this->messageService->getFileMissionUrl($mission$file['name']); 
  786.                             $link "$urlDomaine$fileUrl";
  787.                         }
  788.                     else{
  789.                         $link "$urlDomaine/uploads/campaign/{$file['idCampaing']}/{$file['name']};
  790.                     }
  791.                     $size '-'
  792.                 }
  793.             }else{
  794.                 $link $file['linkInMessage'];
  795.                 $size '-';
  796.             }
  797.             $fileWithLink = [...$fileWithLink,[...$file'linkStorage'=> $link'size'=> $size]];
  798.         }
  799.         return $fileWithLink
  800.     }
  801.     
  802. }