src/Controller/AgencyController.php line 99

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\BalanceTransactions;
  4. use App\Entity\Company;
  5. use App\Entity\CompanyData;
  6. use App\Entity\SubContractorCompany;
  7. use App\Entity\User;
  8. use App\Entity\CreditHistory;
  9. use App\Enum\BillingMethod;
  10. use App\Enum\CommandeLoggingType;
  11. use App\Enum\CompanyContract;
  12. use App\Enum\TypePack;
  13. use App\Enum\ProductType;
  14. use App\Event\Client\NoticeOfInsufficientBudgetEvent;
  15. use App\Event\ClientUpdatedEvent;
  16. use App\Event\CompanyUpdatedEvent;
  17. use App\Event\SubContractor\SubContractorReferencedEvent;
  18. use App\Event\SubContractorUpdatedEvent;
  19. use App\Form\CompanyAgencyType;
  20. use App\Form\SubContractorCompanyType;
  21. use App\Form\AddCreditCompanyType;
  22. use App\Repository\BalanceTransactionsRepository;
  23. use App\Repository\CampaignRepository;
  24. use App\Repository\CompanyRepository;
  25. use App\Repository\CreditHistoryRepository;
  26. use App\Repository\ServiceRepository;
  27. use App\Repository\SubContractorCompanyRepository;
  28. use App\Repository\UserRepository;
  29. use App\Service\ClientSoldService;
  30. use App\Service\CompanyService;
  31. use App\Service\ServiceService;
  32. use App\Service\SharedResourceCategoryService;
  33. use App\Service\UserService;
  34. use App\Service\CreditService;
  35. use App\Service\EmailService;
  36. use App\Service\MyFlowMarginService;
  37. use App\Service\NumberFormatService;
  38. use Doctrine\ORM\EntityManagerInterface;
  39. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  40. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  41. use Symfony\Component\HttpFoundation\Request;
  42. use Symfony\Component\HttpFoundation\Response;
  43. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  44. use Symfony\Component\Routing\Annotation\Route;
  45. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  46. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  47. use Symfony\Component\Serializer\SerializerInterface;
  48. use Symfony\Component\Validator\Constraints\Email;
  49. use Symfony\Component\Validator\Validator\ValidatorInterface;
  50. use GuzzleHttp\Client;
  51. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  52. use Symfony\Component\HttpFoundation\JsonResponse;
  53. use Symfony\Component\HttpFoundation\RedirectResponse;
  54. use App\Service\PackService;
  55. use App\Service\FrontAPIService;
  56. use App\Service\GoogleStorageService;
  57. use function PHPUnit\Framework\matches;
  58. use App\Service\DynamicHostService;
  59.  
  60. #[Route('/admin')]
  61. class AgencyController extends AbstractController
  62. {
  63.      public function __construct(
  64.         private NumberFormatService $numberFormatService,
  65.         private CompanyService $companyAgencyService,
  66.         private FrontAPIService $frontAPIService,
  67.         private DynamicHostService $dynamicHostService,
  68.         private SharedResourceCategoryService $sharedResourceCategoryService,
  69.     )
  70.     {
  71.         
  72.     }
  73.       /**
  74.      * @param CompanyRepository $companyAgencyRepository
  75.      * @return Response template company/index.html.twig
  76.      */
  77.     #[Route('/agences'name'agency_index')]
  78.     public function index(CompanyRepository $companyAgencyRepository,GoogleStorageService $googleStorageService): Response
  79.     {
  80.         if (!$this->isGranted('ROLE_ADMIN')) {
  81.             throw new \NotFoundHttpException('La page que vous demandez est introuvable.');
  82.         }
  83.          return $this->render('agency/agency_index.html.twig', [
  84.             'companys' => $companyAgencyRepository->findBy(["deleted"=>false,"typeCompany"=>true], ['name' => 'DESC']),
  85.         ]);
  86.     }
  87.      /**
  88.      * @param CompanyRepository $companyAgencyRepository
  89.      * @return Response template company/index.html.twig
  90.      */
  91.     #[Route('/agences/ajouter'name'agency_add')]
  92.     #[Route('/agences/{id}/{userTab}'name'agency_edit'methods: ['GET''POST'], defaults: ['userTab' => null])]
  93.     public function handleAgency(SubContractorCompany $subContractorCompany nullCompanyService $companyAgencyServiceMyFlowMarginService $myFlowMarginServiceUser $user nullCreditHistory $creditHistory nullCreditService $creditServiceCompany $companyAgency nullRequest $requestUserService $userServiceUserPasswordEncoderInterface $encoderUserRepository $userRepositoryCreditHistoryRepository $creditHistoryRepositoryCampaignRepository $campaignRepositorySerializerInterface $serializerEmailService $emailServiceEntityManagerInterface $entityManagerSubContractorCompanyRepository $subContractorCompanyRepositoryEventDispatcherInterface $dispatcherValidatorInterface $validatorServiceRepository $serviceRepositoryServiceService $serviceServiceParameterBagInterface $parameterPackService $packService,GoogleStorageService $googleStorageService, ?string $userTab null): Response
  94.     {
  95.       
  96.         //aucun manager n'y a access
  97.         if (in_array("ROLE_MANAGER"$this->getUser()->getRoles())) {
  98.            throw new \NotFoundHttpException('La page que vous demandez est introuvable.');
  99.         }
  100.         if ($request->get('_route') === 'agency_add' && !$this->isGranted('ROLE_ADMIN')) {
  101.             throw new \NotFoundHttpException('La page que vous demandez est introuvable.');
  102.         }
  103.         $agency = !is_null($request->query->get('type')) ? true false;
  104.        
  105.         $thisCompany null;
  106.         $oldServiceSubcontractor = [];
  107.         $creditsHistoryCompany = [];
  108.         $modifSubcontractor = (null !== $request->query->get('modifSubcontractor')) and ($request->query->get('modifSubcontractor') == 1) ? 0;
  109.         if (null == $companyAgency) {
  110.             $companyAgency = new Company();
  111.             $companyData = new CompanyData();
  112.             $companyAgency->setTypeCompany(true)
  113.             ->setCustomerDiscount(0)
  114.             ->setCostOfDiscountedCredit(0)
  115.             ->setCompanyData($companyData)
  116.             ;
  117.             $companyAgency->setContract(CompanyContract::CASH->value);
  118.             $listClients null;
  119.             $listOfManager null;
  120.             $listSubContractors null;
  121.             $listServices null;
  122.             $creditHistory = new CreditHistory();
  123.             $allCredit 0;
  124.             $roleSubContractor 'ROLE_SUBCONTRACTOR';
  125.             
  126.         } else {
  127.             
  128.             $allRoleClient = ['["ROLE_CLIENT"]','["ROLE_CLIENT_ADMIN"]','["ROLE_MANAGER"]','["ROLE_ADMIN_AGENCY"]'];
  129.             $roleCLient 'ROLE_CLIENT';
  130.             $roleCLientAdmin 'ROLE_CLIENT_ADMIN';
  131.             $roleSubContractor 'ROLE_SUBCONTRACTOR';
  132.             $thisCompany $companyAgency->getId();
  133.             $listClients $userRepository->findAllRoleByCompany($thisCompany$allRoleClient,!$this->dynamicHostService->isAgency());
  134.          
  135.             $listSubContractors $subContractorCompanyRepository->findBy(['company' => $companyAgency]);
  136.             
  137.             $creditAvailable $creditService->CreditAvailable($companyAgency);
  138.             $allCredit 0;
  139.             foreach ($creditAvailable as $credit) {
  140.                 $allCredit += $credit->getCredit();
  141.             }
  142.             $creditsHistoryCompany $creditHistoryRepository->findByCompanyWithDeletedState($companyAgencyfalse);
  143.             $campainsHistory $campaignRepository->findBy(['company' => $companyAgency]);
  144.             
  145.             $sorted = [];
  146.             foreach ($creditsHistoryCompany as $creditHistoryCompany) {
  147.                 $date $creditHistoryCompany->getCreatedAt()->format('YmdHis');
  148.                 $sorted[$date] = $creditHistoryCompany;
  149.             }
  150.             foreach ($campainsHistory as $campainHistory) {
  151.                 $date $campainHistory->getCreatedAt()->format('YmdHis');
  152.                 $sorted[$date] = $campainHistory;
  153.             }
  154.             foreach ($companyAgency->getCommandeLoggings() as $commandeLogging) {
  155.                 $date $commandeLogging->getCreatedAt()->format('YmdHis');
  156.                 $sorted[$date] = $commandeLogging;
  157.             }
  158.             ksort($sorted);
  159.             $sorted array_reverse($sorted);
  160.             
  161.         }
  162.         /**
  163.          * Form for add company
  164.          */
  165.         $form $this->createForm(CompanyAgencyType::class, $companyAgency,['admin' => $this->isGranted('ROLE_ADMIN')]);
  166.         $form->handleRequest($request);
  167.         if ($form->isSubmitted() && $form->isValid()) {
  168.           
  169.             if ($request->get('_route') === 'agency_add') {
  170.                 $companyAgency->setCreatedAt(new \DateTime());
  171.                 $companyAgency->setLogoFile($form->get('logoFile')->getData());
  172.                 $companyAgency->setFaviconFile($form->get('faviconFile')->getData());
  173.                 $creditHistory =  new CreditHistory();
  174.                 $creditHistory->setCompany($companyAgency)
  175.                     ->setName("Facturation individuelle")
  176.                     ->setTypePack(TypePack::CASH->value)
  177.                     ->setIdentifier($creditService->getNewReference())
  178.                     ->setOrderedBy($this->getUser());
  179.                 $entityManager->persist($companyAgency);
  180.                 $entityManager->persist($creditHistory);
  181.                 $emailService->createSystemeEmailForAgency($companyAgency);
  182.                 $this->sharedResourceCategoryService->setDefaultSharedResourceCategory($companyAgency);
  183.                 $this->addFlash('success''L\'agence a bien été ajouté');
  184.             } else {
  185.                 //dd($form->get('logoFile')->getData());
  186.                 $companyAgency->setLogoFile($form->get('logoFile')->getData());
  187.                 $companyAgency->setFaviconFile($form->get('faviconFile')->getData());
  188.                 $companyAgency->setUpdatedAt(new \DateTime());
  189.                 $this->addFlash('success''L\'agence a bien été modifiée');
  190.             }
  191.             
  192.                 $entityManager->flush();
  193.             $companyAgency->setLogoFile(null);
  194.             $companyAgency->setFaviconFile(null);
  195.             // dispatch the company.update event
  196.             $event = new CompanyUpdatedEvent($companyAgency);
  197.             $dispatcher->dispatch($eventCompanyUpdatedEvent::NAME);
  198.             if ($this->isGranted("ROLE_ADMIN_AGENCY")) {
  199.                  return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
  200.             }
  201.             if($this->isGranted("ROLE_ADMIN")){
  202.                 return $this->redirectToRoute('agency_index', [], Response::HTTP_SEE_OTHER);
  203.             }else{
  204.                  return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
  205.             }
  206.         }
  207.         /**
  208.          * Form for add subContractor that does not exist to company
  209.          */
  210.         $form2 $this->createForm(SubContractorCompanyType::class, $user);
  211.         $form2->handleRequest($request);
  212.         $allSubContractorsEmails $userRepository->findByRole($roleSubContractor);
  213.         if ($form2->isSubmitted() && $form2->isValid()) {
  214.             $oldServiceSubcontractor = [];
  215.             $oldJobSubcontractor = [];
  216.             $email $request->request->get('emailSubContractor');
  217.             $modifSubcontractor $request->request->get('modification_subcontractor');
  218.             $separateEmail explode(" "$email);
  219.             $email $separateEmail[0];
  220.             if ($validator->validate($email, [new Email()])->count() > 0) {
  221.                 $this->addFlash('error''L\'adresse ' $email ' n\'est pas valide. Nous vous invitons à vérifier votre saisie');
  222.                 return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
  223.             }
  224.             $checkEmail $userRepository->findOneBy(['email' => $email]);
  225.             $subContractorCompany = new  SubContractorCompany();
  226.             //compare company 
  227.             $isAlreadyExist false;
  228.             //end company
  229.             if (empty($checkEmail)) {
  230.                 $user = new User();
  231.                 $password $userService->generatePassword();
  232.                 $encodedPassword $encoder->encodePassword($user$password);
  233.                 $user->setPassword($encodedPassword);
  234.                 $user->setEmail($email);
  235.                 $user->setRoles([$roleSubContractor]);
  236.                 $user->setEnabled(false);
  237.                 $user->setCompany($companyAgency);
  238.             } else {
  239.                 $user $userRepository->findOneBy(['email' => $email]);
  240.                 //Si pas vide vérifié si l'utilisateur éxiste déja sur d'autre agence ou sur MyFlow
  241.                 if ($companyAgency != $user->getCompany()) {
  242.                     $isAlreadyExist true;
  243.                     //alors creez un utilisateur enfant parceque l'utilisateur est dans un autre entreprise
  244.                     //create new user
  245.                     $userGenerate = new User;//for just generate the id automaticly
  246.                     $userChild = clone $user;
  247.                     $emailUniq uniqid().$user->getEmail();
  248.                     $userChild->setId($userGenerate->getId())->setEmail($emailUniq)->setEnabled($user->getEnabled())->setNewAdd(false)->setParent($user)->setPassword($user->getPassword())->setOriginalEmail($user->getEmail())->setCompany($companyAgency);
  249.                     $user->addChild($userChild);
  250.                     $entityManager->persist($user);
  251.                     $user $userChild;
  252.                     //need to add user in child
  253.                 }
  254.             }
  255.             $subconctractors $subContractorCompanyRepository->findBy(['user'=>$user,'company' => $companyAgency]);
  256.             if ($modifSubcontractor == 1) {
  257.                 foreach ($user->getSubContractorCompanies() as $subCompany) {
  258.                     if($companyAgency == $subCompany->getCompany())
  259.                         $subContractorCompany $subCompany;
  260.                 }
  261.             }
  262.             //get all old product of subcontractor // no need to control perte if product already link
  263.             foreach ($subconctractors as $sub) {
  264.                 foreach ($sub->getProducts() as $product) {
  265.                     $oldServiceSubcontractor[] = $product->getId();
  266.                 }
  267.             }
  268.             
  269.             if ($request->query->get('perte') == null) {
  270.                 $listServicesForSubcontractor $serviceRepository->findBy(['user' => $checkEmail]);
  271.                 $allJob = [];
  272.                 $allProduct = [];
  273.                 foreach ($form2->getData()->getJobs() as $jobName) {
  274.                     $nameJob $jobName->getId();
  275.                     $allJob[] =$jobName->getId();
  276.                 }
  277.                 foreach ($form2->getData()->getProducts() as $productName) {
  278.                     $allProduct[] = $productName->getId();
  279.                 }
  280.                 if (!empty($user->getResaleRate() || empty($checkEmail))) {
  281.                     $flag false;
  282.                     foreach ($form2->getData()->getProducts() as $productName) {
  283.                         $name $productName->getId();
  284.                   
  285.                         foreach ($listServicesForSubcontractor as $service) {
  286.                             if ($service->getProduct()->getId() === $name) {
  287.                                 $flag true;
  288.                             }
  289.                         }
  290.                     if ($flag !== true) {
  291.                         $this->addFlash('error''Veuillez ajouter le produit et le prix pratique par ce partenaire au niveau de sa fiche.');
  292.                         return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId(),'modifSubcontractor' => $modifSubcontractor], Response::HTTP_SEE_OTHER);
  293.                     }
  294.                     foreach ($listServicesForSubcontractor as $service) {
  295.                         if ($user->isEnabled()) {
  296.                             if ($service->getProduct()->getId() === $name and !in_array($service->getProduct()->getId(),$oldServiceSubcontractor)) {
  297.                                 if ($service->getProduct()->getType() === ProductType::AU_FORFAIT) {
  298.                                     $currentMarge $this->numberFormatService->format($myFlowMarginService->getMarge($service$companyAgency));
  299.                                 }else{
  300.                                     $currentMarge $this->numberFormatService->format($myFlowMarginService->getMargeTJM($user));
  301.                                 }
  302.                                 $service->getProduct()->getName();
  303.                                 $fullName $user->getFullName();
  304.                                 if ($currentMarge 30) {
  305.                                     $this->addFlash(
  306.                                     "error"
  307.                                     "En ajoutant $fullName pour le service $productName, le total de marge pour le(s) sous-traitant(s) est de $currentMarge %");
  308.                                     return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId(), 'perte' => $currentMarge'email' => $email'product' => implode(","$allProduct), 'job' => implode(","$allJob),'modifSubcontractor' => $modifSubcontractor ], Response::HTTP_SEE_OTHER);
  309.                                 }
  310.                             }
  311.                         } else {
  312.                             $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');
  313.                             return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId(),'modifSubcontractor' => $modifSubcontractor], Response::HTTP_SEE_OTHER);
  314.                         }
  315.                     }
  316.                  }
  317.                 } else {
  318.                     $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.');
  319.                     return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId(),'modifSubcontractor' => $modifSubcontractor], Response::HTTP_SEE_OTHER);
  320.                 }
  321.             }
  322.             $verifyEmailSend $subContractorCompanyRepository->findBy(['user' => $user'company' => $companyAgency]);
  323.             
  324.             $flagSend false;
  325.             foreach ($verifyEmailSend as $verify) {
  326.                 if ($verify->getEmailSend() == true) {
  327.                     $flagSend true;
  328.                 }
  329.             }
  330.             //delte product/job before add in modification
  331.             if ($modifSubcontractor == 1) {
  332.                foreach ($subContractorCompany->getJobs() as $jobs) {
  333.                     $subContractorCompany->removeJob($jobs);
  334.                }
  335.                foreach ($subContractorCompany->getProducts() as $product) {
  336.                     $subContractorCompany->removeProduct($product);
  337.                }
  338.             }
  339.             foreach ($form2->getData()->getJobs() as $job) {
  340.                 $subContractorCompany->addJob($job);
  341.             }
  342.             foreach ($form2->getData()->getProducts() as $product) {
  343.                 $subContractorCompany->addProduct($product);
  344.             }
  345.             $subContractorCompany->setCompany($companyAgency)
  346.                 ->setUser($user)
  347.                 ->setEmailSend(true);
  348.             if ($modifSubcontractor == 0) {
  349.                 $user->addSubContractorCompany($subContractorCompany);
  350.             }
  351.             
  352.             if (!empty($listSubContractors)) {
  353.                 $newListOfSubcontractor = [];
  354.                 //if modification , don't take a subcontractor in test
  355.                 if ($modifSubcontractor == ) {
  356.                    foreach ($listSubContractors as $subContractor) {
  357.                         if ($subContractor->getUser()->getId() != $user->getId()) {
  358.                             $newListOfSubcontractor[] = $subContractor;
  359.                         }
  360.                     }     
  361.                  }else{
  362.                     $newListOfSubcontractor $listSubContractors;
  363.                  }
  364.                     //verify if subcontractor is already linked job and product
  365.                     foreach ($form2->getData()->getJobs() as $job) {
  366.                         foreach ($newListOfSubcontractor as $subContractor) {
  367.                             foreach ($subContractor->getJobs() as $jobSubcontractor) {
  368.                                 if ($jobSubcontractor === $job ) {
  369.                                     $alreadyLinkJob true;
  370.                                     //after job is already linked verify is already link a product
  371.                                     foreach ($subContractor->getProducts() as $product) {
  372.                                         foreach ($form2->getData()->getProducts() as $productInForm  ) {
  373.                                             if ($productInForm === $product) {
  374.                                                 $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');
  375.                                                 return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
  376.                                             }
  377.                                         }
  378.                                     }
  379.                                 }
  380.                             }
  381.                         }
  382.                     }
  383.                 $entityManager->persist($user);
  384.                 //if ($modifSubcontractor == 0) {
  385.                     $entityManager->persist($subContractorCompany);
  386.                 //}
  387.                 $entityManager->flush();
  388.             } else {
  389.                 $entityManager->persist($user);
  390.                  //if ($modifSubcontractor == 0) {
  391.                     $entityManager->persist($subContractorCompany);
  392.                  //}
  393.                 $entityManager->flush();
  394.             }
  395.             
  396.             //$this->companyService->syncSubcontractorsForAllMissions(subContractorCompany : $subContractorCompany);
  397.             $event true;
  398.             foreach ($user->getServices() as $service) {
  399.                 if (empty($service->getResale())) {
  400.                     $event false;
  401.                 }
  402.             }
  403.             if ($event && $flagSend == false) {
  404.                 $event = new SubContractorReferencedEvent($user);
  405.                 $dispatcher->dispatch($eventSubContractorReferencedEvent::NAME);
  406.             }
  407.             // dispatch the subonctractor.updated event
  408.             if (!$isAlreadyExist) {
  409.                 $event = new SubContractorUpdatedEvent($user, empty($checkEmail));
  410.                 $dispatcher->dispatch($eventSubContractorUpdatedEvent::NAME);
  411.             }
  412.             
  413.             if ($modifSubcontractor == 1) {
  414.                 $this->addFlash('success''L\'utilisateur a bien été modifié');
  415.             }else{
  416.                 $this->addFlash('success''L\'utilisateur a bien été ajouté');
  417.             }
  418.             return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
  419.         }
  420.         /**
  421.          * Add credit for company
  422.          */
  423.         $creditHistory =  new CreditHistory();
  424.         $form4 $this->createForm(AddCreditCompanyType::class, $creditHistory);
  425.         $form4->handleRequest($request);
  426.         if ($form4->isSubmitted() && $form4->isValid()) {
  427.             $nbCredits $form4->getData()->getCredit();
  428.             $typePack $form4->getData()->getTypePack();
  429.             //dd($form4->getData()->getStartDateContract());
  430.             $dateStartContract $form4->getData()->getStartDateContract();
  431.             if ($typePack == 0) {
  432.                 $dateStartContractModified = clone $dateStartContract;
  433.                 $endDateContract $dateStartContractModified;
  434.             } else {
  435.                 $endDateContract $form4->getData()->getendDateContract();
  436.             }
  437.             $orderPrice = match ($typePack) {
  438.                 '0' =>  $nbCredits,
  439.                 '1' => $form4->getData()->getMensualite(),
  440.                 '2' =>  $form4->getData()->getAnnuite(),
  441.                 //if conctract is fin de mois, we set as a annuite
  442.                 '3' => 0,
  443.             };
  444.        
  445.             $cost 0;
  446.             if ($typePack == 0) {
  447.                 $cost $companyAgency->getCostOfDiscountedCredit() * $nbCredits;
  448.             } else {
  449.                 $cost $orderPrice;
  450.             }
  451.             $creditHistory->setCompany($companyAgency)
  452.                 ->setCredit($nbCredits)
  453.                 ->setName($form4->getData()->getName())
  454.                 ->setTypePack($typePack)
  455.                 ->setAnnuite($form4->getData()->getAnnuite())
  456.                 ->setMensualite($form4->getData()->getMensualite())
  457.                 ->setReport($form4->getData()->getReport())
  458.                 ->setCurrentBalance($orderPrice)
  459.                 ->setOrderPrice($orderPrice)
  460.                 ->setAutomaticRenewal($form4->getData()->getAutomaticRenewal())
  461.                 ->setStartDateContract($dateStartContract)
  462.                 ->setEndDateContract($endDateContract)
  463.                 ->setCost($cost)
  464.                 ->setIdentifier($creditService->getNewReference())
  465.                 ->setAvailabilityDuration($form4->getData()->getAvailabilityDuration())
  466.                 ->setOrderedBy($this->getUser());
  467.             $balanceTransaction = new BalanceTransactions();
  468.             $balanceTransaction->setName("Initialisation solde contrat type  $typePack")
  469.                 ->setType('credit')
  470.                 ->setOrderBy($this->getUser())
  471.                 ->setCreditHistory($creditHistory)
  472.                 ->setAmount($creditHistory->getCurrentBalance())
  473.                 ->setCurrentBalance($creditHistory->getCurrentBalance());
  474.             $entityManager->persist($companyAgency);
  475.             $entityManager->persist($balanceTransaction);
  476.             $entityManager->persist($creditHistory);
  477.             $entityManager->flush();
  478.             $packService->initialize($creditHistory->getId());
  479.             $dataSolde $packService->getSolde();
  480.             $nbSolde count($dataSolde);
  481.             $dateEnd $dataSolde[$nbSolde]['dateEnd'];
  482.             if ($typePack == 0) {
  483.                 $creditHistory->setCreditExpiredAt($dateEnd)->setEndDateContract($dateStartContractModified);
  484.             } else {
  485.                 $creditHistory->setCreditExpiredAt($dateEnd);
  486.             }
  487.             //do reflush
  488.             $entityManager->flush();
  489.             $this->addFlash(
  490.                 type'success',
  491.                 message"La campagne reprend avec succès ",
  492.             );
  493.             return $this->redirectToRoute('agency_edit', ['id' => $companyAgency->getId()], Response::HTTP_SEE_OTHER);
  494.         }
  495.         $clients $userRepository->findBy([], ['email' => 'ASC']);
  496.         $mailClientToCommand "";
  497.         if ($thisCompany != null) {
  498.             $clientListForOrderAs $userRepository->findClientByCompany($thisCompany$roleCLient$roleCLientAdmin);
  499.         }
  500.         if (!empty($clientListForOrderAs)) {
  501.             foreach ($clientListForOrderAs as $client) {
  502.                 if (($client->isEnabled())) {
  503.                     $mailClientToCommand $client->getEmail();
  504.                     break;
  505.                 }
  506.             }
  507.         }
  508.         $orderAsLink = !empty($mailClientToCommand) ? $parameter->get('url_redirect_to_front') . '?tsso=' hash('sha256'$mailClientToCommand $mailClientToCommand) : null;
  509.         //data in modal company ---------------------------------------------------------------
  510.         $allCampaign $campaignRepository->findAllCampaingByCompany($companyAgency);
  511.         $listOfFilesByDate = [];
  512.         $dataSummaryByDate = [];
  513.         $nameOfBucket "company-".strtolower($companyAgency->getId());
  514.         foreach ($allCampaign as $campaign) {
  515.             foreach ($campaign->getMessages() as $message) {
  516.                foreach ($message->getFileMessages() as $file) {
  517.                     if ($file->isIsNew()) {
  518.                         $year $message->getCreatedAt()->format('Y');
  519.                         $month $message->getCreatedAt()->format('m');
  520.                         $listOfFilesByDate["{$year}-{$month}"][] = "Campaigns/{$campaign->getId()}/{$file->getName()}";
  521.                     }
  522.                }
  523.             }
  524.            foreach ($campaign->getFileMissions() as $file) {
  525.                 if ($file->isIsNew()) {
  526.                     $year $file->getCreatedAt()->format('Y');
  527.                     $month $file->getCreatedAt()->format('m');
  528.                      $listOfFilesByDate["{$year}-{$month}"][] = "Campaigns/{$campaign->getId()}/{$file->getName()}";
  529.                 }
  530.            } 
  531.         }
  532.         //prendre toutes les tailles selon le mois et l'années
  533.         foreach ($listOfFilesByDate as $key => $list) {
  534.             $size $googleStorageService->sizeOfBucketByFile($nameOfBucket,$list);
  535.             $dataSummaryByDate[$key] = $size;
  536.             krsort($dataSummaryByDate);
  537.         }
  538.         
  539.         return $this->renderForm('agency/handle.html.twig', [
  540.             'isAgency' => $agency,
  541.             'hideInfoifIsAgency' => $agency "style=display:none" "",
  542.             'form' => $form,
  543.             'form2' => $form2,
  544.             'dataSummaryStorage' => $dataSummaryByDate,
  545.             'modifSubcontractor' => $modifSubcontractor,
  546.             'form4' => $form4,
  547.             'company' => $companyAgency,
  548.             'listClients' => $listClients,
  549.             'listSubContractors' => $listSubContractors,
  550.             'listServices' => $listServices ?? [],
  551.             'allCredit' => $allCredit,
  552.             'creditHistories' => $creditsHistoryCompany,
  553.             'clients' => $serializer->serialize($clients'json', [AbstractNormalizer::ATTRIBUTES => ['email']]),
  554.             'sorted' => $sorted ?? [],
  555.             'allSubContractorsEmails' => $serializer->serialize($allSubContractorsEmails'json', [AbstractNormalizer::ATTRIBUTES => ['email']]),
  556.             'orderAsLink' => $orderAsLink
  557.             'clientsList' => $userRepository->findBy(['company'=>$companyAgency'deleted'=>false'enabled'=>true]), 
  558.             'user_tab'  => $userTab,
  559.             'avalaiblecreditHistories' => $companyAgencyService->getAvailableContract($creditHistoryRepository->findAvailableServiceHistory($companyAgency, new \DateTime()), true)
  560.         ]);
  561.     }
  562.     #[Route('/admin/agency/delete/{id}'name'agency_delete'methods: ['GET'])]
  563.     public function deleteAgency(Company $company,EventDispatcherInterface $dispatcherSubContractorCompanyRepository $subContractorCompanyRepositoryUserRepository $userRepository,EmailService $emailServiceEntityManagerInterface $entityManager,CompanyRepository $companyRepository){
  564.         if($this->isGranted("ROLE_ADMIN")){
  565.             $emailService->removeSystemeEmailForAgency($company);
  566.             $users $userRepository->getAllUserByCompany($company);
  567.             $allCompanyAgency $companyRepository->findBy(['parent'=>$company]);
  568.             $subcontractorsCompany $subContractorCompanyRepository->getAllSubcontractorByCompany($company);
  569.             foreach($allCompanyAgency as $companyAgency) {
  570.                 $companyAgency->setDeleted(true);
  571.                 $entityManager->persist($companyAgency);
  572.                 $entityManager->flush();
  573.             }
  574.             foreach ($users as $user) {
  575.                 $user->setCompany(null);
  576.                 $user->setDeleted(true);
  577.                 $user->setEnabled(false);
  578.                 $entityManager->flush();
  579.                 $this->frontAPIService->pushClientToFront($user$user->getPassword());
  580.             
  581.             }
  582.             
  583.             foreach ( $subcontractorsCompany as  $subcontractorCompany) {
  584.                 $user$subcontractorCompany->getUser();
  585.                 $event = new SubContractorUpdatedEvent($user);
  586.                 $dispatcher->dispatch($eventSubContractorUpdatedEvent::NAME);
  587.                 $entityManager->remove($subcontractorCompany);
  588.                 $entityManager->flush();
  589.             }
  590.             $company->setName(uniqid())->setDeleted(true)->setDomaineName("")->setEmailProject(null)->setMdpEmailProject(null);
  591.             $entityManager->persist($company);
  592.             $entityManager->flush();
  593.         }else{
  594.             $this->addFlash("error""Impossible de supprimer l'agence");
  595.         }
  596.         $this->addFlash("success""Agence supprimée avec succès");
  597.         return$this->redirectToRoute('agency_index', [], Response::HTTP_SEE_OTHER);
  598.          
  599.     }
  600. }