<?php
namespace App\Controller;
use App\Entity\Campaign;
use App\Entity\FileMessage;
use App\Entity\FileMission;
use App\Entity\Historique;
use App\Entity\InfoMission;
use App\Entity\Message;
use App\Entity\Mission;
use App\Entity\MissionParticipant;
use App\Enum\BillingMethod;
use App\Enum\ProductType;
use App\Enum\Role;
use App\Entity\UserData;
use App\Event\Mission\MissionClosedEvent;
use App\Event\Admin\MissionInitialTimeAfterValidationUpdatedEvent;
use App\Event\Admin\MissionNotificationActivatedEvent;
use App\Event\Chat\MessageSentEvent;
use App\Event\Client\NoticeOfInsufficientBudgetEvent;
use App\Event\Mission\MissionAcceptedEvent;
use App\Event\Mission\MissionActivatedEvent;
use App\Event\Mission\MissionCancelledEvent;
use App\Event\Mission\MissionDesiredDeliveryUpdatedAfterValidationEvent;
use App\Event\Mission\MissionInitialTimeEvent;
use App\Event\Mission\MissionRefusedEvent;
use App\Event\Mission\MissionArchivedEvent;
use App\Event\Mission\MissionCanActivateEvent;
use App\Event\Mission\MissionDesiredDeliveryUpdatedBeforeValidationEvent;
use App\Event\Workflow\Step\WorkflowStepEnteredEvent;
use App\Form\AddMissionContactType;
use App\Form\AddMissionContactProjectType;
use App\Form\AddMissionContactExternalType;
use App\Form\AddMissionSubContractorType;
use App\Form\CampaignCancelType;
use App\Form\CampaignDeleteType;
use App\Form\ChangeInitialTimeType;
use App\Form\ChangeRealTimeType;
use App\Form\EditDesiredDeliveryType;
use App\Form\EditSubcontractorParticipantType;
use App\Form\FileMissionType;
use App\Form\InfoMissionType;
use App\Form\CampaignNameType;
use App\Form\InitialBriefType;
use App\Form\MessageType;
use App\Form\MissionCancelType;
use App\Form\MissionEditInitialTimeType;
use App\Form\MissionParticipantDelaisType;
use App\Form\MissionParticipantIncomeType;
use App\Form\MissionParticipantType;
use App\Form\MissionQuantityType;
use App\Form\CampaignCreditHistoryType;
use App\Repository\CampaignRepository;
use App\Repository\HistoriqueRepository;
use App\Repository\InfoMissionRepository;
use App\Repository\MessageRepository;
use App\Repository\MissionParticipantRepository;
use App\Repository\CompanyRepository;
use App\Repository\FileMissionRepository;
use App\Repository\MissionRepository;
use App\Repository\ServiceRepository;
use App\Repository\UserRepository;
use App\Service\CreditService;
use App\Service\ResaleRateService;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Workflow\Registry;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use App\Event\Mission\MissionResendEvent;
use App\Event\User\UserMentionnedEvent;
use App\Form\MissionAddWorkflowType;
use App\Form\FilterType;
use App\Repository\WorkflowRepository;
use App\Service\CampaignService;
use App\Service\ClientSoldService;
use App\Service\MessageService;
use App\Service\MissionService;
use App\Service\MyFlowMarginService;
use App\Service\NumberFormatService;
use Twig\Environment;
use App\Service\PackService;
use App\Service\PriceService;
use Knp\Component\Pager\PaginatorInterface;
use App\Repository\WorkflowStepRepository;
use function PHPSTORM_META\type;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use App\Service\ContractService;
use App\Form\CampaignType;
use App\Form\DesiredDeliveryType;
use App\Form\StorageMissionType;
use App\Repository\CommandeLoggingRepository;
use App\Service\CampaignApiService;
use DateTime;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Mime\Address;
use App\Service\GoogleStorageService;
use App\Service\DynamicHostService;
use App\Service\MissionParticipantService;
use App\Service\SwitchConnexionService;
class MissionController extends AbstractController
{
const COST_OF_A_CREDIT = 220;
public function __construct(
private EntityManagerInterface $entityManager,
private Environment $twig,
private CampaignService $campaignService,
private MissionService $missionService,
private NumberFormatService $numberFormatService,
private ContractService $contractService,
private UserRepository $userRepository,
private EventDispatcherInterface $dispatcher,
private MessageService $messageService,
private GoogleStorageService $googleStorageService,
private PriceService $priceService,
private DynamicHostService $dynamicHostService,
private CampaignApiService $campaignApiService,
private MissionParticipantService $missionParticipantService,
) {
}
/**
* Displays the missions index
*
* The admin views all the missions
* A company user view only his company's missions
* A subcontractor view only his missions
*
* @param CampaignRepository $campaignRepository
* @param CreditService $creditService
*
* @return Response template /mission/index.html.twig
*/
#[Route('/mission', name: 'mission_index')]
#[Route('/mission/archived', name: 'mission_index_archived')]
#[Route('/mission/deleted', name: 'mission_index_deleted')]
public function index(Request $request,CampaignService $campaignService, CommandeLoggingRepository $commandeLoggingRepository, CampaignRepository $campaignRepository, ClientSoldService $clientSoldService, CreditService $creditService, MissionParticipantRepository $missionParticipantRepository, UserRepository $userRepository, ParameterBagInterface $parameterBagInterface, PackService $packService, PriceService $priceService, MissionRepository $missionRepository, PaginatorInterface $paginator, SessionInterface $session, CompanyRepository $companyRepository,SwitchConnexionService $switchConnexionService): Response
{
$routeName = $request->attributes->get('_route');
$filterDownAndTop = !is_null($session->get('filterDownAndTop')) ? $session->get('filterDownAndTop') : [];
if (!is_null($request->query->get('nb_mission'))) {
$session->set('nbrMissionByPage', $request->query->get('nb_mission'));
}
$nbMissionByPage = !is_null($session->get('nbrMissionByPage')) ? $session->get('nbrMissionByPage') : 10;
//top down filter // ASC and DESC
if (
!is_null($request->query->get('companyFilter'))
or !is_null($request->query->get('campaingFilter'))
or !is_null($request->query->get('statusFilter'))
or !is_null($request->query->get('priceFilter'))
or !is_null($request->query->get('referenceFilter'))
or !is_null($request->query->get('referenceRandomFilter'))
or !is_null($request->query->get('companyRandomFilter'))
or !is_null($request->query->get('campaingRandomFilter'))
or !is_null($request->query->get('statusRandomFilter'))
or !is_null($request->query->get('priceRandomFilter'))
) {
//random filter for reference
if (!is_null($request->query->get('referenceRandomFilter'))) {
$ord = (isset($filterDownAndTop['referenceFilter']) && $filterDownAndTop['referenceFilter'] == "ASC") ? "DESC" : "ASC";
$request->query->set('referenceFilter', $ord);
}
//random for company
if (!is_null($request->query->get('companyRandomFilter'))) {
$ord = (isset($filterDownAndTop['companyFilter']) && $filterDownAndTop['companyFilter'] == "ASC") ? "DESC" : "ASC";
$request->query->set('companyFilter', $ord);
}
//random for campaing
if (!is_null($request->query->get('campaingRandomFilter'))) {
$ord = (isset($filterDownAndTop['campaingFilter']) && $filterDownAndTop['campaingFilter'] == "ASC") ? "DESC" : "ASC";
$request->query->set('campaingFilter', $ord);
}
//random for status
if (!is_null($request->query->get('statusRandomFilter'))) {
$ord = (isset($filterDownAndTop['statusFilter']) && $filterDownAndTop['statusFilter'] == "ASC") ? "DESC" : "ASC";
$request->query->set('statusFilter', $ord);
}
//random for status
if (!is_null($request->query->get('priceRandomFilter'))) {
$ord = (isset($filterDownAndTop['priceFilter']) && $filterDownAndTop['priceFilter'] == "ASC") ? "DESC" : "ASC";
$request->query->set('priceFilter', $ord);
}
$filterDownAndTop = [
'companyFilter' => $request->query->get('companyFilter'),
'campaingFilter' => $request->query->get('campaingFilter'),
'statusFilter' => $request->query->get('statusFilter'),
'priceFilter' => $request->query->get('priceFilter'),
'referenceFilter' => $request->query->get('referenceFilter'),
];
$session->set('filterDownAndTop', $filterDownAndTop);
return $this->redirectToRoute($routeName, [], Response::HTTP_SEE_OTHER);
}
//reset filter
if ($request->get('reset')) {
$session->set('criteriaFilter', []);
$session->set('filterDownAndTop', []);
$this->addFlash(
type: 'success',
message: 'Le filtre a été réinitialisé',
);
return $this->redirectToRoute($routeName, [], Response::HTTP_SEE_OTHER);
}
$criteriaFilter = !is_null($session->get('criteriaFilter')) ? $session->get('criteriaFilter') : [];
//creation formulaire
$campaignCommand = [];
$campaignsPrice = [];
$totalHtPerMonth = [];
$creditConso = [];
$invoiced = [];
$nombreCampaignCommande = 0;
$listSubContractorId = [];
if($this->isGranted(Role::ROLE_CLIENT->value) || $this->isGranted(Role::ROLE_CLIENT_ADMIN->value) ){
$listCampaignWithSubContractor = $campaignRepository->findAllInterlocutors($this->getUser(), 3);
foreach ($listCampaignWithSubContractor as $campaign) {
foreach ($campaign->getMissions() as $mission) {
foreach ($mission->getParticipants() as $participant) {
if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR) {
if (!in_array($participant->getUser()->getEmail(), $listSubContractorId)) {
$listSubContractorId []= $participant->getUser()->getId();
}
}
}
}
}
}
$searchFilterForm = $this->createForm(FilterType::class, null, ['user' => $this->getUser(), 'route' => $routeName,'listParticipantId'=>array_unique($listSubContractorId)]);
$formMissionQuantity = $this->createForm(MissionQuantityType::class);
$formMissionInitialTime = $this->createForm(MissionParticipantType::class);
$formMissionInitialTimeManually = $this->createForm(MissionParticipantDelaisType::class);
$formMissionIncomeManually = $this->createForm(MissionParticipantIncomeType::class);
$determineIfArchive = $routeName == "mission_index_archived" ? true : false;
$determineIfDelete = $routeName == "mission_index_deleted" ? true : false;
$querySearch = $request->get('query', null) ?? null;
$typeSearch = ($request->get('typeSearch')) ?? null;
$subContractorAndAdmin = ($this->isGranted(Role::ROLE_ADMIN->value) or $this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) ? true : false;
//for filter
$searchFilterForm->handleRequest($request);
if ($searchFilterForm->isSubmitted() && $searchFilterForm->isValid()) {
$criteriaFilter = [
'company' => $searchFilterForm->get('company')->getData(),
'campaign' => $searchFilterForm->get('campaign')->getData(),
'state' => $searchFilterForm->get('state')->getData(),
'max' => $searchFilterForm->get('max')->getData(),
'min' => $searchFilterForm->get('min')->getData(),
'user' => $searchFilterForm->get('user')->getData(),
'client' => (in_array('ROLE_ADMIN',$this->getUser()->getRoles()) or in_array('ROLE_ADMIN_AGENCY',$this->getUser()->getRoles()) or in_array('ROLE_MANAGER',$this->getUser()->getRoles()) ) ? $searchFilterForm->get('client')->getData() : null,
];
$session->set('criteriaFilter', $criteriaFilter);
return $this->redirectToRoute($routeName);
}
if (!is_null($request->query->get('query'))) {
$session->set('filterDownAndTop', []);
$criteriaFilter = [];
}
// $company = ;
// $isAgency = $this->dynamicHostService->isAgency();
if ($this->isGranted(Role::ROLE_ADMIN->value) or $this->isGranted(Role::ROLE_ADMIN_AGENCY->value)) {
$adminCompany =$this->isGranted(Role::ROLE_ADMIN_AGENCY->value) ? $this->getUser()->getCompany() : null;
$campaigns = $campaignRepository->orderedByDesiredDelivery($this->dynamicHostService->getCompany(), $determineIfArchive, $querySearch, $determineIfDelete, $criteriaFilter, $filterDownAndTop);
$priceCampaign = $missionParticipantRepository->findByInitialTime();
$estimatedIncome = [];
$initialTime = [];
$price = [];
foreach ($priceCampaign as $value) {
if (!isset($estimatedIncome[$value->getMission()->getId()])) {
$estimatedIncome[$value->getMission()->getId()] = [];
}
$initialTime[$value->getMission()->getId()][] = $value->getInitialTime();
$price[$value->getMission()->getId()][] = $value->getEstimatedIncome();
}
} elseif ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
$campaigns = $campaignRepository->findForSubcontractor($this->getUser(), null, $determineIfArchive, $querySearch, $subContractorAndAdmin, $determineIfDelete, $filterDownAndTop);
$estimatedIncome = $missionParticipantRepository->getMissionForUserGroupById($this->getUser());
} else {
$clientCompany =$this->isGranted(Role::ROLE_CLIENT_ADMIN->value) ? $this->getUser()->getCompany() : null;
$campaigns = $campaignRepository->findForSubcontractor($this->getUser(), $clientCompany , $determineIfArchive, $querySearch, false, $determineIfDelete, $filterDownAndTop, $criteriaFilter);
if ($this->isGranted(Role::ROLE_CLIENT->value) || $this->isGranted(Role::ROLE_CLIENT_ADMIN->value)) {
$estimatedIncome = null;
} else {
$estimatedIncome = $missionParticipantRepository->getMissionForUserGroupById($this->getUser());
}
}
$company = $this->getUser()->getCompany();
$creditAvailable = $creditService->CreditAvailable($company);
$allCredit = 0;
foreach ($creditAvailable as $credit) {
$allCredit += $credit->getCredit();
}
$formCancelCampaign = $this->createForm(CampaignCancelType::class);
$formDeleteCampaign = $this->createForm(CampaignDeleteType::class);
$formCancelMission = $this->createForm(MissionCancelType::class);
$urlToConnectWp = $parameterBagInterface->get('front_website_url') . "?tsso=" . hash('sha256', $this->getUser()->getEmail() . $this->getUser()->getEmail());
if(empty($filterDownAndTop)){
$campaigns = $campaignService->reOrderByNumberMessageUnreadAndState($campaigns);
}
$pagination = $paginator->paginate(
$campaigns,
$request->query->getInt('page', 1),
$nbMissionByPage
);
$totalIndividualBilling = $campaignRepository->getTotalIndividualBilling($this->getUser(), $company);
$totalOtherCommande= $company!=null ? $commandeLoggingRepository->getTotalOtherCommande(type:4,user: $this->getUser(),company : $company ): ['sum'=>0];
$isFilterMissionOpen = false;
if($session->has('is_filter_open')){
$isFilterMissionOpen = $session->get('is_filter_open') == "true" ? true : false;
}
return $this->renderForm('mission/index.html.twig', [
'campaigns' => $pagination,
'isEmpty' => empty($campaigns) ? true : false,
'creditConso' => $creditConso,
'searchFilterForm' => $searchFilterForm,
'invoiced' => $invoiced,
'formMissionQuantity' => $formMissionQuantity,
'formMissionInitialTime' => $formMissionInitialTime,
'formMissionInitialTimeManually' => $formMissionInitialTimeManually,
'formMissionIncomeManually' => $formMissionIncomeManually,
'formCancelCampaign' => $formCancelCampaign,
'formDeleteCampaign' => $formDeleteCampaign,
'formCancelMission' => $formCancelMission,
'estimatedIncome' => $estimatedIncome,
// 'formFf' => $estimatedIncome,
'urlToConnectWp' => $urlToConnectWp,
'user' => $this->getUser(),
'archive' => $determineIfArchive,
'delete' => $determineIfDelete,
'querySearch' => $querySearch,
'typeSearch' => $typeSearch,
'nombreOfresults' => count($campaigns),
'balanceHistories' => $clientSoldService->groupByTypeOfContractNotDeleted(company: $company),
'totalIndividualBilling' => ($totalIndividualBilling != null ? $totalIndividualBilling['sum'] : 0)+ $totalOtherCommande['sum'],
'criteriaFilter' => $criteriaFilter,
'routeName' => $routeName,
'nbMissionByPage' => $nbMissionByPage,
'isFilterMissionOpen' => $isFilterMissionOpen,
]);
}
#[Route('/mission/history', name: 'mission_index_history')]
public function historyCommande(CampaignRepository $campaignRepository,PriceService $priceService, ParameterBagInterface $parameterBagInterface)
{
$groupedData = [];
if ($this->isGranted('ROLE_ADMIN')) {
$company = null;
if ($this->isGranted('ROLE_ADMIN_AGENCY') or $this->isGranted('ROLE_MANAGER')) {
$company = $this->getUser()->getCompany();
}
$history = $campaignRepository->findAllCampaignByMonth($company);
foreach ($history as $element) {
//dateClosed
$date = $element['dateClosed'] != null ? $element['dateClosed']->format('m:Y') : $element['dateActivation']->format('m:Y');
$info = $element;
if (!isset($groupedData[$date])) {
$groupedData[$date] = [];
}
$groupedData[$date][] = $info;
}
}
elseif($this->isGranted('ROLE_SUBCONTRACTOR')){
$campaigns = $campaignRepository->findAllForSubonconctractotCampaignByMonth($this->getUser());
foreach ($campaigns as $campaign) {
$date = $campaign->getDateClosed() != null ? $campaign->getDateClosed()->format('m:Y') : $campaign->getActivatedAt()->format('m:Y');
if (!isset($groupedData[$date])) {
$groupedData[$date] = [
'total'=>0,
'missions'=>[]
];
}
$groupedData[$date]['total'] += $priceService->getTotalPriceAndTimeMissionSubcontractorById($campaign, $this->getUser())['price'] ;
$groupedData[$date]['missions']=[...$groupedData[$date]['missions'],...$campaign->getMissions()];
}
}
$urlToConnectWp = $parameterBagInterface->get('front_website_url') . "?tsso=" . hash('sha256', $this->getUser()->getEmail() . $this->getUser()->getEmail());
uksort($groupedData, function($a, $b) {
$dateA = DateTime::createFromFormat('m:Y', $a);
$dateB = DateTime::createFromFormat('m:Y', $b);
return $dateA <=> $dateB;
});
return $this->renderForm('mission/history.html.twig', [
'histories' => $groupedData,
'urlToConnectWp' => $urlToConnectWp,
'archive' => 0,
'delete' => 0,
'querySearch' => "",
'typeSearch' => "",
]);
}
#[Route('/mission/{missionId}/{id}/delete', name: 'mission_info_delete', methods: ['GET'])]
public function deleteInfoMission(EntityManagerInterface $em, InfoMissionRepository $infoMissionRepository, $id, $missionId): Response
{
$infoMission = $infoMissionRepository->find($id);
$em->remove($infoMission);
$em->flush();
$this->addFlash(
type: 'success',
message: 'Info supprimeé avec succés.'
);
return $this->redirectToRoute('mission_edit', ['id' => $missionId]);
}
#[Route('/mission/ajaxEditInfoMission', name: 'mission_info_ajax_edit', methods: ['POST'])]
public function ajaxEditInfoMission(Request $request, EntityManagerInterface $em, InfoMissionRepository $infoMissionRepository): JsonResponse
{
$data = json_decode($request->getContent());
$infoMission = $infoMissionRepository->find($data[0]);
$infoMission->setContent($data[1]);
$em->persist($infoMission);
try {
$em->flush();
return new JsonResponse(['status' => 'OK']);
} catch (\Exception $e) {
return new JsonResponse([
'status' => 'KO',
'message' => $e->getMessage(),
]);
}
}
#[Route('/mission/edit/{missionId}/{id}', name: 'mission_info_edit', methods: ['POST'])]
public function editInfoMission(Request $request, EntityManagerInterface $entityManager, InfoMissionRepository $infoMissionRepository, $id, $missionId): Response
{
$newContent = $request->request->get('info_mission_edit')['content'];
$infoMission = $infoMissionRepository->find($id);
$infoMission->setContent($newContent);
$entityManager->persist($infoMission);
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Info enregistré avec succés.'
);
return $this->redirectToRoute('mission_edit', ['id' => $missionId], Response::HTTP_SEE_OTHER);
}
#[Route('/missionParticipant/{id}/changeInitialTime', name: 'mission_change_manually_time', methods: ['GET', 'POST'])]
public function changeManuallyTime(Request $request, MissionParticipant $missionParticipant, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher, PriceService $priceService): JsonResponse
{
$mission = $missionParticipant->getMission();
$MANS_DAY_FROM_7_HOURS_TO_MINUTES = 420;
$this->campaignService->changeStateCampaignToRESEND($mission->getCampaign(), $mission, $missionParticipant);
$mission->setAdminTime($request->query->get('delais'));
$mission->setAdminIncome($missionParticipant->getUser()->getResaleRate() * $request->query->get('delais') / $MANS_DAY_FROM_7_HOURS_TO_MINUTES);
if ($missionParticipant->getUser()->getBillingMethod() == 2 && $missionParticipant->getMission()->getState() == 'in_progress') {
$missionParticipant->setInitialTime($request->query->get('delais'));
$entityManager->persist($missionParticipant);
$entityManager->flush();
$event = new MissionInitialTimeAfterValidationUpdatedEvent($mission = $missionParticipant->getMission());
$dispatcher->dispatch($event, MissionInitialTimeAfterValidationUpdatedEvent::NAME);
$this->addFlash(
type: 'success',
message: 'Le délais client a bien été mis à jour',
);
return new JsonResponse(['redirect' => $this->generateUrl('mission_index', [], UrlGeneratorInterface::ABSOLUTE_URL)]);
}
$ratio = null;
if (!empty($missionParticipant->getEstimatedIncome()) && !empty($missionParticipant->getInitialTime())) {
$ratio = $missionParticipant->getEstimatedIncome() / $missionParticipant->getInitialTime();
}
$formMissionInitialTimeManually = $this->createForm(MissionParticipantDelaisType::class, $missionParticipant);
$formMissionInitialTimeManually->handleRequest($request);
$missionParticipant->setInitialTime($request->query->get('delais'));
if (empty($ratio)) {
$missionParticipant->setEstimatedIncome($missionParticipant->getInitialTime() * $missionParticipant->getUser()->getDailyRate() / $MANS_DAY_FROM_7_HOURS_TO_MINUTES);
} else {
$missionParticipant->setEstimatedIncome($missionParticipant->getInitialTime() * $ratio);
}
$entityManager->persist($missionParticipant);
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Le délais client a bien été mis à jour',
);
return new JsonResponse(['redirect' => $this->generateUrl('mission_index', [], UrlGeneratorInterface::ABSOLUTE_URL)]);
}
#[Route('/missionParticipant/changeInitialTimeModal', name: 'mission_change_manually_modal_all', methods: ['GET', 'POST'])]
public function changeManuallyTimeModalAll(Request $request, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher, PriceService $priceService): JsonResponse
{
$formData = $request->request->all();
$currentUser = $this->getUser();
$filteredValues = array_filter($formData, function($key) {
return strpos($key, 'Mission_') === 0;
}, ARRAY_FILTER_USE_KEY);
$idMissions = array_values($filteredValues);
foreach ($idMissions as $idMission) {
$mission = $entityManager->getRepository(Mission::class)->find($idMission);
$timeSubcontractor = $request->request->get('mission_initial_time_'.$idMission);
$priceSubcontractor = $request->request->get('mission_initial_price_'.$idMission);
//search participant
$missionParticipant = null;
foreach ($mission->getParticipants() as $participant) {
if ($currentUser->getId() == $participant->getUser()->getId()) {
$missionParticipant = $participant;
break;
}
}
//upldate subcontractor information price and time
$missionParticipant->setInitialTime($timeSubcontractor);
$priceFoSubcontractor = $priceService->tarifSubcontractor($missionParticipant->getUser()->getDailyRate(), $timeSubcontractor);
$missionParticipant->setEstimatedIncome($priceFoSubcontractor);
$missionParticipant->setInitialTimeAdmin($timeSubcontractor);
//prive for admin / client
$priceForAdmin = $priceService->tarifAdminAndClient($missionParticipant->getUser()->getResaleRate(), $timeSubcontractor);
$missionParticipant->setEstimatedIncomeAdmin($priceForAdmin);
$entityManager->persist($missionParticipant);
$entityManager->flush();
//update information mission based in price and time for admin
$priceAndTimeMission = $priceService->priceAndTimeMission($mission);
$mission->setAdminIncome($priceAndTimeMission['price']);
$mission->setPrice($priceAndTimeMission['price']);
$mission->setAdminTime($priceAndTimeMission['time']);
$entityManager->persist($mission);
//with marge if agency
$margeMyFlow = $this->dynamicHostService->getMargeMyFlow();
if ($margeMyFlow != 0) {
$mission->setPriceWithMargeMyFlow($priceService->getPriceMissionWithMargeMyFlow($margeMyFlow,$priceAndTimeMission['price']))->setMargeMyFlow($margeMyFlow);
}
$entityManager->flush();
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "mission_evaluate", option: $missionParticipant);
$this->campaignService->changeStateEvaluateForParticipant($mission, $missionParticipant);
if ($this->campaignService->canResendOrderToClient(campaign: $mission->getCampaign(), missionEvaluate: $mission)) {
$this->campaignService->resendCampaignForValidation(campaign: $mission->getCampaign(), user: $this->getUser());
}
}
return new JsonResponse('ok');
}
#[Route('/missionParticipant/{id}/changeIncome', name: 'mission_change_manually_income', methods: ['GET', 'POST'])]
public function changeManuallyIncome(Request $request, MissionParticipant $missionParticipant, EntityManagerInterface $entityManager)
{
$formMissionIncomeManually = $this->createForm(MissionParticipantIncomeType::class, $missionParticipant);
$formMissionIncomeManually->handleRequest($request);
$missionParticipant->setEstimatedIncome($request->query->get('income'));
$entityManager->persist($missionParticipant);
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Le revenu client a bien été mis à jour',
);
return $this->redirect($request->headers->get('referer'), Response::HTTP_SEE_OTHER);
}
#[Route('/mission/{id}/relancer', name: 'mission_relancer')]
public function campaignRelancer(Request $request, Mission $mission, MissionService $missionService, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher): Response
{
$event = new MissionResendEvent($mission);
$dispatcher->dispatch($event, MissionResendEvent::NAME);
$this->addFlash(
type: 'success',
message: 'La Mission a bien été relancer'
);
return $this->redirectToRoute('mission_index');
}
#[Route('/mission/{id}/changeQuantity', name: 'mission_change_quantity', methods: ['GET', 'POST'])]
public function changeQuantity(Request $request, Mission $mission, EntityManagerInterface $entityManager, MissionService $missionService, PriceService $priceService): JsonResponse
{
$formMissionQuantity = $this->createForm(MissionQuantityType::class, $mission);
$formMissionQuantity->handleRequest($request);
$mission->getCampaign()->setReSendToClient(true);
$mission->setQuantity($request->query->get('quantity'));
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "quantity_update");
$entityManager->flush();
if ($this->campaignService->canResendOrderToClient(campaign: $mission->getCampaign(), missionEvaluate: $mission)) {
$this->campaignService->resendCampaignForValidation(campaign: $mission->getCampaign(), user: $this->getUser());
}
return new JsonResponse($this->getMissionDetailArray(mission: $mission, missionService: $missionService, price: $priceService));
}
#[Route('/mission/{id}/changeInitialTime', name: 'mission_change_initial_time', methods: ['GET', 'POST'])]
public function changeInitialTime(Request $request, MissionParticipant $missionParticipant, MissionService $missionService, EntityManagerInterface $entityManager, PriceService $priceService): JsonResponse
{
$mission = $missionParticipant->getMission();
$formMissionInitialTime = $this->createForm(MissionParticipantType::class, $missionParticipant);
$formMissionInitialTime->handleRequest($request);
//upldate subcontractor information price and time
$missionParticipant->setInitialTime($formMissionInitialTime->getData()->getInitialTime());
$priceFoSubcontractor = $priceService->tarifSubcontractor($missionParticipant->getUser()->getDailyRate(), $formMissionInitialTime->getData()->getInitialTime());
$missionParticipant->setEstimatedIncome($priceFoSubcontractor);
$missionParticipant->setInitialTimeAdmin($formMissionInitialTime->getData()->getInitialTime());
//add price suggered
$missionParticipant->setIncomeSuggested($formMissionInitialTime->getData()->getIncomeSuggested());
//end price suggered
//prive for admin / client
$priceForAdmin = $priceService->tarifAdminAndClient($missionParticipant->getUser()->getResaleRate(), $formMissionInitialTime->getData()->getInitialTime());
$missionParticipant->setEstimatedIncomeAdmin($priceForAdmin);
$entityManager->persist($missionParticipant);
$entityManager->flush();
//update information mission based in price and time for admin
$priceAndTimeMission = $priceService->priceAndTimeMission($mission);
//dd($priceAndTimeMission['price']);
$mission->setAdminIncome($priceAndTimeMission['price']);
$mission->setPrice($priceAndTimeMission['price']);
$mission->setAdminTime($priceAndTimeMission['time']);
$entityManager->persist($mission);
//with marge if agency
$margeMyFlow = $this->dynamicHostService->getMargeMyFlow();
if ($margeMyFlow != 0) {
$mission->setPriceWithMargeMyFlow($priceService->getPriceMissionWithMargeMyFlow($margeMyFlow,$priceAndTimeMission['price']))->setMargeMyFlow($margeMyFlow);
}
$entityManager->flush();
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "mission_evaluate", option: $missionParticipant);
$this->campaignService->changeStateEvaluateForParticipant($mission, $missionParticipant);
if ($this->campaignService->canResendOrderToClient(campaign: $mission->getCampaign(), missionEvaluate: $mission)) {
$this->campaignService->resendCampaignForValidation(campaign: $mission->getCampaign(), user: $this->getUser());
}
return new JsonResponse($this->getMissionDetailArray(mission: $mission, missionService: $missionService, price: $priceService));
}
#[Route('/mission/{id}/adminSetTime', name: 'mission_admin_set_initial_time', methods: ['POST'])]
#[IsGranted('ROLE_ADMIN')]
public function adminSetTime(Request $request, Mission $mission, EntityManagerInterface $entityManager, MissionService $missionService, PriceService $priceService): JsonResponse
{
$formMissionInitialTime = $this->createForm(MissionParticipantType::class);
$formMissionInitialTime->handleRequest($request);
$isAlreadySendMailResoumissionPanierAdmin = false;
foreach ($mission->getParticipants() as $participant) {
if ($participant->getRole() === Role::ROLE_SUBCONTRACTOR) {
$participant->setInitialTime($formMissionInitialTime->getData()->getInitialTime());
$participant->setIncomeSuggested($formMissionInitialTime->getData()->getIncomeSuggested());
$priceFoSubcontractor = $priceService->tarifSubcontractor($participant->getUser()->getDailyRate(), $formMissionInitialTime->getData()->getInitialTime());
$participant->setEstimatedIncome($priceFoSubcontractor);
$participant->setInitialTimeAdmin($formMissionInitialTime->getData()->getInitialTime());
$participant->setEstimatedIncomeAdmin($formMissionInitialTime->getData()->getEstimatedIncome());
$entityManager->flush();
if($isAlreadySendMailResoumissionPanierAdmin == false) {
$isAlreadySendMailResoumissionPanierAdmin = $this->campaignService->changeStateEvaluateForParticipant($mission, $participant);
}
}
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "mission_evaluate", option: $participant);
}
$priceAndTimeMission = $priceService->priceAndTimeMission($mission);
$mission->setAdminIncome($priceAndTimeMission['price']);
$mission->setPrice($priceAndTimeMission['price']);
$mission->setAdminTime($priceAndTimeMission['time']);
//with marge if agency
$margeMyFlow = $this->dynamicHostService->getMargeMyFlow();
if ($margeMyFlow != 0) {
$mission->setPriceWithMargeMyFlow($priceService->getPriceMissionWithMargeMyFlow($margeMyFlow,$priceAndTimeMission['price']))->setMargeMyFlow($margeMyFlow);
}
//reflush
$entityManager->persist($mission);
$entityManager->flush();
if ($this->campaignService->canResendOrderToClient(campaign: $mission->getCampaign(), missionEvaluate: $mission)) {
if(!$isAlreadySendMailResoumissionPanierAdmin){
$this->campaignService->resendCampaignForValidation(campaign: $mission->getCampaign(), user: $this->getUser());
$isAlreadySendMailResoumissionPanierAdmin = true;
}
}
return new JsonResponse($this->getMissionDetailArray(mission: $mission, missionService: $missionService, price: $priceService));
}
private function getMissionDetailArray(Mission $mission, MissionService $missionService, PriceService $price): array
{
$isSubContractor = in_array("ROLE_SUBCONTRACTOR", $this->getUser()->getRoles()) ? $this->getUser()->getId() : false;
$total = $price->totalPriceCampaign($mission->getCampaign(), $isSubContractor);
$currency = $price->currency($mission->getCampaign());
if($mission->getCampaign()->getState()=='closing_in_progress' && sizeof($this->campaignApiService->getSubcontractorNoEstimatedIncome($mission->getCampaign())) == 0){
$this->campaignApiService->closedCampaign($mission->getCampaign());
}
$priceAndTime = $this->getPriceAndTimeForTwig(mission: $mission, missionService: $missionService, priceService: $price);
// dd((float) $priceAndTime['price']);
$price = $this->numberFormatService->format((float) $priceAndTime['price']);
$time = $this->numberFormatService->format((float) $priceAndTime['time']);
// //credit or euros
return [
'incomeSuggested' => $mission?->onlySubcontractorInMission()?->getIncomeSuggested(),
// 'total' => $this->campaignService->getTotalCost(campaign: $mission->getcampaign(), withCurrency: true),
'total' => $this->numberFormatService->format($total) . $currency,
'price' => $price,
'time' => $time,
'id' => $mission->getId(),
'campaign_id' => $mission->getCampaign()->getId(),
'campaign_status' => $this->twig->render('services/status_campaign.html.twig', [
'campaign' => $mission->getCampaign(),
]),
'subcontractor_status' => $this->twig->render('services/subcontractor_status.html.twig', [
'campaign' => $mission->getCampaign(),
'mission' => $mission
]),
'campaign_action_button' => $this->twig->render('services/_button_campaign.html.twig', [
'campaign' => $mission->getCampaign(),
'campaign_service' => $this->campaignService,
]),
'mission_action_button' => $this->twig->render('services/action_button_mission.html.twig', [
'campaign' => $mission->getCampaign(),
'mission' => $mission
]),
'subcontractor_list' => $this->twig->render('services/subcontractor_list.html.twig', [
'campaign' => $mission->getCampaign(),
'mission' => $mission
]),
'marge' => $this->twig->render('services/_marge_get_to_ajax.html.twig', [
'mission' => $mission
]),
'isAdmin' => in_array("ROLE_ADMIN", $this->getUser()->getRoles()) ? true : false,
'product_type' => $mission->getProduct()->getType()->value
];
}
private function getPriceAndTimeForTwig(Mission $mission, MissionService $missionService, PriceService $priceService)
{
$estimatedIncomeAndTime = $this->missionService->getEstimatedIncomeAndTime(mission: $mission, user: $this->getUser());
$priceOrTimeAdmin = $priceService->priceAndTimeMission($mission);
$price = "";
$time = "";
$validAllAdmin = false;
if (in_array("ROLE_ADMIN", $this->getUser()->getRoles())
or in_array("ROLE_MANAGER", $this->getUser()->getRoles())
or in_array("ROLE_ADMIN_AGENCY", $this->getUser()->getRoles())
) {
$validAllAdmin = true;
}
if ($mission->getProduct()->getType() == ProductType::A_EVALUER) {
// if (!$missionService->isAllSubcontractorEvaluate(mission: $mission)) {
// $price = $validAllAdmin ? "not-evaluate" : $estimatedIncomeAndTime["income"];
// $time = in_array("ROLE_ADMIN", $this->getUser()->getRoles()) ? "not-evaluate" : $estimatedIncomeAndTime["time"];
// } else {
$price = $validAllAdmin ? $priceOrTimeAdmin['price'] : $estimatedIncomeAndTime["income"];
$time = $validAllAdmin ? $priceOrTimeAdmin['time'] : $estimatedIncomeAndTime["time"];
// }
} else {
$price = $validAllAdmin ? $priceOrTimeAdmin['price'] : $estimatedIncomeAndTime["income"];
$time = $validAllAdmin ? $priceOrTimeAdmin['time'] : $estimatedIncomeAndTime["time"];
}
return [
'price' => $price,
'time' => $time
];
}
#[Route('/subcontractor/html', name: 'mission_subcontractor_html', methods: ['GET', 'POST'])]
public function getMissionSubcontractorHtml(Request $request, UserRepository $userRepository): Response
{
$formEditSubcontractor = $this->createForm(EditSubcontractorParticipantType::class);
return $this->render('services/subcontractror_edit_form.html.twig', [
'formEditSubcontractor' => $formEditSubcontractor->createView(),
'urlAction' => $request->getContent()
]);
}
#[Route('/subcontractor/html/add', name: 'mission_subcontractor_html_add', methods: ['GET', 'POST'])]
public function getMissionSubcontractorHtmlAdd(Request $request): Response
{
return $this->render('services/subcontractror_add_form.html.twig', [
'formAddMissionSubContractor' => $this->createForm(AddMissionSubContractorType::class)->createView(),
'name' => $request->getContent()
]);
}
/**
* @param Mission $mission
* @param FileMission|null $fileMission
* @param Request $request
* @param MessageRepository $messageRepository
* @param InfoMissionRepository $infoMissionRepository
* @param HistoriqueRepository $historiqueRepository
* @return Response
*/
#[Route('/mission/ajouter', name: 'mission_new', methods: ['GET', 'POST'])]
#[Route('/mission/{id}', name: 'mission_edit', methods: ['GET', 'POST'])]
public function handle(Mission $mission, WorkflowRepository $workflowRepository, MessageService $messageService, FileMission $fileMission = null, Request $request, MessageRepository $messageRepository, InfoMissionRepository $infoMissionRepository, HistoriqueRepository $historiqueRepository, EventDispatcherInterface $dispatcher, EntityManagerInterface $entityManager, MissionParticipantRepository $missionParticipantRepository, ServiceRepository $serviceRepository, MissionRepository $missionRepository, UserRepository $userRepository,CampaignRepository $campaignRepository,FileMissionRepository $fileMissionRepository,ParameterBagInterface $parameterBagInterface): Response
{
if ("Espace de discussion" == $mission?->getProduct()?->getName() && count($mission->getCampaign()?->getMissionsWithoutEspaceDeDiscussion()) > 0) {
return $this->redirectToRoute('mission_edit', ['id' => $mission->getCampaign()->getMissionsWithoutEspaceDeDiscussion()?->first()?->getId()], Response::HTTP_SEE_OTHER);
}
//dd($this->missionParticipantService->getUniqByFutureActions($mission->getCampaign()->getId(), $this->getUser()->getId()));
ini_set("memory_limit", "-1");
$routeName = $request->attributes->get('_route');
$confirmation = $request->query->get('confirmation');
$isMine = false;
$companyId = $this->getUser()?->getCompany()?->getId();
foreach ($mission->getParticipants() as $participant) {
if ($participant->getUser()->getId() == $this->getUser()->getId() || $mission->getCampaign()?->getOrderedBy()->getId()== $this->getUser()->getId()) {
$isMine = true;
}
}
if (
$this->isGranted(Role::ROLE_ADMIN->value)
||
($this->isGranted(Role::ROLE_CLIENT_ADMIN->value) && $companyId == $mission->getCampaign()?->getCompany()?->getId())
)
{
$isMine = true;
}
if (!$isMine and $routeName == 'mission_edit') {
$this->addFlash(
type: 'error',
message: "Vous n'etes plus sur cette missions",
);
return $this->redirectToRoute('mission_index');
}
$message = new Message();
$messages = $messageRepository->findBy(['campaign' => $mission->getCampaign()->getId()], ['createdAt' => 'ASC']);
$informations = $infoMissionRepository->findBy(['mission' => $mission->getId()], ['createdAt' => 'ASC']);
$campaign = $mission->getCampaign();
$oldPack = $campaign->getCreditHistory();
$formEditCampaignCredit = $this->createForm(CampaignCreditHistoryType::class, $campaign);
$formEditCampaignCredit->handleRequest($request);
if ($formEditCampaignCredit->isSubmitted() && $formEditCampaignCredit->isValid()) {
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: 'credit_campagne_modified');
$this->contractService->balanceAllocation($campaign, $oldPack);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($campaign);
$entityManager->flush();
$creditHistory = $campaign->getCreditHistory();
$currentBlance = $creditHistory->getCurrentBalance();
$totalPrice = $this->priceService->totalPriceCampaign($campaign, false);
if($currentBlance - $totalPrice < 0) {
$event = new NoticeOfInsufficientBudgetEvent($campaign->getCompany(), $mission->getCampaign());
$this->dispatcher->dispatch($event, NoticeOfInsufficientBudgetEvent::NAME);
}
$this->addFlash('success', 'La contrat de la campagne a bien été modifiée');
return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
}
/*
* Form handle Campaign name
*/
$form1 = $this->createForm(CampaignNameType::class, $campaign);
$form1->handleRequest($request);
if ($form1->isSubmitted() && $form1->isValid()) {
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: 'title_campagne_modified');
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($campaign);
$entityManager->flush();
$this->addFlash('success', 'La campagne a bien été modifiée');
return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
}
if ($this->isGranted(Role::ROLE_ADMIN->value)) {
$priceCampaign = $missionParticipantRepository->findByInitialTime();
$estimatedIncome = [];
$initialTime = [];
$price = [];
foreach ($priceCampaign as $value) {
if (!isset($estimatedIncome[$value->getMission()->getId()])) {
$estimatedIncome[$value->getMission()->getId()] = [];
}
$initialTime[$value->getMission()->getId()][] = $value->getInitialTime();
$price[$value->getMission()->getId()][] = $value->getEstimatedIncome();
}
} elseif ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
$visibleCampaign = ['orderedBy' => $this->getUser()];
$estimatedIncome = $missionParticipantRepository->getSubcontractorForUserAndMission($this->getUser());
} else {
$estimatedIncome = null;
}
$formMissionInitialTime = $this->createForm(MissionParticipantType::class);
$formMissionInitialTimeManually = $this->createForm(MissionParticipantDelaisType::class);
$formMissionIncomeManually = $this->createForm(MissionParticipantIncomeType::class);
/**
* Form handle chatbox
*/
$form = $this->createForm(MessageType::class, $message);
$form->handleRequest($request);
$formAddFileStorage = $this->createForm(StorageMissionType::class,$message);
/*
* Form form add worflow
*/
$formAddWorkflow = $this->createForm(MissionAddWorkflowType::class, $mission);
$formAddWorkflow->handleRequest($request);
if ($formAddWorkflow->isSubmitted() && $formAddWorkflow->isValid()) {
$worklowdId = $request->request->get('mission_add_workflow');
if ($worklowdId != null) {
$worklowdId = $worklowdId['workflow'];
$workflow = $workflowRepository->findOneBy(['id' => $worklowdId]);
$workflowClone = clone $workflow;
$workflowClone->setTemplate(false);
$mission->setWorkflow($workflowClone);
$this->entityManager->persist($workflowClone);
//if campaing is in progress so active first steps
if ($mission->getState() == 'in_progress') {
$step = $mission->getWorkflow()->getSteps()->first();
$step->setActive(true);
if ($step->getManager() == 0) {
$mission->setStateClient('Déclenchement en attente');
} else {
$mission->setStateProvider($step->getName());
}
$this->entityManager->flush();
// $event = new WorkflowStepEnteredEvent($step);
// $dispatcher->dispatch($event, WorkflowStepEnteredEvent::NAME);
}
$this->entityManager->flush();
$this->addFlash('success', 'Le workflow a bien été modifié');
}
return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
}
/*
* Form handle information général
*/
$infoMission = new InfoMission();
$form2 = $this->createForm(InfoMissionType::class, $infoMission);
$form2->handleRequest($request);
if ($form2->isSubmitted() && $form2->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$infoMission->setMission($mission)
->setUser($this->getUser());
$mission->addInfoMission($infoMission);
$entityManager->persist($infoMission);
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Message enregistré avec succés.'
);
return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
}
/*
* Form handle edit single line in information général
*/
$infoFormArr = [];
$infoEditForm = [];
foreach ($informations as $information) {
$key = $information->getId();
$infoEditForm[$key] = $this->createform(InfoMissionType::class, $information);
$infoFormArr[$key] = $infoEditForm[$key]->createView();
}
$actualDesiredDelivery = null;
if (null !== $mission->getDesiredDelivery()) {
$actualDesiredDelivery = clone $mission->getDesiredDelivery();
}
$formChangeDateDelivery = $this->createForm(EditDesiredDeliveryType::class, $mission);
$formChangeDateDelivery->handleRequest($request);
if ($formChangeDateDelivery->isSubmitted() && $formChangeDateDelivery->isValid()) {
if (null !== $actualDesiredDelivery && $actualDesiredDelivery->format('Y-m-d') !== $formChangeDateDelivery->getData()->getDesiredDelivery()->format('Y-m-d')) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($mission);
$entityManager->flush();
if ($mission->getState() != 'provisionnal') {
$event = new MissionDesiredDeliveryUpdatedAfterValidationEvent($mission);
$dispatcher->dispatch($event, MissionDesiredDeliveryUpdatedAfterValidationEvent::NAME);
}
$this->addFlash(
type: 'success',
message: 'La date de livraison souhaitée à bien été modifiée'
);
}
return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
}
$formInitialTime = $this->createForm(ChangeInitialTimeType::class, $mission);
$formInitialTime->handleRequest($request);
if ($formInitialTime->isSubmitted() && $formInitialTime->isValid()) {
$initialTime = $formInitialTime->getData()->getInitialTime();
$product = $mission->getProduct()->getId();
$participant = $missionParticipantRepository->findOneBy(['mission' => $mission]);
$service = $serviceRepository->findOneBy(['user' => $participant->getUser(), 'product' => $product]);
$calculPrice = $initialTime / 60 * $service->getResale() * $mission->getQuantity();
$mission->setPrice($calculPrice);
$entityManager->persist($mission);
$entityManager->flush();
$event = new MissionInitialTimeEvent($mission);
$dispatcher->dispatch($event, MissionInitialTimeEvent::NAME);
$this->addFlash(
type: 'success',
message: 'Le temps initial a bien été ajouté'
);
return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
}
$formRealTime = $this->createForm(ChangeRealTimeType::class, $mission);
$formRealTime->handleRequest($request);
if ($formRealTime->isSubmitted() && $formRealTime->isValid()) {
$entityManager->persist($mission);
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Le temps réel passé a bien été ajouté'
);
return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
}
/**
* Form handle fichier demande initial
*/
$form3 = $this->createForm(FileMissionType::class, $fileMission);
$form3->handleRequest($request);
if ($form3->isSubmitted() && $form3->isValid()) {
$path = 'file_mission_directory';
$entityManager = $this->getDoctrine()->getManager();
$files = $form3->get('fileMissions')->getData();
$filesystem = new Filesystem();
foreach ($files as $file) {
$destination = $this->getParameter($path) . '/' . $mission->getId();
$campaignDestination = $this->getParameter("file_campaing_directory") . '/' . $mission->getCampaign()->getId();
if (!$filesystem->exists($destination)) {
$filesystem->mkdir($destination);
}
if (!$filesystem->exists($campaignDestination)) {
$filesystem->mkdir($campaignDestination);
}
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$newFilename = $originalFilename . '-' . uniqid() . '.' . $file->guessExtension();
// $file->move(
// $destination,
// $newFilename
// );
// $fileMission = $destination."/".$newFilename;
// copy($fileMission,$campaignDestination."/".$newFilename);
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$extensionFile = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
$newFilename = $originalFilename . '-' . uniqid() . '.' . $extensionFile;
//upload file in google storage
$nameUniqueCompany = strtolower("company-".$mission->getCampaign()->getCompany()->getId());
$this->googleStorageService->uploadFile($nameUniqueCompany,$file,$newFilename,'Campaigns/'.$campaign->getId());
$fileMission = new FileMission();
$fileMission->setName($newFilename);
$mission->getCampaign()->addFileMission($fileMission);
$fileMission->setIsNew(1);
$fileMission->setUser($this->getUser());
$entityManager->persist($fileMission);
}
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Le fichier a bien été ajouté à la demande'
);
return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
}
$mission = $mission->getInitialBriefing() == null ? $mission->setInitialBriefing($mission->getCampaign()->getBrief()) : $mission;
$formInitialBrief = $this->createForm(InitialBriefType::class, $mission);
$formInitialBrief->handleRequest($request);
if ($formInitialBrief->isSubmitted() && $formInitialBrief->isValid()) {
$mission->getCampaign()->setBrief($mission->getInitialBriefing());
$entityManager->persist($mission);
// $historique = (new Historique())
// ->setUser($this->getUser())
// ->setMission($mission)
// ->setMessage('Modification de la demande initiale');
// $entityManager->persist($historique);
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "initial_time");
$campaign->setBrief($mission->getInitialBriefing());
//all initial brief is impact of all mission
foreach ($mission->getCampaign()->getMissions() as $otherMission) {
if ($otherMission->getId() !== $mission->getId()) {
$otherMission->setInitialBriefing($mission->getInitialBriefing(), false);
$entityManager->persist($otherMission);
}
}
$entityManager->flush();
$this->addFlash(
type: 'success',
message: 'Demande initiale modifiée avec succès.'
);
return $this->redirectToRoute('mission_edit', ['id' => $mission->getId()], Response::HTTP_SEE_OTHER);
}
$formAddMissionContact = $this->createForm(AddMissionContactType::class, null, ['action' => $this->generateUrl('mission_participant_add', ['mission' => $mission->getId()])]);
$formAddMissionContactProject = $this->createForm(AddMissionContactProjectType::class, null, ['action' => $this->generateUrl('mission_participant_add', ['mission' => $mission->getId()])]);
$formAddMissionContactExternal = $this->createForm(AddMissionContactExternalType::class, null, ['action' => $this->generateUrl('mission_participant_add', ['mission' => $mission->getId()])]);
$formAddMissionSubContractor = $this->createForm(AddMissionSubContractorType::class, null, ['action' => $this->generateUrl('mission_participant_add', ['mission' => $mission->getId()])]);
$formEditSubcontractor = $this->createForm(EditSubcontractorParticipantType::class);
$formCancelMission = $this->createForm(MissionCancelType::class);
$formDeleteCampaign = $this->createForm(CampaignDeleteType::class);
$formCancelCampaign = $this->createForm(CampaignCancelType::class);
//now participant in this mission if edit mission
$missionParticipant = null;
foreach ($mission->getParticipants() as $participant) {
if ($participant->getUser()->getId() == $this->getUser()->getId()) {
$missionParticipant = $participant;
}
}
$allClientParticipantsMail = [];
$allClientParticipants = [];
foreach ($mission->getCampaign()->getMissions() as $m) {
foreach ($m->getParticipants() as $participant) {
if ($participant->getRole() !== Role::ROLE_SUBCONTRACTOR) {
if (!in_array($participant->getUser()->getEmail(), $allClientParticipantsMail)) {
$allClientParticipantsMail[] = $participant->getUser()->getEmail();
$allClientParticipants[] = $participant;
}
}
}
}
$formDesiredDelivery = $this->createForm(DesiredDeliveryType::class,$mission);
$formDesiredDelivery->handleRequest($request);
$allMission = $missionRepository->findBy(['campaign'=>$campaign],['positionOrder'=>'ASC']);
//all files in storage
$allMissionId = [];
foreach ($campaign->getMissions() as $m) {
$allMissionId[] = $m->getId();
}
$allMessageContent = $messageRepository->findMessagesContent($campaign);
$allMessageWithLink = [];
$links = [];
//get all link in message
foreach ($allMessageContent as $message) {
$dom = new \DOMDocument();
if (!empty($message['content']) and $message['content'] != null) {
@$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];
}
}
}
$allMessages = $messageRepository->allMessageHaveFile($campaign);
$allJointes = $fileMissionRepository->allFile($campaign,$allMissionId);
$allFiles = array_merge($allMessageWithLink,$allMessages, $allJointes) ;
usort($allFiles, function($a,$b){
return $b['createdAt'] <=> $a['createdAt'];
});
$url = $parameterBagInterface->get('back_website_url');
//end
$initialDemande = $mission?->getCampaign()?->getBrief();
$joinFilesMessage = $mission->getCampaign()?->getFileMissions();
$futurActions = $this->missionParticipantService->getUniqByFutureActions($mission->getCampaign()->getId(),$this->getUser()->getId());
$thisUserData= $this->getUser()->getUserData();
$activeMissionTab = [];
if($thisUserData != null){
$userActiveMissionTab = $thisUserData->getMissionTabActive();
if(!is_null($userActiveMissionTab)) {
$arrayActiveTabUser = explode('#',$userActiveMissionTab);
if(isset($arrayActiveTabUser[0])){
$activeMissionTab['mission'] = $arrayActiveTabUser[0];
}
if(isset($arrayActiveTabUser[1])){
$activeMissionTab['tab_actif'] = $arrayActiveTabUser[1];
}
}
}
if ($confirmation) {
$this->addFlash(
type: 'success',
message: "Les délais ont été bien mis à jour",
);
}
return $this->renderForm('mission/handle_ux.html.twig', [
'allMessages' => $allFiles,
'price_service' => $this->priceService,
'futurActions' => $futurActions,
'urlDomaine' => $url,
'initialDemande' => $initialDemande,
'joinFilesMessage' => $joinFilesMessage,
'mission' => $mission,
'allMission' => $allMission,
'form' => $form,
'form1' => $form1,
'form2' => $form2,
'form3' => $form3,
'infoFormArr' => $infoFormArr,
'messages' => $messages,
'informations' => $informations,
'formDesiredDelivery'=> $formDesiredDelivery,
'formAddMissionContact' => $formAddMissionContact,
'formAddMissionContactExternal' => $formAddMissionContactExternal,
'formAddMissionContactProject' => $formAddMissionContactProject,
'formEditSubcontractor' => $formEditSubcontractor,
'formChangeDateDelivery' => $formChangeDateDelivery,
'formAddMissionSubContractor' => $formAddMissionSubContractor,
'formMissionInitialTime' => $formMissionInitialTime,
'formMissionInitialTimeManually' => $formMissionInitialTimeManually,
'formMissionIncomeManually' => $formMissionIncomeManually,
'formInitialTime' => $formInitialTime,
'formRealTime' => $formRealTime,
'formInitialBrief' => $formInitialBrief,
'campaign' => $campaign,
'estimatedIncome' => $estimatedIncome,
'formCancelMission' => $formCancelMission,
'formDeleteCampaign' => $formDeleteCampaign,
'formCancelCampaign' => $formCancelCampaign,
'formAddWorkflow' => $formAddWorkflow,
'formEditCampaignCredit' => $formEditCampaignCredit,
'userConnected' => $this->getUser(),
'missionParticipant' => $missionParticipant,
'allClientParticipants' => $allClientParticipants,
'formAddFileStorage' =>$formAddFileStorage,
'userActiveTab' => $activeMissionTab,
]);
}
#[Route('/mission/{id}/refus', name: 'mission_refus', methods: ['GET'])]
public function refuse(Mission $mission, UserRepository $userRepository, Request $request, MissionParticipantRepository $missionParticipantRepository, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher)
{
$intervenant = $userRepository->find($request->query->get('intervenant'));
if (null === $intervenant) {
throw new NotFoundHttpException();
}
$event = new MissionRefusedEvent($mission, $intervenant);
$dispatcher->dispatch($event, MissionRefusedEvent::NAME);
$this->addFlash(
type: 'success',
message: 'La mission a bien été refusée',
);
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "refus");
return $this->redirectToRoute('mission_index');
}
#[Route('/mission/{id}/accepter', name: 'mission_accept', methods: ['GET'])]
public function accept(Mission $mission, ClientSoldService $clientSoldService, UserRepository $userRepository, Request $request, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher)
{
if (empty($request->query->get('intervenant'))) {
$intervenant = $this->getUser();
} else {
$intervenant = $userRepository->find($request->query->get('intervenant'));
}
if (null === $intervenant) {
throw new NotFoundHttpException();
}
if ($mission->getWorkflow()) {
$step = $mission->getWorkflow()->getSteps()->first();
$step->setActive(true);
if ($step->getManager() == 0) {
$mission->setStateClient('Déclenchement en attente');
} else {
$mission->setStateProvider($step->getName());
}
$event = new WorkflowStepEnteredEvent($step);
$dispatcher->dispatch($event, WorkflowStepEnteredEvent::NAME);
}
$campaign = $mission->getCampaign();
$campaign->setState('in_progress');
$mission->setState('in_progress');
$entityManager->flush();
$event = new MissionAcceptedEvent($mission, $intervenant);
$dispatcher->dispatch($event, MissionAcceptedEvent::NAME);
$this->addFlash(
type: 'success',
message: 'La mission a bien été acceptée',
);
return $this->redirectToRoute('mission_index');
}
#[Route('/mission/{id}/{transition<pause|unpause|cancel|archive>}', name: 'mission_transition')]
public function transition(Mission $mission, string $transition, ClientSoldService $clientSoldService, EventDispatcherInterface $dispatcher, Request $request, Registry $workflows, EntityManagerInterface $entityManager): RedirectResponse
{
$workflow = $workflows->get($mission, 'classic');
$originalMission = clone $mission;
$originalCampaign = clone $mission->getCampaign();
if ($workflow->can($mission, $transition)) {
$workflow->apply($mission, $transition);
$applyToCampaign = true;
foreach ($mission->getCampaign()->getMissions() as $otherMission) {
if ($otherMission->getState() !== $mission->getState()) {
$applyToCampaign = false;
break;
}
}
if ($applyToCampaign) {
$campaign = $mission->getCampaign();
$workflow = $workflows->get($campaign, 'classic');
if ($workflow->can($campaign, $transition)) {
$workflow->apply($campaign, $transition);
}
$entityManager->persist($campaign);
}
if ($transition === 'cancel') {
$formCancelMission = $this->createForm(MissionCancelType::class, $mission);
$formCancelMission->handleRequest($request);
$mission->setLastState($originalMission->getState());
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "cancel");
//when all mission is canceled change status campaing
$allmissionIsCanceled = true;
foreach ($originalCampaign->getMissions() as $missionP) {
if ($missionP->getState() != "cancelled") {
$allmissionIsCanceled = false;
}
}
if ($allmissionIsCanceled) {
$mission->getCampaign()->setLastState($originalCampaign->getState());
$mission->getCampaign()->setState("cancelled");
}
$event = new MissionCancelledEvent($mission);
$dispatcher->dispatch($event, MissionCancelledEvent::NAME);
}
}
if ($transition === 'archive') {
$event1 = new MissionClosedEvent($mission);
$dispatcher->dispatch($event1, MissionClosedEvent::NAME);
$mission->setState('finalized');
$mission->setLastState($originalMission->getLastState());
$event = new MissionArchivedEvent($mission);
$dispatcher->dispatch($event, MissionArchivedEvent::NAME);
$numberOfMissionFinalized = 0;
$campaign = $mission->getCampaign();
if ($mission->getProduct()->getType() != ProductType::AU_FORFAIT) {
$clientSoldService->decreaseCurrentBalanceByMissionCost(mission: $mission);
}
foreach ($campaign->getMissions() as $missionPersited) {
if ($missionPersited->getProduct()->getName() == "Espace de discussion") {
$numberOfMissionFinalized++;
}
if ($missionPersited->getid() == $mission->getId()) {
$numberOfMissionFinalized++;
} elseif ($missionPersited->getState() == "finalized" or $missionPersited->getState() == "cancelled") {
$numberOfMissionFinalized++;
}
}
if ($numberOfMissionFinalized == sizeof($campaign->getMissions())) {
$campaign->setState('closed');
$entityManager->persist($campaign);
$this->addFlash(
type: 'success',
message: 'La campagne a bien été clôturée',
);
}
}
$entityManager->flush();
$message = match ($transition) {
'archive' => 'archivée',
'pause' => 'mise en pause',
'unpause' => 'relancée',
'cancel' => 'annulée',
default => 'enregistrée',
};
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: $transition);
$this->addFlash(
type: 'success',
message: 'La mission a bien été ' . $message,
);
return $this->redirectToRoute('mission_index');
}
#[Route('/mission/{id}/list/participant', name: 'mission_list_participant', methods: ['GET'])]
public function ListParticipant($id, Request $request, MissionRepository $missionRepository, MissionParticipantRepository $missionParticipantRepository, ServiceRepository $serviceRepository, PriceService $priceService)
{
$mission = $missionRepository->find($id);
$formMissionInitialTimeManually = $this->createForm(MissionParticipantDelaisType::class);
return $this->renderForm(
'mission/_modal_list_all_participant.html.twig',
[
'mission' => $mission,
'campaign' => $mission->getCampaign(),
'formMissionInitialTimeManually' => $formMissionInitialTimeManually
]
);
}
#[Route('/mission/{id}/activation', name: 'mission_activate', methods: ['GET', 'POST'])]
public function Activate(NumberFormatService $numberFormatService, MyFlowMarginService $myFlowMarginService, MissionService $missionService, ClientSoldService $clientSoldService, Mission $mission, EventDispatcherInterface $dispatcher, EntityManagerInterface $entityManager, MissionParticipantRepository $missionParticipantRepository, RouterInterface $router, PriceService $priceService, WorkflowStepRepository $workflowStepRepository): RedirectResponse
{
$error = false;
if (!$this->missionService->canActivateMission(mission: $mission)) {
$error = true;
$this->addFlash(
type: 'error',
message: 'La mission n\'est pas activable pour le moment'
);
return $this->redirectToRoute('mission_index');
}
if (null === $mission->getWorkflow()) {
$error = true;
$this->addFlash(
type: 'error',
message: 'La mission n\'a pas de workflow, merci de contacter l\'administrateur',
);
return $this->redirectToRoute('mission_index');
}
$campaign = $mission->getCampaign();
if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value) or $this->isGranted(Role::ROLE_ADMIN->value)) {
$missionService->setDefaultValueIfAnUserClickedAnActivationButtonWithoutADelaisAndTimeIsEmpty($mission, $priceService);
if (empty($mission->getPreActivatedAt())) {
$mission->setPreActivatedAt(new \DateTime());
}
//////////////////// Check marge mission
$getMargeMyFlow = $priceService->marginExceeded(mission: $mission);
if ($getMargeMyFlow['marginExceeded'] == true and $mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
$error = true;
$this->addFlash(
type: 'error',
message: "Nous avons rencontré un problème, l'administrateur vient d'être informé pour activer la mission",
);
$event = new MissionCanActivateEvent(mission: $mission);
$dispatcher->dispatch($event, MissionCanActivateEvent::NAME);
return $this->redirectToRoute('mission_index');
}
if ($this->isGranted(Role::ROLE_ADMIN->value)) {
$this->addFlash(
type: 'success',
message: "La mission {$mission->getReference()} a bien activée",
);
}
}
////////////////////////
foreach ($mission->getParticipants() as $missionParticipation) {
if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
if ($this->getUser() == $missionParticipation->getUser()) {
// check marge Myflow
$missionParticipation->setActivated(true);
$missionParticipation->setActivatedAt(new \DateTime());
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "activation");
$entityManager->persist($missionParticipation);
$entityManager->flush();
break;
}
} elseif ($this->isGranted(Role::ROLE_ADMIN->value)) {
$missionParticipation->setActivated(true);
$missionParticipation->setActivatedAt(new \DateTime());
$entityManager->persist($missionParticipation);
$entityManager->flush();
}
}
if (sizeof($this->missionService->getListSubcontractorNotActivate(mission: $mission)) == 0) {
if ($mission->getProduct()->getType() === ProductType::A_EVALUER) {
$client = $mission->getCampaign()->getOrderedBy();
$event = new MissionActivatedEvent($mission, $client);
$dispatcher->dispatch($event, MissionActivatedEvent::NAME);
}
if ($this->missionService->lackSubcontractorTest(mission: $mission)) {
$event = new MissionNotificationActivatedEvent($mission);
$dispatcher->dispatch($event, MissionNotificationActivatedEvent::NAME);
$this->addFlash(
type: 'success',
message: "La mission {$mission->getReference()} a bien activée",
);
} else {
$this->addFlash(
type: 'success',
message: "Votre activation a bien été prise en compte.Nous devons toutefois attendre d'autres intervenants pour démarrer la mission. Vous serez prochainement notifié par Email.",
);
}
if ($mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
$clientSoldService->decreaseCurrentBalanceByMissionCost(mission: $mission);
}
if ($error === false) {
$mission->setState('in_progress');
////////////////////////////////
//////////////////////
$entityManager->flush();
}
} else {
$this->addFlash(
type: 'success',
message: "Votre activation a bien été prise en compte.Nous devons toutefois attendre la validation des autres intervenants pour démarrer la mission. Vous serez prochainement notifié par Email.",
);
}
//new validation for all subcontractor not activate
foreach ($this->campaignService->getListSubcontractorNotActivate(campaign: $campaign) as $participant) {
$event = new MissionAcceptedEvent($mission, $participant);
$dispatcher->dispatch($event, MissionAcceptedEvent::NAME);
}
if ($this->campaignService->isCanStart(campaign: $campaign)) {
$campaign->setState('in_progress');
$campaign->setReSendToClient(false);
$campaign->setClientStatus("");
// --------------------------
$campaign->setReSendToClient(false);
foreach ($campaign->getMissions() as $mission) {
if (!empty($mission->getWorkflow())) {
//take a step first by position
$step = $workflowStepRepository->getFirstStep($mission->getWorkflow());
$step->setActive(true);
} else {
$this->addFlash(
type: 'error',
message: 'Activation impossible car la campagne n\'a pas de workflow',
);
return $this->redirectToRoute('mission_index');
}
if ($step->getManager() == 0) {
$mission->setStateClient('Déclenchement en attente');
} else {
$mission->setStateProvider($step->getName());
}
$event = new WorkflowStepEnteredEvent($step);
$dispatcher->dispatch($event, WorkflowStepEnteredEvent::NAME);
}
// ---------------------------
$this->addFlash(
type: 'success',
message: "La campagne {$campaign->getName()} à démarrer ",
);
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "activation");
}
//if error not persist
if ($error === false) {
$entityManager->flush();
}
}
return $this->redirectToRoute('mission_index');
}
#[Route('/mission/{id}/uncancelled', name: "mission_uncancelled")]
public function missionUncancelled(Mission $mission, EntityManagerInterface $entityManagerInterface): Response
{
$mission->setState($mission->getLastState());
$entityManagerInterface->flush();
$this->addFlash(
type: 'success',
message: "La mission reprend avec succès ",
);
return $this->redirectToRoute('mission_index');
}
#[Route('/mission/desired-delivery/{id}', name: "mission_desired_delivery_change")]
public function changeDesiredDelivery(Mission $mission,EventDispatcherInterface $dispatcher, Request $request, EntityManagerInterface $entityManager){
$date = $request->request->get('desired-delivery');
$datetime = new DateTime($date);
$mission->setDesiredDelivery($datetime);
$entityManager->persist($mission);
$entityManager->flush();
$event = new MissionDesiredDeliveryUpdatedAfterValidationEvent($mission);
$dispatcher->dispatch($event, MissionDesiredDeliveryUpdatedAfterValidationEvent::NAME);
$this->missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "deadline_change");
$this->addFlash('success','Nouvelle échéance enregistrée avec succès');
return $this->redirectToRoute('mission_edit',['id'=>$mission->getId()]) ;
}
#[Route('/mission/file-history/{id}/{type}/{fileName}', name: "file_history")]
public function addFileHistory(Mission $mission,MissionService $missionService,string $type, string $fileName){
if($type=='save'){
$bucket = strtolower("company-".$mission->getCampaign()->getCompany()->getId());
$missionService->addHistorique($mission, $this->getUser(), 'save_file', $fileName) ;
}
elseif($type=="delete"){
$missionService->addHistorique($mission, $this->getUser(), 'delete_file', $fileName) ;
}
return new JsonResponse([
'status'=>'ok'
]) ;
}
#[Route('/mission/file-save/{id}/all', name: "file_history_save_all")]
public function saveFileHistory(Mission $mission,MissionService $missionService,){
// $company = $mission->getCampaign()->getCompany();
// $campaign = $mission->getCampaign();
// $nameOfBucket = strtolower("company-".$company->getId());
// $path = 'file_campaing_directory';
// $pathMessage = "file_message_directory";
// $backurl = 'back_website_url';
// $destZip = $this->getParameter($path) . '/' . $mission->getCampaign()->getId()."/zip/";
// $dest = $this->getParameter($path) . '/' . $mission->getCampaign()->getId().'/';
// $destMessage = $this->getParameter($pathMessage)."/";
// $destinationPath = $this->getParameter($path) . '/' . $mission->getCampaign()->getId()."/zip/";
// $url = $this->getParameter($backurl) . '/uploads/campaign/' . $mission->getCampaign()->getId()."/zip/";
// $zip = new \ZipArchive();
// if (!is_dir($destinationPath)) {
// mkdir($destinationPath, 0777, true);
// }
// $cheminDestination = '/uploads/campaign/'.$mission->getCampaign()->getId()."/";
// $cheminFichierZip = $destZip.$mission->getCampaign()->getId().".zip";
// //supprimer le fichier zip en premier
// if(is_file($cheminFichierZip)){
// unlink($cheminFichierZip);
// }
// if ($zip->open($cheminFichierZip, \ZipArchive::CREATE) === true) {
// $listOfFiles = [];
// //list of file in campaing
// foreach ($campaign->getMessages() as $message) {
// foreach ($message->getFileMessages() as $file) {
// if ($file->isIsNew()) {
// $year = $message->getCreatedAt()->format('Y');
// $month = $message->getCreatedAt()->format('m');
// $listOfFiles[] = "Campaigns/{$campaign->getId()}/{$file->getName()}";
// }
// }
// }
// foreach ($campaign->getFileMissions() as $file) {
// if ($file->isIsNew()) {
// $year = $file->getCreatedAt()->format('Y');
// $month = $file->getCreatedAt()->format('m');
// $listOfFiles[] = "Campaigns/{$campaign->getId()}/{$file->getName()}";
// }
// }
// //end
// $objects = $this->googleStorageService->getAllObject($nameOfBucket,$listOfFiles);
// foreach ($objects as $object) {
// $objectName = $object->name();
// if (in_array($objectName, $listOfFiles)) {
// $fileContent = $object->downloadAsString();
// $nameOfFile = explode("/", $object->name());
// $zip->addFromString($nameOfFile[2], $fileContent);
// }
// }
// //for the file of campaing
// foreach ($mission->getCampaign()->getFileMissions() as $file) {
// if (is_file($dest.$file->getName())) {
// $zip->addFile($dest.$file->getName(), $file->getName());
// }
// }
// //for the file of all messages
// $filesystem = new Filesystem();
// $fileAlredyZip = [];
// foreach ($campaign->getMessages() as $message) {
// foreach ($message->getFileMessages() as $file) {
// foreach ($mission->getCampaign()->getMissions() as $mission) {
// $destination = "{$destMessage}{$mission->getId()}/message/{$file->getName()}";
// if($filesystem->exists($destination) && !in_array($file->getName(), $fileAlredyZip)){
// $zip->addFile($destination, $file->getName());
// $fileAlredyZip[] = $file->getName();
// }
// }
// }
// }
// $zip->close();
// }
return new JsonResponse([
'file'=> $this->googleStorageService->saveFileHistory($mission, $missionService)
]) ;
}
#[Route('/mission/file-save-one/{id}', name: "file_save")]
public function donwloadFile(Mission $mission, MissionService $missionService,GoogleStorageService $googleStorageService,Request $request){
$url = $request->request->get('url');
$company = $mission->getCampaign()->getCompany();
$nameOfBucket = strtolower("company-".$company->getId());
return new JsonResponse($this->googleStorageService->getUrl($nameOfBucket,$url));
}
private function addLeadingSlashToImagePath($htmlContent) {
// Use preg_replace to find image tags and modify the src attribute
$pattern = '/<img([^>]+)src="([^"]+)"([^>]+)>/';
$replacement = '<img$1src="/$2"$3>'; // Add a slash at the beginning of the captured src attribute
$newHtmlContent = preg_replace($pattern, $replacement, $htmlContent);
return $newHtmlContent;
}
#[Route('/update-active-tab', name: "update_active_tab")]
public function UpdateActiveTab(Request $request,EntityManagerInterface $entityManager) : JsonResponse
{
$missionActiveTab = $request->request->get('mission-active-tab');
$connectedUser = $this->getUser();
if($connectedUser->getUserData() == null) {
$userData = new UserData();
$userData->setMissionTabActive($missionActiveTab);
}else{
$userData = $connectedUser->getUserData();
$userData->setMissionTabActive($missionActiveTab);
}
$entityManager->persist($userData);
$connectedUser->setUserData($userData);
$entityManager->persist($connectedUser);
$entityManager->flush();
return new JsonResponse('ok');
}
}