<?php
namespace App\Controller\API;
use App\Entity\FileMessage;
use App\Entity\FileMission;
use App\Entity\Mission;
use App\Entity\User;
use App\Entity\MissionParticipant;
use App\Enum\AdminMail;
use App\Enum\Role;
use App\Repository\MissionRepository;
use App\Repository\UserRepository;
use App\Service\CampaignApiService;
use App\Service\DateService;
use App\Service\MessageService;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Request\ParamFetcherInterface;
use Nelmio\ApiDocBundle\Annotation\Model;
use OpenApi\Attributes as OA;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Event\SubContractor\SubContractorRequestEvaluateMissionEvent;
use App\Repository\CampaignRepository;
use App\Repository\FileMissionRepository;
use App\Repository\MessageRepository;
use App\Repository\MissionParticipantRepository;
use App\Service\CampaignService;
use App\Service\ConfidentialityService;
use App\Service\MissionApiService;
use App\Service\MissionParticipantService;
use App\Service\MissionService;
use App\Service\NotificationService;
use App\Service\NumberFormatService;
use App\Service\PriceService;
use Doctrine\ORM\EntityManagerInterface;
use App\Service\StepsService;
use App\Service\UpcomingActionService;
use App\Service\WorkflowStepService;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\Address;
use App\Service\WpMissionService;
use App\Service\GoogleStorageService;
use App\Service\DynamicHostService;
use Twig\Environment;
use Symfony\Component\HttpClient\HttpClient;
#[OA\Tag(name: 'Missions')]
class MissionController extends AbstractController
{
public function __construct(
private WorkflowStepService $workflowStepService,
private GoogleStorageService $googleStorageService,
private MissionParticipantService $missionParticipantService,
private MessageRepository $messageRepository,
private MissionService $missionService,
private PriceService $priceService,
private MessageService $messageService,
private MissionRepository $missionRepository,
private CampaignApiService $campaignApiService,
private DynamicHostService $dynamicHostService,
private FileMissionRepository $fileMissionRepository
){
}
/**
* Get all the details about a mission
*/
#[Rest\Get('/api/v2/missions/{id}/{numberPage}')]
#[Rest\View(serializerGroups: ['mission_read'])]
#[OA\Response(
response: 200,
description: 'Get all the details about a mission',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: Mission::class, groups: ['mission_read']))
)
)]
#[OA\Response(
response: 401,
description: 'Unauthorized - the user isn\'t logged in',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(properties: [
new OA\Property(property: 'code', type: 'integer'),
new OA\Property(property: 'message', type: 'string'),
], type: 'object')
)
)]
#[OA\Response(
response: 404,
description: 'The mission with id doesn\'t exists',
)]
public function getOne(Mission $mission,UpcomingActionService $upcomingActions,NumberFormatService $numberFormatService, PriceService $priceService, MessageService $messageService, DateService $dateService)
{
$userSetPicture=[];
$mission->setRemainDays($dateService->getDaysRemaining($mission->getDesiredDelivery()));
$mission->setPlanningAdditionalInformation($mission->canStart());
$mission->setCampaignAmountApi($numberFormatService->format($priceService->totalPriceCampaign($mission->getCampaign())));
$mission->setResponsable($this->workflowStepService->getResponsableStepByMission($mission));
foreach ($mission->getCampaign()->getMessages() as $message) {
foreach ($message->getFileMessages() as $fileMessage) {
if($fileMessage->isIsNew()){
$nameOfFileinBucket = "Campaigns/{$mission->getCampaign()->getId()}/{$fileMessage->getName()}";
$nameOfBucket = "company-{$mission->getCampaign()->getCompany()->getId()}";
$link = $this->googleStorageService->getUrlBucketForApi(strtolower($nameOfBucket),$nameOfFileinBucket);
}
else{
$link = "{$this->getParameter('back_website_url')}/{$messageService->getFileMissionUrl($mission, $fileMessage->getName())}";
}
$fileMessage->setName("$link;=;{$fileMessage->getName()}");
}
}
return [
'missions'=>$mission,
'all_mission_of_campaign'=> $mission->getCampaign()->getMissionsWithoutEspaceDeDiscussion(),
'upcoming_actions'=> $upcomingActions->get(mission: $mission, user: $this->getUser()),
'step_active_responsable' => $this->workflowStepService->getIdResponsableStepActive($mission),
];
}
#[Rest\GET('/api/v2/missions/confidentiality/{id}/{userId}', name: 'api_confidentialityContract')]
#[Rest\View(statusCode: Response::HTTP_OK)]
public function getConfidentialityContract(Mission $mission,Environment $twig, string $userId, UserRepository $userRepository )
{
$user = $userRepository->findOneBy(['id'=>$userId]);
return new JsonResponse([
'status'=>'success',
'confidentiality'=> $twig->render('confidentiality/termApi.html.twig',[
'company'=>$mission->getCampaign()->getCompany(),
'user'=>$user,
'prenom_nom_validateur'=> $this->getPrenomNomNalidateur($mission) ,
])
]) ;
}
#[Rest\GET('/api/v2/link-file/{id}', name: 'api_link_file_message')]
#[Rest\View(statusCode: Response::HTTP_OK)]
public function getFileLink(FileMessage $fileMessage){
$campaign = $fileMessage->getMessages()->getCampaign();
$campaignId = $campaign->getId();
$companyId = $campaign->getCompany()->getId();
if($fileMessage->isIsNew()){
$nameOfFileinBucket = "Campaigns/$campaignId/{$fileMessage->getName()}";
$nameOfBucket = "company-$companyId";
$link = $this->googleStorageService->getUrlBucket(strtolower($nameOfBucket),$nameOfFileinBucket);;
}
else{
$link = "{$this->getParameter('back_website_url')}/{$this->messageService->getFileMissionUrlByCampaign( $campaign, $fileMessage->getName())}";
}
return new JsonResponse($link);
}
/**
* Get all the details about a mission
*/
#[Rest\Get('/api/v2/mission/initialbrief/{id}')]
#[Rest\View(serializerGroups: ['mission_read'])]
#[OA\Response(
response: 200,
description: 'Get all the details about a mission',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: Mission::class, groups: ['mission_read']))
)
)]
#[OA\Response(
response: 401,
description: 'Unauthorized - the user isn\'t logged in',
content: new OA\JsonContent(
type: 'array',
)
)]
#[OA\Response(
response: 404,
description: 'The mission with id doesn\'t exists',
)]
public function getInitialBrief(Mission $mission)
{
$fileList = [];
$incomesAndTimes = [];
foreach ( $mission->getCampaign()->getFileMissions() as $file ) {
$nameOfFileinBucket = "Campaigns/{$mission->getCampaign()->getId()}/{$file->getName()}";
$nameOfBucket = "company-{$mission->getCampaign()->getCompany()->getId()}";
$fileList = [ ...$fileList,
[
'link' => $this->googleStorageService->getUrlBucketForApi(strtolower($nameOfBucket),$nameOfFileinBucket),
'name'=>$file->getName()
]
] ;
}
foreach ($mission->getCampaign()->getMissions() as $key => $mission) {
if(in_array('ROLE_SUBCONTRACTOR', $this->getUser()->getRoles()) && $this->missionService->isMyMission($mission)){
$product = $mission->getProduct();
$priceAndTime = $this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_CLIENT') ?
$this->priceService->priceAndTimeMissionBasedOnPriceSale($mission) :
$this->priceService->priceAndTimeMissionSubcontractorById($mission,$this->getUser()->getId());
$price = floatval($priceAndTime['price']);
$time = floatval($priceAndTime['time']);
$participant = $this->missionParticipantService->getParticipantByUser($mission, $this->getUser());
$incomesAndTimes = [
...$incomesAndTimes,
[
'mission_id'=> $mission->getId(),
'product'=> [
'name' => $product->getName(),
'type' => $product->getType()->value,
],
'income'=> $price,
'time' => $time,
'participant'=> $participant,
]
];
}
}
return [
'initial_brief' => $mission->getCampaign()->getBrief(),
'missions' => $incomesAndTimes,
'file_list'=>$fileList
];
}
#[Rest\Get('/api/v2/mission/google-storage/{id}')]
#[Rest\View(serializerGroups: ['mission_read'])]
#[OA\Response(
response: 200,
description: 'Get all the details about a mission',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: Mission::class, groups: ['mission_read']))
)
)]
#[OA\Response(
response: 401,
description: 'Unauthorized - the user isn\'t logged in',
content: new OA\JsonContent(
type: 'array',
)
)]
#[OA\Response(
response: 404,
description: 'The mission with id doesn\'t exists',
)]
public function getFileInGoogleStorage(Mission $mission)
{
$allMissionId = [];
$campaign = $mission->getCampaign();
foreach ($campaign->getMissions() as $key => $mission) {
$allMissionId[] = $mission->getId();
}
$allMessageContent = $this->messageRepository->findMessagesContent($campaign, $this->getUser());
$allMessageContentGroup = $this->messageRepository->findMessagesContentGroup($campaign,$this->getUser());
$allMessageWithLink = [];
$allMessageWithLinkGroup = [];
$links = [];
//get all link in message
foreach ($allMessageContent as $message) {
$dom = new \DOMDocument();
@$dom->loadHTML($message['content']);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) {
$links = $anchor->getAttribute('href');
$message['linkInMessage'] = $links;
$message['linkInMessageShort'] = mb_substr($links, 0, 40)."...";
$allMessageWithLink = [...$allMessageWithLink,$message];
}
}
//get all link in message Group
foreach ($allMessageContentGroup as $messageGroup) {
$dom = new \DOMDocument();
if (!empty($messageGroup['content']) and $messageGroup['content'] != null) {
@$dom->loadHTML($messageGroup['content']);
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) {
$links = $anchor->getAttribute('href');
$messageGroup['linkInMessage'] = $links;
$messageGroup['linkInMessageShort'] = mb_substr($links, 0, 40)."...";
$allMessageWithLinkGroup = [...$allMessageWithLinkGroup,$messageGroup];
}
}
}
$allMessages = $this->messageRepository->allMessageHaveFile($campaign, $this->getUser());
$allMessagesGroup = $this->messageRepository->allMessageHaveFileGroup($campaign,$this->getUser());
$allJointes = $this->fileMissionRepository->allFile($campaign,$allMissionId);
$allFiles = $this->addLinkStorage(array_merge($allMessageWithLinkGroup,$allMessageWithLink,$allMessages,$allMessagesGroup, $allJointes)) ;
usort($allFiles, function($a,$b){
return $b['createdAt'] <=> $a['createdAt'];
});
return [ 'all_file' => $allFiles ];
}
#[Rest\Get('/api/v6/mission/google-storage/download-all-file/{id}')]
#[Rest\View(serializerGroups: ['mission_read'])]
#[OA\Response(
response: 200,
description: 'Get all the details about a mission',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: Mission::class, groups: ['mission_read']))
)
)]
#[OA\Response(
response: 401,
description: 'Unauthorized - the user isn\'t logged in',
content: new OA\JsonContent(
type: 'array',
)
)]
#[OA\Response(
response: 404,
description: 'The mission with id doesn\'t exists',
)]
public function getAllFileAsZip(Mission $mission)
{
$fileUrl = $this->googleStorageService->saveFileHistory($mission, $this->missionService);
$client = HttpClient::create();
$response = $client->request('GET', $fileUrl);
// Vérifier le statut de la réponse
if ($response->getStatusCode() !== 200) {
throw $this->createNotFoundException('L\'image n\'a pas pu être téléchargée.');
}
// Obtenir le contenu de l'image
$imageContent = $response->getContent();
// Déterminer le type de contenu
$contentType = $response->getHeaders()['content-type'][0] ?? 'application/octet-stream';
// Déterminer le nom du fichier
$filename = basename(parse_url($fileUrl, PHP_URL_PATH));
// Créer la réponse pour le téléchargement
return new Response(
$imageContent,
Response::HTTP_OK,
[
'Content-Description' => 'File Transfer',
'Content-Type' => $contentType,
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
'Content-Length' => strlen($imageContent),
]
);
}
#[Rest\Get('/api/v6/mission/_google-storage/download-one-file')]
#[Rest\View(serializerGroups: ['mission_read'])]
#[OA\Response(
response: 200,
description: 'Get all the details about a mission',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: Mission::class, groups: ['mission_read']))
)
)]
#[OA\Response(
response: 401,
description: 'Unauthorized - the user isn\'t logged in',
content: new OA\JsonContent(
type: 'array',
)
)]
#[OA\Response(
response: 404,
description: 'The mission with id doesn\'t exists',
)]
public function downloadOneFile(Request $request)
{
$url = $request->query->get('url');
$Expires = urlencode($request->query->get('Expires'));
$Signature = urlencode($request->query->get('Signature'));
// dd( $url);
$fileUrl = "$url&Expires=$Expires&Signature=$Signature";
// Vérifier que l'URL est présente
if (!$fileUrl) {
throw $this->createNotFoundException('URL de fichier non fournie.');
}
// Utiliser HttpClient pour obtenir l'image
$client = HttpClient::create();
$response = $client->request('GET', $fileUrl);
// Vérifier le statut de la réponse
if ($response->getStatusCode() !== 200) {
throw $this->createNotFoundException('L\'image n\'a pas pu être téléchargée.');
}
// Obtenir le contenu de l'image
$imageContent = $response->getContent();
// Déterminer le type de contenu
$contentType = $response->getHeaders()['content-type'][0] ?? 'application/octet-stream';
// Déterminer le nom du fichier
$filename = basename(parse_url($fileUrl, PHP_URL_PATH));
// Créer la réponse pour le téléchargement
return new Response(
$imageContent,
Response::HTTP_OK,
[
'Content-Description' => 'File Transfer',
'Content-Type' => $contentType,
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
'Content-Length' => strlen($imageContent),
]
);
}
#[Rest\Get('/api/v6/mission/_google-storage/download-one-file-custom')]
#[Rest\View(serializerGroups: ['mission_read'])]
#[OA\Response(
response: 200,
description: 'Get all the details about a mission',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: Mission::class, groups: ['mission_read']))
)
)]
#[OA\Response(
response: 401,
description: 'Unauthorized - the user isn\'t logged in',
content: new OA\JsonContent(
type: 'array',
)
)]
#[OA\Response(
response: 404,
description: 'The mission with id doesn\'t exists',
)]
public function downloadOneFileCustom(Request $request): Response|JsonResponse
{
$url = $request->query->get('url');
$Expires = urlencode($request->query->get('Expires'));
$Signature = urlencode($request->query->get('Signature'));
$fileUrl = "$url&Expires=$Expires&Signature=$Signature";
// Vérifier que l'URL est présente
if (!$fileUrl) {
throw $this->createNotFoundException('URL de fichier non fournie.');
}
// Utiliser HttpClient pour obtenir l'image
$client = HttpClient::create();
$response = $client->request('GET', $fileUrl);
// Vérifier le statut de la réponse
if ($response->getStatusCode() !== 200) {
throw $this->createNotFoundException('L\'image n\'a pas pu être téléchargée.');
}
// Obtenir le contenu de l'image
$imageContent = $response->getContent();
// Déterminer le type de contenu
$contentType = $response->getHeaders()['content-type'][0] ?? 'application/octet-stream';
// Déterminer le nom du fichier
$filename = basename(parse_url($fileUrl, PHP_URL_PATH));
// Créer la réponse pour le téléchargement
return new Response(
$imageContent,
Response::HTTP_OK,
[
'Content-Description' => 'File Transfer',
'Content-Type' => $contentType,
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
'Content-Length' => strlen($imageContent),
]
);
}
#[Rest\Post('/api/v2/mission/fileHistory/{id}/{fileName}/{fileId}/{action}')]
#[Rest\View(serializerGroups: ['mission_read'])]
#[OA\Response(
response: 200,
description: 'Get all the details about a mission',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: Mission::class, groups: ['mission_read']))
)
)]
#[OA\Response(
response: 401,
description: 'Unauthorized - the user isn\'t logged in',
content: new OA\JsonContent(
type: 'array',
)
)]
#[OA\Response(
response: 404,
description: 'The mission with id doesn\'t exists',
)]
public function addFileHistory(Mission $mission, $fileName,$fileId, $action)
{
$this->missionService->addHistorique($mission, $this->getUser(), $action, $fileName) ;
return [ 'status' => 'ok'];
}
/**
* List all the missions for the authenticated user
*
* @param MissionRepository $missionRepository
* @param ParamFetcherInterface $paramFetcher
* @return \App\Entity\Mission[]|float|int|mixed|string
*/
#[Rest\Get('/api/v2/missions/{page}/{loadMore}/{query}')]
#[Rest\View(serializerGroups: ['mission_list'])]
#[Rest\QueryParam(
name: 'archived',
requirements: '\d',
default: 0,
description: 'Filter the results to show only the archived or cancelled missions. Only accepts 0 (shows missions in progress) or 1 (shows archived missions).'
)]
#[OA\Response(
response: 200,
description: 'Returns all the missions for the authenticated user',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: Mission::class, groups: ['mission_list']))
)
)]
#[OA\Response(
response: 401,
description: 'Unauthorized - the user isn\'t logged in',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(properties: [
new OA\Property(property: 'code', type: 'integer'),
new OA\Property(property: 'message', type: 'string'),
], type: 'object')
)
)]
public function getMissions(MissionRepository $missionRepository,ConfidentialityService $confidentialityService, MissionApiService $missionApiService, EntityManagerInterface $entityManager, WpMissionService $wpMissionService, NumberFormatService $numberFormatService, PriceService $priceService, CampaignService $campaignService,CampaignRepository $campaignRepository, MessageService $messageService, ParamFetcherInterface $paramFetcher,string $loadMore="0", string $page = "1", string $query ="")
{
if ($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_ADMIN_AGENCY') || $this->isGranted('ROLE_MANAGER')) {
$company = $this->dynamicHostService->getCompany() ;
$curentUser = $this->getUser();
if (!is_null($curentUser) and !is_null($curentUser?->getRoles()) and in_array('ROLE_MANAGER', $curentUser?->getRoles())) {
$company = $curentUser?->getCompany();
}
$missions = $missionRepository->findMissionsFor(Role::ROLE_ADMIN, $this->getUser(), $paramFetcher->get('archived') == 0, $query, $company);
} elseif ($this->isGranted('ROLE_CLIENT')) {
$missions = $missionRepository->findMissionsFor(Role::ROLE_CLIENT, $this->getUser(), $paramFetcher->get('archived') == 0,$query);
}
else{
$missions = $missionRepository->findMissionsFor(Role::ROLE_SUBCONTRACTOR, $this->getUser(), $paramFetcher->get('archived') == 0,$query);
}
// $limit = 10;
// $offset = $loadMore == "0" ? 0 : ($page - 1) * $limit;
$page = $page == 0 ? 1 : $page;
$offset = 0;
$limit = $page*10;
$totalItems = count($missions);
$totalPages = ceil($totalItems / $limit);
$paginatedMission = array_slice($missions, $offset, $limit);
foreach ($paginatedMission as $key => $mission) {
$mission->setMessageUnreadApi($messageService->getNumberAllMessageUnread($mission));
$mission->setCanActivateApi($this->isGranted('ROLE_SUBCONTRACTOR') && $campaignService->canActivateCampaign($mission->getCampaign())&& !in_array($mission->getCampaign()->getState(),["resend","waiting_validation","closed", "archived", "deleted","finalized"]));
$mission->setCanValidateApi($mission->getCampaign()->getState() == "waiting_validation" && ($this->isGranted('ROLE_ADMIN') || ($this->isGranted('ROLE_CLIENT') && !$campaignService->isExternalParticipant($mission->getCampaign(), $this->getUser()) )));
$mission->setCampaignAmountApi($numberFormatService->format($priceService->totalPriceCampaign($mission->getCampaign())));
if($this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_CLIENT')){
$priceAndTime = $priceService->priceAndTimeMissionBasedOnPriceSale($mission);
$price = floatval($priceAndTime['price']) ;
$time = floatval($priceAndTime['time']);
}else{
$priceAndTime = $priceService->priceAndTimeMissionSubcontractorById($mission,$this->getUser()->getId());
$price = floatval($priceAndTime['price']);
$time = floatval($priceAndTime['time']);
}
$mission->setPriceApi($price);
$stepActive = $this->workflowStepService->getStepActive($mission);
$mission->setResponsable($this->workflowStepService->getResponsableStepByMission($mission, false, $stepActive ));
$mission->setTimeApi($time);
$mission->setConfidential($mission->getCampaign()->getConfidentiality()!=null ? $mission->getCampaign()->getConfidentiality() : false);
$mission->setAlreadyAcceptConfidentialityContract($confidentialityService->canShowConfidentialCampaign($this->getUser(), $mission->getCampaign()));
$mission->setCampaignStateApi([
...$missionApiService->getCampaignState($mission->getCampaign()),
...[
'isAlreadyStart'=> $mission->getCampaign()->isAlreadyStart(),
'state'=> $mission->getCampaign()->getState()
]
]);
}
return [
'success' => true,
'totalPage'=> $totalPages,
'data'=>$paginatedMission
];
}
/**
* Send email for subcontractor not evaluate a mission
*/
#[Rest\POST('/api/v2/mission/subcontrator/notify/{id}')]
#[Rest\View(serializerGroups: ['mission_read'])]
#[OA\Response(
response: 200,
description: 'Send email for subcontractor not evaluate a mission',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: Mission::class, groups: ['mission_read']))
)
)]
#[OA\Response(
response: 401,
description: 'Unauthorized - the user isn\'t logged in',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(properties: [
new OA\Property(property: 'code', type: 'integer'),
new OA\Property(property: 'message', type: 'string'),
], type: 'object')
)
)]
#[OA\Response(
response: 404,
description: 'The mission with id doesn\'t exists',
)]
public function sendEmailForSubcontractor(Mission $mission,EventDispatcherInterface $dispatcher)
{
$event = new SubContractorRequestEvaluateMissionEvent($mission);
$dispatcher->dispatch($event, SubContractorRequestEvaluateMissionEvent::NAME);
return new JsonResponse([
'status'=>'ok'
]);
}
#[Rest\Post('/api/v2/mission/subcontractor-cancelled-evaluation/{id}', name: 'subcontractor_cancelled_evaluation')]
#[Rest\View(statusCode: Response::HTTP_OK)]
public function sendEmailSubcontractorEvaluateByNotValidate(NotificationService $notificationService, Mission $mission){
$emails = $this->dynamicHostService->getMailAdmin();
foreach ($emails as $email) {
$notificationService->sendEmail(
new Address('caroline.b@my-flow.fr','myFlow'),
new Address($email->value),
'mission évaluée mais pas resoumise',
"La mission ref: {$mission->getReference()} - {$mission->getProduct()->getName()} a été évaluée mais n 'a pas été resoumise au client par {$this->getUser()->getFullName()}"
) ;
}
return new JsonResponse([
'status'=>'ok'
]);
}
#[Rest\Post('/api/v2/mission/subcontractor-validated-evaluation', name: 'estimated_income_subcontractor')]
#[Rest\View(statusCode: Response::HTTP_OK)]
public function estimatedIncomeSubcontractor(MissionParticipantRepository $missionParticipantRepository, CampaignService $campaignService,MissionApiService $missionApiService, MissionService $missionService, PriceService $priceService, MissionParticipantService $missionParticipantService, Request $request){
$request= $request->request->All();
$datas = $request['data'] ;
foreach ($datas as $key => $data) {
$missionParticipant = $missionParticipantRepository->findOneBy(['id'=>$data['participant']['id']]);
$mission = $missionParticipant->getMission();
$income = $data['income'];
$time = $data['time'];
$missionParticipantService->setEstimatedIncomeSubcontractor($campaignService,$missionService,$priceService,$missionParticipant,$income, $time);
}
if($mission){
if($mission->getCampaign()->getState()=='closing_in_progress' && sizeof($this->campaignApiService->getSubcontractorNoEstimatedIncome($mission->getCampaign())) == 0){
$this->campaignApiService->closedCampaign($mission->getCampaign());
}
}
return new JsonResponse([
'status'=>'ok',
'datas'=> $datas
// 'state'=>$missionApiService->getCampaignStateHtml($mission->getCampaign())
]);
}
#[Rest\Get('/api/v2/mission/actions/{id}', name: 'actions')]
#[Rest\View(serializerGroups: ['mission_read'], statusCode: Response::HTTP_OK)]
public function actions(Mission $mission){
$fileList = [];
$incomesAndTimes = [];
if(in_array('ROLE_SUBCONTRACTOR', $this->getUser()->getRoles())) {
foreach ($mission->getCampaign()->getMissions() as $key => $mission) {
if($this->missionService->isMyMission($mission) && $this->missionService->subcontractorCanEvaluate($mission, $this->getUser())){
$evaluationInformation = null;
$product = $mission->getProduct();
$priceAndTime = $this->isGranted('ROLE_ADMIN') || $this->isGranted('ROLE_CLIENT') ?
$this->priceService->priceAndTimeMissionBasedOnPriceSale($mission) :
$this->priceService->priceAndTimeMissionSubcontractorById($mission,$this->getUser()->getId());
$price = floatval($priceAndTime['price']);
$time = floatval($priceAndTime['time']);
$participants = $this->missionParticipantService->getParticipantByUser($mission, $this->getUser(), true);
$jobsForParticipant = $this->missionParticipantService->getJobsForParticipant($mission, $this->getUser());
$sizeofParticipant = $participants!= null ? sizeof($participants) : 0 ;
$sizeofjobsForParticipant = $jobsForParticipant!= null ? sizeof($jobsForParticipant) : 0 ;
$roles = $sizeofjobsForParticipant > 1 ? implode(',', $jobsForParticipant) : '';
$evaluationInformation = $sizeofjobsForParticipant > 1 ? "Vous avez plusieurs rôles sur cette mission. Veuillez renseigner un temps ou un budget pour les rôle de [{$roles}]." : null;
$participant = $sizeofParticipant > 0 ? $participants[0] : null ;
$incomesAndTimes = [
...$incomesAndTimes,
[
'mission_id'=> $mission->getId(),
'product'=> [
'name' => $product->getName(),
'type' => $product->getType()->value,
],
'income'=> $price,
'time' => $time,
'participant'=> [
'id'=> $participant!=null ? $participant->getId() : null
],
'evaluationInformation'=> $evaluationInformation
]
];
}
}
}
return new JsonResponse([
'status'=>'ok',
'incomesAndTimes'=> $incomesAndTimes
// 'state'=>$missionApiService->getCampaignStateHtml($mission->getCampaign())
]);
}
#[Rest\Post('/api/v2/mission/delete-file-mission/{id}', name: 'delete-file-mission')]
#[Rest\View(statusCode: Response::HTTP_OK)]
#[Route('/mission/delete-file-mission/{id}', name: 'delete-file-mission-desktop')]
public function deleteFileMission(FileMission $fileMission, EntityManagerInterface $entityManagerInterface,FileMissionRepository $fileMissionRepository,Request $request,GoogleStorageService $googleStorageService)
{
$campaign = $fileMission->getCampaign();
$fileMissionCampain = $fileMissionRepository->findOneBy(['name'=>$fileMission->getName(),'campaign'=>$campaign]);
$bucketName = "company-".strtolower($campaign->getCompany()->getId());
$fileName = "Campaigns/".$campaign->getId()."/".$fileMissionCampain->getName();
try {
unlink('uploads/campaign/'.$fileMission->getMission()->getCampaign()->getId().'/'.$fileMission->getName());
} catch (\Throwable $th) {
}
if (!is_null($fileMissionCampain)) {
$campaign->removeFileMission($fileMissionCampain);
$entityManagerInterface->remove($fileMissionCampain);
}
$entityManagerInterface->remove($fileMission);
$entityManagerInterface->flush();
$this->addFlash(
type: 'success',
message: 'le fichier joint au message est supprimée'
);
$googleStorageService->deleteFile($bucketName,$fileName);
return new JsonResponse([
'status'=>'success'
]) ;
}
private function getPrenomNomNalidateur(Mission $mission){
foreach ($mission->getParticipants() as $participant) {
if($participant->getRole()->value=='ROLE_VALIDATOR'){
return $participant->getUser()->getFullName();
}
}
return '--';
}
private function getParticipantByUser(Mission $mission,User $user){
$participant = null;
foreach ($mission->getParticipants() as $key => $participant) {
if($participant->getUser() == $user){
return $participant;
}
}
return $participant;
}
private function addLinkStorage(array $files){
$urlDomaine = "";
$fileWithLink = [];
foreach ($files as $key => $file) {
$link = "" ;
if($file['linkInMessage'] == 0){
if($file['isNew'] == 1){
$nameOfFileinBucket = "Campaigns/{$file['idCampaing']}/{$file['name']}";
$nameOfBucket = "company-{$file['idCompany']}";
$link = $this->googleStorageService->getUrlBucketForApi(strtolower($nameOfBucket),$nameOfFileinBucket) ;
}else{
if ( $file['isBrief'] == 0 ){
$mission =$this->missionRepository->find($file['idMission']);
$fileUrl = $this->messageService->getFileMissionUrl($mission, $file['name']);
$link = "$urlDomaine/ $fileUrl";
}
else{
$link = "$urlDomaine/uploads/campaign/{$file['idCampaing']}/{$file['name']}" ;
}
}
}else{
$link = $file['linkInMessage'];
}
$fileWithLink = [...$fileWithLink,[...$file, 'linkStorage'=> $link]];
}
return $fileWithLink;
}
}