<?php
namespace App\Controller;
use App\Enum\Role;
use Dompdf\Dompdf;
use Dompdf\Options;
use App\Entity\User;
use App\Enum\TypePack;
use GuzzleHttp\Client;
use App\Entity\Company;
use App\Entity\Mission;
use App\Entity\Product;
use App\Form\AddMissionContactProjectType;
use App\Entity\Service;
use App\Enum\AdminMail;
use App\Entity\Campaign;
use App\Enum\ProductType;
use App\Entity\Historique;
use App\Form\CampaignType;
use App\Entity\FileMission;
use App\Enum\TypeFrequency;
use App\Entity\CreditHistory;
use App\Service\OrderService;
use App\Service\PriceService;
use App\Service\UtilsService;
use App\Service\CompanyService;
use App\Service\MissionService;
use App\Form\CampaignCancelType;
use App\Form\CampaignDeleteType;
use App\Form\CampaignEditWpType;
use App\Service\CampaignService;
use App\Service\ContractService;
use App\Event\ClientUpdatedEvent;
use App\Form\ListMissionFormType;
use App\Repository\JobRepository;
use App\Entity\MissionParticipant;
use App\Repository\UserRepository;
use App\Service\ClientSoldService;
use Symfony\Component\Mime\Address;
use App\Enum\CampaignTypeInitiation;
use App\Service\MyFlowMarginService;
use App\Service\NumberFormatService;
use App\Event\AdminCommandErrorEvent;
use App\Repository\CompanyRepository;
use App\Repository\MissionRepository;
use App\Repository\ProductRepository;
use App\Service\GoogleStorageService;
use App\Repository\CampaignRepository;
use App\Repository\WorkflowRepository;
use App\Service\CampaignWpEditService;
use App\Event\Mission\MissionSendEvent;
use App\Event\Mission\ContactAddedEvent;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Workflow\Registry;
use App\Event\Client\PremiumPackageEvent;
use App\Repository\FileMissionRepository;
use App\Service\CampaignRecurrentService;
use App\Repository\WorkflowStepRepository;
use App\Service\MissionParticipantService;
use App\Event\Campaign\CampaignResendEvent;
use App\Event\Campaign\CampaignResumeEvent;
use App\Repository\CreditHistoryRepository;
use App\Event\Campaign\CampaignCreatedEvent;
use App\Event\Campaign\CampaignDeclineEvent;
use App\Event\Campaign\CampaignDeletedEvent;
use App\Event\Campaign\CampaignWaitingEvent;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpClient\HttpClient;
use App\Event\Campaign\CampaignModifiedEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use App\Event\Campaign\CampaignCancelledEvent;
use App\Event\Campaign\CampaignRecurrentEvent;
use App\Event\Campaign\CampaignValidatedEvent;
use App\Event\Mission\MissionCanActivateEvent;
use App\Form\EditSubcontractorParticipantType;
use Symfony\Component\HttpFoundation\Response;
use App\Event\Campaign\DevisCreatedNotFinished;
use App\Service\ActivationSubcontractorService;
use Symfony\Bridge\Twig\Mime\NotificationEmail;
use Symfony\Component\Routing\Annotation\Route;
use App\Event\Campaign\CampaignEvaluationEventt;
use App\Event\Campaign\CampaignNotFinishedEvent;
use App\Repository\MissionParticipantRepository;
use App\Repository\BalanceTransactionsRepository;
use App\Event\Mission\MissionWithoutWorkflowEvent;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Service\ConsumptionBalanceForCompanyService;
use App\Event\Workflow\Step\WorkflowStepEnteredEvent;
use Symfony\Component\Serializer\SerializerInterface;
use App\Event\SubcontractorActivateOrThereIsABotEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use App\Event\Workflow\Step\WorkflowFirstStepEnteredEvent;
use App\Event\Campaign\CampaignValidatedPerActivationEvent;
use App\Event\SubContractor\SubContractorMissionAddedEvent;
use App\Form\DataTransformer\ProductTextToObjectTransformer;
use App\Event\Mission\MissionWithoutSubContractorCheckedEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use App\Event\Campaign\CampaignNotifyThatDeliveryDateChangeEvent;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Event\Mission\MissionDesiredDeliveryUpdatedAfterValidationEvent;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use App\Event\Mission\MissionDesiredDeliveryUpdatedBeforeValidationEvent;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use App\Event\SubContractorVigilanceCertificateAbsentEvent;
use App\Entity\BalanceTransactions;
use App\Event\Campaign\CampaignEvaluationEvent;
use App\Service\DynamicHostService;
use App\Service\CampaignApiService;
use App\Entity\Workflow;
class CampaignController extends AbstractController
{
public function __construct(
private CampaignService $campaignService,
private MissionService $missionService,
private UtilsService $utilsService,
private ProductTextToObjectTransformer $productTextToObjectTransformer,
private ContractService $contractService,
private GoogleStorageService $googleStorageService,
private DynamicHostService $dynamicHostService,
private CampaignApiService $campaignApiService,
) {
}
/**
* @param UserRepository $userRepository
* @param Request $request
* @return JsonResponse
*/
#[Route('/api/client-infos', name: 'get_client_info', methods: ['GET'])]
public function clientInfos(UserRepository $userRepository, Request $request): JsonResponse
{
$email = base64_decode($request->get('emailCli'));
$user = $userRepository->findOneByEmail($email);
$company = $user->getCompany();
$response = new JsonResponse(
[
'companyName' =>$company != null ?$company->getName() : '--',
'cellPhone' => $user->getCellPhone(),
'address'=> $company != null ?$company->getCompanyData()->getAddress() : '--',
]
);
$response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type');
return $response;
}
/**
* @param CampaignRepository $campaignRepository
* @param Request $request
* @return JsonResponse
*/
#[Route('/search', name: 'result_for_search_bar', methods: ['GET'])]
public function search(CampaignRepository $campaignRepository, Request $request): JsonResponse
{
$data = [];
$query = ($request->get('query'));
$archived = ($request->get('archived'));
$deleted = ($request->get('deleted'));
$company = null;
$subContractorAndAdmin = ($this->isGranted(Role::ROLE_ADMIN->value) or $this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) ? true : false;
$isSubcontractor = ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) ? true : false;
//determine who is connected and return result by user
if ($this->isGranted(Role::ROLE_ADMIN->value)) { //all campaing
$user = null;
} elseif ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) { //only your campaing in all company
$user = $this->getUser();
} else { //user only all campain in all company
$user = $this->getUser();
$company = $user->getCompany();
}
$campaigns = $campaignRepository->querySearch($query, $archived, $user, $company, $subContractorAndAdmin, $deleted,$isSubcontractor);
foreach ($campaigns as $campaign) {
$data[] = ['name' => str_pad($campaign['reference'], 5, 0, STR_PAD_LEFT) . " " . $campaign['name'] . " (" . $campaign['nameCompany'] . ") ", 'key' => $query, 'idCampaing' => $campaign['id']];
}
$response = new JsonResponse(['data' => $data]);
$response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type');
return $response;
}
/**
* @param UserRepository $userRepository
* @param ProductRepository $productRepository
* @param Request $request
* @return JsonResponse
*/
#[Route('/api/remise-product-credit', name: 'get_price_product_with_remise_when_credit', methods: ['GET'])]
public function remiseProduct(UserRepository $userRepository, ProductRepository $productRepository, Request $request): JsonResponse
{
$email = base64_decode($request->get('emailCli'));
$credit = 220;
$product = $productRepository->findOneByFrontId($request->get('product_id'));
$user = $userRepository->findOneByEmail($email);
$discount = $user->getCompany()->getCustomerDiscount();
$response = new JsonResponse(
[
'product_price' => $product->getPrice(),
'discount' => $discount,
'price_credit_with_remise' => ($credit - (($credit * $discount) / 100))
]
);
$response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type');
return $response;
}
/**
* @param CompanyRepository $companyRepository
* @param Request $request
* @return JsonResponse
*/
#[Route('/api/premium-package', name: 'premium_package', methods: ['POST'])]
public function premiumPackage(UserRepository $userRepository, EventDispatcherInterface $dispatcher, Request $request): JsonResponse
{
$email = $request->request->get('email');
$otherEmail = $request->request->get('otherEmail');
$user = $userRepository->findOneByEmail($email);
try {
$event = new PremiumPackageEvent($user, $otherEmail);
$dispatcher->dispatch($event, PremiumPackageEvent::NAME);
$response = new JsonResponse(['success']);
} catch (\Error $e) {
$response = new JsonResponse(['failed']);
}
$response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type');
return $response;
}
/**
* @param CompanyRepository $companyRepository
* @param Request $request
* @return JsonResponse
*/
#[Route('/api/discount', name: 'company_discount', methods: ['POST'])]
public function discount(CompanyRepository $companyRepository, Request $request): JsonResponse
{
$id = $request->request->get('id');
$company = $companyRepository->findByFrontId((int)$id);
return new JsonResponse((int)$company[0]->getCustomerDiscount());
}
/**
* @param CompanyRepository $companyRepository
* @param Request $request
* @return JsonResponse
*/
#[Route('/api/discountinBack/{id}', name: 'company_discount_in_back', methods: ['GET'])]
public function discountInBack($id,CompanyRepository $companyRepository, Request $request): JsonResponse
{
$company = $companyRepository->findById($id);
return new JsonResponse($company[0]->getCustomerDiscount());
}
/**
* @param CompanyRepository $companyRepository
* @param Request $request
* @return JsonResponse
*/
#[Route('/api/getAllUser/{id}/{idCampaing}', name: 'company_getAll_user_in_back', methods: ['GET'])]
public function allUsersCompany($id,$idCampaing, CampaignApiService $campaignApiService, UserRepository $userRepository,CampaignRepository $campaignRepository, Request $request,CompanyRepository $companyRepository): JsonResponse
{
/*
return sprintf('%s - %s (%s)', $user->getLastname(), $user->getFirstname(), $user->getEmail());
*/
$alldataUser = [];
$alldataUser[] = [
'id' => 0,
'text' => 'Choisir un utilisateur',
];
$company = $companyRepository->find($id);
if($this->getUser()!=null && in_array('ROLE_SUBCONTRACTOR', $this->getUser()->getRoles())){
$campaigns = $campaignRepository->findAllInterlocutors($this->getUser(), 5);
$allClientParticipantsMail = [];
$allClientParticipants = [];
foreach ($campaigns as $campaign) {
foreach ($campaign->getMissions() as $mission) {
foreach ($mission->getParticipants() as $participant) {
if ($participant->getRole() !== Role::ROLE_SUBCONTRACTOR && !in_array('ROLE_ADMIN',$participant->getUser()->getRoles()) ) {
if (!in_array($participant->getUser()->getEmail(), $allClientParticipantsMail)) {
$allClientParticipantsMail[] = $participant->getUser()->getEmail();
$allClientParticipants[] = $participant->getUser();
}
}
}
}
}
$allUsers = $allClientParticipants;
}
else{
$allUsers = $userRepository->findByIdCompany($id,$company);
}
//get all user externaly
$ids = [];
$campaign = $campaignRepository->find($idCampaing);
if (!is_null($campaign) and !empty($campaign)) {
$userExternal = $campaign->getAllUserExternal();
$additionnal = $campaignApiService->getAdditionalUserEmail($campaign, true);
if (!is_null($userExternal) and !empty($userExternal)) {
foreach($userExternal as $user) {
if (!in_array($user->getId(), $ids)) {
$alldataUser []= [
'id' => $user->getId(),
'text' => sprintf('%s - %s (%s)', $user->getLastname(), $user->getFirstname(), $user->getEmail())
];
}
$ids[] = $user->getId();
}
}
foreach($additionnal as $user) {
if (!in_array($user->getId(), $ids)) {
$alldataUser []= [
'id' => $user->getId(),
'text' => sprintf('%s - %s (%s)', $user->getLastname(), $user->getFirstname(), $user->getEmail())
];
}
$ids[] = $user->getId();
}
}
foreach ($allUsers as $user) {
if (!in_array($user->getId(), $ids)) {
$alldataUser[] = [
'id' => $user->getId(),
'text' => sprintf('%s - %s (%s)', $user->getLastname(), $user->getFirstname(), $user->getEmail())
];
}
$ids[] = $user->getId();
}
return new JsonResponse(($alldataUser));
}
/**
* @param CompanyRepository $companyRepository
* @param Request $request
* @return JsonResponse
*/
#[Route('/api/getAllJob/{id}', name: 'product_all_id_job', methods: ['GET'])]
public function allJobId($id,ProductRepository $productRepository, Request $request): JsonResponse
{
$idJob = "";
$product = $productRepository->findById((int) $id );
if (!empty($product)) {
foreach ($product[0]->getJobs() as $job) {
$idJob .= $job->getId().",";
}
}
return new JsonResponse($idJob);
}
/**
* @param CompanyRepository $companyRepository
* @param Request $request
* @return JsonResponse
*/
#[Route('/api/creditHistory/company/{id}', name: 'company_get_credit_in_back', methods: ['GET'])]
public function creditHistoryForCompany($id,CreditHistoryRepository $creditHistoryRepository, CompanyRepository $companyRepository, Request $request)
{
$company = $companyRepository->findById($id);
$creditHistory = $creditHistoryRepository->findAvailableServiceHistory($company[0],new \DateTime());
return $this->renderForm('credit_history/list.html.twig', [
'creditHistory' => $creditHistory,
]);
}
/**
* @param CompanyRepository $companyRepository
* @param Request $request
* @return JsonResponse
*/
#[Route('/api/imgCompany', name: 'company_img', methods: ['GET'])]
public function imgCompany(CompanyRepository $companyRepository, Request $request, ParameterBagInterface $parameter): JsonResponse
{
$idCompany = $request->get('companyId');
$urlDir = $parameter->get('dir_logo_company');
if (empty($idCompany)) {
$response = new JsonResponse(['failed']);
}
$company = $companyRepository->findById($idCompany);
if (is_null($company[0]?->getLogoName())) {
$response = new JsonResponse(['failed']);
} else {
$response = new JsonResponse([$urlDir . $company[0]->getLogoName()]);
}
$response->setEncodingOptions($response->getEncodingOptions() | JSON_UNESCAPED_UNICODE);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type');
return $response;
}
/**
* Display the view/handle how to edit a campaign
*
* @param Request $request
* @param EntityManagerInterface $entityManager
* @return Json
*/
#[Route('/api/preCommande', name: 'pre_commande', methods: ['POST'])]
public function preCommande(Request $request, EntityManagerInterface $entityManager, UserRepository $userRepository, ProductRepository $productRepository, EventDispatcherInterface $dispatcher)
{
$campaignData = $request->request->get('campaign');
$missionData = $request->request->get('missions');
$type = $request->request->get('type');
$user = $userRepository->findOneBy(['email' => $campaignData['orderedBy']]);
$admins = $this->dynamicHostService->getMailAdmin();
$campaign = new Campaign();
$campaign->setName($campaignData['name'])
->setBrief($campaignData['brief']);
$entityManager->persist($campaign);
$campaign->setCompany($user->getCompany())
->setOrderedBy($user);
foreach ($missionData as $missions) {
if (isset($missions['product'])) {
$mission = new Mission();
$product = $productRepository->findByFrontId($missions['product']);
if (!empty($product)) {
$mission->setProduct($product[0])
->setPrice(floatval(str_replace(",", ".", $missions['price'])))
->setQuantity($missions['quantity']);
}
$campaign->addMission($mission);
}
}
if ($type === "devis") {
$event = new DevisCreatedNotFinished($campaign, $user);
$dispatcher->dispatch($event, DevisCreatedNotFinished::NAME);
} else {
$event = new CampaignNotFinishedEvent($campaign, $mission, $user);
$dispatcher->dispatch($event, CampaignNotFinishedEvent::NAME);
}
$entityManager->remove($campaign);
$entityManager->flush();
return new JsonResponse([]);
}
#[Route('/campaigns/draft/edit/{id}', name: 'edit_draft', methods: ['GET','POST'])]
public function editDraft(Campaign $campaign,CampaignWpEditService $campaignWpEditService, EntityManagerInterface $entityManager, Request $request,MissionParticipantService $missionParticipantService,EventDispatcherInterface $dispatcher,UserPasswordHasherInterface $passwordHasher,UserRepository $userRepository, CompanyService $companyService, CreditHistoryRepository $creditHistoryRepository){
if($campaign->getState() == 'draft'){
$formWpEdit = $this->createForm(CampaignEditWpType::class, $campaign);
$formWpEdit->handleRequest($request);
if($formWpEdit->isSubmitted()){
$campaignWpEditService->removeAllParticipantNotSubcontractor($campaign);
$participants = $request->request->get('participants');
$creditHistoryId = $request->request->get('campaign_edit_wp')['contract'];
$confidentiality = isset($request->request->get('campaign_edit_wp')['confidentiality']) ? true : false;
$attachements = $request->files->get('attachements');
// dd($request->files->get('attachements'));
if($creditHistoryId != null){
$creditHistory = $creditHistoryRepository->findOneById($creditHistoryId);
$campaign->setCreditHistory($creditHistory);
}
$campaign->setConfidentiality($confidentiality);
$observerList = [];
$defaultValidator = [];
$defaultValidatorExternal = [];
$defaultObserverExernal = [];
foreach ($campaign->getMissions() as $mission) {
if($participants != null){
foreach ($participants as $participant) {
$email = $participant['email_de_participant'];
$role = $participant['type_de_participant'];
$role = $campaignWpEditService->formatToValidRole($role);
$user = $userRepository->findOneBy(['email' => $email]);
$role_client = "ROLE_CLIENT";
if (null === $user) {
$user = (new User())
->setEmail($email)
->setRoles([$role_client])
->setEnabled(false)
->setIsNewClient(true)
;
$user->setPassword($passwordHasher->hashPassword($user, $user->getPassword()));
$entityManager->persist($user);
$entityManager->flush();
$event = new ClientUpdatedEvent($user, true);
$newUserCreateId[] = $user->getId();
$dispatcher->dispatch($event, ClientUpdatedEvent::NAME);
}
if($this->campaignService->isMyCompany($campaign->getCompany(), $user) || $this->campaignService->isMyEmailSameExtensionOfCompanyExtension($campaign->getCompany(),$user)){
$user->setCompany($campaign->getCompany());
$role = $this->campaignService->getRoleForInternalClient(Role::tryFrom($role ));
switch ($role->value) {
case 'ROLE_OBSERVER':
$observerList = [...$observerList, $user->getEmail()];
break;
case 'ROLE_VALIDATOR':
$defaultValidator = [...$defaultValidator, $user->getEmail()];
break;
}
}else{
$role = $this->campaignService->getRoleForExternalClient(Role::from($role ));
switch ($role->value) {
case 'ROLE_VALIDATOR_EXTERNAL':
$defaultValidatorExternal = [...$defaultValidatorExternal, $user->getOriginalMailUser()];
break;
case 'ROLE_OBSERVER_EXTERNAL':
$defaultObserverExernal = [...$defaultObserverExernal, $user->getOriginalMailUser()];
break;
}
}
$campaignWpEditService->addPartipant($mission, $email, $role->value );
}
}
}
$campaign->setDefautObserver($observerList);
$campaign->setDefautObserverExternal($defaultObserverExernal);
$campaign->setDefaultValidator($defaultValidator);
$campaign->setDefaultValidatorExternal($defaultValidatorExternal);
$campaign->setLastStepWp(4);
$entityManager->flush();
$pathCampaing = 'file_campaing_directory';
$pathMission = 'file_mission_directory';
foreach ($attachements as $file) {
$destination = $this->getParameter($pathCampaing) . '/' . $campaign->getId();
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$newFilename = $originalFilename . '-' . uniqid() . '.' . $file->guessExtension();
$file->move(
$destination,
$newFilename
);
$fileMission = new FileMission();
$fileMission->setName($newFilename);
$campaign->addFileMission($fileMission);
//add to mission
foreach ($campaign->getMissions() as $mission) {
$destinationFileMission = $this->getParameter($pathMission) . '/' . $mission->getId();
if (!is_dir($destinationFileMission)) {
mkdir($destinationFileMission, 0755, true);
}
copy($destination . '/' . $newFilename, $destinationFileMission . '/' . $newFilename);
$fileMission = new FileMission();
$fileMission->setName($newFilename);
$mission->addFileMission($fileMission);
}
}
$entityManager->flush();
return $this->redirectToRoute('campaign_recapitulatif',[
'id'=>$campaign->getId(),
'showStep'=> 'step'
]);
}
$creditHistories= $companyService->getAvailableContract(creditHistories: $creditHistoryRepository->findAvailableServiceHistory($campaign->getCompany(),new \DateTime()));
$creditHistoriesFormated = array_reduce($creditHistories, function($carry, $item){ return [...$carry, ...$item];},[]);
$participants = $missionParticipantService->getParticipants($campaign, 'user', false);
return $this->render('/draft/edit.html.twig',[
'campaign'=>$campaign,
'form_wp_edit'=> $formWpEdit->createView(),
'credit_histories' => $creditHistoriesFormated,
'participants_client' => $missionParticipantService->getClient($campaign, '', false),
'participants_subcontractor' => $missionParticipantService->getSubcontractorWithMissing($campaign),
'step'=> $campaign->getLastStepWp() != null ? ($campaign->getLastStepWp() == 4 ? 3 : $campaign->getLastStepWp()) : 1,
'show_step'=>true
]);
}
$this->addFlash('error','Cette commande n\'est pas un brouillon !');
return $this->redirectToRoute('mission_index');
}
#[Route('/campaigns/draft/validate/{id}/{fromRecap}', name: 'validate_draft', methods: ['GET'], defaults:['fromRecap'=>''])]
public function validateDraft(Campaign $campaign,string $fromRecap,CampaignRecurrentService $campaignRecurrentService, EventDispatcherInterface $dispatcher, EntityManagerInterface $entityManager, Request $request): RedirectResponse
{
$isDevis = sizeof($campaign->getMissions()) == 0 ? true : false;
$campaign->setState($isDevis ? 'provisional' : 'waiting') ;
if ($campaign->getActiveFrequency()) {
$now = new \DateTime();
$startDate = $campaign->getFrequency()->getStartDate();
$hours = $now->format('G');
$minutes = $now->format('i');
$second = $now->format('s');
$newStartDate = $startDate->setTime($hours, $minutes, $second);
$campaign->getFrequency()->setStartDate($newStartDate);
$campaign->setIsRecurrent(true);
$campaign->setRecurringState('in_progress');
$campaign->setState('recurred');
//create a campaign in new start date
$eventRecurrent = new CampaignRecurrentEvent($campaign, true);
$dispatcher->dispatch($eventRecurrent, CampaignRecurrentEvent::NAME);
if($now->format('y/d/m G:i') >= $startDate->format('y/d/m G:i')){
$campaignRecurrentService->updateLaunchRecurringAt($campaign);
$newCampaign = $campaignRecurrentService->clone($campaign);
$entityManager->persist($newCampaign);
$campaign = $newCampaign;
}else{
$campaignRecurrentService->updateLaunchRecurringAt(campaign:$campaign,dateToLaunch:$newStartDate);
}
$entityManager->flush();
}
$event = $isDevis ? new CampaignCreatedEvent($campaign, 'CREATION_DEVIS') : new CampaignCreatedEvent($campaign);
$dispatcher->dispatch($event, CampaignCreatedEvent::NAME);
$this->addFlash('success','Commande enregistrée avec succès');
$entityManager->flush();
$fromRecap = $fromRecap == "recap" ? true : false;
return $fromRecap ? $this->redirectToRoute('mission_index') : $this->redirect($request->headers->get('referer'));
}
#[Route('/api/campaigns', name: 'api_campaigns_create', methods: ['POST', 'GET'])]
public function create(Request $request,CampaignWpEditService $campaignWpEditService, CampaignRecurrentService $campaignRecurrentService, EntityManagerInterface $entityManager, SerializerInterface $serializer, CreditHistoryRepository $creditHistoryRepository, WorkflowRepository $workflowRepository, UserRepository $userRepository, EventDispatcherInterface $dispatcher, UserPasswordHasherInterface $passwordHasher, MissionService $missionService, MailerInterface $mailer, MissionRepository $missionRepository,GoogleStorageService $googleStorageService): JsonResponse
{
$campaign = new Campaign();
$form = $this->createForm(CampaignType::class, $campaign);
$form->handleRequest($request);
// $errors = $form->getErrors(true, true);
// foreach ($errors as $error) {
// mail('r.rado@yopmail.com','name',$error->getOrigin()->getName());
// mail('r.rado@yopmail.com','valeur',$error->getOrigin()->getData());
// mail('r.rado@yopmail.com','message',$error->getMessage());
// mail('r.rado@yopmail.com', 'Erreur : Fichier',$error->getCause() );
// mail('r.rado@yopmail.com', 'Erreur : Ligne',$error->getMessageTemplate());
// }
// mail('r.rado@yopmail.com','kmlkjmlkj',$campaign->getConfidentiality() ? "true": "false");
// mail('r.rado@yopmail.com','user',$campaign->getOrderedBy()!=null ? $campaign->getOrderedBy()->getFullName(): "false");
if ($form->isSubmitted() && $form->isValid()) {
$stateDraft= "";
if($campaign->getLastStepWp()!=null){
$stateDraft = 'draft';
//$campaignWpEditService->deleteOldDraft($campaign);
}
$newUserCreateId = [];
$launchJustOne = true;
$isDevis = false;
$observerList = [];
$defaultValidator = [];
$defaultValidatorExternal = [];
$defaultObserverExernal = [];
$company = $campaign->getOrderedBy()->getCompany();
$creditHistoryId = $form->get('creditserviceId')->getData();
$orderedByAdmin = $request->query->get('ordered_by_admin', "false") == "true" ? true : false;
$idAdmin = (!is_null($request->query->get('admin_id'))) ? $request->query->get('admin_id') : false;
$campaignTypeInitiation = CampaignTypeInitiation::CAMPAIGN_FROM_TUNNEL_CLIENT->value;
$historyActionCampaignInitiation = 'campaign_initiate_by_tunnel_client';
if (empty($creditHistoryId) or is_null($creditHistoryId)) {
$creditHistory = $creditHistoryRepository->findBy(['company'=>$company,'typePack' => '4']);
if (empty($creditHistory)) {
$creditHistory = $creditHistoryRepository->findBy(['company'=>$company])[0];
}else{
$creditHistory = $creditHistory[0];
}
}else{
$creditHistory = $creditHistoryRepository->findOneById($creditHistoryId);
}
$campaign->setCompany($company);
$campaign->setCreditHistory($creditHistory);
$campaign->setBrief(nl2br($this->utilsService->formatLinkToAnchor($campaign->getBrief())));
$campaign->setIsOrdoredByAdmin($orderedByAdmin);
$attachments = explode('|', $form->get('attachments')->getData());
$participants = explode('|', $form->get('participants')->getData());
$verifOrderByIsHer = false;
foreach ($participants as $p) {
if (strpos($p, $campaign->getOrderedBy()->getEmail()) !== false) {
$verifOrderByIsHer = true;
}
}
if (!$verifOrderByIsHer ) {
$participants[] = "{$campaign->getOrderedBy()->getEmail()},ROLE_VALIDATOR";
}
$state = 'waiting';
foreach ($campaign->getMissions() as $mission) {
$mission->setInitialBriefing(nl2br($this->utilsService->formatLinkToAnchor($mission->getInitialBriefing())));
if ($mission->getProduct()->getType() === ProductType::A_EVALUER) {
$state = 'waiting';
}
}
if ($campaign->getMissions()->count() === 0) {
$state = 'provisional';
$isDevis = true;
$campaignTypeInitiation = CampaignTypeInitiation::CAMPAIGN_FROM_DEVIS_CLIENT->value;
//send mail new user in demande de devis
foreach ($participants as $participant) {
if (!empty($participant)) {
[$email, $role] = explode(',', $participant);
$user = $userRepository->findOneBy(['email' => $email]);
$role_client = "ROLE_CLIENT";
if (null === $user) {
$user = (new User())
->setEmail($email)
->setRoles([$role_client])
->setEnabled(false)
->setIsNewClient(true)
;
$user->setPassword($passwordHasher->hashPassword($user, $user->getPassword()));
$entityManager->persist($user);
$entityManager->flush();
$event = new ClientUpdatedEvent($user, true);
$newUserCreateId[] = $user->getId();
$dispatcher->dispatch($event, ClientUpdatedEvent::NAME);
}
if($this->campaignService->isMyCompany($campaign->getCompany(), $user) || $this->campaignService->isMyEmailSameExtensionOfCompanyExtension($campaign->getCompany(),$user)){
$role = $this->campaignService->getRoleForInternalClient(Role::from($role ));
$user->setCompany($campaign->getCompany());
switch ($role->value) {
case 'ROLE_OBSERVER':
$observerList = [...$observerList, $user->getEmail()];
break;
case 'ROLE_VALIDATOR':
$defaultValidator = [...$defaultValidator, $user->getEmail()];
break;
}
}else{
$role = $this->campaignService->getRoleForExternalClient(Role::from($role ));
switch ($role->value) {
case 'ROLE_VALIDATOR_EXTERNAL':
$defaultValidatorExternal = [...$defaultValidatorExternal, $user->getOriginalMailUser()];
break;
case 'ROLE_OBSERVER_EXTERNAL':
$defaultObserverExernal = [...$defaultObserverExernal, $user->getOriginalMailUser()];
break;
}
}
}
}
//creation piece jointe
$filesystem = new Filesystem();
foreach ($attachments as $attachment) {
if (!empty($attachment)) {
$fileContent = file_get_contents($attachment);
// Créez une instance de fichier téléchargé à partir du contenu téléchargé
$tempFilePath = tempnam(sys_get_temp_dir(), 'file');
file_put_contents($tempFilePath, $fileContent);
$uploadedFile = new UploadedFile(
$tempFilePath,
basename($attachment),
mime_content_type($tempFilePath)
);
$originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
$extensionFile = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_EXTENSION);
$newFilename = $originalFilename . '-' . uniqid() . '.' . $extensionFile;
//upload file in google storage
$nameUniqueCompany = strtolower("company-".$campaign->getCompany()->getId());
$this->googleStorageService->uploadFile($nameUniqueCompany,$uploadedFile,$newFilename,'Campaigns/'.$campaign->getId());
$fileMission = new FileMission();
$fileMission->setName($newFilename);
$fileMission->setIsNew(1);
$fileMission->setUser($campaign->getOrderedBy());
$fileMission->setUser($campaign->getOrderedBy());
$campaign->addFileMission($fileMission);
}
}
$campaign->setDefautObserver($observerList);
$campaign->setDefaultValidator($defaultValidator)
->setDefaultValidatorExternal($defaultValidatorExternal)
->setDefautObserverExternal($defaultObserverExernal);
}
$state = $stateDraft == 'draft' ? $stateDraft : $state ;
$campaign->setState($state);
foreach ($campaign->getMissions() as $mission) {
if (empty($mission->getReference())) {
$mission->setReference($missionService->generateReference());
}
if (
$state === 'waiting' &&
($mission->getProduct()->getType() === ProductType::AU_FORFAIT) || ($mission->getProduct()->getType() === ProductType::AU_TEMPS_PASSE)
) {
$mission->setState('provisional');
} else {
$mission->setState($state);
}
$mission->getState() === 'waiting' ? $mission->setStateProvider('A évaluer') : $mission->setStateProvider('A activer');
// recalculate the price of a mission from a product price not from a price of a mission
$mission->setOriginalPrice($mission->getProduct()->getPrice());
if ($mission->getProduct()->getType() != ProductType::AU_FORFAIT) {
$mission->setPrice(null);
$mission->setOriginalPrice(null);
}
$mission->setDiscountForCompany($campaign->getCompany()->getCustomerDiscount());
$campaign->setPaymentMethod($campaign->getCompany()->getContract());
$campaign->setDiscountForCompany($campaign->getCompany()->getCustomerDiscount());
if ($campaign->getCompany()->getContract() == 0) {
$DEFAULT_CREADIT_COST = 220;
$mission->setPrice(round($mission->getOriginalPrice() / $DEFAULT_CREADIT_COST, 2));
$campaign->setIsPaidOnCredit(true);
} else {
$discountValueForOneCompany = $campaign->getCompany()->getCustomerDiscount() / 100;
$mission->setPrice($mission->getOriginalPrice() - $mission->getOriginalPrice() * $discountValueForOneCompany);
$campaign->setIsPaidOnCredit(false);
}
$filesystem = new Filesystem();
foreach ($attachments as $attachment) {
if (!empty($attachment)) {
$fileContent = file_get_contents($attachment);
// Créez une instance de fichier téléchargé à partir du contenu téléchargé
$tempFilePath = tempnam(sys_get_temp_dir(), 'file');
file_put_contents($tempFilePath, $fileContent);
$uploadedFile = new UploadedFile(
$tempFilePath,
basename($attachment),
mime_content_type($tempFilePath)
);
$originalFilename = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_FILENAME);
$extensionFile = pathinfo($uploadedFile->getClientOriginalName(), PATHINFO_EXTENSION);
$newFilename = $originalFilename . '-' . uniqid() . '.' . $extensionFile;
//upload file in google storage
$nameUniqueCompany = strtolower("company-".$campaign->getCompany()->getId());
$this->googleStorageService->uploadFile($nameUniqueCompany,$uploadedFile,$newFilename,'Campaigns/'.$campaign->getId());
$fileMission = new FileMission();
$fileMission->setName($newFilename);
$fileMission->setIsNew(1);
$fileMission->setUser($campaign->getOrderedBy());
$fileMission->setUser($campaign->getOrderedBy());
$campaign->addFileMission($fileMission);
}
}
$workflow = $workflowRepository->findOneBy(['template' => true, 'product' => $mission->getProduct(), 'company' => $campaign->getCompany(), 'active' => true]);
if (null === $workflow) {
$workflow = $workflowRepository->findOneBy(['template' => true, 'product' => $mission->getProduct(), 'active' => true]);
if (null === $workflow) {
$mission->setWorkflow(null);
$event = new MissionWithoutWorkflowEvent($mission);
/*$dispatcher->dispatch($event, MissionWithoutWorkflowEvent::NAME);*/
$this->onMissionWithoutWorkflow($event, $userRepository, $mailer);
}
}
if (null !== $workflow) {
$missionWorkflow = clone $workflow;
$missionWorkflow->setTemplate(false);
$mission->setWorkflow($missionWorkflow);
$missionWorkflow->setMission($mission);
foreach ($missionWorkflow->getSteps() as $step) {
foreach ($step->getActions() as $action) {
if ($action->getRecipient() == Role::ROLE_OBSERVER_EXTERNAL or $action->getRecipient() == Role::ROLE_VALIDATOR_EXTERNAL) {
//take user and integrating in external user
foreach ($action->getUser() as $user) {
$participant = (new MissionParticipant())
->setUser($user)
->setMission($mission)
->setRole(Role::tryFrom($action->getRecipient()->value));
$mission->addParticipant($participant);
$event = new ContactAddedEvent($mission, $user, $participant);
$dispatcher->dispatch($event, ContactAddedEvent::NAME);
}
}
}
}
}
$filesystem = new Filesystem();
$listIdUser = [];
foreach ($participants as $participant) {
if (!empty($participant)) {
[$email, $role] = explode(',', $participant);
$isExternal = false;
$user = $userRepository->findOneBy(['email' => $email]);
if($this->campaignService->isMyCompany($campaign->getCompany(), $user) || $this->campaignService->isMyEmailSameExtensionOfCompanyExtension($campaign->getCompany(),$user)){
$isExternal = false;
$role = $this->campaignService->getRoleForInternalClient(Role::tryFrom($role ));
$user->setCompany($campaign->getCompany());
switch ($role->value) {
case 'ROLE_OBSERVER':
$observerList = [...$observerList, $user->getEmail()];
break;
case 'ROLE_VALIDATOR':
$defaultValidator = [...$defaultValidator, $user->getEmail()];
break;
}
}else{
$isExternal = true;
$role = $this->campaignService->getRoleForExternalClient(Role::tryFrom($role ));
switch ($role->value) {
case 'ROLE_VALIDATOR_EXTERNAL':
$defaultValidatorExternal = [...$defaultValidatorExternal, $user->getOriginalMailUser()];
break;
case 'ROLE_OBSERVER_EXTERNAL':
$defaultObserverExernal = [...$defaultObserverExernal, $user->getOriginalMailUser()];
break;
}
}
if (null === $user) {
//role external is just a client
$role_client = "ROLE_CLIENT";
$user = (new User())
->setEmail($email)
->setRoles([$role_client])
->setEnabled(false)
->setIsNewClient(true)
;
if ($isExternal) {
$user->setExternal(true);
}
$user->setPassword($passwordHasher->hashPassword($user, $user->getPassword()));
$entityManager->persist($user);
$entityManager->flush();
$event = new ClientUpdatedEvent($user, true);
$newUserCreateId[] = $user->getId();
$dispatcher->dispatch($event, ClientUpdatedEvent::NAME);
} else {
if (!in_array($user->getId(), $newUserCreateId) && true === $launchJustOne) {
if ($user->getId() != $mission->getCampaign()->getOrderedBy()->getId()) {
$event = new MissionSendEvent($mission, $user, $role);
$dispatcher->dispatch($event, MissionSendEvent::NAME);
}
}
}
$participant = (new MissionParticipant())
->setUser($user)
->setMission($mission)
->setRole( $role);
if (in_array($user->getId(), $listIdUser)) {
$participant->setInitialTime(0)
->setEstimatedIncome(0)
->setAdminTime(0)
->setEstimatedIncomeAdmin(0)
->setActivated(1);
}
$listIdUser[] = $user->getId();
$mission->addParticipant($participant);
if ($role == "ROLE_OBSERVER") {
$observerList = [...$observerList, $email];
}
}
}
$launchJustOne = false;
}
try {
$campaign->setNumberInitialOfMissions(sizeof($campaign->getMissions()));
$campaign->setDefautObserver($observerList);
$campaign->setTypeInitiation($campaignTypeInitiation);
$entityManager->persist($campaign);
$entityManager->flush();
foreach ($campaign->getMissions() as $mission) {
// $this->missionService->addHistorique(mission: $mission, user:$campaign->getOrderedBy() , action: $historyActionCampaignInitiation);
$listOfUser = [];
foreach ($mission->getParticipants() as $participant) {
if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR) {
if (in_array($participant->getUser()->getId(), $listOfUser)) {
$participant->setInitialTime(0)
->setEstimatedIncome(0)
->setInitialTimeAdmin(0)
->setEstimatedIncomeAdmin(0)
->setActivated(1);
$entityManager->persist($participant);
$entityManager->flush();
}
$listOfUser[] = $participant->getUser()->getId();
}
}
}
$missionsPersited = $campaign->getMissions();
foreach ($missionsPersited as $missionPersisted) {
if ($missionPersisted->getWorkflow() !== null && count($missionPersisted->getWorkflow()->getSteps()) > 0) {
$missionPersisted->getWorkflow()->getSteps()->first()->setActive(false);
}
$missionPersisted->setOldCommand("{$missionPersisted->getQuantity()}-{$missionPersisted->getPrice()}-{$missionPersisted->getProduct()->getId()}-{$mission->getDesiredDelivery()->getTimestamp()}");
}
$entityManager->flush();
if ($campaign->getActiveFrequency() && $campaign->getState() != "draft") {
$now = new \DateTime();
$startDate = $campaign->getFrequency()->getStartDate();
$campaignTypeInitiation = CampaignTypeInitiation::CAMPAIGN_FROM_RECURRENT->value;
$historyActionCampaignInitiation = 'campaign_initiate_by_recurrent';
$hours = $now->format('G');
$minutes = $now->format('i');
$second = $now->format('s');
$newStartDate = $startDate->setTime($hours, $minutes, $second);
$campaignTypeInitiation = CampaignTypeInitiation::CAMPAIGN_FROM_RECURRENT->value;
$campaign->getFrequency()->setStartDate($newStartDate);
$campaign->setIsRecurrent(true);
if( !is_null($orderedByAdmin) && isset($orderedByAdmin) && $orderedByAdmin != false ){
$campaign->setRecurringState('waiting_validation');
}else{
$campaign->setRecurringState('in_progress');
}
$campaign->setState('recurred');
$campaign->setTypeInitiation($campaignTypeInitiation);
//create a campaign in new start date
if($campaign->getState() != "draft"){
$eventRecurrent = new CampaignRecurrentEvent($campaign, true);
$dispatcher->dispatch($eventRecurrent, CampaignRecurrentEvent::NAME);
}
if($now->format('y/d/m G:i') >= $startDate->format('y/d/m G:i') && $campaign->getRecurringState()!='waiting_validation'){
$campaign->getFrequency()->setStartDate(new \DateTime());
$campaignRecurrentService->updateLaunchRecurringAt($campaign);
$newCampaign = $campaignRecurrentService->clone($campaign);
$entityManager->persist($newCampaign);
$campaign = $newCampaign;
// $this->createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$campaign,$now,$entityManager);
}elseif($campaign->getRecurringState()!='waiting_validation'){
$campaignRecurrentService->updateLaunchRecurringAt(campaign:$campaign,dateToLaunch:$newStartDate);
}
$entityManager->flush();
}
foreach($campaign->getMissions() as $mission) {
$this->missionService->addHistorique(mission: $mission, user:$campaign->getOrderedBy() , action:$historyActionCampaignInitiation);
break;
}
if($campaign->getState() != "draft" && $campaign->getRecurringState()!='waiting_validation'){
$event = $isDevis ? new CampaignCreatedEvent($campaign, 'CREATION_DEVIS') : new CampaignCreatedEvent($campaign, 'TUNNEL_COMMANDE');
$dispatcher->dispatch($event, CampaignCreatedEvent::NAME);
}
return new JsonResponse(
json_decode($serializer->serialize($campaign, 'json', [AbstractNormalizer::GROUPS => ['campaign']])),
Response::HTTP_CREATED
);
} catch (\Exception $e) {
foreach (array_unique($newUserCreateId) as $id) {
$user = $userRepository->findOneBy(['id' => $id]);
$entityManager->remove($user);
$entityManager->flush();
}
$campaign->setErrorCommand($e->getMessage());
$event = new AdminCommandErrorEvent($campaign);
$dispatcher->dispatch($event, AdminCommandErrorEvent::NAME);
}
}
return new JsonResponse([], Response::HTTP_BAD_REQUEST);
}
private function createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign,$now,$entityManager){
$campaignRecurrentService->updateLaunchRecurringAt($originalCampaign);
$campaignFrequency = $originalCampaign->getFrequency()->getLaunchRecurrenceAt();
$newCampaign = $campaignRecurrentService->clone($originalCampaign);
$campaign = $newCampaign;
$entityManager->persist($campaign);
$entityManager->flush();
if($campaignFrequency<$now){
$this->createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign, $now,$entityManager);
}
return;
}
/**
* Display the view/handle how to edit a campaign
*
* @param Campaign $campaign - the campaign to edit
* @param Request $request
* @param EntityManagerInterface $entityManager
*
* @return Response template /mission/handle_campaign.html.twig
*/
#[Route('/campagnes/{id}', name: 'campaign_edit')]
public function edit(Campaign $campaign, Request $request, EntityManagerInterface $entityManager): Response
{
$form = $this->createForm(CampaignType::class, $campaign);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->addFlash('success', 'La campagne a bien été modifiée');
$entityManager->flush();
return $this->redirectToRoute('mission_index');
}
return $this->renderForm('campaign/edit.html.twig', [
'form' => $form,
'campaign' => $campaign,
]);
}
#[Route('/campaign/{id}/uncancelled', name: "campaign_uncancelled")]
public function campaignUncancelled(Campaign $campaign, EntityManagerInterface $entityManagerInterface,EventDispatcherInterface $dispatcher,MissionService $missionService): Response
{
$campaign->setState($campaign->getLastState());
foreach ($campaign->getMissions() as $mission) {
$mission->setState($mission->getLastState());
}
$event = new CampaignResumeEvent($campaign, true);
$dispatcher->dispatch($event, CampaignResumeEvent::NAME);
foreach ($campaign->getMissions() as $mission) {
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "unpause");
}
$entityManagerInterface->flush();
$this->addFlash(
type: 'success',
message: "La campagne reprend avec succès ",
);
return $this->redirectToRoute('mission_index');
}
/**
* If applicable, apply the workflow transition $transition on a campaign
* and on all its missions.
*
* Only validate, pause, unpause, cancel and archived transitions are allowed
*
* @param Campaign $campaign - the campaign on whom to apply the transition
* @param string $transition - the transition to apply
* @param Registry $workflows
* @param EntityManagerInterface $entityManager
* @param EventDispatcherInterface $dispatcher
*
* @return Response Redirect to the mission's index
*/
#[Route('/campagne/{id}/{transition<validate|pause|unpause|resend|cancel|archive|validation_by_client|activated|closed|delete|decline>}/{currentRouteName}/{firstClickedMissionId?}/{subcontractorId?}', name: 'campaign_transition', defaults: ['currentRouteName' => null, 'firstClickedMissionId' => null, 'subcontractorId' => null])]
public function transition(Campaign $campaign, MissionParticipantService $missionParticipantService, ClientSoldService $clientSoldService, NumberFormatService $numberFormatService, CampaignService $campaignService, MissionService $missionService, string $transition, Registry $workflows, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher, Request $request, PriceService $priceService, WorkflowStepRepository $workflowStepRepository, BalanceTransactionsRepository $balanceTransactionsRepository, $currentRouteName = null, $firstClickedMissionId = null, $subcontractorId = null): Response
{
$workflow = $workflows->get($campaign, 'classic');
$redirect = $this->redirectToRoute('mission_index');
if (isset($currentRouteName) && $currentRouteName == 'mission_edit' && isset($firstClickedMissionId)) {
$redirect = $this->redirectToRoute('mission_edit', ['id' => $firstClickedMissionId]);
}
// clone original campagne
$originalCampaign = clone $campaign;
$originalMissions = $originalCampaign->getMissions();
if ($transition === "delete") {
if($campaign->getState()=="draft"){
$campaign->setDeleteReason('Brouillon');
}
else {
$formDeleteCampaign = $this->createForm(CampaignDeleteType::class, $campaign);
$formDeleteCampaign->handleRequest($request);
}
$campaign->setLastState($originalCampaign->getState());
$pack = $campaign->getCreditHistory();
$isDeteleCampaignRecurrend = $request->query->get('recurred') == true ? true : false;
if (!$isDeteleCampaignRecurrend) {
// remove all price in creditHistory and BalanceTransaction if $transition is delete
$dataCampainState = ['in_progress', 'closed', 'cancelled', 'archived'];
if (in_array($campaign->getState(), $dataCampainState)) {
$totalAmountInBalance = 0;
$isNull = false;
$isNull = count($campaign->getMissions()) === 0 ? true : false;
foreach ($campaign->getMissions() as $mission) {
$balanceTransaction = $balanceTransactionsRepository->soldeByMission($pack, $mission);
if (is_null($balanceTransaction)) {
$isNull = true;
break;
}
$creditHistory = $balanceTransaction->getCreditHistory();
$totalAmountInBalance += $balanceTransaction->getAmount();
$entityManager->remove($balanceTransaction);
$this->missionService->addHistorique($mission, $this->getUser(),'mission_deleted',$mission);
}
if (!$isNull) {
$oldTotalConsuption = $creditHistory->getTotalConsumption();
$oldCurrentBalance = $creditHistory->getCurrentBalance();
$creditHistory->setTotalConsumption($oldTotalConsuption - $totalAmountInBalance);
$creditHistory->setCurrentBalance($oldCurrentBalance + $totalAmountInBalance);
}
}
foreach ($originalCampaign->getMissions() as $mission) {
$mission->setLastState($mission->getState());
$mission->setState('deleted');
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "deleted");
}
if($campaign->getState() !== "deleted"){
$event = new CampaignDeletedEvent($campaign, $this->getUser());
$dispatcher->dispatch($event, CampaignDeletedEvent::NAME);
}
$campaign->setState('deleted');
}
else{
$campaign->setRecurringState('deleted');
}
$entityManager->flush();
$this->addFlash(
type: 'success',
message: "La campagne {$campaign->getName()} a bien été supprimée"
);
if ($isDeteleCampaignRecurrend) {
return $this->redirectToRoute('recurring_service');
} elseif (isset($currentRouteName) && $currentRouteName == 'mission_edit' && isset($firstClickedMissionId)) {
return $this->redirectToRoute('mission_edit', ['id' => $firstClickedMissionId]);
} else {
return $this->redirectToRoute('mission_index');
}
}
if ($transition === 'decline') {
foreach ($campaign->getMissions() as $mission) {
foreach ($mission->getParticipants() as $participant) {
if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR && $participant->getUser()->getId() == $subcontractorId) {
$entityManager->remove($participant);
$entityManager->flush();
$this->missionService->addHistorique($mission, $this->getUser(), 'decline_mission');
continue 2;
}
}
}
$event = new CampaignDeclineEvent($campaign, true, $this->getUser());
$dispatcher->dispatch($event, CampaignDeclineEvent::NAME);
foreach ($campaign->getMissions() as $mission) {
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "refus");
}
$this->addFlash(
type: 'success',
message: "La mission {$campaign->getName()} a bien été supprimée"
);
}
if ($workflow->can($campaign, $transition)) {
$workflow->apply($campaign, $transition);
if ($transition === 'unpause') {
$event = new CampaignResumeEvent($campaign, true);
$dispatcher->dispatch($event, CampaignResumeEvent::NAME);
foreach ($campaign->getMissions() as $mission) {
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "unpause");
}
}
if ($transition === 'resend') {
foreach ($campaign->getMissions() as $mission) {
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "resend");
}
}
if ($transition === 'pause') {
$event = new CampaignWaitingEvent($campaign, true);
$dispatcher->dispatch($event, CampaignWaitingEvent::NAME);
foreach ($campaign->getMissions() as $mission) {
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "pause");
}
}
if ($transition === 'cancel') {
$formCancelCampaign = $this->createForm(CampaignCancelType::class, $campaign);
$formCancelCampaign->handleRequest($request);
$campaign->setLastState($originalCampaign->getState());
foreach ($originalCampaign->getMissions() as $mission) {
$mission->setLastState($mission->getState());
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "cancel");
}
$entityManager->flush();
$event = new CampaignCancelledEvent($campaign, $this->getUser(),);
$dispatcher->dispatch($event, CampaignCancelledEvent::NAME);
}
if ($transition === "closed") {
foreach ($campaign->getMissions() as $mission) {
$mission->setState('finalized');
$campaign->setIsToBeinvoiced(true);
if(sizeof($this->campaignApiService->getSubcontractorNoEstimatedIncome($campaign)) != 0){
$campaign->setState('closing_in_progress');
}
// if ($mission->getProduct()->getType() == ProductType::AU_TEMPS_PASSE) {
$clientSoldService->decreaseCurrentBalanceByMissionCost(mission: $mission);
// }
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "closed");
}
}
foreach ($campaign->getMissions() as $mission) {
$workflow = $workflows->get($mission, 'classic');
if ($workflow->can($mission, $transition)) {
$workflow->apply($mission, $transition);
}
}
// If we validate the campaign, we dispatch the campaign.validated event
if ($transition === 'validate') {
$flag = true;
foreach ($campaign->getMissions() as $mission) {
$i = 0;
foreach ($mission->getParticipants() as $participant) {
if ($participant->getRole() == Role::ROLE_SUBCONTRACTOR) {
$i++;
}
if ($i < 1 || $participant->getMission()->getStateProvider() == 'A évaluer') {
$flag = false;
}
}
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "validate");
}
if ($flag == true) {
$event = new CampaignValidatedEvent($campaign);
$dispatcher->dispatch($event, CampaignValidatedEvent::NAME);
} else {
return $this->redirectToRoute('handle_mission_campaign', ['id' => $campaign->getId(), 'erreur' => true]);
}
}
if ($transition === 'activated') {
$canStartCampaign = true;
$error = false;
$userConnected = $this->getUser();
if (in_array("ROLE_SUBCONTRACTOR", $userConnected->getRoles())) {
$message = [];
foreach ($campaign->getMissions() as $mission) {
$missionService->setDefaultValueIfAnUserClickedAnActivationButtonWithoutADelaisAndTimeIsEmpty($mission, $priceService);
//////////////////// Check marge mission
$getMargeMyFlow = $priceService->marginExceeded(mission: $mission);
if ($missionService->isMyMission(mission: $mission) and $getMargeMyFlow['percentage'] <= 0 and $mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
$this->addFlash(
type: 'error',
message: "Une action de l'administrateur est attendue pour pouvoir valider cette mission.",
);
$event = new MissionCanActivateEvent(mission: $mission, marge: $getMargeMyFlow['percentage'] );
$dispatcher->dispatch($event, MissionCanActivateEvent::NAME);
}
$campaign->setState($originalCampaign->getState());
$mission->setState($mission->getLastState());
$entityManager->flush();
$canStartCampaign = false;
continue;
//return $redirect;
}
////////////////////////
foreach ($mission->getParticipants() as $missionParticipation) {
if (!$missionParticipation->isEvaluate() && !$missionParticipation->isActivated() && !$missionParticipation->isRefused() && $this->getUser() == $missionParticipation->getUser()) {
$missionParticipation->setActivated(true);
$missionParticipation->setActivatedAt(new \DateTime());
$entityManager->flush();
$this->missionService->addHistorique($mission, $this->getUser(), 'accept_mission');
//break;
}
}
$listUserNotEvaluate = "";
$listUserEvaluate = "";
$message = [0 => "- Mission lancée avec succès"];
foreach ($missionService->determineAllSubcontractorEvaluated(mission: $mission) as $userEvaluate) {
if ($userEvaluate != $this->getUser()) {
$listUserNotEvaluate .= "{$userEvaluate->getFullName()} ,";
}
if (strlen($listUserNotEvaluate) > 3 && $campaign->getState() != "resend") {
$listUserNotEvaluate = rtrim($listUserNotEvaluate, ",");
$message[1] = " - Merci pour votre validation. Les intervenants suivants ont réévalué la mission. Nous attendons donc la validation du client pour démarrer le travail : $listUserNotEvaluate.";
}
}
$allSubcontractorEvaluated = $missionService->getListSubcontractorNotActivate(mission: $mission);
$msg = count($allSubcontractorEvaluated) > 1 ? "Les intervenants suivants ont réévalué la mission" : "L'intervenant suivant a réévalué la mission";
foreach ($allSubcontractorEvaluated as $userNotEvaluate) {
if ($userNotEvaluate != $this->getUser()) {
$listUserNotEvaluate .= "{$userNotEvaluate->getFullName()} ,";
}
if (strlen($listUserNotEvaluate) > 3 && $campaign->getState() != "resend") {
$listUserNotEvaluate = rtrim($listUserNotEvaluate, ",");
$message[2] = " - Vous venez d'accepter la mission, nous attendons maintenant l'activation de l'intervenant ci-dessous pour démarrer le travail : $listUserNotEvaluate.";
}
}
if ($missionService->lackSubcontractorTest(mission: $mission) && sizeof($missionService->getListSubcontractorNotActivate(mission: $mission)) == 0 && !$missionService->aSubcontractorBotIsInThisMission(mission: $mission)) {
$mission->setState('in_progress');
$entityManager->flush();
foreach ($originalMissions as $missionOriginal) {
if (in_array($missionOriginal->getState(), ["cancelled", "archived", "closed"]) && $missionOriginal->getId() == $mission->getId()) {
$mission->setState($originalMissions->getState());
$entityManager->flush();
}
}
} else {
if ($missionService->lackSubcontractorTest(mission: $mission) && !$missionService->aSubcontractorBotIsInThisMission(mission: $mission)) {
$message[3] = "- Vous venez d'accepter la mission, nous attendons maintenant l'intervention de l'administrateur pour poursuivre le processus";
$event = new SubcontractorActivateOrThereIsABotEvent($mission);
$dispatcher->dispatch($event, SubcontractorActivateOrThereIsABotEvent::NAME);
}
$campaign->setState($campaign->getLastState());
foreach ($originalCampaign->getMissions() as $missionOriginal) {
if ($missionOriginal->getId() == $mission->getId()) {
$mission->setState("provisional");
}
}
$entityManager->flush();
$canStartCampaign = false;
}
foreach ($missionService->determineAllSubcontractorEvaluated(mission: $mission) as $userEvaluate) {
if ($userEvaluate != $this->getUser()) {
$listUserEvaluate .= "{$userEvaluate->getFullName()} ,";
}
if (strlen($listUserEvaluate) > 3) {
$listUserEvaluate = rtrim($listUserEvaluate, ",");
$message[4] = " - Merci pour votre validation. " . $msg . ". Nous attendons donc la validation du client pour démarrer le travail : $listUserEvaluate.";
}
}
}
if ($this->campaignService->canResendOrderToClient(campaign: $mission->getCampaign(), missionEvaluate: $mission) && $originalCampaign->getState() == "waiting_resend") {
$this->campaignService->resendCampaignForValidation(campaign: $mission->getCampaign(), user: $this->getUser());
$canStartCampaign = false;
}
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "activation_campaign");
$allMessage = "";
foreach ($message as $msg) {
//$allMessage .= "{$msg} <br> <br>";
$this->addFlash(
type: 'success',
message: $msg,
);
}
} elseif (in_array("ROLE_ADMIN", $userConnected->getRoles())) {
foreach ($campaign->getMissions() as $mission) {
//////////////////// Check marge mission
$getMargeMyFlow = $priceService->marginExceeded(mission: $mission);
if ($getMargeMyFlow['percentage'] <= 0 && $mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE ) {
$this->addFlash(
type: 'error',
message: "Nous avons rencontré un problème, une des missions a une marge de {$getMargeMyFlow['percentage']} % .",
);
$campaign->setState($originalCampaign->getState());
$entityManager->flush();
$canStartCampaign = false;
continue;
//return $redirect;
}
foreach ($mission->getParticipants() as $missionParticipation) {
if (!$missionParticipation->isActivated() && !$missionParticipation->isRefused()) {
$missionParticipation->setActivated(true);
$missionParticipation->setEvaluate(false);
$missionParticipation->setActivatedAt(new \DateTime());
$entityManager->flush();
}
}
if ($mission->isEvaluate()) {
$mission->setEvaluate(false);
}
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "activation_campaign");
}
$canStartCampaign = true;
} else {
foreach ($campaign->getMissions() as $mission) {
//////////////////// Check marge mission
$missionCanActive = true;
$getMargeMyFlow = $priceService->marginExceeded(mission: $mission);
if ($getMargeMyFlow['percentage'] <= 0) {
if ($this->isGranted(Role::ROLE_SUBCONTRACTOR->value)) {
$event = new MissionCanActivateEvent($mission, $getMargeMyFlow['percentage']);
$dispatcher->dispatch($event, MissionCanActivateEvent::NAME);
$missionCanActive = false;
}
$missionCanActive = false;
continue;
}
foreach ($mission->getParticipants() as $missionParticipation) {
if ($missionParticipation->isEvaluate() && !$missionParticipation->isRefused()) {
$missionParticipation->setActivated(true);
$missionParticipation->setEvaluate(false);
$missionParticipation->setActivatedAt(new \DateTime());
$entityManager->flush();
}
}
if ($mission->isEvaluate()) {
$mission->setEvaluate(false);
}
if ($missionCanActive && $missionService->lackSubcontractorTest(mission: $mission)) {
if (in_array($mission->getState(), ["cancelled", "archived", "closed"])) {
foreach ($originalCampaign->getMissions() as $missionOriginal) {
if ($missionOriginal->getId() == $mission->getId()) {
$mission->setState($originalCampaign->getState());
$entityManager->flush();
}
}
}
} else {
foreach ($originalCampaign->getMissions() as $missionOriginal) {
if ($missionOriginal->getId() == $mission->getId()) {
$mission->setState("provisional");
$entityManager->persist($mission);
$entityManager->flush();
}
}
$canStartCampaign = false;
}
}
}
if (!$canStartCampaign) {
$campaign->setState($originalCampaign->getState());
$entityManager->flush();
}
//verification de BOT
if ($campaign->haveBot()) {
if (in_array("ROLE_SUBCONTRACTOR", $userConnected->getRoles())) {
$this->addFlash(
type: 'error',
message: 'l\'activation de la campagne nécessite encore l\'intevention de l\'administrateur.',
);
} else {
$this->addFlash(
type: 'error',
message: 'Activation impossible car certaines mission sont encore liées a des Bots.',
);
}
$campaign->setState($originalCampaign->getState());
$entityManager->flush();
return $redirect;
}
if ($canStartCampaign && $campaignService->isCanStart(campaign: $campaign)) {
// campaign and setState() in progress managed by symfony workflow in config/packages/workflow
$campaign->setReSendToClient(false);
$campaign->setClientStatus("");
foreach ($campaign->getMissions() as $mission) {
if (!empty($mission->getWorkflow())) {
$stepIsActive = false;
//verifié si un step est active // si active alors ne plus faire de mise a jour.
foreach ($mission->getWorkflow()->getSteps() as $step) {
if ($step->isActive()) {
$stepIsActive = true;
}
}
$step = $workflowStepRepository->getFirstStep($mission->getWorkflow());
if (empty($step) || $step === false) {
if (in_array("ROLE_SUBCONTRACTOR", $userConnected->getRoles())) {
$this->addFlash(
type: 'error',
message: 'l\'activation de la campagne nécessite encore l\'intevention de l\'administrateur.',
);
} else {
$this->addFlash(
type: 'error',
message: 'Activation impossible car le workflow n\'as pas d\'étape prédéfinie.',
);
}
$campaign->setState($originalCampaign->getState());
$entityManager->flush();
return $redirect;
}
if (!$stepIsActive) {
$step->setActive(true);
$now = new \DateTime();
$timezone = new \DateTimeZone("UTC");
$now->setTimezone($timezone);
$step->setStartDate($now);
$event = new WorkflowStepEnteredEvent($step);
$dispatcher->dispatch($event, WorkflowStepEnteredEvent::NAME);
}
} else {
if (in_array("ROLE_SUBCONTRACTOR", $userConnected->getRoles())) {
$this->addFlash(
type: 'error',
message: 'l\'activation de la campagne nécessite encore l\'intevention de l\'administrateur.',
);
} else {
$this->addFlash(
type: 'error',
message: 'Activation impossible car la campagne n\'a pas de workflow',
);
}
$campaign->setState($originalCampaign->getState());
$entityManager->flush();
return $this->redirectToRoute('mission_index');
}
//fin vérification
if ($step->getManager() == 0) {
$mission->setStateClient('Déclenchement en attente');
} else {
$mission->setStateProvider($step->getName());
}
$mission->setCanInvoiced(true);
$entityManager->flush();
if ($mission->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
$missionService->setDefaultValueIfAnUserClickedAnActivationButtonWithoutADelaisAndTimeIsEmpty($mission, $priceService);
$clientSoldService->decreaseCurrentBalanceByMissionCost($mission);
}
$missionParticipantService->markAsAllParticipantClickActivationButton(mission: $mission);
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "start");
}
$event = new CampaignValidatedPerActivationEvent($campaign, $this->getUser());
$dispatcher->dispatch($event,CampaignValidatedPerActivationEvent::NAME);
} else {
if ($campaign->getState() !== "waiting_validation") {
$campaign->setState($originalCampaign->getState());
$entityManager->flush();
}
return $redirect;
}
}
/* if(($transition == "activated" || $transition == "validate") && $currentRouteName == null ){
$campaign->setActivatedAt(new \DateTimeImmutable());
} */
$entityManager->flush();
$message = match ($transition) {
'validate' => 'validée',
'pause' => 'mise en pause',
'unpause' => 'relancée',
'cancel' => 'annulée',
'closed' => 'clôturée',
'activated' => 'activée',
default => 'enregistrée',
};
$this->addFlash(
type: 'success',
message: "La campagne {$campaign->getName()} a bien été " . $message,
);
}
return $redirect;
}
#[Route('/campagne/{id}/detail/check', name: 'handle_detail_campaing', methods: ['GET', 'POST'])]
public function campaignDetail(Campaign $campaign,MissionService $missionService,EntityManagerInterface $entityManager,UserRepository $userRepository){
if (count($campaign->getMissions()) != 0) {
return $this->redirectToRoute('mission_edit',['id'=>$campaign->getMissions()->first()->getId()]) ;
}
//count nb mission
$product = new Product();
$product->setName("Espace de discussion");
$product->setFrontId(0);
$product->setType(ProductType::AU_TEMPS_PASSE);
$entityManager->persist($product);
$today = new \DateTime();
$mission = new Mission();
$campaignDefaultObserver = $campaign->getDefautObserver();
$campaignDefaultValidator = $campaign->getDefaultValidator();
$campaignDefaultValidatorExternal = $campaign->getDefaultValidatorExternal();
$campaignDefaultObserverExternal = $campaign->getDefautObserverExternal();
if(!empty($campaignDefaultValidator)){
foreach($campaignDefaultValidator as $validatorEmail){
$user = $userRepository->findOneBy(['email'=>$validatorEmail]);
$userDefaultValidatorParticipant = (new MissionParticipant())
->setUser($user)
->setMission($mission)
->setRole(Role::ROLE_VALIDATOR);
$mission->addParticipant($userDefaultValidatorParticipant);
}
}
if(!empty($campaignDefaultObserver)){
foreach($campaignDefaultObserver as $observerEmail){
$user = $userRepository->findOneBy(['email'=>$observerEmail]);
$userDefaultObserverParticipant = (new MissionParticipant())
->setUser($user)
->setMission($mission)
->setRole(Role::ROLE_OBSERVER);
$mission->addParticipant($userDefaultObserverParticipant);
}
}
if(!empty($campaignDefaultValidatorExternal)){
foreach($campaignDefaultValidatorExternal as $validatorExternalEmail){
$user = $userRepository->findOneBy(['email'=>$validatorExternalEmail]);
$userDefaultValidatorExternalParticipant = (new MissionParticipant())
->setUser($user)
->setMission($mission)
->setRole(Role::ROLE_VALIDATOR_EXTERNAL);
$mission->addParticipant($userDefaultValidatorExternalParticipant);
}
}
if(!empty($campaignDefaultObserverExternal)){
foreach($campaignDefaultObserverExternal as $observerExternalEmail){
$user = $userRepository->findOneBy(['email'=>$observerExternalEmail]);
$userDefaultValidatorExternalParicipant = (new MissionParticipant())
->setUser($user)
->setMission($mission)
->setRole(Role::ROLE_OBSERVER_EXTERNAL);
$mission->addParticipant($userDefaultValidatorExternalParicipant);
}
}
$workflow = $entityManager->getRepository(Workflow::class)->findOneBy(['template'=>1,'name'=>'Discussion']);
$newWorkflow = clone($workflow);
$mission->setProduct($product)
->setQuantity(1)
->setDesiredDelivery($today->add(new \DateInterval('P1Y')))
->setState('provisional')
->setWorkflow($newWorkflow)
->setCampaign($campaign)
//->setReference($this->missionService->generateReference());
;
$campaign->setState('provisional');
$entityManager->persist($mission);
$entityManager->persist($campaign);
$entityManager->flush();
return $this->redirectToRoute('mission_edit',['id'=> $mission->getId()]) ;
}
#[Route('/campagne/{id}/missions', name: 'handle_mission_campaign', methods: ['GET', 'POST'])]
public function handleAllMission($id,Request $request, CreditHistoryRepository $creditHistoryRepository, JobRepository $jobRepository, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher, MissionParticipant $missionParticipant = null, MissionRepository $missionRepository, MissionParticipantRepository $missionParticipantRepository, MissionService $missionService, UserRepository $userRepository, ParameterBagInterface $parameter,CampaignRepository $campaignRepository,CompanyRepository $companyRepository,FileMissionRepository $fileMissionRepository,CampaignRecurrentService $campaignRecurrentService,UserPasswordHasherInterface $passwordHasher,GoogleStorageService $googleStorageService): Response
{
$newUserCreateId = [];
$launchJustOne = true;
$matriceFrequencyType = [0=>'hours',1=>'months',2=>'days',3=>'years'];
$error = false;
$campaignBrief = null;
$allMissionsInCampaign = [];
$isNewCampaing = false;
if ($id == "new") {
$campaign = new Campaign();
$campaign->setOrderedBy($this->getUser())
->setIsNew(true)
->setDisabled(true)
->setTypeInitiation(CampaignTypeInitiation::CAMPAIGN_FROM_ADMIN->value);
$isNewCampaing = true;
if(in_array('ROLE_ADMIN', $this->getUser()->getRoles())){
$campaign->setRecurringState('waiting_validation');
}
$entityManager->persist($campaign);
$entityManager->flush();
$missionAlreadyExist = false;
$campaignInitiator = $this->getUser();
$url = $this->generateUrl('handle_mission_campaign', ["id" => $campaign->getId()]);
return new RedirectResponse($url);
}else{
$campaign = $campaignRepository->findOneBy(['id'=>$id]);
$campaignInitiator = $campaign->getOrderedBy();
$campaignBeforeState = $campaign->getState();
$oldCampaign = clone $campaign;
$missionAlreadyExist = (count($oldCampaign->getMissions()) == 0) ? false : true;
$campaignBrief = $campaign->getBrief();
$allMissionsInCampaign = $missionRepository->findBy(['campaign' => $campaign]);
}
$stateRecurred = $campaign->getState() ;
$oldCampaignStateActiveFrequency = $campaign->getActiveFrequency();
$oldFrequency = $campaign->getFrequency() != null ? clone $campaign->getFrequency() : null;
$oldPack = $campaign->getCreditHistory();
$sendEmailDeliveryDateChange = true;
$missionsInCampaign = [];
foreach ($allMissionsInCampaign as $missionInCampaign) {
if (!isset($missionsInCampaign[$missionInCampaign->getId()])) {
$missionsInCampaign[$missionInCampaign->getId()] = [];
}
if (!empty($missionInCampaign->getDesiredDelivery())) {
$missionsInCampaign[$missionInCampaign->getId()] = clone $missionInCampaign->getDesiredDelivery();
}
}
$oldMissionId = [];
$oldMission = $campaign->getMissions();
$oldParticipantMail= [];
foreach ($oldMission as $key => $mission) {
$oldMissionId[] = $mission->getId();
foreach ($mission->getParticipants() as $participant) {
$oldParticipantMail [] = $participant->getUser()->getEmail();
}
}
//list of user to link of all mission
$user = $userRepository->findAll();
$isadminAgency = false;
$company = null;
if (in_array("ROLE_ADMIN_AGENCY", $this->getUser()->getRoles()) ) {
$isadminAgency = true;
$company = $this->getUser()->getCompany();
}
foreach ($campaign->getMissions() as $mission) {
$mission->setPrice($this->getPrice( $mission->getProduct(),$this->getUser()));
}
$formEditCampaign = $this->createForm(ListMissionFormType::class, $campaign,['user'=>$user,'isadminAgency'=>$isadminAgency,'company'=> $company]);
$formEditCampaign->handleRequest($request);
$errors = $formEditCampaign->getErrors(true, true);
$canResendToClient = true;
$nbrAU_FORFAIT = 0;
$nbrA_EVALUER = 0;
$nbrAU_TEMPS_PASSE = 0;
$nbrMission = 0;
$allMissionNewId = [];
$pathCampaing = 'file_campaing_directory';
$pathMission = 'file_mission_directory';
$newCampaign = false;
if ($formEditCampaign->isSubmitted() && $formEditCampaign->isValid()) {
$contactProjects = [];
if ($campaign->getDisabled() == 1) {
$newCampaign = true;
}
$state = 'waiting';
$missions = $formEditCampaign->get('missions');
$otherInformationThanDateChange = false;
$newMissionInCampaign = false;
//validateur external an user validator / observer----------------
//first delete all user in mission
foreach ($campaign->getMissions() as $mission) {
foreach ($mission->getParticipants() as $participant) {
if (in_array($participant->getRole()->value, ['ROLE_OBSERVER_EXTERNAL','ROLE_VALIDATOR_EXTERNAL','ROLE_OBSERVER','ROLE_VALIDATOR'])) {
$entityManager->remove($participant);
$entityManager->flush();
}
}
}
$userAlreadyAdd = [];
$userToAdd = $formEditCampaign->get('user')->getData();
$files = $formEditCampaign->get('fileMissions')->getData();
//dd($userToAdd);
// $files = $files != null ? $files : [];
/* $droppedFilesMissions = $formEditCampaign->get('droppedFileMissions')->getData(); */
//second add participant
$defaultObserver = [];
$defaultObserverExernal = [];
$defaultValidator = [];
$defaultValidatorExternal = [];
foreach ($userToAdd as $element) {
$user = $element['user'];
$role = $element['role'];
if (is_null($user) || is_null( $role)) {
continue;
}
$clientIntern=false;
if($this->campaignService->isMyCompany($campaign->getCompany(), $user) ||
$this->campaignService->isMyEmailSameExtensionOfCompanyExtension($campaign->getCompany(),$user)){
$role = $this->campaignService->getRoleForInternalClient($element['role']);
$clientIntern=true;
switch ($role->value) {
case 'ROLE_OBSERVER':
$defaultObserver = [...$defaultObserver, $user->getOriginalMailUser()];
break;
case 'ROLE_VALIDATOR':
$defaultValidator = [...$defaultValidator, $user->getOriginalMailUser()];
break;
}
}else{
$clientIntern=false;
$roleList = ['ROLE_VALIDATOR_EXTERNAL','ROLE_OBSERVER_EXTERNAL'];
if (!in_array($role,$roleList)) {
$role = $this->campaignService->getRoleForExternalClient($element['role']);
}
switch ($role->value) {
case 'ROLE_VALIDATOR_EXTERNAL':
$defaultValidatorExternal = [...$defaultValidatorExternal, $user->getOriginalMailUser()];
break;
case 'ROLE_OBSERVER_EXTERNAL':
$defaultObserverExernal = [...$defaultObserverExernal, $user->getOriginalMailUser()];
break;
}
}
if ($user->getNewAdd()) {
//role external is just a client
$user->setRoles(['ROLE_CLIENT'])
->setEnabled(false)
->setNewAdd(false)
;
//add company in user new add
$companyUser = $formEditCampaign?->get('company')?->getData();
if ($companyUser !== null && $clientIntern==true) {
$user->setCompany($companyUser);
}
//end
if (in_array($role, ['ROLE_OBSERVER_EXTERNAL','ROLE_VALIDATOR_EXTERNAL'])) {
$user->setExternal(true);
$user->setCompany(null);
}
$user->setPassword($passwordHasher->hashPassword($user, $user->getPassword()));
$entityManager->persist($user);
$entityManager->flush();
$event = new ClientUpdatedEvent($user, true);
$newUserCreateId[] = $user->getId();
if (!in_array($user->getEmail(),$oldParticipantMail)) {
$dispatcher->dispatch($event, ClientUpdatedEvent::NAME);
}
} else {
if (!in_array($user->getId(), $newUserCreateId) && true === $launchJustOne&& isset($mission) && !is_null($mission)) {
if ($user->getId() != $mission->getCampaign()->getOrderedBy()->getId()) {
$event = new MissionSendEvent($mission, $user, $role);
if (!in_array($user->getEmail(),$oldParticipantMail)) {
$dispatcher->dispatch($event, MissionSendEvent::NAME);
}
}
}
}
foreach ($campaign->getMissions() as $mission) {
$participantAlredyExiste = false;
foreach ($mission->getParticipants() as $participant) {
if($participant->getUser()->getId() == $user->getId() && $participant->getRole()->value == $role && $role!="ROLE_SUBCONTRACTOR"){
$participantAlredyExiste = true ;
}
}
if (!is_null($user) and !empty($user) and !in_array($user->getId(),$userAlreadyAdd) && !$participantAlredyExiste) {
//add participant
$participant = (new MissionParticipant())
->setUser($user)
->setMission($mission)
->setRole($role);
$mission->addParticipant($participant);
}
}
}
//prendre les contact projet sur une des mission
foreach ($campaign->getMissions() as $miss) {
foreach ($miss->getParticipants() as $p) {
if ($p->getRole() == Role::PROJECT_CONTACT ) {
$contactProjects[] = $p->getUser();
}
}
}
if (!empty($contactProjects)) {
//first remove all contact project
foreach ($campaign->getMissions() as $mission) {
foreach ($mission->getParticipants() as $participant) {
if ($participant->getRole() == Role::PROJECT_CONTACT) {
$entityManager->remove($participant);
$entityManager->flush();
}
}
}
//add contact project in all mission
foreach ($campaign->getMissions() as $mission) {
$contactProjects = array_unique($contactProjects);
foreach ($contactProjects as $contact) {
$contactUser = $userRepository->find($contact);
$participant = (new MissionParticipant())
->setUser($contactUser)
->setMission($mission)
->setRole(Role::PROJECT_CONTACT);
$mission->addParticipant($participant);
}
}
}else{
$contactProjectIsAvailable = false;
foreach ($campaign->getMissions() as $mission) {
foreach ($mission->getParticipants() as $participant) {
if ($participant->getRole() == Role::PROJECT_CONTACT) {
$contactProjectIsAvailable = true;
}
}
}
//add contact project in all mission
foreach ($campaign->getMissions() as $mission) {
if (!$contactProjectIsAvailable) {
$contactProject = array_column($userRepository->getContactProjectByCompany($campaign->getCompany()),'id');
$contactProject = array_unique($contactProject);
foreach ($contactProject as $contact) {
$userContact = $userRepository->find($contact);
$missionParticipantContactProject = (new MissionParticipant())
->setUser($userContact)
->setMission($mission)
->setRole(Role::PROJECT_CONTACT);
$mission->addParticipant($missionParticipantContactProject);
}
}
}
}
$campaign->setDefautObserver($defaultObserver)
->setDefaultValidator($defaultValidator)
->setDefaultValidatorExternal($defaultValidatorExternal)
->setDefautObserverExternal($defaultObserverExernal);
$launchJustOne = false;
$fileToDeleted = $formEditCampaign->get('listfileMissionsToDeleted')->getData();
//delete files
if (!empty($fileToDeleted) and !is_null($fileToDeleted) ) {
$fileExplode = explode(';',$fileToDeleted);
foreach ($fileExplode as $file) {
$fileMission = $fileMissionRepository->findOneBy(['name'=>$file,'campaign'=>$campaign]);
if (!is_null($fileMission)) {
$fileName = $fileName = "Campaigns/".$campaign->getId()."/".$fileMission->getName();
$bucketName = "company-".strtolower($campaign->getCompany()->getId());
$destination = $this->getParameter($pathCampaing) . '/' . $campaign->getId();
if (file_exists($destination."/".$fileMission->getName())) {
unlink($destination."/".$fileMission->getName());
}
//delete file in repertory
$campaign->removeFileMission($fileMission);
//remove in repertory
foreach ($campaign->getMissions() as $mission) {
$fileMission = $fileMissionRepository->findOneBy(['name'=>$file,'mission'=>$mission]);
$destinationFileMission = $this->getParameter($pathMission) . '/' . $mission->getId();
if (!is_null($fileMission) && file_exists($destinationFileMission."/".$fileMission->getName())) {
unlink($destinationFileMission."/".$fileMission->getName());
}
if (!is_null($fileMission)) {
$mission->removeFileMission($fileMission);
$entityManager->remove($fileMission);
}
//suppression file in storage
}
$googleStorageService->deleteFile($bucketName,$fileName);
$entityManager->flush();
}
}
}
foreach ($files as $file) {
$destination = $this->getParameter($pathCampaing) . '/' . $campaign->getId();
$originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
$extensionFile = pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION);
$newFilename = $originalFilename . '-' . uniqid() . '.' . $extensionFile;
//upload file in google storage
$nameUniqueCompany = strtolower("company-".$campaign->getCompany()->getId());
$this->googleStorageService->uploadFile($nameUniqueCompany,$file,$newFilename,'Campaigns/'.$campaign->getId());
$fileMission = new FileMission();
$fileMission->setName($newFilename);
$fileMission->setIsNew(1);
$fileMission->setUser($this->getUser());
$campaign->addFileMission($fileMission);
}
// dd( $campaign->getFileMissions());
$jobSub = $request->request->get('jobsub');
$nbrMission = sizeof($missions);
if ($campaign->getNumberInitialOfMissions() != null && intval($campaign->getNumberInitialOfMissions()) != $nbrMission) {
$isCampaignContainsEvaluateProduct = $this->checkIfCampaignContainsProductEvaluate($campaign);
$newStateOfThisCampaign = 'resend';
$campaign->setReSendToClient(true);
if($isCampaignContainsEvaluateProduct){
$newStateOfThisCampaign = 'waiting';
}
if(in_array('ROLE_ADMIN', $this->getUser()->getRoles())){
$campaign->setRecurringState('waiting_validation');
}
$campaign->setState($newStateOfThisCampaign);
$campaign->setNumberInitialOfMissions(sizeof($missions));
}
if ($campaign->getMissions()->count() === 0) {
$state = 'provisional';
//$campaignTypeInitiation = CampaignTypeInitiation::CAMPAIGN_FROM_DEVIS_CLIENT->value;
//$campaign->setTypeInitiation($campaignTypeInitiation);
}
if (count($campaign->getMissions()) == 1 and $campaign->getMissions()->first()->getProduct()->getName()=="Espace de discussion") {
$campaign->setState('provisional');
}
$ids =[];
foreach ($missions as $key => $mission) {
$serviceParticipant = new Service();
//determine if mission is new // add normal state
if ($newCampaign) {
if ($mission->getData()->getProduct()->getType() === ProductType::A_EVALUER) {
$state = 'waiting';
}
}
//add brief
$mission->getData()->setInitialBriefing($campaignBrief, true);
if (!$missionService->haveAvalidator(mission: $mission->getData())) {
$id = $missionService->setValidatorUserWhoOrder(mission: $mission->getData());
if (null !== $id) {
$allMissionNewId[] = $id;
}
}
if ($mission->getData()->getProduct()->getType() != ProductType::AU_TEMPS_PASSE) {
$nbrAU_TEMPS_PASSE++;
}
if ($mission->getData()->getProduct()->getType() == ProductType::A_EVALUER) {
$nbrA_EVALUER++;
}
if ($mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT) {
$nbrAU_FORFAIT++;
}
if(sizeof(explode("-", $mission->getData()->getOldCommand()))==1){
$newMissionInCampaign = true;
}
if ($mission->getData()->getOldCommand() != null && sizeof(explode("-", $mission->getData()->getOldCommand())) == 4) {
[$quatity, $price, $productId, $timestamp] = explode("-", $mission->getData()->getOldCommand());
// Check if timestamp an other information change;
if ($mission->getData()->getQuantity() != $quatity || $mission->getData()->getProduct()->getId() != $productId) {
$otherInformationThanDateChange = true;
//add information to historique
if(in_array('ROLE_ADMIN', $this->getUser()->getRoles())){
$campaign->setRecurringState('waiting_validation');
}
$historique = (new Historique())
->setUser($this->getUser())
->setMission($mission->getData())
->setMessage('Le panier a été mis à jour par : ' . $this->getUser());
$entityManager->persist($historique);
$entityManager->flush();
}
if ($mission->getData()->getDesiredDelivery()?->getTimestamp() && intval($timestamp) != intval($mission->getData()->getDesiredDelivery()->getTimestamp())) {
if (!$otherInformationThanDateChange) {
$missionService->addHistorique(mission: $mission->getData(), user: $this->getUser(), action: "deadline_change");
}
}
if ($otherInformationThanDateChange and !$newCampaign) {
$campaign->setReSendToClient(true);
$campaign->setState("resend");
if(in_array('ROLE_ADMIN', $this->getUser()->getRoles())){
$campaign->setRecurringState('waiting_validation');
}
$canResendToClient = false;
}
}
if ($mission->getData()->getOldCommand() != null and !$newCampaign and $otherInformationThanDateChange) {
$campaign->setReSendToClient(true);
$campaign->setState("resend");
$entityManager->persist($campaign);
$entityManager->flush();
}
$originalMission = $missionRepository->find($mission->getData()->getId());
if (!is_null($mission->getData()->getAdminIncome())) {
$mission->getData()->setPrice($mission->getData()->getAdminIncome());
}
//-----------------------add default observer if new mission-------------------
if (!is_null($originalMission) and empty($originalMission->getReference()) ) {
// //add default observer
if($campaign->getDefautObserver() != null){
$missionService->addDefaultClient($mission->getData(), 'observer',$stateRecurred);
}
// add default validator
if($campaign->getDefaultValidator() != null){
$missionService->addDefaultClient($mission->getData(), 'validator',$stateRecurred);
}
//------------------------------------------------------------------------------
}
if (!is_null($originalMission)) {
if (!$isNewCampaing) {
$mission->getData()->setOldCommand("{$mission->getData()->getQuantity()}-{$originalMission->getPrice()}-{$mission->getData()->getProduct()->getId()}-{$mission->getData()->getDesiredDelivery()?->getTimestamp()}");
}
}
if (empty($mission->getData()->getReference())) {
foreach ($campaign->getMissions() as $mis) {
if (!empty($mis->getReference())) {
$mission->getData()->setReference($mis->getReference());
break;
}
}
if (empty($mission->getData()->getReference())) {
$mission->getData()->setReference($missionService->generateReference());
}
}
$missionId = $missionRepository->findOneBy(['id' => $mission->get('missionId')->getData()]);
if ($sendEmailDeliveryDateChange and !$newCampaign) {
if (isset($missionsInCampaign[$mission->getData()->getId()]) && $mission->getData()->getDesiredDelivery() != $missionsInCampaign[$mission->getData()->getId()] && !in_array($mission->getData()->getState(), ['provisional', 'waiting'])) {
$event = new MissionDesiredDeliveryUpdatedAfterValidationEvent($missionId);
$dispatcher->dispatch($event, MissionDesiredDeliveryUpdatedAfterValidationEvent::NAME);
$sendEmailDeliveryDateChange = false;
} elseif (isset($missionsInCampaign[$mission->getData()->getId()]) && $mission->getData()->getDesiredDelivery() != $missionsInCampaign[$mission->getData()->getId()] && ($mission->getData()->getState() == 'provisional' || $mission->getData()->getState() == 'waiting')) {
// $campaign->setState('provisional');
$event = new MissionDesiredDeliveryUpdatedBeforeValidationEvent($mission->getData());
$dispatcher->dispatch($event, MissionDesiredDeliveryUpdatedBeforeValidationEvent::NAME);
$sendEmailDeliveryDateChange = false;
}
}
//--------------------------add New Subcontractor ------------------------------------------
$jobsubForThisMission = $jobSub[$key];
$jobsubForThisMissionInArray = explode(";", $jobsubForThisMission);
$newSubcontractorList = [];
foreach ($jobsubForThisMissionInArray as $newSubontractor) {
$newSubontractor = explode("-:", $newSubontractor);
if (sizeof($newSubontractor) == 3 or sizeof($newSubontractor) == 2 or sizeof($newSubontractor) == 4) {
$newSubcontractorList = [
...$newSubcontractorList,
[
"job_id" => $newSubontractor[0],
"email_user" => $newSubontractor[1],
"income_suggested" => isset($newSubontractor[2]) ? $newSubontractor[2]: null,
"priceForProduct" => isset($newSubontractor[3]) ? $newSubontractor[3]: null,
]
];
}
}
$alreadySent = [];
foreach ($newSubcontractorList as $key => $newSuboContractor) {
echo "début insertion sous traitant<br>";
$errorAddSub = false;
$newUser = $userRepository->findOneBy(['email' => $newSuboContractor['email_user']]);
$newjob = $jobRepository->findOneBy(['id' => $newSuboContractor['job_id']]);
if ($newUser == null) {
$errorAddSub = true;
$error = true;
$this->addFlash(
type: 'error',
message: "Veuillez vérifier le contact opérationnel suivant " . $newSuboContractor['email_user']
);
return $this->redirectToRoute('handle_mission_campaign', ["id" => $campaign->getId()]);
}
$productMission = $mission->getData()->getProduct();
foreach ($mission->getData()->getParticipants() as $participant) {
$fullName = $newUser->getFullName();
if ($participant->getUser() == $newUser && $participant->getJob() == $newjob) {
$this->addFlash(
type: 'error',
message: "Le sous-traitant $fullName vous essayé d'ajouté est deja sur cette mission"
);
$errorAddSub = true;
$error = true;
}
$services = $entityManager->getRepository(Service::class)->findBy(['user' => $newUser]);
$linkService = false;
$matriceLink = [];
foreach ($services as $service) {
if ($service->getProduct()->getId() === $productMission->getId()) {
$linkService = true;
}
}
if (!$linkService and !in_array('ROLE_SUBCONTRACTOR', $this->getUser()->getRoles())) {
$serviceParticipant->setProduct($productMission)
//->setPrice($productMission->getPrice())
->setUser($newUser);
if ($mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT and $newSuboContractor['priceForProduct'] != null) {
// mail("anthonyssdfsffffff@yopmail.com", "mission", $newSuboContractor['priceForProduct']);
$serviceParticipant->setPrice($newSuboContractor['priceForProduct'])->setResale($productMission->getPrice());
$entityManager->persist($serviceParticipant);
}
}else{
if( in_array('ROLE_SUBCONTRACTOR', $this->getUser()->getRoles()) &&
$mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT &&
!$linkService && !in_array($mission->getData()->getId(),$ids)
){
$dailyRate = floatval($newUser->getDailyRate());
$resaleRate = floatval($newUser->getResaleRate());
$missionPrice = floatval($mission->getData()->getPrice());
$time = $missionPrice * 420 / $dailyRate ;
$resalePrice = $time*$resaleRate/420;
$serviceParticipant->setProduct($productMission)
->setUser($newUser)
->setPrice($missionPrice)
->setResale($resalePrice)
;
$ids = [...$ids,$mission->getData()->getId()];
$mission->getData()->setPrice($resalePrice);
$productMission->setPrice($resalePrice);
$entityManager->persist($serviceParticipant);
}
elseif(!$linkService and $mission->getData()->getProduct()->getType() == ProductType::AU_FORFAIT and $newSuboContractor['priceForProduct'] == null) {
$errorAddSub = true;
$error = true;
$this->addFlash('error', "Veuillez ajouter le produit et le prix pratique par $fullName au niveau de sa fiche ou au niveau de l'ajout du sous traitant lors de la commande.");
}
}
}
if (!$errorAddSub) {
$missionParticipant = new MissionParticipant();
if (empty($missionId)) {
$missionParticipant->setMission($mission->getData());
} else {
$missionParticipant->setMission($missionId);
}
$missionParticipant->setUser($newUser);
//$missionParticipant->setIncomeSuggested($newSuboContractor['income_suggested']);
$missionParticipant->setJob($newjob);
$missionParticipant->setRole(Role::ROLE_SUBCONTRACTOR);
if (!empty($newSuboContractor['income_suggested'])) {
$missionParticipant->setIncomeSuggested($newSuboContractor['income_suggested']);
}
$mission->getData()->addParticipant($missionParticipant);
$entityManager->persist($missionParticipant);
$entityManager->flush();
if (!in_array($missionParticipant->getUser(), $alreadySent) && !$newCampaign) {
$event = new SubContractorMissionAddedEvent($missionParticipant->getUser(), $mission->getData());
$dispatcher->dispatch($event, SubContractorMissionAddedEvent::NAME);
$alreadySent[] = $missionParticipant->getUser();
}
}
}
$searchParticipant = $missionParticipantRepository->findOneBy(['mission' => $missionId, 'role' => 'ROLE_SUBCONTRACTOR']);
if (empty($searchParticipant)) {
$event = new MissionWithoutSubContractorCheckedEvent($mission->getData());
$dispatcher->dispatch($event, MissionWithoutSubContractorCheckedEvent::NAME);
}
if (!empty($mission->get('newWorkflow')->getData())) {
$newWorkflow = clone $mission->get('newWorkflow')->getData();
$newWorkflow->setTemplate(false);
$mission->getData()->setWorkflow($newWorkflow);
$entityManager->persist($newWorkflow);
}
}
$entityManager->flush();
if ($error) {
foreach ($allMissionNewId as $id) {
if (!in_array($id, $oldMissionId) or empty($oldMissionId)) {
$missionToRemove = $entityManager->getRepository(Mission::class)->find($id);
$missionToRemove->setWorkflow(null);
$entityManager->persist($missionToRemove);
$entityManager->flush();
$entityManager->remove($missionToRemove);
$entityManager->flush();
}
}
return $this->redirectToRoute('handle_mission_campaign', ["id" => $campaign->getId()]);
}
foreach ($campaign->getMissions() as $mission) {
//$mission->setState('provisional');
if ($newCampaign) {
if (
$state === 'waiting' &&
($mission->getProduct()->getType() === ProductType::AU_FORFAIT) || ($mission->getProduct()->getType() === ProductType::AU_TEMPS_PASSE)
) {
$mission->setState('provisional');
} else {
$mission->setState($state);
}
if ($mission->getState() === 'waiting') {
$mission->setStateProvider('A évaluer');
} else {
$mission->setStateProvider('A activer');
}
}
}
if ($campaign->getCreditHistory() == null) {
$creditHistory = $creditHistoryRepository->findOneBy(['company' => $campaign->getCompany(), "typePack" => 4]);
$campaign->setCreditHistory($creditHistory);
}
if ($newCampaign) {
$campaign->setState($state);
//if(!empty($campaign->getMissions())){
foreach($campaign->getMissions() as $mission) {
$this->missionService->addHistorique(mission: $mission, user:$campaignInitiator, action: 'campaign_initiate_by_admin');
break;
}
//}
}
if( ($otherInformationThanDateChange || $newMissionInCampaign) && ( in_array('ROLE_SUBCONTRACTOR', $this->getUser()->getRoles()))&& !$this->campaignService->isAllProductHaveA_EvaluerMission($campaign) ){
$this->campaignService->resendCampaignForValidation($campaign,$this->getUser());
}
$campaign->setDisabled(null);
$entityManager->persist($campaign);
$entityManager->flush();
if (!$newCampaign) {
if ($otherInformationThanDateChange && $nbrAU_FORFAIT > 0 && $nbrAU_FORFAIT == $nbrMission && $this->campaignService->areAllRequiredSubcontractorsPresent(campaign: $campaign)) {
$campaign->setReSendToClient(true);
$entityManager->persist($campaign);
$entityManager->flush();
}
if ($formEditCampaign->getClickedButton() && 'editGlobalMssion' === $formEditCampaign->getClickedButton()->getName()) {
// Btn édit on envoie juste un email.
$event = new CampaignModifiedEvent($campaign);
$dispatcher->dispatch($event, CampaignModifiedEvent::NAME);
} else if ($formEditCampaign->getClickedButton() && 'saveGlobalMission' === $formEditCampaign->getClickedButton()->getName()) {
$nbMission = [];
$nbInitialNotEmpty = [];
foreach ($campaign->getMissions() as $mission) {
$nbMission[] = $mission;
$initialTime = $mission->getInitialTime();
if (!empty($initialTime)) {
$nbInitialNotEmpty[] = $initialTime;
}
}
if (count($nbMission) === count($nbInitialNotEmpty)) {
return $this->redirectToRoute('campaign_transition', ['id' => $campaign->getId(), 'transition' => 'unpause']);
}
}
}
//recurrency
if($stateRecurred == 'recurred'){
$campaign->setState('recurred');
$entityManager->flush();
$stateActiveFrequency = $oldCampaignStateActiveFrequency == false && $campaign->getActiveFrequency() == true ? true : false;
$isActiveFrequency = $campaign->getActiveFrequency()== true ? true : false;
$recurringState = !is_null($campaign->getRecurringState()) && $campaign->getRecurringState() == "waiting_validation" || (
in_array('ROLE_ADMIN',$this->getUser()->getRoles()) && $campaignRecurrentService->isAnElementFrequencyChange($campaign->getFrequency() ,$oldFrequency ) ) ? 'waiting_validation': 'in_progress';
$campaign->setRecurringState(recurringState: $recurringState );
$campaignRecurrentService->toogleRecurrent($campaign,$isActiveFrequency, $stateActiveFrequency);
$now = new \DateTime();
$startDate = $campaign->getFrequency()->getStartDate();
if($now->format('y/d/m G:i') >= $startDate->format('y/d/m G:i') && $campaign->getRecurringState()!='waiting_validation'){
$campaign->getFrequency()->setStartDate(new \DateTime());
$campaignRecurrentService->updateLaunchRecurringAt($campaign);
$newCampaign = $campaignRecurrentService->clone($campaign);
$entityManager->persist($newCampaign);
$campaign = $newCampaign ;
}elseif($campaign->getRecurringState()!='waiting_validation'){
$campaignRecurrentService->updateLaunchRecurringAt(campaign:$campaign,dateToLaunch:$newStartDate);
}
$eventRecurrent = new CampaignRecurrentEvent($campaign, false, true);
$dispatcher->dispatch($eventRecurrent, CampaignRecurrentEvent::NAME);
$this->addFlash(
type: 'success',
message: 'Votre commande réccurente a été modifier avec succès'
);
return $this->redirectToRoute('recurring_service');
}
else{
if ($campaign->getActiveFrequency()) {
$now = new \DateTime();
$startDate = $campaign->getFrequency()->getStartDate();
$hours = $now->format('G');
$minutes = $now->format('i');
$second = $now->format('s');
$campaignTypeInitiation = CampaignTypeInitiation::CAMPAIGN_FROM_RECURRENT->value;
$newStartDate = $startDate->setTime($hours, $minutes, $second);
$campaign->getFrequency()->setStartDate($newStartDate);
$campaign->setIsRecurrent(true);
$recurringState = !is_null($campaign->getRecurringState()) && $campaign->getRecurringState() == "waiting_validation" ? $campaign->getRecurringState() : 'in_progress';
$campaign->setRecurringState($recurringState );
$campaign->setState('recurred');
$campaign->setTypeInitiation($campaignTypeInitiation);
$eventRecurrent = new CampaignRecurrentEvent($campaign, true);
$dispatcher->dispatch($eventRecurrent, CampaignRecurrentEvent::NAME);
if($now->format('y/d/m G:i') >= $startDate->format('y/d/m G:i') && $campaign->getRecurringState()!='waiting_validation'){
$this->updateCampaignFrequencyDateUntilNow($campaignRecurrentService,$campaign,$now,$entityManager,$dispatcher);
}else{
$campaignRecurrentService->updateLaunchRecurringAt(campaign:$campaign,dateToLaunch:$newStartDate);
}
$this->addFlash(
type: 'success',
message: 'Votre commande réccurente a été crée avec succès'
);
return $this->redirectToRoute('recurring_service');
}
else{
if ($newCampaign) {
$event = new CampaignCreatedEvent($campaign,'CREER_PAR_ADMIN',$contactProjects,true);
$dispatcher->dispatch($event, CampaignCreatedEvent::NAME);
$this->addFlash('success', 'Votre commande a été enregistrée avec succès');
}else{
$this->addFlash('success', 'Modification enregistrée');
}
if (count($campaign->getMissions()) == 1 and $campaign->getMissions()->first()->getProduct()->getName()=="Espace de discussion") {
$campaign->setState('provisional');
$entityManager->persist($campaign);
$entityManager->flush();
}
}
}
if (!is_null($oldPack) and $oldPack != $campaign->getCreditHistory() and isset($mission) and !is_null($mission)) {
$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();
}
if (count($campaign->getMissions()) == 1 and $campaign->getMissions()->first()->getProduct()->getName()=="Espace de discussion") {
$campaign->setState('provisional');
$entityManager->persist($campaign);
$entityManager->flush();
}
$hitoryExist = null;
foreach ($campaign->getMissions() as $m) {
if (!$m->getHistoriques()->isEmpty()) {
$hitoryExist = $m->getHistoriques();
break;
}
}
;
if ($hitoryExist !== null) {
foreach ($campaign->getMissions() as $m) {
if ($m->getHistoriques()->isEmpty()) {
foreach ($hitoryExist as $h) {
$historyNew = clone $h;
$m->addHistorique($historyNew);
$entityManager->persist($historyNew);
}
$entityManager->persist($m);
$entityManager->flush();
}
}
}
return $this->redirectToRoute('mission_index');
}
$formEditSubcontractor = $this->createForm(EditSubcontractorParticipantType::class);
setcookie('missionIDs','',0,"/");
return $this->renderForm('campaign/edit_mission.html.twig', [
'campaign' => $campaign,
'form' => $formEditCampaign,
'formEditSubcontractor' => $formEditSubcontractor,
'user' => $user
]);
}
private function updateCampaignFrequencyDateUntilNow($campaignRecurrentService,$originalCampaign, $now,$entityManager,$dispatcher){
$campaignRecurrentService->updateLaunchRecurringAt($originalCampaign);
$campaignFrequency = $originalCampaign->getFrequency()->getLaunchRecurrenceAt();
$newCampaign = $campaignRecurrentService->clone($originalCampaign);
$campaign = $newCampaign;
$entityManager->persist($campaign);
$entityManager->flush();
$event = new CampaignCreatedEvent($campaign);
$dispatcher->dispatch($event, CampaignCreatedEvent::NAME);
foreach($newCampaign->getMissions() as $mission ){
$this->missionService->addHistorique(mission: $mission, user:$newCampaign->getOrderedBy() , action: 'campaign_initiate_by_recurrent');
}
if($campaignFrequency<$now){
$this->updateCampaignFrequencyDateUntilNow($campaignRecurrentService,$originalCampaign, $now,$entityManager,$dispatcher);
}
return;
}
#[Route('/campagne/{id}/demande-evaluation', name: 'campaign_demande_evaluation')]
public function evaluation(Request $request, Campaign $campaign, MissionService $missionService, EventDispatcherInterface $dispatcher): Response
{
$event = new CampaignEvaluationEvent($campaign);
$dispatcher->dispatch($event, CampaignEvaluationEvent::NAME);
foreach ($campaign->getMissions() as $mission) {
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "evaluation_request");
}
$this->addFlash(
type: 'success',
message: 'La demande d\'évaluation a bien été envoyée'
);
return $this->redirect($request->headers->get('referer'));
}
#[Route('/campagne/{id}/recapitulatif/{showStep}', name: 'campaign_recapitulatif', defaults: ['showStep'=>""])]
public function recapPanier(string $showStep, PriceService $priceService,MissionParticipantService $missionParticipantService, NumberFormatService $numberFormatService, CampaignService $campaignService, ConsumptionBalanceForCompanyService $consumptionBalanceForCompanyService, Campaign $campaign): Response
{
$creditHistory = $campaign->getCreditHistory();
$typePack = $creditHistory->getTypePack();
$text = match ((int) $typePack) {
0 => 'Votre solde actuel',
1 => 'Solde sur ' . $numberFormatService->format($creditHistory->getOrderPrice()) . ' € HT/mois',
2 => 'Solde sur ' . $numberFormatService->format($creditHistory->getOrderPrice()) . ' € HT/an',
3 => 'Budget HT consommé depuis le 1er du mois',
4 => '',
default => '',
};
$currency = match ((int) $campaign->getCreditHistory()->getTypePack()) {
0 => '€',
default => '€',
};
$balance = $campaign->getCreditHistory()->getTypePack() == 3 ? $consumptionBalanceForCompanyService->consumptionOfTheMonth(company: $campaign->getCompany()) : $campaign->getCreditHistory()->getCurrentBalance();
return $this->renderForm('campaign/recapitulatif.html.twig', [
'campaign' => $campaign,
'participants_subcontractor' => $missionParticipantService->getSubcontractorWithMissing($campaign),
'text' => $text,
'price_service' => $priceService,
'currency' => $currency,
'balance' => $balance,
'show_step'=> $showStep == "step" ? true : false,
'step'=>4
]);
}
#[Route('/campagne/{id}/accepter/{currentRouteName?}/{firstClickedMissionId?}', name: 'campaign_accept_all', defaults: ['currentRouteName' => null, 'firstClickedMissionId' => null])]
public function campaignAccept(CampaignService $campaignService, MissionService $missionService, Campaign $campaign, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher, ClientSoldService $clientSoldService, $currentRouteName = null, $firstClickedMissionId = null): Response
{
$campaign->setState($campaignService->getStateCampaign(campaign: $campaign));
$campaign->setReSendToClient(false);
$campaign->setClientStatus("");
$entityManager->flush();
$campaignService->setAllMissionAsNotEvaluate(campaign: $campaign);
$event = new CampaignValidatedEvent($campaign);
$dispatcher->dispatch($event, CampaignValidatedEvent::NAME);
foreach ($campaign->getMissions() as $mission) {
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "accepter");
}
$this->addFlash(
type: 'success',
message: "Le panier a bien été validé avec succès"
);
if (isset($currentRouteName) && $currentRouteName == 'mission_edit' && isset($firstClickedMissionId)) {
return $this->redirectToRoute('campaign_transition', [
'id' => $campaign->getId(),
"transition" => "activated",
"currentRouteName" => $currentRouteName,
"firstClickedMissionId" => $firstClickedMissionId
]);
} else {
return $this->redirectToRoute('campaign_transition', ['id' => $campaign->getId(), "transition" => "activated"]);
}
}
#[Route('/campagne/{id}/resoumission', name: 'campaign_resoumission')]
public function campaignResoumission(Request $request, MissionService $missionService, Campaign $campaign, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher): Response
{
$event = new CampaignWaitingEvent($campaign, false, $this->getUser());
$dispatcher->dispatch($event, CampaignWaitingEvent::NAME);
foreach ($campaign->getMissions() as $mission) {
$missionService->addHistorique(mission: $mission, user: $this->getUser(), action: "resoumission");
}
$campaign->setClientStatus('waiting_for_confirmation');
$campaign->setState('waiting_validation');
$entityManager->flush();
$message = "Le panier est bien soumis avec succès";
if ($this->isGranted("ROLE_SUBCONTRACTOR")) {
$listMissionNotEvaluate = $this->campaignService->getMissionListNotEvaluate(user: $this->getUser(), campaign: $mission->getCampaign());
$message = "";
if ($this->missionService->isMyMission(mission: $mission) && $mission->getCampaign()->getState() != "in_progress" && $mission->isEvaluate()) {
$message = "Vous avez évalué la mission. Nous attendons maintenant la validation du client {$mission->getCampaign()->getCompany()->getName()}";
} elseif ($listMissionNotEvaluate > 0 && $this->campaignService->evaluateAllHerMission(campaign: $mission->getCampaign(), user: $this->getUser()) && $this->missionService->isMyMission(mission: $mission)) {
$intervenants = "";
foreach ($mission->getCampaign()->getMissions() as $mission) {
foreach ($mission->getParticipants() as $participant) {
if (!$participant->isEvaluate()) {
$intervenants .= "{$participant->getUser()->getFullName()} , ";
}
}
}
$intervenants = rtrim($intervenants, ",");
$message = "Vous avez évalué la mission. Nous attendons maintenant le retour de ces partenaires pour resoumettre la proposition au client ( { $intervenants})";
}
$this->addFlash(
type: 'success',
message: $message
);
} else {
$this->addFlash(
type: 'success',
message: 'La campagne à bien été resoumise'
);
}
return $this->redirect($request->headers->get('referer'));
}
#[Route('/campagne/activated/{id}', name: 'order_reactivated')]
public function orderReactivated(Request $request,OrderService $orderService, Campaign $campaign, EntityManagerInterface $entityManager,CampaignService $campaignService, EventDispatcherInterface $dispatcher): Response
{
$orderService->reActive($campaign);
$this->addFlash(
type: 'success',
message: 'La campagne a bien été réactiver'
);
return $this->redirect($request->headers->get('referer'));
}
#[Route('/campagne/{id}/relancer', name: 'campaign_relancer')]
public function campaignRelancer(Request $request, Campaign $campaign, EntityManagerInterface $entityManager, EventDispatcherInterface $dispatcher): Response
{
$event = new CampaignResendEvent($campaign);
$dispatcher->dispatch($event, CampaignResendEvent::NAME);
$this->addFlash(
type: 'success',
message: 'La campagne a bien été relancer'
);
return $this->redirect($request->headers->get('referer'));
}
public function onMissionWithoutWorkflow(MissionWithoutWorkflowEvent $event, $userRepository, $mailer)
{
$mission = $event->getMission();
if (!$mission instanceof Mission) {
return;
}
$admins = $this->dynamicHostService->getMailAdmin();
foreach ($admins as $admin) {
$notification = (new NotificationEmail())
->to(new Address($admin->value))
->subject('Une mission a été créée sans workflow')
->content('
<p>Bonjour,</p>
<p>La mission ' . $mission->getReference() . ' contient un produit "' . $mission->getProduct()->getName() . '" qui n\'a pas de Workflow associé.</p>
<p>Merci d\'en créer un pour ce produit et d\'aller le relier à la mission.</p>
')
->action('Modifier la mission', $this->generateUrl('handle_mission_campaign', ['id' => $mission->getCampaign()->getId()], UrlGeneratorInterface::ABSOLUTE_URL))
->markAsPublic();
$mailer->send($notification);
}
}
#[Route('/campagne/cart/{id}/{type}', name: 'campaign_pdf_cart', defaults: ['type' => 'pdf'])]
public function getPdfCart(Campaign $campaign, string $type, PriceService $priceService)
{
$update_ref = true;
foreach ($campaign->getMissionsWithoutEspaceDeDiscussion() as $mission) {
$mission->additionnal = $this->getAdditionalInformation($mission->getProduct()->getFrontId(), $update_ref);
$update_ref = false;
}
$twigRender = [
'link' => "campaign/pdf_cart/index.html.twig",
'param' => [
'campaign' => $campaign,
'price_service' => $priceService,
'currency' => "€",
'balance' => "0",
]
];
if ($type == 'pdf') {
$pdfOptions = new Options();
$pdfOptions->set('defaultFont', 'Arial');
$pdfOptions->set('enable_remote', true);
$pdfOptions->setIsRemoteEnabled(true);
$dompdf = new Dompdf($pdfOptions);
$context = stream_context_create([
'ssl' => [
'verify_peer' => FALSE,
'verify_peer_name' => FALSE,
'allow_self_signed' => TRUE
]
]);
$dompdf->setHttpContext($context);
$html = $this->renderView($twigRender['link'], $twigRender['param']);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$fichier = "commande_myflow_" . date('dmY');
$dompdf->stream($fichier, [
'attachement' => true
]);
return new JsonResponse(['status' => "Ok"], Response::HTTP_CREATED, ["Content-type" => "application/pdf"]);
} else {
return $this->render($twigRender['link'], $twigRender['param']);
}
}
private function getAdditionalInformation(string $productFrontId, bool $updateRef = false)
{
$param = $updateRef ? "$productFrontId&update_id=true" : $productFrontId;
$frontWebSiteUrl = $this->getParameter('front_website_url');
$client = new Client();
$response = $client->request('GET', "$frontWebSiteUrl/wp-json/my-flow/v1/product_info?product_id=$param", []);
$responseDecode = json_decode($response->getBody()->getContents());
return [
"ref" => $responseDecode->ref,
"attachement" => gettype($responseDecode->attachement) == "array" && sizeof($responseDecode->attachement) > 0 ? $responseDecode->attachement[0] : "",
"link" => $responseDecode->link,
];
}
private function updateUserDataDateCertificate($userData){
$dateAddCertificate = new \DateTime();
//if(is_null($userData->getVigilanceCertificate())){
$userData->setDateUpdateCertificate($dateAddCertificate);
//}
}
#[Route('/campagne/modification/price', name: 'campaign_modif_price')]
public function modificationPrestation(Request $request,PriceService $priceService,EntityManagerInterface $entityManager,ClientSoldService $clientSoldService)
{
$neddToReajustSold = false;
$allData = $request->request->all();
foreach ($allData as $missionId => $value) {
$mission = $entityManager->getRepository(Mission::class)->find($missionId);
$campaign = $mission->getCampaign();
$firstIdMission = $campaign->getMissions()->first()->getId();
$creditHistory = $campaign->getCreditHistory();
$dateActidatedAt = $campaign->getActivatedAt();
//price mission after update price prestation
$priceMissionNotTouch = $priceService->priceAndTimeMissionBasedOnPriceSale($mission)['price'];
if ($priceMissionNotTouch != $value) {
$neddToReajustSold = true;
//update priceSales mission if price original <> de new price
//first update price sales mission
$mission->setPriceSale($value);
$entityManager->persist($mission);
$entityManager->flush();
//second need to delete all balance transaction
$balanceTransaction = $entityManager->getRepository(BalanceTransactions::class)->soldeByMission($creditHistory,$mission);
if (is_null($balanceTransaction)) {
$oldTotalConsuption = $creditHistory->getTotalConsumption();
$oldCurrentBalance = $creditHistory->getCurrentBalance();
$creditHistory->setTotalConsumption($oldTotalConsuption - $value );
$creditHistory->setCurrentBalance($oldCurrentBalance + $value);
//remove balance transaction
}
//third decrease all value in balance transactions.
$clientSoldService->decreaseCurrentBalanceByMissionCost($mission,$dateActidatedAt);
}
}
$entityManager->flush();
$this->addFlash('success','Prix de la prestation changé avec succées');
return $this->redirectToRoute('mission_edit', ['id' => $firstIdMission], Response::HTTP_SEE_OTHER);
}
// private function createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign,$now,$entityManager){
// $campaignRecurrentService->updateLaunchRecurringAt($originalCampaign);
// $campaignFrequency = $originalCampaign->getFrequency()->getLaunchRecurrenceAt();
// $newCampaign = $campaignRecurrentService->clone($originalCampaign);
// $campaign = $newCampaign;
// $entityManager->persist($campaign);
// $entityManager->flush();
// if($campaignFrequency<$now){
// $this->createCampaignRecurrentFromFrontUntilNow($campaignRecurrentService,$originalCampaign, $now,$entityManager);
// }
// return;
// }
private function checkIfCampaignContainsProductEvaluate(Campaign $campaign){
foreach($campaign->getMissions() as $mission){
if($mission->getProduct()->getType()==ProductType::A_EVALUER){
return true;
}
}
return false;
}
#[Route('/contact-project/html/add', name: 'campaing_contact_project_html_add', methods: ['GET', 'POST'])]
public function modalContactProjectCampaing(Request $request): Response
{
$formAddMissionContactProject = $this->createForm(AddMissionContactProjectType::class);
return $this->render('campaign/_contact_project.html.twig', [
'formAddMissionContactProject' => $formAddMissionContactProject->createView()
]);
}
#[Route('/contact-project/take-info/{email}', name: 'campaing_contact_project_take_info', methods: ['GET', 'POST'])]
public function contactTakeInfos(Request $request,EntityManagerInterface $entityManager,$email = null): Response
{
$user = null;
if ($email !== null and !empty($email) ) {
$user = $entityManager->getRepository(User::class)->findOneByEmail($email);
}
return $this->render('campaign/_contact_project_list.html.twig', [
'user' => $user
]);
}
private function getProductList(?User $user=null){
if($user ==null){
return [];
}
$productList = [];
$services = $user->getServices();
foreach ($services as $service) {
$productList[$service->getProduct()->getId()] = $service->getPrice();
}
return $productList;
}
private function getPrice(Product $product, $user){
$productPrice = $product->getPrice();
if($user != null && in_array('ROLE_SUBCONTRACTOR', $user->getRoles())){
$listService = $this->getProductList($user);
$productPrice = $product->getId()!=null && array_key_exists($product->getId(),$listService) && $listService[$product->getId()]!=null ? floatval($listService[$product->getId()]) : 0;
}
return ($product->getType()->value != 2 and $product->getType()->value != 3) ? $productPrice : 0 ;
}
}