src/Controller/CompanyController.php line 246

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\BalanceTransactions;
  4. use App\Entity\Campaign;
  5. use App\Entity\Company;
  6. use App\Entity\Mission;
  7. use App\Entity\Product;
  8. use App\Entity\SubContractorCompany;
  9. use App\Entity\User;
  10. use App\Entity\CreditHistory;
  11. use App\Enum\BillingMethod;
  12. use App\Enum\CommandeLoggingType;
  13. use App\Repository\ProductRepository;
  14. use App\Service\ContractService;
  15. use App\Enum\CompanyContract;
  16. use App\Enum\TypePack;
  17. use App\Enum\ProductType;
  18. use App\Event\Client\NoticeOfInsufficientBudgetEvent;
  19. use App\Event\ClientUpdatedEvent;
  20. use App\Event\CompanyUpdatedEvent;
  21. use App\Event\SubContractor\SubContractorReferencedEvent;
  22. use App\Event\SubContractorUpdatedEvent;
  23. use App\Form\CompanyType;
  24. use App\Form\SubContractorCompanyType;
  25. use App\Form\AddCreditCompanyType;
  26. use App\Repository\BalanceTransactionsRepository;
  27. use App\Repository\CampaignRepository;
  28. use App\Repository\CompanyRepository;
  29. use App\Repository\CreditHistoryRepository;
  30. use App\Repository\ServiceRepository;
  31. use App\Repository\SubContractorCompanyRepository;
  32. use App\Repository\UserRepository;
  33. use App\Service\ClientSoldService;
  34. use App\Service\CompanyService;
  35. use App\Service\MissionService;
  36. use App\Service\ServiceService;
  37. use App\Service\UserService;
  38. use App\Service\CreditService;
  39. use App\Service\EmailService;
  40. use App\Service\MyFlowMarginService;
  41. use App\Service\NumberFormatService;
  42. use Doctrine\ORM\EntityManagerInterface;
  43. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  44. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  45. use Symfony\Component\HttpFoundation\Request;
  46. use Symfony\Component\HttpFoundation\Response;
  47. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  48. use Symfony\Component\Routing\Annotation\Route;
  49. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  50. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  51. use Symfony\Component\Serializer\SerializerInterface;
  52. use Symfony\Component\Validator\Constraints\Email;
  53. use Symfony\Component\Validator\Validator\ValidatorInterface;
  54. use GuzzleHttp\Client;
  55. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  56. use Symfony\Component\HttpFoundation\JsonResponse;
  57. use Symfony\Component\HttpFoundation\RedirectResponse;
  58. use App\Service\PackService;
  59. use App\Service\FrontAPIService;
  60. use App\Service\GoogleStorageService;
  61. use App\Service\SharedResourceCategoryService;
  62. use function PHPUnit\Framework\matches;
  63. use App\Service\DynamicHostService;
  64. use App\Service\PriceService;
  65. use App\Entity\noteCompany;
  66. use  App\Enum\Note;
  67. class CompanyController extends AbstractController
  68. {
  69.      
  70.     public function __construct(
  71.         private NumberFormatService $numberFormatService,
  72.         private CompanyService $companyService,
  73.         private FrontAPIService $frontAPIService,
  74.         private DynamicHostService $dynamicHostService,
  75.          private BalanceTransactionsRepository $balanceTransactionsRepository,
  76.          private ContractService $contractService,
  77.          private PriceService $priceService,
  78.          private SharedResourceCategoryService $sharedResourceCategoryService,
  79.     )
  80.     {
  81.         
  82.     }
  83.     #[Route('/admin/resume/contract/{id}'name'contract_resume')]
  84.     public function resumeContract(Request $requeststring $id,  CreditHistoryRepository $creditHistoryRepositoryEntityManagerInterface $entityManagerPackService $packService): Response|RedirectResponse
  85.     {
  86.             $listCampaings = [];
  87.            $creditHistory $creditHistoryRepository->findOneBy(['id' => $id]);
  88.            $totalAmountInBalance 0;
  89.            $totalPrice 0;
  90.            $priceCampaing 0;
  91.            if (count($creditHistory?->getCampaigns()) > 0) {
  92.                foreach ($creditHistory?->getCampaigns() as $campaign) {
  93.                    $refMission "";
  94.                    $idMission '';
  95.                    $priceCampaing += $this->priceService->totalPriceCampaign($campaign);
  96.                    foreach ($campaign->getMissions() as $mission) {
  97.                         $idMission $mission->getId();
  98.                         $refMission $mission->getReference();
  99.                         $balanceTransaction $this->balanceTransactionsRepository->soldeByMission($creditHistory,$mission);
  100.                         if (null !== $balanceTransaction) {
  101.                             $totalAmountInBalance += $balanceTransaction->getAmount();
  102.                             $totalPrice+= $balanceTransaction->getAmount();
  103.                         }
  104.                         
  105.                     }
  106.                     $listCampaings[$campaign->getId()][] = [
  107.                             'idCampaing'=>$campaign->getId(),
  108.                             'nameCampaign' => $campaign->getName(),
  109.                             'price' => $totalAmountInBalance,
  110.                             'reference' => $refMission,
  111.                             'idMission' => $idMission,
  112.                             'priceCampaing' => $this->priceService->totalPriceCampaign($campaign),
  113.                         ];
  114.                     $totalAmountInBalance 0;
  115.                }
  116.            }
  117.            
  118.             return $this->render(
  119.             'company/_resume_contract.html.twig',
  120.             [
  121.                'campaigns' => $listCampaings,
  122.                 'creditHistory' => $creditHistory,
  123.                 'totalPrice' => $priceCampaing,
  124.             ]
  125.         );
  126.     }
  127.     #[Route('/admin/contract/{id}'name'contract_edit')]
  128.     public function companyContractEdit(Request $requeststring $id,  CreditHistoryRepository $creditHistoryRepositoryEntityManagerInterface $entityManagerPackService $packService): Response|RedirectResponse
  129.     {
  130.         $creditHistory $creditHistoryRepository->findOneBy(['id' => $id]);
  131.         $form4 $this->createForm(AddCreditCompanyType::class,  $creditHistory);
  132.         $form4->handleRequest($request);
  133.         if ($form4->isSubmitted()) {
  134.             $nbCredits $form4->getData()->getCredit();
  135.             $typePack $form4->getData()->getTypePack();
  136.             $dateStartContract $form4->getData()->getStartDateContract();
  137.             $endDateContract $form4->getData()->getendDateContract();
  138.             $creditHistory =  $entityManager->getRepository(CreditHistory::class)->find($form4->getData()->getId());
  139.             $creditHistory->setName($form4->getData()->getName())
  140.                 ->setAutomaticRenewal($form4->getData()->getAutomaticRenewal())
  141.                 ->setStartDateContract($dateStartContract)
  142.                 ->setEndDateContract($endDateContract)
  143.                 ->setOrderedBy($this->getUser());
  144.             $entityManager->persist($creditHistory);
  145.             $entityManager->flush();
  146.             $packService->initialize($creditHistory->getId());
  147.             $dataSolde $packService->getSolde();
  148.             $nbSolde count($dataSolde);
  149.             $dateEnd $dataSolde[$nbSolde]['dateEnd'];
  150.             if ($typePack == 0) {
  151.                 $creditHistory->setCreditExpiredAt($dateEnd);
  152.             } else {
  153.                 $creditHistory->setCreditExpiredAt($dateEnd);
  154.             }
  155.             //do reflush
  156.             $entityManager->flush();
  157.             $this->addFlash(
  158.                 type'success',
  159.                 message"Contrat modifié avec succès "
  160.             );
  161.             return new RedirectResponse($this->generateUrl('company_edit', ['id' => $creditHistory->getCompany()->getId()]));
  162.         }
  163.         return $this->render(
  164.             'company/_form_edit_contract.html.twig',
  165.             [
  166.                 'form4' => $form4->createView(),
  167.                 'company' => $creditHistory->getCompany()
  168.             ]
  169.         );
  170.     }
  171.     #[Route('/admin/contract/delete/{id}'name'contract_delete'methods: ['GET'])]
  172.     /**
  173.      * @param CreditHistory $creditHistory
  174.      * @param EntityManagerInterface $entityManager
  175.      * 
  176.      * @return RedirectResponse
  177.      */
  178.     public function companyContractdelete(CreditHistory $creditHistoryEntityManagerInterface $entityManager): RedirectResponse
  179.     {
  180.        
  181.         if (in_array("ROLE_ADMIN"$this->getUser()->getRoles())) {
  182.             try {
  183.                 //find facturation individual pack for company
  184.                 $newPackToReaffect $entityManager->getRepository(CreditHistory::class)->findOneBy(['company'=>$creditHistory->getCompany(),'typePack'=>4]);
  185.                 $oldPack $creditHistory;
  186.                 //faire une reaffectation de solde
  187.                 foreach ($creditHistory?->getCampaigns() as $campaign) {
  188.                     $campaign->setCreditHistory($newPackToReaffect);
  189.                     $this->contractService->balanceAllocation($campaign$oldPack,$newPackToReaffect);
  190.                 }
  191.                 $creditHistory->setDeleted(true);
  192.                 $entityManager->persist($creditHistory);
  193.                 $entityManager->flush();
  194.                 $this->addFlash(
  195.                     type"success",
  196.                     message"Contrat supprimé avec succès et la réaffectation a été lancé avec succès"
  197.                 );
  198.                 return $this->redirectToRoute('company_edit', ['id' => $creditHistory->getCompany()->getId()], Response::HTTP_SEE_OTHER);
  199.             } catch (\Throwable $th) {
  200.       
  201.                 $this->addFlash(
  202.                     type"error",
  203.                     message"Une érreur est survenue lors de la suppréssion de ce contrat"
  204.                 );
  205.                 return $this->redirectToRoute('company_index', [], Response::HTTP_SEE_OTHER);
  206.             }
  207.         }else{
  208.             $this->addFlash(
  209.                 type"error",
  210.                 message"Vous êtes pas autorisé de supprimer ce contract"
  211.             );
  212.         }
  213.         return $this->redirectToRoute('company_index', [], Response::HTTP_SEE_OTHER);
  214.     }
  215.     /**
  216.      * @param CompanyRepository $companyRepository
  217.      * @return Response template company/index.html.twig
  218.      */
  219.     #[Route('/admin/entreprises'name'company_index'methods: ['GET'])]
  220.     public function index(CompanyRepository $companyRepository,GoogleStorageService $googleStorageService): Response
  221.     {
  222.         
  223.         $company $this->dynamicHostService->getCompany();
  224.         return $this->render('company/index.html.twig', [
  225.             'companys' => $companyRepository->findOnlyCompany($company),
  226.         ]);
  227.     }
  228.     /**
  229.      * @param User|null $user
  230.      * @param CreditHistory|null $creditHistory
  231.      * @param CreditService $creditService
  232.      * @param Company|null $company
  233.      * @param Request $request
  234.      * @param UserService $userService
  235.      * @param UserPasswordEncoderInterface $encoder
  236.      * @param UserRepository $userRepository
  237.      * @param CreditHistoryRepository $creditHistoryRepository
  238.      * @param CampaignRepository $campaignRepository
  239.      * @param ParameterBagInterface $parameter
  240.      *
  241.      * @return Response template company/handle.html.twig
  242.      */
  243.     #[Route('/admin/entreprise/ajouter'name'company_new'methods: ['GET''POST'])]
  244.     #[Route('/admin/entreprise/{id}'name'company_edit'methods: ['GET''POST'])]
  245.     #[Route('/my-admin/entreprise/{id}'name'my_company_edit'methods: ['GET''POST'])]
  246.     public function handleCompany(SubContractorCompany $subContractorCompany null,CompanyService $companyServiceMyFlowMarginService $myFlowMarginServiceUser $user nullCreditHistory $creditHistory nullCreditService $creditServiceCompany $company nullRequest $requestUserService $userServiceUserPasswordEncoderInterface $encoderUserRepository $userRepositoryCreditHistoryRepository $creditHistoryRepositoryCampaignRepository $campaignRepositorySerializerInterface $serializerEmailService $emailServiceEntityManagerInterface $entityManagerSubContractorCompanyRepository $subContractorCompanyRepositoryEventDispatcherInterface $dispatcherValidatorInterface $validatorServiceRepository $serviceRepositoryServiceService $serviceServiceParameterBagInterface $parameterPackService $packService,GoogleStorageService $googleStorageService): Response
  247.     {
  248.         $agency = !is_null($request->query->get('type')) ? true false;
  249.         $userConnected $this->getUser();
  250.         $thisCompany null;
  251.         $oldServiceSubcontractor = [];
  252.         $creditsHistoryCompany = [];
  253.         $modifSubcontractor = (null !== $request->query->get('modifSubcontractor')) and ($request->query->get('modifSubcontractor') == 1) ? 0;
  254.         if (null == $company) {
  255.             $company = new Company();
  256.             if ($agency) {
  257.                 $company->setTypeCompany(true)->setCustomerDiscount(0)->setCostOfDiscountedCredit(0);
  258.             }
  259.             $company->setContract(CompanyContract::CASH->value);
  260.             $listClients null;
  261.             $listSubContractors null;
  262.             $listServices null;
  263.             $creditHistory = new CreditHistory();
  264.             $allCredit 0;
  265.             $roleSubContractor 'ROLE_SUBCONTRACTOR';
  266.         } else {
  267.             $roleCLient 'ROLE_CLIENT';
  268.             $roleCLientAdmin 'ROLE_CLIENT_ADMIN';
  269.             $roleSubContractor 'ROLE_SUBCONTRACTOR';
  270.             $roleManager 'ROLE_MANAGER';
  271.             $thisCompany $company->getId();
  272.             $listClients $userRepository->findClientByCompany($thisCompany$roleCLient$roleCLientAdmin$roleManager);
  273.             $listSubContractors $subContractorCompanyRepository->findBy(['company' => $company]);
  274.             //            $listServices = $serviceRepository->findServiceByUser($thisCompany);
  275.             
  276.             $creditAvailable $creditService->CreditAvailable($company);
  277.             $allCredit 0;
  278.             foreach ($creditAvailable as $credit) {
  279.                 $allCredit += $credit->getCredit();
  280.             }
  281.             $creditsHistoryCompany $creditHistoryRepository->findByCompanyWithDeletedState($companyfalse);
  282.             $campainsHistory $campaignRepository->findBy(['company' => $company]);
  283.             
  284.             $sorted = [];
  285.             foreach ($creditsHistoryCompany as $creditHistoryCompany) {
  286.                 $date $creditHistoryCompany->getCreatedAt()->format('YmdHis');
  287.                 $sorted[$date] = $creditHistoryCompany;
  288.             }
  289.             foreach ($campainsHistory as $campainHistory) {
  290.                 $date $campainHistory->getCreatedAt()->format('YmdHis');
  291.                 $sorted[$date] = $campainHistory;
  292.             }
  293.             foreach ($company->getCommandeLoggings() as $commandeLogging) {
  294.                 $date $commandeLogging->getCreatedAt()->format('YmdHis');
  295.                 $sorted[$date] = $commandeLogging;
  296.             }
  297.             ksort($sorted);
  298.             $sorted array_reverse($sorted);
  299.             
  300.         }
  301.         /**
  302.          * Form for add company
  303.          */
  304.         
  305.         //$isAdmin = in_array('ROLE_ADMIN',$userConnected->getRoles()) ? true : false;
  306.         $form $this->createForm(CompanyType::class, $company,['admin' => $this->isGranted('ROLE_ADMIN'),'clientAdmin'=>$this->isGranted('ROLE_CLIENT_ADMIN'),'selectedCompany'=>$thisCompany]);
  307.         $form->handleRequest($request);
  308.         if ($form->isSubmitted() && $form->isValid()) {
  309.             $dataInMapped $request->request->all();
  310.             $note $dataInMapped['note_company']['content'] ?? null;
  311.             if (!is_null($note) and  !empty($note)) {
  312.                 $newNote = new noteCompany();
  313.                 $newNote->setContent($note);
  314.                 $newNote->setCreatedAt(new \DateTime());
  315.                 $newNote->setType(Note::NOTE_PRIVATE->value);
  316.                 $newNote->setUserToCommented($this->getUser());
  317.                 $entityManager->persist($newNote);
  318.                 $entityManager->flush();
  319.                 $company->addNoteCompany($newNote);
  320.             }
  321.             if ($request->get('_route') === 'company_new') {
  322.                 $company->setCreatedAt(new \DateTime());
  323.                 
  324.                 $company->setLogoFile($form->get('logoFile')->getData());
  325.               
  326.               
  327.                 $creditHistory =  new CreditHistory();
  328.                 $creditHistory->setCompany($company)
  329.                     ->setName("Facturation individuelle")
  330.                     ->setTypePack(TypePack::CASH->value)
  331.                     ->setOrderedBy($this->getUser())
  332.                     ->setIdentifier($creditService->getNewReference())
  333.                     ;
  334.                 $entityManager->persist($company);
  335.                 $entityManager->persist($creditHistory);
  336.                 //si gestionnaire alors liées directement le gestinnaire a l'entreprise
  337.                 if (in_array("ROLE_MANAGER"$userConnected->getRoles())) {
  338.                     //ajouter l'entreprise au gestinnaire qui le créent
  339.                     $userConnected->addOtherCompany($company);
  340.                     $entityManager->persist($userConnected);
  341.                     $entityManager->flush();
  342.                 }
  343.                 $this->sharedResourceCategoryService->setDefaultSharedResourceCategory($company);
  344.                 $this->addFlash('success''L\'entreprise a bien été ajoutée');
  345.                 //ajouter parent si agence 
  346.                 $companyParent $this->dynamicHostService->getCompany();
  347.                 if (null !== $companyParent) {
  348.                     $company->setParent($companyParent);
  349.                 }
  350.                 //fin ajout
  351.                 
  352.             } else {
  353.               
  354.                 $company->setLogoFile($form->get('logoFile')->getData());
  355.                 $company->setUpdatedAt(new \DateTime());
  356.                 $this->addFlash('success''L\'entreprise a bien été modifiée');
  357.             }
  358.             
  359.             if (!empty($form->getData()->getExtensionDomain())) {
  360.                 $extensions $form->getData()->getExtensionDomain();
  361.                 
  362.                 if ($this->checkString($extensions)) {
  363.                     $company->setExtensionDomain($extensions);
  364.                 } else {
  365.                     $this->addFlash('error''Les formats des extensions de domaine associés ne sont pas valides');
  366.                 }
  367.             }
  368.             $entityManager->flush();
  369.            
  370.             // dispatch the company.update event
  371.             $company->setLogoFile(null);
  372.             $event = new CompanyUpdatedEvent($company);
  373.             $dispatcher->dispatch($eventCompanyUpdatedEvent::NAME);
  374.             if($this->isGranted("ROLE_ADMIN")){
  375.                 // return $this->redirectToRoute('company_index', [], Response::HTTP_SEE_OTHER);
  376.                  if ($request->get('_route') === 'company_new'){
  377.                     return $this->redirectToRoute('company_index', [], Response::HTTP_SEE_OTHER);
  378.                  }
  379.                  return $this->redirectToRoute('company_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  380.             }else{
  381.                  return $this->redirectToRoute('company_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  382.             }
  383.         }
  384.         /**
  385.          * Form for add subContractor that does not exist to company
  386.          */
  387.         $form2 $this->createForm(SubContractorCompanyType::class, $user);
  388.         $form2->handleRequest($request);
  389.         $allSubContractorsEmails $userRepository->findByRole($roleSubContractor);
  390.         if ($form2->isSubmitted() && $form2->isValid()) {
  391.             $isAlreadyExist false;
  392.             $oldServiceSubcontractor = [];
  393.             $oldJobSubcontractor = [];
  394.             $email $request->request->get('emailSubContractor');
  395.             $modifSubcontractor $request->request->get('modification_subcontractor');
  396.             if ($validator->validate($email, [new Email()])->count() > 0) {
  397.                 $this->addFlash('error''L\'adresse ' $email ' n\'est pas valide. Nous vous invitons à vérifier votre saisie');
  398.                 return $this->redirectToRoute('company_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  399.             }
  400.             $checkEmail $userRepository->findOneBy(['email' => $email]);
  401.             $subContractorCompany = new  SubContractorCompany();
  402.             $separateEmail explode(" "$email);
  403.             $email $separateEmail[0];
  404.             if (empty($checkEmail)) {
  405.                 $user = new User();
  406.                 $password $userService->generatePassword();
  407.                 $encodedPassword $encoder->encodePassword($user$password);
  408.                 $user->setPassword($encodedPassword);
  409.                 $user->setEmail($email);
  410.                 $user->setRoles([$roleSubContractor]);
  411.                 $user->setEnabled(false);
  412.             } else {
  413.                 $user $userRepository->findOneBy(['email' => $email]);
  414.                 //Si pas vide vérifié si l'utilisateur éxiste déja sur d'autre agence ou sur MyFlow
  415.                 if (null != $user->getCompany()) {
  416.                     $isAlreadyExist true;
  417.                     //alors creez un utilisateur enfant parceque l'utilisateur est dans un autre entreprise
  418.                     //create new user
  419.                     $userGenerate = new User;//for just generate the id automaticly
  420.                     $userChild = clone $user;
  421.                     $emailUniq uniqid().$user->getEmail();
  422.                     $userChild->setId($userGenerate->getId())->setEmail($emailUniq)->setEnabled($user->getEnabled())->setNewAdd(false)->setParent($user)->setPassword($user->getPassword())->setOriginalEmail($user->getEmail())->setCompany(null);
  423.                     $user->addChild($userChild);
  424.                     $entityManager->persist($user);
  425.                     $user $userChild;
  426.                     //need to add user in child
  427.                 }
  428.             }
  429.             $subconctractors $subContractorCompanyRepository->findBy(['user'=>$user,'company' => $company]);
  430.             if ($modifSubcontractor == 1) {
  431.                 foreach ($user->getSubContractorCompanies() as $subCompany) {
  432.                     if($company == $subCompany->getCompany())
  433.                         $subContractorCompany $subCompany;
  434.                 }
  435.             }
  436.             //get all old product of subcontractor // no need to control perte if product already link
  437.             foreach ($subconctractors as $sub) {
  438.                 foreach ($sub->getProducts() as $product) {
  439.                     $oldServiceSubcontractor[] = $product->getId();
  440.                 }
  441.             }
  442.             
  443.             if ($request->query->get('perte') == null) {
  444.                 $listServicesForSubcontractor $serviceRepository->findBy(['user' => $checkEmail]);
  445.                 $allJob = [];
  446.                 $allProduct = [];
  447.                 foreach ($form2->getData()->getJobs() as $jobName) {
  448.                     $nameJob $jobName->getId();
  449.                     $allJob[] =$jobName->getId();
  450.                 }
  451.                 foreach ($form2->getData()->getProducts() as $productName) {
  452.                     $allProduct[] = $productName->getId();
  453.                 }
  454.                 if (!empty($user->getResaleRate() || empty($checkEmail)) && (!$isAlreadyExist)) {
  455.                     $flag false;
  456.                     foreach ($form2->getData()->getProducts() as $productName) {
  457.                         $name $productName->getId();
  458.                   
  459.                         foreach ($listServicesForSubcontractor as $service) {
  460.                             if ($service->getProduct()->getId() === $name) {
  461.                                 $flag true;
  462.                             }
  463.                         }
  464.                     if ($flag !== true and !$isAlreadyExist) {
  465.                         $this->addFlash('error''Veuillez ajouter le produit et le prix pratique par ce partenaire au niveau de sa fiche.');
  466.                         return $this->redirectToRoute('company_edit', ['id' => $company->getId(),'modifSubcontractor' => $modifSubcontractor], Response::HTTP_SEE_OTHER);
  467.                     }
  468.                     foreach ($listServicesForSubcontractor as $service) {
  469.                         if ($user->isEnabled()) {
  470.                             if ($service->getProduct()->getId() === $name and !in_array($service->getProduct()->getId(),$oldServiceSubcontractor)) {
  471.                                 if ($service->getProduct()->getType() === ProductType::AU_FORFAIT) {
  472.                                     $currentMarge $this->numberFormatService->format($myFlowMarginService->getMarge($service$company));
  473.                                 }else{
  474.                                     $currentMarge $this->numberFormatService->format($myFlowMarginService->getMargeTJM($user));
  475.                                 }
  476.                                 $service->getProduct()->getName();
  477.                                 $fullName $user->getFullName();
  478.                                 if ($currentMarge 30) {
  479.                                     $this->addFlash(
  480.                                     "error"
  481.                                     "En ajoutant $fullName pour le service $productName, le total de marge pour le(s) sous-traitant(s) est de $currentMarge %");
  482.                                     return $this->redirectToRoute('company_edit', ['id' => $company->getId(), 'perte' => $currentMarge'email' => $email'product' => implode(","$allProduct), 'job' => implode(","$allJob),'modifSubcontractor' => $modifSubcontractor ], Response::HTTP_SEE_OTHER);
  483.                                 }
  484.                             }
  485.                         } else {
  486.                             $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');
  487.                             return $this->redirectToRoute('company_edit', ['id' => $company->getId(),'modifSubcontractor' => $modifSubcontractor], Response::HTTP_SEE_OTHER);
  488.                         }
  489.                     }
  490.                  }
  491.                 } else {
  492.                     $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.');
  493.                     return $this->redirectToRoute('company_edit', ['id' => $company->getId(),'modifSubcontractor' => $modifSubcontractor], Response::HTTP_SEE_OTHER);
  494.                 }
  495.             }
  496.             $verifyEmailSend $subContractorCompanyRepository->findBy(['user' => $user'company' => $company]);
  497.             
  498.             $flagSend false;
  499.             foreach ($verifyEmailSend as $verify) {
  500.                 if ($verify->getEmailSend() == true) {
  501.                     $flagSend true;
  502.                 }
  503.             }
  504.             //delte product/job before add in modification
  505.             if ($modifSubcontractor == 1) {
  506.                foreach ($subContractorCompany->getJobs() as $jobs) {
  507.                     $subContractorCompany->removeJob($jobs);
  508.                }
  509.                foreach ($subContractorCompany->getProducts() as $product) {
  510.                     $subContractorCompany->removeProduct($product);
  511.                }
  512.             }
  513.             foreach ($form2->getData()->getJobs() as $job) {
  514.                 $subContractorCompany->addJob($job);
  515.             }
  516.             foreach ($form2->getData()->getProducts() as $product) {
  517.                 $subContractorCompany->addProduct($product);
  518.             }
  519.             $subContractorCompany->setCompany($company)
  520.                 ->setUser($user)
  521.                 ->setEmailSend(true);
  522.             if ($modifSubcontractor == 0) {
  523.                 $user->addSubContractorCompany($subContractorCompany);
  524.             }
  525.             
  526.             if (!empty($listSubContractors)) {
  527.                 $newListOfSubcontractor = [];
  528.                 //if modification , don't take a subcontractor in test
  529.                 if ($modifSubcontractor == ) {
  530.                    foreach ($listSubContractors as $subContractor) {
  531.                         if ($subContractor->getUser()->getId() != $user->getId()) {
  532.                             $newListOfSubcontractor[] = $subContractor;
  533.                         }
  534.                     }     
  535.                  }else{
  536.                     $newListOfSubcontractor $listSubContractors;
  537.                  }
  538.                     //verify if subcontractor is already linked job and product
  539.                     foreach ($form2->getData()->getJobs() as $job) {
  540.                         foreach ($newListOfSubcontractor as $subContractor) {
  541.                             foreach ($subContractor->getJobs() as $jobSubcontractor) {
  542.                                 if ($jobSubcontractor === $job ) {
  543.                                     $alreadyLinkJob true;
  544.                                     //after job is already linked verify is already link a product
  545.                                     foreach ($subContractor->getProducts() as $product) {
  546.                                         foreach ($form2->getData()->getProducts() as $productInForm  ) {
  547.                                             if ($productInForm === $product) {
  548.                                                 $this->addFlash('error''Un sous traitant est déjà associé à cette entreprise pour ce produit et ce metier. Nous vous invitons à retirer le partenaire actuel avant d\'en ajouter un nouveau');
  549.                                                 return $this->redirectToRoute('company_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  550.                                             }
  551.                                         }
  552.                                     }
  553.                                 }
  554.                             }
  555.                         }
  556.                     }
  557.                 $entityManager->persist($user);
  558.                 //if ($modifSubcontractor == 0) {
  559.                     $entityManager->persist($subContractorCompany);
  560.                 //}
  561.                 $entityManager->flush();
  562.             } else {
  563.                 $entityManager->persist($user);
  564.                  //if ($modifSubcontractor == 0) {
  565.                     $entityManager->persist($subContractorCompany);
  566.                  //}
  567.                 $entityManager->flush();
  568.             }
  569.             
  570.             //$this->companyService->syncSubcontractorsForAllMissions(subContractorCompany : $subContractorCompany);
  571.             $event true;
  572.             foreach ($user->getServices() as $service) {
  573.                 if (empty($service->getResale())) {
  574.                     $event false;
  575.                 }
  576.             }
  577.             if ($event && $flagSend == false) {
  578.                 $event = new SubContractorReferencedEvent($user);
  579.                 $dispatcher->dispatch($eventSubContractorReferencedEvent::NAME);
  580.             }
  581.             // dispatch the subonctractor.updated event
  582.             $event = new SubContractorUpdatedEvent($user, empty($checkEmail));
  583.             $dispatcher->dispatch($eventSubContractorUpdatedEvent::NAME);
  584.             if ($modifSubcontractor == 1) {
  585.                 $this->addFlash('success''L\'utilisateur a bien été modifié');
  586.             }else{
  587.                 $this->addFlash('success''L\'utilisateur a bien été ajouté');
  588.             }
  589.             return $this->redirectToRoute('company_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  590.         }
  591.         /**
  592.          * Add credit for company
  593.          */
  594.         $creditHistory =  new CreditHistory();
  595.         $form4 $this->createForm(AddCreditCompanyType::class, $creditHistory);
  596.         $form4->handleRequest($request);
  597.         if ($form4->isSubmitted() && $form4->isValid()) {
  598.             $nbCredits $form4->getData()->getCredit();
  599.             $typePack $form4->getData()->getTypePack();
  600.             //dd($form4->getData()->getStartDateContract());
  601.             $dateStartContract $form4->getData()->getStartDateContract();
  602.             if ($typePack == 0) {
  603.                 $dateStartContractModified = clone $dateStartContract;
  604.                 $endDateContract $dateStartContractModified;
  605.             } else {
  606.                 $endDateContract $form4->getData()->getendDateContract();
  607.             }
  608.             $orderPrice = match ($typePack) {
  609.                 '0' =>  $nbCredits,
  610.                 '1' => $form4->getData()->getMensualite(),
  611.                 '2' =>  $form4->getData()->getAnnuite(),
  612.                 //if conctract is fin de mois, we set as a annuite
  613.                 '3' => 0,
  614.             };
  615.        
  616.             $cost 0;
  617.             if ($typePack == 0) {
  618.                 $cost $company->getCostOfDiscountedCredit() * $nbCredits;
  619.             } else {
  620.                 $cost $orderPrice;
  621.             }
  622.             $creditHistory->setCompany($company)
  623.                 ->setCredit($nbCredits)
  624.                 ->setName($form4->getData()->getName())
  625.                 ->setTypePack($typePack)
  626.                 ->setAnnuite($form4->getData()->getAnnuite())
  627.                 ->setMensualite($form4->getData()->getMensualite())
  628.                 ->setReport($form4->getData()->getReport())
  629.                 ->setCurrentBalance($orderPrice)
  630.                 ->setOrderPrice($orderPrice)
  631.                 ->setAutomaticRenewal($form4->getData()->getAutomaticRenewal())
  632.                 ->setStartDateContract($dateStartContract)
  633.                 ->setEndDateContract($endDateContract)
  634.                 ->setCost($cost)
  635.                 ->setIdentifier($creditService->getNewReference())
  636.                 ->setAvailabilityDuration($form4->getData()->getAvailabilityDuration())
  637.                 ->setOrderedBy($this->getUser());
  638.             $balanceTransaction = new BalanceTransactions();
  639.             $balanceTransaction->setName("Initialisation solde contrat type  $typePack")
  640.                 ->setType('credit')
  641.                 ->setOrderBy($this->getUser())
  642.                 ->setCreditHistory($creditHistory)
  643.                 ->setAmount($creditHistory->getCurrentBalance())
  644.                 ->setCurrentBalance($creditHistory->getCurrentBalance());
  645.             $entityManager->persist($company);
  646.             $entityManager->persist($balanceTransaction);
  647.             $entityManager->persist($creditHistory);
  648.             $entityManager->flush();
  649.             $packService->initialize($creditHistory->getId());
  650.             $dataSolde $packService->getSolde();
  651.             $nbSolde count($dataSolde);
  652.             $dateEnd $dataSolde[$nbSolde]['dateEnd'];
  653.             if ($typePack == 0) {
  654.                 $creditHistory->setCreditExpiredAt($dateEnd)->setEndDateContract($dateStartContractModified);
  655.             } else {
  656.                 $creditHistory->setCreditExpiredAt($dateEnd);
  657.             }
  658.             //do reflush
  659.             $entityManager->flush();
  660.             $this->addFlash(
  661.                 type'success',
  662.                 message"La campagne reprend avec succès ",
  663.             );
  664.             return $this->redirectToRoute('company_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  665.         }
  666.         $clients $userRepository->findBy([], ['email' => 'ASC']);
  667.         $mailClientToCommand "";
  668.         if ($thisCompany != null) {
  669.             $clientListForOrderAs $userRepository->findClientByCompany($thisCompany$roleCLient$roleCLientAdmin);
  670.         }
  671.         if (!empty($clientListForOrderAs)) {
  672.             foreach ($clientListForOrderAs as $client) {
  673.                 if (($client->isEnabled())) {
  674.                     $mailClientToCommand $client->getEmail();
  675.                     break;
  676.                 }
  677.             }
  678.         }
  679.         $orderAsLink = !empty($mailClientToCommand) ? $parameter->get('url_redirect_to_front') . '?tsso=' hash('sha256'$mailClientToCommand $mailClientToCommand) : null;
  680.         //data in modal company ---------------------------------------------------------------
  681.         $allCampaign $campaignRepository->findAllCampaingByCompany($company);
  682.         
  683.         $listOfFilesByDate = [];
  684.         $dataSummaryByDate = [];
  685.         $nameOfBucket "company-".strtolower($company->getId());
  686.         foreach ($allCampaign as $campaign) {
  687.             foreach ($campaign->getMessages() as $message) {
  688.                foreach ($message->getFileMessages() as $file) {
  689.                     if ($file->isIsNew()) {
  690.                         $year $message->getCreatedAt()->format('Y');
  691.                         $month $message->getCreatedAt()->format('m');
  692.                         $listOfFilesByDate["{$year}-{$month}"][] = "Campaigns/{$campaign->getId()}/{$file->getName()}";
  693.                     }
  694.                }
  695.             }
  696.            foreach ($campaign->getFileMissions() as $file) {
  697.                 if ($file->isIsNew()) {
  698.                     $year $file->getCreatedAt()->format('Y');
  699.                     $month $file->getCreatedAt()->format('m');
  700.                      $listOfFilesByDate["{$year}-{$month}"][] = "Campaigns/{$campaign->getId()}/{$file->getName()}";
  701.                 }
  702.            } 
  703.         }
  704.         //prendre toutes les tailles selon le mois et l'années
  705.         foreach ($listOfFilesByDate as $key => $list) {
  706.             $size $googleStorageService->sizeOfBucketByFile($nameOfBucket,$list);
  707.             $dataSummaryByDate[$key] = $size;
  708.             krsort($dataSummaryByDate);
  709.         }
  710.         
  711.         return $this->renderForm('company/handle.html.twig', [
  712.             'isAgency' => $this->dynamicHostService->isAgency(),
  713.             'hideInfoifIsAgency' => $agency "style=display:none" "",
  714.             'form' => $form,
  715.             'form2' => $form2,
  716.             'dataSummaryStorage' => $dataSummaryByDate,
  717.             'modifSubcontractor' => $modifSubcontractor,
  718.             'form4' => $form4,
  719.             'company' => $company,
  720.             'listClients' => $listClients,
  721.             'listSubContractors' => $listSubContractors,
  722.             'listServices' => $listServices ?? [],
  723.             'allCredit' => $allCredit,
  724.             'creditHistories' => $creditsHistoryCompany,
  725.             'clients' => $serializer->serialize($clients'json', [AbstractNormalizer::ATTRIBUTES => ['email']]),
  726.             'sorted' => $sorted ?? [],
  727.             'allSubContractorsEmails' => $serializer->serialize($allSubContractorsEmails'json', [AbstractNormalizer::ATTRIBUTES => ['email']]),
  728.             'orderAsLink' => $orderAsLink
  729.             'clientsList' => $userRepository->findBy(['company'=>$company'deleted'=>false'enabled'=>true]), 
  730.             'avalaiblecreditHistories' => $companyService->getAvailableContract($creditHistoryRepository->findAvailableServiceHistory($company, new \DateTime()), true)
  731.         ]);
  732.     }
  733.     /**
  734.      * @param Request $request
  735.      * @param UserRepository $userRepository
  736.      * @param CompanyRepository $companyRepository
  737.      * @param EmailService $emailService
  738.      * @param EntityManagerInterface $entityManager
  739.      * @param UserService $userService
  740.      * @param UserPasswordEncoderInterface $encoder
  741.      * @return \Symfony\Component\HttpFoundation\RedirectResponse
  742.      */
  743.     #[Route('/admin/client-company/ajouter'name'company_add_client'methods: ['GET''POST'])]
  744.     public function addClientCompany(Request $requestUserRepository $userRepositoryCompanyRepository $companyRepositoryEntityManagerInterface $entityManagerUserService $userServiceUserPasswordHasherInterface $passwordHasherEventDispatcherInterface $dispatcherValidatorInterface $validator)
  745.     {
  746.         /**
  747.          * We get the user and the company in the query and then register them
  748.          */
  749.   
  750.         $email str_replace(" ""+"$request->query->get('email'));
  751.         $email explode("+"$email)[0];
  752.         $agency = !is_null($request->query->get('agency')) ? true false;
  753.         $isAgencyModification $this->dynamicHostService->isAgency();
  754.         $user $userRepository->findOneBy(['email' => $email]);
  755.         $company $companyRepository->findOneBy(['id' => $request->query->get('company')]);
  756.         // check if a email is already in company,
  757.         //$company = !$isAgencyModification ? null : $company;
  758.         $isCompanyAgency $this->dynamicHostService->isAgencyByCompany($company);
  759.          //test if same user already exist in myflow or agency / dont repeat secondly
  760.         $userExist $userRepository->getUniqUserByCompanyByEmail($email,$company);
  761.         
  762.         if (!is_null($userExist)) {
  763.             $this->addFlash('error'"Cette adresse email existe déjà dans la liste");
  764.             if ($agency) {
  765.                 return $this->redirectToRoute('agency_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  766.             }
  767.             return $this->redirectToRoute('company_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  768.         }
  769.         //end test
  770.         $users $company->getUsers();
  771.         $userExist false;
  772.         if (!empty($user)) {
  773.             //create new user
  774.             $userGenerate = new User;//for just generate the id automaticly
  775.             $userChild = clone $user;
  776.             $emailUniq uniqid().$user->getEmail();
  777.             $token hash('sha256'uniqid(preg_replace('/\s/','-',$userChild->getFullName())));
  778.             $userChild->setId($userGenerate->getId())->setEmail($emailUniq)->setEnabled($user->getEnabled())->setNewAdd(false)->setParent($user)->setPassword($user->getPassword())->setOriginalEmail($user->getEmail())->setCompany($company)->setOneTimeLoginToken($token);
  779.             //need to add user in child
  780.             $userChild->setRoles(['ROLE_CLIENT']);
  781.             if ($isCompanyAgency and in_array("ROLE_ADMIN"$this->getUser()->getRoles()) ) {
  782.                 $userChild->setRoles(['ROLE_ADMIN_AGENCY']);
  783.             }
  784.             $user->addChild($userChild);
  785.             $entityManager->persist($user);
  786.             $userExist true;
  787.         } else {
  788.             $user = new User();
  789.             $password $userService->generatePassword();
  790.             $encodedPassword $passwordHasher->hashPassword($user$password);
  791.             $user->setPassword($encodedPassword);
  792.             $user->setEmail($email);
  793.             $user->setRoles(['ROLE_CLIENT']);
  794.             if ($isCompanyAgency and in_array("ROLE_ADMIN"$this->getUser()->getRoles())) {
  795.                 $user->setRoles(['ROLE_ADMIN_AGENCY']);
  796.             }
  797.             $user->setEnabled(false);
  798.             $user->setCompany($company);
  799.         }
  800.         if ($validator->validate($email, [new Email()])->count() > 0) {
  801.             $this->addFlash('error''L\'adresse ' $email ' n\'est pas valide. Nous vous invitons à vérifier votre saisie');
  802.             if ($agency) {
  803.                 return $this->redirectToRoute('agency_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  804.             }
  805.             return $this->redirectToRoute('company_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  806.         } else {
  807.             $entityManager->persist($user);
  808.             $entityManager->flush();
  809.             if ($isCompanyAgency) {
  810.                 $this->addFlash('success'"L'administrateur à bien été ajouté");
  811.             }else{
  812.                 $this->addFlash('success'"Le client à bien été ajouté");
  813.             }
  814.             if (!$userExist) {
  815.                 $event = new ClientUpdatedEvent($usertrue);
  816.                 $dispatcher->dispatch($eventClientUpdatedEvent::NAME);
  817.             }
  818.        
  819.         }
  820.         if ($agency) {
  821.             return $this->redirectToRoute('agency_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  822.         }
  823.         return $this->redirectToRoute('company_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  824.     }
  825.     /**
  826.      * @param Request $request
  827.      * @param UserRepository $userRepository
  828.      * @param CompanyRepository $companyRepository
  829.      * @param EmailService $emailService
  830.      * @param EntityManagerInterface $entityManager
  831.      * @param UserService $userService
  832.      * @param UserPasswordEncoderInterface $encoder
  833.      * @return \Symfony\Component\HttpFoundation\RedirectResponse
  834.      */
  835.     #[Route('/admin/subcontractor-company/ajouter'name'company_add_subcontractor'methods: ['GET''POST'])]
  836.     public function addSubContractorCompany(Request $requestSubContractorCompany $subContractorCompany nullUserRepository $userRepositoryCompanyRepository $companyRepositoryEmailService $emailServiceEntityManagerInterface $entityManagerUserService $userServiceUserPasswordEncoderInterface $encoder)
  837.     {
  838.         /**
  839.          * We get the subContractor and the company in the query and then register them
  840.          */
  841.         $subContractorCompany = new SubContractorCompany();
  842.         $user $userRepository->findOneBy(['email' => $request->query->get('email')]);
  843.         $company $companyRepository->findOneBy(['id' => $request->query->get('company')]);
  844.         $subContractorCompany->setCompany($company)
  845.             ->setUser($user);
  846.         $subContractorCompany->addJob();
  847.         $subContractorCompany->addProduct();
  848.         $user->setRoles(['ROLE_SUBCONTRACTOR']);
  849.         $entityManager->persist($user);
  850.         $entityManager->persist($subContractorCompany);
  851.         $entityManager->flush();
  852.         $this->addFlash('success''Le sous-traitant à bien été ajouté');
  853.         return $this->redirectToRoute('company_edit', ['id' => $company->getId()], Response::HTTP_SEE_OTHER);
  854.     }
  855.     #[Route('/admin/entreprise/delete/{id}'name'company_delete'methods: ['GET'])]
  856.     public function deleteCompany(Company $company,EventDispatcherInterface $dispatcherSubContractorCompanyRepository $subContractorCompanyRepositoryUserRepository $userRepositoryEntityManagerInterface $entityManager){
  857.         if($this->isGranted("ROLE_ADMIN")){
  858.             $users$userRepository->findBy(['company'=>$company]);
  859.             $subcontractorsCompany $subContractorCompanyRepository->findBy(['company'=>$company]);
  860.             foreach ($users as $user) {
  861.                 $user->setCompany(null);
  862.                 $user->setDeleted(true);
  863.                 $entityManager->flush();
  864.                 $this->frontAPIService->pushClientToFront($user$user->getPassword());
  865.             
  866.             }
  867.             
  868.             foreach ( $subcontractorsCompany as  $subcontractorCompany) {
  869.                 $user$subcontractorCompany->getUser();
  870.                 $event = new SubContractorUpdatedEvent($user);
  871.                 $dispatcher->dispatch($eventSubContractorUpdatedEvent::NAME);
  872.                 $entityManager->remove($subcontractorCompany);
  873.                 $entityManager->flush();
  874.             }
  875.             $company->setDeleted(true);
  876.             $entityManager->flush();
  877.         }else{
  878.             $this->addFlash("error""Impossible de supprimer l'entreprise");
  879.         }
  880.         $this->addFlash("success""Entreprise supprimée avec succès");
  881.         return$this->redirectToRoute('company_index', [], Response::HTTP_SEE_OTHER);
  882.          
  883.     }
  884.     #[Route('/admin/entreprise/command/add/{id}'name'add_command_company'methods: ['POST'])]
  885.     public function addCommand(Company $company,UserRepository $userRepository,EventDispatcherInterface $dispatcherRequest $request,ClientSoldService $clientSoldService,EntityManagerInterface $em,BalanceTransactionsRepository $balanceTransactionsRepositoryCreditHistoryRepository $creditHistoryRepositoryProductRepository $productRepositoryMissionService $missionService ){
  886.         
  887.         $creditHistory $creditHistoryRepository->findOneBy(['id'=>$request->request->get('creditHistory')]);
  888.         $amount $amountCredit =  floatval($request->request->get('amount'));
  889.         $description $request->request->get('description');
  890.         $orderById =$request->request->get('orderedBy'null) ; 
  891.     
  892.         $orderBy =  $orderById != null $userRepository->findOneBy(['id'=> $orderById]) : $this->getUser();
  893.      
  894.         $individualBilling null;
  895.         
  896.         if($creditHistory->getTypePack() == TypePack::CREDIT->value ){
  897.             $amountCredit /=  $creditHistory->getCost()/$creditHistory->getCredit() ; 
  898.         }
  899.         if(in_array($creditHistory->getTypePack(), [TypePack::CASHTypePack::FACTURATION_FIN_DU_MOIS])){
  900.             $newCurrentBalance =   $creditHistory->getCurrentBalance() + $amountCredit;
  901.         }else{
  902.             $newCurrentBalance =   $creditHistory->getCurrentBalance() - $amountCredit;
  903.         }
  904.         if ($newCurrentBalance 0) {
  905.             $individualBilling $amountCredit $creditHistory->getCurrentBalance();
  906.             $event = new  NoticeOfInsufficientBudgetEvent($company,nullnull, [ $orderBy ]);
  907.             $dispatcher->dispatch($eventNoticeOfInsufficientBudgetEvent::NAME);
  908.         }
  909.     
  910.         $creditHistory->setCurrentBalance($newCurrentBalance);
  911.         $product $productRepository->findOneBy(['name'=>'autre commande']); 
  912.         $referenceMission $missionService->generateReference($this->getUser()) ; 
  913.         if( $product === null ){
  914.             $product = new Product(); 
  915.             $product->setName('autre commande');
  916.             $product ->setDeleted(true);
  917.             $product->setType(ProductType::AU_TEMPS_PASSE); 
  918.             $product ->setTemplate(false);
  919.             ; 
  920.         }
  921.        
  922.         $mission = new Mission(); 
  923.         $mission->setPriceSale($amount);
  924.         $mission->setReference($referenceMission);
  925.         $mission->setQuantity(1); 
  926.         $mission->setProduct($product);
  927.         $mission->setState('finalized');
  928.         ;
  929.         $campaign = new Campaign();
  930.         $campaign->setState('closed');
  931.         $campaign->setBrief('Autre commande');
  932.         $campaign->setName('Autre commande');
  933.         $campaign->setCreditHistory($creditHistory);
  934.         $campaign->setIsToBeinvoiced(true);
  935.         $campaign->setCompany($creditHistory->getCompany());
  936.         $campaign->setOrderedBy($this->getUser()); 
  937.         $campaign->setTypeInitiation(1);
  938.         $campaign->addMission($mission);
  939.         ; 
  940.       
  941.         $em->persist($product);
  942.         $em->persist($mission);
  943.         $em->persist($campaign);
  944.         $em->flush();
  945.         $clientSoldService->addbanlanceTransation(
  946.             creditHistory:$creditHistory,
  947.             name$description
  948.             type'debit',
  949.             amount$amountCredit
  950.             currentBalance$creditHistory->getCurrentBalance(),
  951.             individualBilling$individualBilling,
  952.             mission:  $mission,
  953.             otherCommandnull
  954.             orderBy$orderBy
  955.         );
  956.         
  957.         $this->addFlash('success''Commande enregistrée avec succès');
  958.         $clientSoldService->addCommandeLogging(company$company,detail: [
  959.             'name'=> 'Autre commande',
  960.             'description'=> $description,
  961.             'type'=> CommandeLoggingType::ADDITIONAL_DEBIT->value,
  962.             'amount' => $amountCredit,
  963.             'typePack' =>$creditHistory->getTypePack(),
  964.             'user'=>$orderBy,
  965.             'creditHistory' => $creditHistory
  966.         ]);
  967.         $clientSoldService->updateTotalConsumptionCreditHistory($creditHistory);
  968.     
  969.         return $this->redirectToRoute('company_edit',[
  970.              'id'=>$company->getId()
  971.         ]);
  972.     }
  973.    
  974.     #[Route('/admin/entreprise/toggle-role/{id}'name'toogleRole'methods: ['POST'])]
  975.     public function toogleRole(Request $requestUser $userEntityManagerInterface $entityManager){
  976.         $user->setRoles([$request->request->get('role')]);
  977.         $entityManager->flush();
  978.         return new JsonResponse([
  979.             'status'=>'ok'
  980.         ]) ;
  981.     }
  982.     private function checkString($input) {
  983.         $parts array_map('trim'explode(','$input));
  984.         
  985.         foreach ($parts as $part) {
  986.             if (empty($part) || strpos($part' ') !== false) {
  987.                 return false;
  988.             }
  989.         }
  990.     
  991.         return !empty($parts) ? true false;
  992.     }
  993.     #[Route('/note-company-modified/{id}'name'note_company_modified'methods: ['GET','POST'])]
  994.     public function noteModificationCompany(noteCompany $noteRequest $request,EntityManagerInterface $entityManager): Response
  995.     
  996.         $content $request->request->get('info_mission_edit')['content'];
  997.         if (!is_null($content) and !empty($content)) {
  998.             $note->setContent($content);
  999.             $entityManager->persist($note);
  1000.             $entityManager->flush();
  1001.            
  1002.         }
  1003.         $this->addFlash(
  1004.             type'success',
  1005.             message'Modification effectuée'
  1006.         );
  1007.         return $this->redirect($request->headers->get('referer'));
  1008.     }
  1009.     #[Route('/note-company-deleted/{id}'name'note_company_deleted'methods: ['GET','POST'])]
  1010.     public function noteDeletedCompany(noteCompany $noteRequest $request,EntityManagerInterface $entityManager): Response
  1011.     
  1012.         $entityManager->remove($note);
  1013.         $entityManager->flush(); 
  1014.         $this->addFlash(
  1015.             type'success',
  1016.             message'Suppression effectuée'
  1017.         );
  1018.         return $this->redirect($request->headers->get('referer'));
  1019.     }
  1020. }