src/Controller/EntrepriseController.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\CSPE;
  4. use App\Entity\Note;
  5. use App\Entity\User;
  6. use App\Entity\Rappel;
  7. use App\Entity\Contact;
  8. use App\Entity\Contrat;
  9. use App\Entity\GasMeter;
  10. use App\Entity\Entreprise;
  11. use App\Entity\EspaceClient;
  12. use App\Entity\ElectricMeter;
  13. use App\Form\EntrepriseType;
  14. use App\Form\ContratType;
  15. use App\Repository\EntrepriseRepository;
  16. use Symfony\Contracts\HttpClient\HttpClientInterface;
  17. use Doctrine\Persistence\ManagerRegistry;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Response;
  22. use Symfony\Component\HttpFoundation\JsonResponse;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. class EntrepriseController extends AbstractController
  25. {
  26.     /**
  27.      * @Route("/entreprise", name="app_entreprise")
  28.      */
  29.     public function index(ManagerRegistry $doctrine): Response
  30.     {
  31.         $entreprises $doctrine->getRepository(Entreprise::class)->findAll();
  32.         $array_entreprises = array();
  33.         
  34.         for ($i=0$i count($entreprises); $i++) { 
  35.             $user_name $doctrine->getRepository(User::class)->findOneBy(['id' => $entreprises[$i]->getUtilisateur()]);
  36.             $user_name $user_name $user_name->getUsername() : '';
  37.             $entreprise_contacts $doctrine->getRepository(Contact::class)->findBy(['entreprise_id' => $entreprises[$i]->getId()]);
  38.             $entreprise_contacts implode(" "array_map(function($contact) {
  39.                 return $contact->getNom()." ".$contact->getPrenom();
  40.             }, $entreprise_contacts));
  41.             $array_entreprises[$i] = [
  42.                 $entreprises[$i]->getRaisonSociale(),
  43.                 $entreprises[$i]->getCommune(),
  44.                 $entreprises[$i]->getSiret(),
  45.                 $entreprise_contacts,
  46.                 $user_name,
  47.                 '<a href="'.$this->generateUrl('app_entreprise_details',['id' => $entreprises[$i]->getId()]).'" type="button" class="btn btn-sm btn-primary mb-1">Consulter</a>
  48.                 <a href="'.$this->generateUrl('app_entreprise_edit',['id' => $entreprises[$i]->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
  49.                 <a href="'.$this->generateUrl('app_entreprise_suppr',['id' => $entreprises[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
  50.             ];
  51.         };
  52.         return $this->render('entreprise/index.html.twig', [
  53.             'entreprises' => $array_entreprises,
  54.         ]);
  55.     }
  56.     /**
  57.      * @Route("/entreprise/add", name="app_entreprise_add")
  58.      */
  59.     public function add(Request $requestEntityManagerInterface $entityManager): Response
  60.     {
  61.         $entreprises = new Entreprise();
  62.         // using createQueryBuilder
  63.         $utilisateurs $entityManager->createQueryBuilder()
  64.             ->select('u')
  65.             ->from(User::class, 'u')
  66.             ->where('u.roles LIKE :roles')
  67.             ->setParameter('roles''%ROLE_TEAM%')
  68.             ->getQuery()
  69.             ->getResult();
  70.         $array_utilisateurs = array();
  71.         for ($i=0$i count($utilisateurs); $i++) { 
  72.             $array_utilisateurs[$utilisateurs[$i]->getUsername()] = $utilisateurs[$i]->getId();
  73.         }
  74.         $form $this->createForm(EntrepriseType::class, $entreprises, ['utilisateurs' => $array_utilisateurs]);
  75.         $form->handleRequest($request);
  76.         if ($form->isSubmitted() && $form->isValid()) {
  77.             $entityManager->persist($entreprises);
  78.             $entityManager->flush();
  79.             return $this->redirectToRoute('app_entreprise');
  80.         }
  81.         return $this->render('entreprise/add.html.twig', [
  82.             'entrepriseForm' => $form->createView(),
  83.             'array_utilisateurs' => $array_utilisateurs,
  84.         ]);
  85.     }
  86.     /**
  87.      * @Route("/entreprise/edit/{id}", name="app_entreprise_edit")
  88.      */
  89.     public function edit(int $idRequest $requestEntityManagerInterface $entityManagerManagerRegistry $doctrine): Response
  90.     {
  91.         $entreprise $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $id]);
  92.         $utilisateurs $entityManager->createQueryBuilder()
  93.             ->select('u')
  94.             ->from(User::class, 'u')
  95.             ->where('u.roles LIKE :roles')
  96.             ->setParameter('roles''%ROLE_TEAM%')
  97.             ->getQuery()
  98.             ->getResult();
  99.         $array_utilisateurs = array();
  100.         for ($i=0$i count($utilisateurs); $i++) { 
  101.             $array_utilisateurs[$utilisateurs[$i]->getUsername()] = $utilisateurs[$i]->getId();
  102.         }
  103.         $form $this->createForm(EntrepriseType::class, $entreprise, ['utilisateurs' => $array_utilisateurs]);
  104.         $form->handleRequest($request);
  105.         $entreprise_entity = [ 'raison_sociale' => $entreprise->getRaisonSociale(),
  106.             'siret' => $entreprise->getSiret(),
  107.             'naf' => $entreprise->getNaf(),
  108.             'rcs' => $entreprise->getRcs(),
  109.             'num_voie' => $entreprise->getNumVoie(),
  110.             'adresse' => $entreprise->getAdresse(),
  111.             'code_postal' => $entreprise->getCodePostal(),
  112.             'commune' => $entreprise->getCommune(),
  113.             'code_insee' => $entreprise->getCodeInsee(),
  114.             'statut' => $entreprise->getStatut(),
  115.             'utilisateur' => $entreprise->getUtilisateur(),
  116.         ];
  117.         if ($form->isSubmitted() && $form->isValid()) {
  118.             $entreprisesEdit $form->getData();
  119.             if($entreprisesEdit->getRaisonSociale() != null){
  120.                 $entreprise->setRaisonSociale($entreprisesEdit->getRaisonSociale());
  121.             }
  122.             if($entreprisesEdit->getSiret() != null){
  123.                 $entreprise->setSiret($entreprisesEdit->getSiret());
  124.             }
  125.             if($entreprisesEdit->getNaf() != null){
  126.                 $entreprise->setNaf($entreprisesEdit->getNaf());
  127.             }
  128.             if($entreprisesEdit->getRcs() != null){
  129.                 $entreprise->setRcs($entreprisesEdit->getRcs());
  130.             }
  131.             if($entreprisesEdit->getNumVoie() != null){
  132.                 $entreprise->setNumVoie($entreprisesEdit->getNumVoie());
  133.             }
  134.             if($entreprisesEdit->getAdresse() != null){
  135.                 $entreprise->setAdresse($entreprisesEdit->getAdresse());
  136.             }
  137.             if($entreprisesEdit->getCodePostal() != null){
  138.                 $entreprise->setCodePostal($entreprisesEdit->getCodePostal());
  139.             }
  140.             if($entreprisesEdit->getCommune() != null){
  141.                 $entreprise->setCommune($entreprisesEdit->getCommune());
  142.             }
  143.             if($entreprisesEdit->getCodeInsee() != null){
  144.                 $entreprise->setCodeInsee($entreprisesEdit->getCodeInsee());
  145.             }
  146.             if($entreprisesEdit->getStatut() != null){
  147.                 $entreprise->setStatut($entreprisesEdit->getStatut());
  148.             }
  149.             if($entreprisesEdit->getUtilisateur() != null){
  150.                 $entreprise->setUtilisateur($entreprisesEdit->getUtilisateur());
  151.             }
  152.             $entityManager->persist($entreprise);
  153.             $entityManager->flush();
  154.             return $this->redirectToRoute('app_entreprise');
  155.         }
  156.         return $this->render('entreprise/edit.html.twig', [
  157.             'entrepriseForm' => $form->createView(),
  158.             'entreprise' => $entreprise_entity
  159.         ]);
  160.     }
  161.     /**
  162.      * @Route("/entreprise/suppr/{id}", name="app_entreprise_suppr")
  163.      */
  164.     public function suppr(int $idRequest $requestEntityManagerInterface $entityManagerManagerRegistry $doctrine): Response
  165.     {
  166.         $notes $doctrine->getRepository(Note::class)->findBy(['entreprise_id' => $id]);
  167.         for ($i=0$i count($notes); $i++) { 
  168.             $entityManager->remove($notes[$i]);
  169.             $entityManager->flush();
  170.         };
  171.         $rappels $doctrine->getRepository(Rappel::class)->findBy(['entreprise_id' => $id]);
  172.         for ($i=0$i count($rappels); $i++) { 
  173.             $entityManager->remove($rappels[$i]);
  174.             $entityManager->flush();
  175.         };
  176.         $electric_meters $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id]);
  177.         for ($i=0$i count($electric_meters); $i++) { 
  178.             $entityManager->remove($electric_meters[$i]);
  179.             $entityManager->flush();
  180.         };
  181.         $gas_meters $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id]);
  182.         for ($i=0$i count($gas_meters); $i++) { 
  183.             $entityManager->remove($gas_meters[$i]);
  184.             $entityManager->flush();
  185.         };
  186.         $cspes $doctrine->getRepository(CSPE::class)->findBy(['entreprise_id' => $id]);
  187.         for ($i=0$i count($cspes); $i++) { 
  188.             $entityManager->remove($cspes[$i]);
  189.             $entityManager->flush();
  190.         };
  191.         $espace_clients $doctrine->getRepository(EspaceClient::class)->findBy(['entreprise_id' => $id]);
  192.         for ($i=0$i count($espace_clients); $i++) { 
  193.             $entityManager->remove($espace_clients[$i]);
  194.             $entityManager->flush();
  195.         };
  196.         $contacts $doctrine->getRepository(Contact::class)->findBy(['entreprise_id' => $id]);
  197.         for ($i=0$i count($contacts); $i++) { 
  198.             $entityManager->remove($contacts[$i]);
  199.             $entityManager->flush();
  200.         };
  201.         $entreprise $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $id]);
  202.         $entityManager->remove($entreprise);
  203.         $entityManager->flush();
  204.         return $this->redirectToRoute('app_entreprise');
  205.     }
  206.     /**
  207.      * @Route("/entreprise/details/{id}", name="app_entreprise_details")
  208.      */
  209.     public function details(int $idManagerRegistry $doctrine): Response
  210.     {
  211.         $entreprise $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $id]);
  212.         if(!$entreprise){
  213.             return $this->redirectToRoute('app_requetes');
  214.         }
  215.         
  216.         $user_name $doctrine->getRepository(User::class)->findOneBy(['id' => $entreprise->getUtilisateur()]);
  217.         $user_name $user_name $user_name->getUsername() : '';
  218.         $entreprise_entity = [ 'id' => $entreprise->getId(),
  219.             'raison_sociale' => $entreprise->getRaisonSociale(),
  220.             'siret' => $entreprise->getSiret(),
  221.             'naf' => $entreprise->getNaf(),
  222.             'rcs' => $entreprise->getRcs(),
  223.             'num_voie' => $entreprise->getNumVoie(),
  224.             'adresse' => $entreprise->getAdresse(),
  225.             'code_postal' => $entreprise->getCodePostal(),
  226.             'commune' => $entreprise->getCommune(),
  227.             'code_insee' => $entreprise->getCodeInsee(),
  228.             'statut' => $entreprise->getStatut(),
  229.             'utilisateur' => $user_name,
  230.         ];
  231.         // Fetch and prepare notes data
  232.         $notes $doctrine->getRepository(Note::class)->findBy(['entreprise_id' => $id], ['date_creation' => 'DESC']);
  233.         $array_notes = array();
  234.         foreach ($notes as $note) {
  235.             $user $note->getUser();
  236.             $array_notes[] = [
  237.                 'date_creation' => $note->getDateCreation() ? $note->getDateCreation()->format('Y-m-d H:i:s') : '',
  238.                 'texte' => $note->getTexte(),
  239.                 'user' => $user $user->getUsername() : 'Non défini',
  240.                 'edit_url' => $this->generateUrl('app_note_edit', ['id' => $note->getId()]),
  241.                 'delete_url' => $this->generateUrl('app_note_suppr', ['id' => $note->getId()]),
  242.             ];
  243.         }
  244.         // Fetch and prepare rappels data
  245.         $rappels $doctrine->getRepository(Rappel::class)->findBy(['entreprise_id' => $id]);
  246.         $array_rappels = array();
  247.         foreach ($rappels as $rappel) {
  248.             $array_rappels[] = [
  249.                 $rappel->getTitre(),
  250.                 $rappel->getDescription(),
  251.                 $rappel->getEcheance()->format('d/m/Y'),
  252.                 $rappel->isCompleter(),
  253.                 '<a href="'.$this->generateUrl('app_rappel_edit',['id' => $rappel->getId()]).'" type="button" class="btn btn-sm btn-primary mb-1">Modifier</a>
  254.                 <a href="'.$this->generateUrl('app_rappel_suppr',['id' => $rappel->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
  255.             ];
  256.         }
  257.         // Fetch only PDLs for electric meters
  258.         $electric_meters $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id]);
  259.         $array_electric_meters array_map(function($meter) {
  260.             return [
  261.                 'pdl' => $meter->getPDL(),
  262.                 'id' => $meter->getId(),
  263.             ];
  264.         }, $electric_meters);
  265.         // Fetch only PDLs for gas meters
  266.         $gas_meters $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id]);
  267.         $array_gas_meters array_map(function($meter) {
  268.             return [
  269.                 'pdl' => $meter->getPDL(),
  270.                 'id' => $meter->getId(),
  271.             ];
  272.         }, $gas_meters);
  273.         $cspes $doctrine->getRepository(CSPE::class)->findBy(['entreprise_id' => $id]);
  274.         $array_cspes = array();
  275.         for ($i=0$i count($cspes); $i++) { 
  276.             $array_cspes[$i] = [
  277.                 $cspes[$i]->getNotes(),
  278.                 date_format($cspes[$i]->getDate(),'d/m/Y'),
  279.                 $cspes[$i]->getValeur(),
  280.                 '<a href="'.$this->generateUrl('app_cspe_edit',['id' => $cspes[$i]->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
  281.                 <a href="'.$this->generateUrl('app_cspe_suppr',['id' => $cspes[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
  282.             ];
  283.         };
  284.         $espace_clients $doctrine->getRepository(EspaceClient::class)->findBy(['entreprise_id' => $id]);
  285.         $array_espace_clients = array();
  286.         for ($i=0$i count($espace_clients); $i++) {
  287.             if(strpos($espace_clients[$i]->getLien(), "http://") === false && strpos($espace_clients[$i]->getLien(), "https://") === false ){
  288.                 $lien "http://".$espace_clients[$i]->getLien();
  289.             }else{
  290.                 $lien $espace_clients[$i]->getLien();
  291.             }
  292.             $array_espace_clients[$i] = [
  293.                 $espace_clients[$i]->getFournisseur(),
  294.                 $espace_clients[$i]->getLogin(),
  295.                 $espace_clients[$i]->getMdp(),
  296.                 '<a href='.$lien.' target="_blank" type="button" class="btn btn-primary">'.explode("."$espace_clients[$i]->getLien())[1].'</a>',
  297.                 '<a href="'.$this->generateUrl('app_espace_client_edit',['id' => $espace_clients[$i]->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
  298.                 <a href="'.$this->generateUrl('app_espace_client_suppr',['id' => $espace_clients[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
  299.             ];
  300.         };
  301.         $contacts $doctrine->getRepository(Contact::class)->findBy(['entreprise_id' => $id]);
  302.         $array_contacts = array();
  303.         for ($i=0$i count($contacts); $i++) { 
  304.             $array_contacts[$i] = [
  305.                 $contacts[$i]->getNom(),
  306.                 $contacts[$i]->getPrenom(),
  307.                 $contacts[$i]->getCivilite(),
  308.                 $contacts[$i]->getFonction(),
  309.                 $contacts[$i]->getFixe(),
  310.                 $contacts[$i]->getEmail(),
  311.                 $contacts[$i]->getPortable(),
  312.                 '<a href="'.$this->generateUrl('app_contact_edit',['id' => $contacts[$i]->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
  313.                 <a href="'.$this->generateUrl('app_contact_suppr',['id' => $contacts[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
  314.             ];
  315.         };
  316.         $contrats $doctrine->getRepository(Contrat::class)->findBy(['entreprise' => $entreprise]);
  317.         $array_contrats = array();
  318.         foreach ($contrats as $contrat) {
  319.             $array_contrats[] = [
  320.                 $contrat->getId(), // Using ID as reference
  321.                 $contrat->getDuree(),
  322.                 $contrat->getValeur(),
  323.                 $contrat->getPdl(),
  324.                 $contrat->getCar(),
  325.                 $contrat->getNombreAnnees(),
  326.                 '<a href="'.$this->generateUrl('app_entreprise_edit_contrat', ['entrepriseId' => $entreprise->getId(), 'id' => $contrat->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
  327.                 <a href="'.$this->generateUrl('app_entreprise_delete_contrat', ['entrepriseId' => $entreprise->getId(), 'id' => $contrat->getId()]).'" type="button" class="btn btn-sm btn-danger">Supprimer</a>',
  328.             ];
  329.         }
  330.         return $this->render('entreprise/details.html.twig', [
  331.             'entreprise' => $entreprise_entity,
  332.             'notes' => $array_notes,
  333.             'rappels' => $array_rappels,
  334.             'electric_meters' => $array_electric_meters,
  335.             'gas_meters' => $array_gas_meters,
  336.             'cspes' => $array_cspes,
  337.             'espace_clients' => $array_espace_clients,
  338.             'contacts' => $array_contacts,
  339.             'contrats' => $array_contrats,
  340.         ]);
  341.     }
  342.     /**
  343.      * @Route("/entreprise/{id}/electric-meter-details", name="app_electric_meter_details")
  344.      */
  345.     public function electricMeterDetails(Request $requestint $idManagerRegistry $doctrine): JsonResponse
  346.     {
  347.         $pdl $request->query->get('pdl');
  348.         $electricMeter $doctrine->getRepository(ElectricMeter::class)->findOneBy([
  349.             'entreprise_id' => $id,
  350.             'PDL' => $pdl
  351.         ]);
  352.         if (!$electricMeter) {
  353.             return new JsonResponse(['error' => 'Electric meter not found'], 404);
  354.         }
  355.         $meterDetails = [
  356.             'adresseCompteur' => $electricMeter->getAdresseCompteur(),
  357.             'dateDebut' => $electricMeter->getDateDebut() ? $electricMeter->getDateDebut()->format('d/m/Y') : '',
  358.             'dateFin' => $electricMeter->getDateFin() ? $electricMeter->getDateFin()->format('d/m/Y') : '',
  359.             'PS' => $electricMeter->getPS(),
  360.             'profil' => $electricMeter->getProfil(),
  361.             'CAR' => $electricMeter->getCAR(),
  362.             'fournisseur' => $electricMeter->getFournisseur(),
  363.             'prix' => $electricMeter->getPrix(),
  364.         ];
  365.         return new JsonResponse($meterDetails);
  366.     }
  367.     /**
  368.      * @Route("/entreprise/{id}/gas-meter-details", name="app_gas_meter_details")
  369.      */
  370.     public function gasMeterDetails(Request $requestint $idManagerRegistry $doctrine): JsonResponse
  371.     {
  372.         $pdl $request->query->get('pdl');
  373.         $gasMeter $doctrine->getRepository(GasMeter::class)->findOneBy([
  374.             'entreprise_id' => $id,
  375.             'PDL' => $pdl
  376.         ]);
  377.         if (!$gasMeter) {
  378.             return new JsonResponse(['error' => 'Gas meter not found'], 404);
  379.         }
  380.         $meterDetails = [
  381.             'adresseCompteur' => $gasMeter->getAdresseCompteur(),
  382.             'dateDebut' => $gasMeter->getDateDebut() ? $gasMeter->getDateDebut()->format('d/m/Y') : '',
  383.             'dateFin' => $gasMeter->getDateFin() ? $gasMeter->getDateFin()->format('d/m/Y') : '',
  384.             'profil' => $gasMeter->getProfil(),
  385.             'CAR' => $gasMeter->getCAR(),
  386.             'fournisseur' => $gasMeter->getFournisseur(),
  387.             'prix' => $gasMeter->getPrix(),
  388.         ];
  389.         return new JsonResponse($meterDetails);
  390.     }
  391.     /**
  392.      * @Route("/entreprise/infoclient", name="app_entreprise_infoclient")
  393.      */
  394.     public function infoclient(HttpClientInterface $httpClient): JsonResponse
  395.     {
  396.         // Utilisez les paramètres appropriés pour votre requête
  397.         $url 'https://api.societe.com/api/v1/infoclient';
  398.         $headers = [
  399.             'headers' => [
  400.                 'X-Authorization' => 'socapi 8938e836988619dc20be14360fba30e3',
  401.             ],
  402.         ];
  403.         // Effectuez la requête
  404.         $response $httpClient->request('GET'$url$headers);
  405.         // Renvoie la réponse JSON
  406.         return new JsonResponse($response->toArray());
  407.     }
  408.     /**
  409.      * @Route("/entreprise/info_entreprise/{numero}", name="app_entreprise_info_entreprise")
  410.      */
  411.     public function info_entreprise(HttpClientInterface $httpClientManagerRegistry $doctrine$numero): JsonResponse
  412.     {
  413.         // Vérification que l'entreprise n'est pas déjà enregistré en BDD
  414.         $entreprise $doctrine->getRepository(Entreprise::class)->findOneBy(['Siret' => $numero]);
  415.         if($entreprise !=null){
  416.             return new JsonResponse("existant");
  417.         }
  418.         $url 'https://api.societe.com/api/v1/entreprise/'.$numero.'/infoslegales';
  419.         $headers = [
  420.             'headers' => [
  421.                 'X-Authorization' => 'socapi 8938e836988619dc20be14360fba30e3',
  422.             ],
  423.         ];
  424.         // Effectuez la requête
  425.         $response $httpClient->request('GET'$url$headers);
  426.         // Renvoie la réponse JSON
  427.         return new JsonResponse($response->toArray());
  428.     }
  429.     /**
  430.      * @Route("/entreprise/{id}/new-contrat", name="app_entreprise_new_contrat")
  431.      */
  432.     public function newContrat(Request $requestEntityManagerInterface $entityManagerManagerRegistry $doctrineint $id): Response
  433.     {
  434.         $entreprise $doctrine->getRepository(Entreprise::class)->find($id);
  435.         
  436.         if (!$entreprise) {
  437.             throw $this->createNotFoundException('Entreprise not found');
  438.         }
  439.         $contrat = new Contrat();
  440.         $contrat->setEntreprise($entreprise);
  441.         $pdlChoices $this->getPDLChoicesForEntreprise($doctrine$entreprise);
  442.         $form $this->createForm(ContratType::class, $contrat, [
  443.             'pdl_choices' => $pdlChoices
  444.         ]);
  445.         $form->handleRequest($request);
  446.         if ($form->isSubmitted() && $form->isValid()) {
  447.             // Calculate the contract value
  448.             $averageEexPrice $this->calculateAverageEexPrice($contrat->getDuree());
  449.             $contratValue $averageEexPrice $contrat->getCar() * $contrat->getNombreAnnees();
  450.             $contrat->setValeur($contratValue);
  451.             // Fetch the User object and set it as the collaborateur
  452.             $userId $entreprise->getUtilisateur();
  453.             if ($userId) {
  454.                 $user $doctrine->getRepository(User::class)->find($userId);
  455.                 if ($user) {
  456.                     $contrat->setCollaborateur($user);
  457.                 }
  458.             }
  459.             $entityManager->persist($contrat);
  460.             $entityManager->flush();
  461.             return $this->redirectToRoute('app_entreprise_details', ['id' => $entreprise->getId()]);
  462.         }
  463.         return $this->render('entreprise/new_contrat.html.twig', [
  464.             'entreprise' => $entreprise,
  465.             'form' => $form->createView(),
  466.         ]);
  467.     }
  468.     /**
  469.      * @Route("/entreprise/{entrepriseId}/edit-contrat/{id}", name="app_entreprise_edit_contrat")
  470.      */
  471.     public function editContrat(Request $requestEntityManagerInterface $entityManagerManagerRegistry $doctrineint $entrepriseIdint $id): Response
  472.     {
  473.         $entreprise $doctrine->getRepository(Entreprise::class)->find($entrepriseId);
  474.         $contrat $doctrine->getRepository(Contrat::class)->find($id);
  475.         if (!$entreprise) {
  476.             throw $this->createNotFoundException('Entreprise not found');
  477.         }
  478.         if (!$contrat) {
  479.             throw $this->createNotFoundException('Contrat not found');
  480.         }
  481.         $pdlChoices $this->getPDLChoicesForEntreprise($doctrine$entreprise);
  482.         $form $this->createForm(ContratType::class, $contrat, [
  483.             'pdl_choices' => $pdlChoices
  484.         ]);
  485.         $form->handleRequest($request);
  486.         if ($form->isSubmitted() && $form->isValid()) {
  487.             // Recalculate the contract value
  488.             $averageEexPrice $this->calculateAverageEexPrice($contrat->getDuree());
  489.             $contratValue $averageEexPrice $contrat->getCar() * $contrat->getNombreAnnees();
  490.             $contrat->setValeur($contratValue);
  491.             $entityManager->flush();
  492.             return $this->redirectToRoute('app_entreprise_details', ['id' => $entreprise->getId()]);
  493.         }
  494.         return $this->render('entreprise/edit_contrat.html.twig', [
  495.             'entreprise' => $entreprise,
  496.             'contrat' => $contrat,
  497.             'form' => $form->createView(),
  498.         ]);
  499.     }
  500.     /**
  501.      * @Route("/entreprise/{entrepriseId}/delete-contrat/{id}", name="app_entreprise_delete_contrat")
  502.      */
  503.     public function deleteContrat(Request $requestEntityManagerInterface $entityManagerManagerRegistry $doctrineint $entrepriseIdint $id): Response
  504.     {
  505.         $entreprise $doctrine->getRepository(Entreprise::class)->find($entrepriseId);
  506.         $contrat $doctrine->getRepository(Contrat::class)->find($id);
  507.         if (!$entreprise) {
  508.             throw $this->createNotFoundException('Entreprise not found');
  509.         }
  510.         if (!$contrat) {
  511.             throw $this->createNotFoundException('Contrat not found');
  512.         }
  513.         if ($this->isCsrfTokenValid('delete'.$contrat->getId(), $request->request->get('_token'))) {
  514.             $entityManager->remove($contrat);
  515.             $entityManager->flush();
  516.         }
  517.         return $this->redirectToRoute('app_entreprise_details', ['id' => $entreprise->getId()]);
  518.     }
  519.     private function calculateAverageEexPrice(int $duration): float
  520.     {
  521.         // This is a placeholder method. In a real-world scenario, you would
  522.         // fetch the EEX prices from a database or an API for the given duration
  523.         // and calculate the average.
  524.         
  525.         // For now, we'll return a dummy value
  526.         return 50.0// Example average price in euros per MWh
  527.     }
  528.     private function getPDLChoicesForEntreprise(ManagerRegistry $doctrineEntreprise $entreprise): array
  529.     {
  530.         $electricMeters $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $entreprise->getId()]);
  531.         $gasMeters $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $entreprise->getId()]);
  532.         $pdlChoices = [];
  533.         foreach ($electricMeters as $meter) {
  534.             $pdlChoices[$meter->getPDL()] = $meter->getPDL();
  535.         }
  536.         foreach ($gasMeters as $meter) {
  537.             $pdlChoices[$meter->getPDL()] = $meter->getPDL();
  538.         }
  539.         return $pdlChoices;
  540.     }
  541. }