<?php
namespace App\Controller;
use App\Entity\BalanceTransactions;
use App\Entity\Company;
use App\Entity\CompanyData;
use App\Entity\SubContractorCompany;
use App\Entity\User;
use App\Entity\CreditHistory;
use App\Enum\BillingMethod;
use App\Enum\CommandeLoggingType;
use App\Enum\CompanyContract;
use App\Enum\TypePack;
use App\Enum\ProductType;
use App\Event\Client\NoticeOfInsufficientBudgetEvent;
use App\Event\ClientUpdatedEvent;
use App\Event\CompanyUpdatedEvent;
use App\Event\SubContractor\SubContractorReferencedEvent;
use App\Event\SubContractorUpdatedEvent;
use App\Form\CompanyAgencyType;
use App\Form\SubContractorCompanyType;
use App\Form\AddCreditCompanyType;
use App\Repository\BalanceTransactionsRepository;
use App\Repository\CampaignRepository;
use App\Repository\CompanyRepository;
use App\Repository\CreditHistoryRepository;
use App\Repository\ServiceRepository;
use App\Repository\SubContractorCompanyRepository;
use App\Repository\UserRepository;
use App\Service\ClientSoldService;
use App\Service\CompanyService;
use App\Service\ServiceService;
use App\Service\SharedResourceCategoryService;
use App\Service\UserService;
use App\Service\CreditService;
use App\Service\EmailService;
use App\Service\MyFlowMarginService;
use App\Service\NumberFormatService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use GuzzleHttp\Client;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use App\Service\PackService;
use App\Service\FrontAPIService;
use App\Service\GoogleStorageService;
use function PHPUnit\Framework\matches;
use App\Service\DynamicHostService;
#[Route('/admin')]
class AgencyController extends AbstractController
{
public function __construct(
private NumberFormatService $numberFormatService,
private CompanyService $companyAgencyService,
private FrontAPIService $frontAPIService,
private DynamicHostService $dynamicHostService,
private SharedResourceCategoryService $sharedResourceCategoryService,
)
{
}
/**
* @param CompanyRepository $companyAgencyRepository
* @return Response template company/index.html.twig
*/
#[Route('/agences', name: 'agency_index')]
public function index(CompanyRepository $companyAgencyRepository,GoogleStorageService $googleStorageService): Response
{
if (!$this->isGranted('ROLE_ADMIN')) {
throw new \NotFoundHttpException('La page que vous demandez est introuvable.');
}
return $this->render('agency/agency_index.html.twig', [
'companys' => $companyAgencyRepository->findBy(["deleted"=>false,"typeCompany"=>true], ['name' => 'DESC']),
]);
}
/**
* @param CompanyRepository $companyAgencyRepository
* @return Response template company/index.html.twig
*/
#[Route('/agences/ajouter', name: 'agency_add')]
#[Route('/agences/{id}/{userTab}', name: 'agency_edit', methods: ['GET', 'POST'], defaults: ['userTab' => null])]
public function handleAgency(SubContractorCompany $subContractorCompany = null, CompanyService $companyAgencyService, MyFlowMarginService $myFlowMarginService, User $user = null, CreditHistory $creditHistory = null, CreditService $creditService, Company $companyAgency = null, Request $request, UserService $userService, UserPasswordEncoderInterface $encoder, UserRepository $userRepository, CreditHistoryRepository $creditHistoryRepository, CampaignRepository $campaignRepository, SerializerInterface $serializer, EmailService $emailService, EntityManagerInterface $entityManager, SubContractorCompanyRepository $subContractorCompanyRepository, EventDispatcherInterface $dispatcher, ValidatorInterface $validator, ServiceRepository $serviceRepository, ServiceService $serviceService, ParameterBagInterface $parameter, PackService $packService,GoogleStorageService $googleStorageService, ?string $userTab = null): Response
{
//aucun manager n'y a access
if (in_array("ROLE_MANAGER", $this->getUser()->getRoles())) {
throw new \NotFoundHttpException('La page que vous demandez est introuvable.');
}
if ($request->get('_route') === 'agency_add' && !$this->isGranted('ROLE_ADMIN')) {
throw new \NotFoundHttpException('La page que vous demandez est introuvable.');
}
$agency = !is_null($request->query->get('type')) ? true : false;
$thisCompany = null;
$oldServiceSubcontractor = [];
$creditsHistoryCompany = [];
$modifSubcontractor = (null !== $request->query->get('modifSubcontractor')) and ($request->query->get('modifSubcontractor') == 1) ? 1 : 0;
if (null == $companyAgency) {
$companyAgency = new Company();
$companyData = new CompanyData();
$companyAgency->setTypeCompany(true)
->setCustomerDiscount(0)
->setCostOfDiscountedCredit(0)
->setCompanyData($companyData)
;
$companyAgency->setContract(CompanyContract::CASH->value);
$listClients = null;
$listOfManager = null;
$listSubContractors = null;
$listServices = null;
$creditHistory = new CreditHistory();
$allCredit = 0;
$roleSubContractor = 'ROLE_SUBCONTRACTOR';
} else {
$allRoleClient = ['["ROLE_CLIENT"]','["ROLE_CLIENT_ADMIN"]','["ROLE_MANAGER"]','["ROLE_ADMIN_AGENCY"]'];
$roleCLient = 'ROLE_CLIENT';
$roleCLientAdmin = 'ROLE_CLIENT_ADMIN';
$roleSubContractor = 'ROLE_SUBCONTRACTOR';
$thisCompany = $companyAgency->getId();
$listClients = $userRepository->findAllRoleByCompany($thisCompany, $allRoleClient,!$this->dynamicHostService->isAgency());
$listSubContractors = $subContractorCompanyRepository->findBy(['company' => $companyAgency]);
$creditAvailable = $creditService->CreditAvailable($companyAgency);
$allCredit = 0;
foreach ($creditAvailable as $credit) {
$allCredit += $credit->getCredit();
}
$creditsHistoryCompany = $creditHistoryRepository->findByCompanyWithDeletedState($companyAgency, false);
$campainsHistory = $campaignRepository->findBy(['company' => $companyAgency]);
$sorted = [];
foreach ($creditsHistoryCompany as $creditHistoryCompany) {
$date = $creditHistoryCompany->getCreatedAt()->format('YmdHis');
$sorted[$date] = $creditHistoryCompany;
}
foreach ($campainsHistory as $campainHistory) {
$date = $campainHistory->getCreatedAt()->format('YmdHis');
$sorted[$date] = $campainHistory;
}
foreach ($companyAgency->getCommandeLoggings() as $commandeLogging) {
$date = $commandeLogging->getCreatedAt()->format('YmdHis');
$sorted[$date] = $commandeLogging;
}
ksort($sorted);
$sorted = array_reverse($sorted);
}
/**
* Form for add company
*/
$form = $this->createForm(CompanyAgencyType::class, $companyAgency,['admin' => $this->isGranted('ROLE_ADMIN')]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($request->get('_route') === 'agency_add') {
$companyAgency->setCreatedAt(new \DateTime());
$companyAgency->setLogoFile($form->get('logoFile')->getData());
$companyAgency->setFaviconFile($form->get('faviconFile')->getData());
$creditHistory = new CreditHistory();
$creditHistory->setCompany($companyAgency)
->setName("Facturation individuelle")
->setTypePack(TypePack::CASH->value)
->setIdentifier($creditService->getNewReference())
->setOrderedBy($this->getUser());
$entityManager->persist($companyAgency);
$entityManager->persist($creditHistory);
$emailService->createSystemeEmailForAgency($companyAgency);
$this->sharedResourceCategoryService->setDefaultSharedResourceCategory($companyAgency);
$this->addFlash('success', 'L\'agence a bien été ajouté');
} else {
//dd($form->get('logoFile')->getData());
$companyAgency->setLogoFile($form->get('logoFile')->getData());
$companyAgency->setFaviconFile($form->get('faviconFile')->getData());
$companyAgency->setUpdatedAt(new \DateTime());
$this->addFlash('success', 'L\'agence a bien été modifiée');
}
$entityManager->flush();
$companyAgency->setLogoFile(null);
$companyAgency->setFaviconFile(null);
// dispatch the company.update event
$event = new CompanyUpdatedEvent($companyAgency);
$dispatcher->dispatch($event, CompanyUpdatedEvent::NAME);
if ($this->isGranted("ROLE_ADMIN_AGENCY")) {
return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
}
if($this->isGranted("ROLE_ADMIN")){
return $this->redirectToRoute('agency_index', [], Response::HTTP_SEE_OTHER);
}else{
return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
}
}
/**
* Form for add subContractor that does not exist to company
*/
$form2 = $this->createForm(SubContractorCompanyType::class, $user);
$form2->handleRequest($request);
$allSubContractorsEmails = $userRepository->findByRole($roleSubContractor);
if ($form2->isSubmitted() && $form2->isValid()) {
$oldServiceSubcontractor = [];
$oldJobSubcontractor = [];
$email = $request->request->get('emailSubContractor');
$modifSubcontractor = $request->request->get('modification_subcontractor');
$separateEmail = explode(" ", $email);
$email = $separateEmail[0];
if ($validator->validate($email, [new Email()])->count() > 0) {
$this->addFlash('error', 'L\'adresse ' . $email . ' n\'est pas valide. Nous vous invitons à vérifier votre saisie');
return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
}
$checkEmail = $userRepository->findOneBy(['email' => $email]);
$subContractorCompany = new SubContractorCompany();
//compare company
$isAlreadyExist = false;
//end company
if (empty($checkEmail)) {
$user = new User();
$password = $userService->generatePassword();
$encodedPassword = $encoder->encodePassword($user, $password);
$user->setPassword($encodedPassword);
$user->setEmail($email);
$user->setRoles([$roleSubContractor]);
$user->setEnabled(false);
$user->setCompany($companyAgency);
} else {
$user = $userRepository->findOneBy(['email' => $email]);
//Si pas vide vérifié si l'utilisateur éxiste déja sur d'autre agence ou sur MyFlow
if ($companyAgency != $user->getCompany()) {
$isAlreadyExist = true;
//alors creez un utilisateur enfant parceque l'utilisateur est dans un autre entreprise
//create new user
$userGenerate = new User;//for just generate the id automaticly
$userChild = clone $user;
$emailUniq = uniqid().$user->getEmail();
$userChild->setId($userGenerate->getId())->setEmail($emailUniq)->setEnabled($user->getEnabled())->setNewAdd(false)->setParent($user)->setPassword($user->getPassword())->setOriginalEmail($user->getEmail())->setCompany($companyAgency);
$user->addChild($userChild);
$entityManager->persist($user);
$user = $userChild;
//need to add user in child
}
}
$subconctractors = $subContractorCompanyRepository->findBy(['user'=>$user,'company' => $companyAgency]);
if ($modifSubcontractor == 1) {
foreach ($user->getSubContractorCompanies() as $subCompany) {
if($companyAgency == $subCompany->getCompany())
$subContractorCompany = $subCompany;
}
}
//get all old product of subcontractor // no need to control perte if product already link
foreach ($subconctractors as $sub) {
foreach ($sub->getProducts() as $product) {
$oldServiceSubcontractor[] = $product->getId();
}
}
if ($request->query->get('perte') == null) {
$listServicesForSubcontractor = $serviceRepository->findBy(['user' => $checkEmail]);
$allJob = [];
$allProduct = [];
foreach ($form2->getData()->getJobs() as $jobName) {
$nameJob = $jobName->getId();
$allJob[] =$jobName->getId();
}
foreach ($form2->getData()->getProducts() as $productName) {
$allProduct[] = $productName->getId();
}
if (!empty($user->getResaleRate() || empty($checkEmail))) {
$flag = false;
foreach ($form2->getData()->getProducts() as $productName) {
$name = $productName->getId();
foreach ($listServicesForSubcontractor as $service) {
if ($service->getProduct()->getId() === $name) {
$flag = true;
}
}
if ($flag !== true) {
$this->addFlash('error', 'Veuillez ajouter le produit et le prix pratique par ce partenaire au niveau de sa fiche.');
return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId(),'modifSubcontractor' => $modifSubcontractor], Response::HTTP_SEE_OTHER);
}
foreach ($listServicesForSubcontractor as $service) {
if ($user->isEnabled()) {
if ($service->getProduct()->getId() === $name and !in_array($service->getProduct()->getId(),$oldServiceSubcontractor)) {
if ($service->getProduct()->getType() === ProductType::AU_FORFAIT) {
$currentMarge = $this->numberFormatService->format($myFlowMarginService->getMarge($service, $companyAgency));
}else{
$currentMarge = $this->numberFormatService->format($myFlowMarginService->getMargeTJM($user));
}
$service->getProduct()->getName();
$fullName = $user->getFullName();
if ($currentMarge < 30) {
$this->addFlash(
"error",
"En ajoutant $fullName pour le service $productName, le total de marge pour le(s) sous-traitant(s) est de $currentMarge %");
return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId(), 'perte' => $currentMarge, 'email' => $email, 'product' => implode(",", $allProduct), 'job' => implode(",", $allJob),'modifSubcontractor' => $modifSubcontractor ], Response::HTTP_SEE_OTHER);
}
}
} else {
$this->addFlash('error', 'Ce partenaire a un profil incomplet, nous vous invitons à vous rendre sur sa fiche pour compléter son profil et l’activer');
return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId(),'modifSubcontractor' => $modifSubcontractor], Response::HTTP_SEE_OTHER);
}
}
}
} else {
$this->addFlash('error', 'Le tarif revente doit obligatoirement être renseigné. Nous vous invitons à vous rendre sur la fiche du partenaire pour compléter son profil.');
return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId(),'modifSubcontractor' => $modifSubcontractor], Response::HTTP_SEE_OTHER);
}
}
$verifyEmailSend = $subContractorCompanyRepository->findBy(['user' => $user, 'company' => $companyAgency]);
$flagSend = false;
foreach ($verifyEmailSend as $verify) {
if ($verify->getEmailSend() == true) {
$flagSend = true;
}
}
//delte product/job before add in modification
if ($modifSubcontractor == 1) {
foreach ($subContractorCompany->getJobs() as $jobs) {
$subContractorCompany->removeJob($jobs);
}
foreach ($subContractorCompany->getProducts() as $product) {
$subContractorCompany->removeProduct($product);
}
}
foreach ($form2->getData()->getJobs() as $job) {
$subContractorCompany->addJob($job);
}
foreach ($form2->getData()->getProducts() as $product) {
$subContractorCompany->addProduct($product);
}
$subContractorCompany->setCompany($companyAgency)
->setUser($user)
->setEmailSend(true);
if ($modifSubcontractor == 0) {
$user->addSubContractorCompany($subContractorCompany);
}
if (!empty($listSubContractors)) {
$newListOfSubcontractor = [];
//if modification , don't take a subcontractor in test
if ($modifSubcontractor == 1 ) {
foreach ($listSubContractors as $subContractor) {
if ($subContractor->getUser()->getId() != $user->getId()) {
$newListOfSubcontractor[] = $subContractor;
}
}
}else{
$newListOfSubcontractor = $listSubContractors;
}
//verify if subcontractor is already linked job and product
foreach ($form2->getData()->getJobs() as $job) {
foreach ($newListOfSubcontractor as $subContractor) {
foreach ($subContractor->getJobs() as $jobSubcontractor) {
if ($jobSubcontractor === $job ) {
$alreadyLinkJob = true;
//after job is already linked verify is already link a product
foreach ($subContractor->getProducts() as $product) {
foreach ($form2->getData()->getProducts() as $productInForm ) {
if ($productInForm === $product) {
$this->addFlash('error', 'Un sous traitant est déjà associé à cette agence pour ce produit et ce metier. Nous vous invitons à retirer le partenaire actuel avant d\'en ajouter un nouveau');
return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
}
}
}
}
}
}
}
$entityManager->persist($user);
//if ($modifSubcontractor == 0) {
$entityManager->persist($subContractorCompany);
//}
$entityManager->flush();
} else {
$entityManager->persist($user);
//if ($modifSubcontractor == 0) {
$entityManager->persist($subContractorCompany);
//}
$entityManager->flush();
}
//$this->companyService->syncSubcontractorsForAllMissions(subContractorCompany : $subContractorCompany);
$event = true;
foreach ($user->getServices() as $service) {
if (empty($service->getResale())) {
$event = false;
}
}
if ($event && $flagSend == false) {
$event = new SubContractorReferencedEvent($user);
$dispatcher->dispatch($event, SubContractorReferencedEvent::NAME);
}
// dispatch the subonctractor.updated event
if (!$isAlreadyExist) {
$event = new SubContractorUpdatedEvent($user, empty($checkEmail));
$dispatcher->dispatch($event, SubContractorUpdatedEvent::NAME);
}
if ($modifSubcontractor == 1) {
$this->addFlash('success', 'L\'utilisateur a bien été modifié');
}else{
$this->addFlash('success', 'L\'utilisateur a bien été ajouté');
}
return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
}
/**
* Add credit for company
*/
$creditHistory = new CreditHistory();
$form4 = $this->createForm(AddCreditCompanyType::class, $creditHistory);
$form4->handleRequest($request);
if ($form4->isSubmitted() && $form4->isValid()) {
$nbCredits = $form4->getData()->getCredit();
$typePack = $form4->getData()->getTypePack();
//dd($form4->getData()->getStartDateContract());
$dateStartContract = $form4->getData()->getStartDateContract();
if ($typePack == 0) {
$dateStartContractModified = clone $dateStartContract;
$endDateContract = $dateStartContractModified;
} else {
$endDateContract = $form4->getData()->getendDateContract();
}
$orderPrice = match ($typePack) {
'0' => $nbCredits,
'1' => $form4->getData()->getMensualite(),
'2' => $form4->getData()->getAnnuite(),
//if conctract is fin de mois, we set as a annuite
'3' => 0,
};
$cost = 0;
if ($typePack == 0) {
$cost = $companyAgency->getCostOfDiscountedCredit() * $nbCredits;
} else {
$cost = $orderPrice;
}
$creditHistory->setCompany($companyAgency)
->setCredit($nbCredits)
->setName($form4->getData()->getName())
->setTypePack($typePack)
->setAnnuite($form4->getData()->getAnnuite())
->setMensualite($form4->getData()->getMensualite())
->setReport($form4->getData()->getReport())
->setCurrentBalance($orderPrice)
->setOrderPrice($orderPrice)
->setAutomaticRenewal($form4->getData()->getAutomaticRenewal())
->setStartDateContract($dateStartContract)
->setEndDateContract($endDateContract)
->setCost($cost)
->setIdentifier($creditService->getNewReference())
->setAvailabilityDuration($form4->getData()->getAvailabilityDuration())
->setOrderedBy($this->getUser());
$balanceTransaction = new BalanceTransactions();
$balanceTransaction->setName("Initialisation solde contrat type $typePack")
->setType('credit')
->setOrderBy($this->getUser())
->setCreditHistory($creditHistory)
->setAmount($creditHistory->getCurrentBalance())
->setCurrentBalance($creditHistory->getCurrentBalance());
$entityManager->persist($companyAgency);
$entityManager->persist($balanceTransaction);
$entityManager->persist($creditHistory);
$entityManager->flush();
$packService->initialize($creditHistory->getId());
$dataSolde = $packService->getSolde();
$nbSolde = count($dataSolde);
$dateEnd = $dataSolde[$nbSolde]['dateEnd'];
if ($typePack == 0) {
$creditHistory->setCreditExpiredAt($dateEnd)->setEndDateContract($dateStartContractModified);
} else {
$creditHistory->setCreditExpiredAt($dateEnd);
}
//do reflush
$entityManager->flush();
$this->addFlash(
type: 'success',
message: "La campagne reprend avec succès ",
);
return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
}
$clients = $userRepository->findBy([], ['email' => 'ASC']);
$mailClientToCommand = "";
if ($thisCompany != null) {
$clientListForOrderAs = $userRepository->findClientByCompany($thisCompany, $roleCLient, $roleCLientAdmin);
}
if (!empty($clientListForOrderAs)) {
foreach ($clientListForOrderAs as $client) {
if (($client->isEnabled())) {
$mailClientToCommand = $client->getEmail();
break;
}
}
}
$orderAsLink = !empty($mailClientToCommand) ? $parameter->get('url_redirect_to_front') . '?tsso=' . hash('sha256', $mailClientToCommand . $mailClientToCommand) : null;
//data in modal company ---------------------------------------------------------------
$allCampaign = $campaignRepository->findAllCampaingByCompany($companyAgency);
$listOfFilesByDate = [];
$dataSummaryByDate = [];
$nameOfBucket = "company-".strtolower($companyAgency->getId());
foreach ($allCampaign as $campaign) {
foreach ($campaign->getMessages() as $message) {
foreach ($message->getFileMessages() as $file) {
if ($file->isIsNew()) {
$year = $message->getCreatedAt()->format('Y');
$month = $message->getCreatedAt()->format('m');
$listOfFilesByDate["{$year}-{$month}"][] = "Campaigns/{$campaign->getId()}/{$file->getName()}";
}
}
}
foreach ($campaign->getFileMissions() as $file) {
if ($file->isIsNew()) {
$year = $file->getCreatedAt()->format('Y');
$month = $file->getCreatedAt()->format('m');
$listOfFilesByDate["{$year}-{$month}"][] = "Campaigns/{$campaign->getId()}/{$file->getName()}";
}
}
}
//prendre toutes les tailles selon le mois et l'années
foreach ($listOfFilesByDate as $key => $list) {
$size = $googleStorageService->sizeOfBucketByFile($nameOfBucket,$list);
$dataSummaryByDate[$key] = $size;
krsort($dataSummaryByDate);
}
return $this->renderForm('agency/handle.html.twig', [
'isAgency' => $agency,
'hideInfoifIsAgency' => $agency ? "style=display:none" : "",
'form' => $form,
'form2' => $form2,
'dataSummaryStorage' => $dataSummaryByDate,
'modifSubcontractor' => $modifSubcontractor,
'form4' => $form4,
'company' => $companyAgency,
'listClients' => $listClients,
'listSubContractors' => $listSubContractors,
'listServices' => $listServices ?? [],
'allCredit' => $allCredit,
'creditHistories' => $creditsHistoryCompany,
'clients' => $serializer->serialize($clients, 'json', [AbstractNormalizer::ATTRIBUTES => ['email']]),
'sorted' => $sorted ?? [],
'allSubContractorsEmails' => $serializer->serialize($allSubContractorsEmails, 'json', [AbstractNormalizer::ATTRIBUTES => ['email']]),
'orderAsLink' => $orderAsLink,
'clientsList' => $userRepository->findBy(['company'=>$companyAgency, 'deleted'=>false, 'enabled'=>true]),
'user_tab' => $userTab,
'avalaiblecreditHistories' => $companyAgencyService->getAvailableContract($creditHistoryRepository->findAvailableServiceHistory($companyAgency, new \DateTime()), true)
]);
}
#[Route('/admin/agency/delete/{id}', name: 'agency_delete', methods: ['GET'])]
public function deleteAgency(Company $company,EventDispatcherInterface $dispatcher, SubContractorCompanyRepository $subContractorCompanyRepository, UserRepository $userRepository,EmailService $emailService, EntityManagerInterface $entityManager,CompanyRepository $companyRepository){
if($this->isGranted("ROLE_ADMIN")){
$emailService->removeSystemeEmailForAgency($company);
$users = $userRepository->getAllUserByCompany($company);
$allCompanyAgency = $companyRepository->findBy(['parent'=>$company]);
$subcontractorsCompany = $subContractorCompanyRepository->getAllSubcontractorByCompany($company);
foreach($allCompanyAgency as $companyAgency) {
$companyAgency->setDeleted(true);
$entityManager->persist($companyAgency);
$entityManager->flush();
}
foreach ($users as $user) {
$user->setCompany(null);
$user->setDeleted(true);
$user->setEnabled(false);
$entityManager->flush();
$this->frontAPIService->pushClientToFront($user, $user->getPassword());
}
foreach ( $subcontractorsCompany as $subcontractorCompany) {
$user= $subcontractorCompany->getUser();
$event = new SubContractorUpdatedEvent($user);
$dispatcher->dispatch($event, SubContractorUpdatedEvent::NAME);
$entityManager->remove($subcontractorCompany);
$entityManager->flush();
}
$company->setName(uniqid())->setDeleted(true)->setDomaineName("")->setEmailProject(null)->setMdpEmailProject(null);
$entityManager->persist($company);
$entityManager->flush();
}else{
$this->addFlash("error", "Impossible de supprimer l'agence");
}
$this->addFlash("success", "Agence supprimée avec succès");
return$this->redirectToRoute('agency_index', [], Response::HTTP_SEE_OTHER);
}
}