<?php
namespace App\Controller;
use App\Entity\CSPE;
use App\Entity\Note;
use App\Entity\User;
use App\Entity\Rappel;
use App\Entity\Contact;
use App\Entity\Contrat;
use App\Entity\GasMeter;
use App\Entity\Entreprise;
use App\Entity\EspaceClient;
use App\Entity\ElectricMeter;
use App\Form\EntrepriseType;
use App\Form\ContratType;
use App\Repository\EntrepriseRepository;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
class EntrepriseController extends AbstractController
{
/**
* @Route("/entreprise", name="app_entreprise")
*/
public function index(ManagerRegistry $doctrine): Response
{
$entreprises = $doctrine->getRepository(Entreprise::class)->findAll();
$array_entreprises = array();
for ($i=0; $i < count($entreprises); $i++) {
$user_name = $doctrine->getRepository(User::class)->findOneBy(['id' => $entreprises[$i]->getUtilisateur()]);
$user_name = $user_name ? $user_name->getUsername() : '';
$entreprise_contacts = $doctrine->getRepository(Contact::class)->findBy(['entreprise_id' => $entreprises[$i]->getId()]);
$entreprise_contacts = implode(" ", array_map(function($contact) {
return $contact->getNom()." ".$contact->getPrenom();
}, $entreprise_contacts));
$array_entreprises[$i] = [
$entreprises[$i]->getRaisonSociale(),
$entreprises[$i]->getCommune(),
$entreprises[$i]->getSiret(),
$entreprise_contacts,
$user_name,
'<a href="'.$this->generateUrl('app_entreprise_details',['id' => $entreprises[$i]->getId()]).'" type="button" class="btn btn-sm btn-primary mb-1">Consulter</a>
<a href="'.$this->generateUrl('app_entreprise_edit',['id' => $entreprises[$i]->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
<a href="'.$this->generateUrl('app_entreprise_suppr',['id' => $entreprises[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
];
};
return $this->render('entreprise/index.html.twig', [
'entreprises' => $array_entreprises,
]);
}
/**
* @Route("/entreprise/add", name="app_entreprise_add")
*/
public function add(Request $request, EntityManagerInterface $entityManager): Response
{
$entreprises = new Entreprise();
// using createQueryBuilder
$utilisateurs = $entityManager->createQueryBuilder()
->select('u')
->from(User::class, 'u')
->where('u.roles LIKE :roles')
->setParameter('roles', '%ROLE_TEAM%')
->getQuery()
->getResult();
$array_utilisateurs = array();
for ($i=0; $i < count($utilisateurs); $i++) {
$array_utilisateurs[$utilisateurs[$i]->getUsername()] = $utilisateurs[$i]->getId();
}
$form = $this->createForm(EntrepriseType::class, $entreprises, ['utilisateurs' => $array_utilisateurs]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($entreprises);
$entityManager->flush();
return $this->redirectToRoute('app_entreprise');
}
return $this->render('entreprise/add.html.twig', [
'entrepriseForm' => $form->createView(),
'array_utilisateurs' => $array_utilisateurs,
]);
}
/**
* @Route("/entreprise/edit/{id}", name="app_entreprise_edit")
*/
public function edit(int $id, Request $request, EntityManagerInterface $entityManager, ManagerRegistry $doctrine): Response
{
$entreprise = $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $id]);
$utilisateurs = $entityManager->createQueryBuilder()
->select('u')
->from(User::class, 'u')
->where('u.roles LIKE :roles')
->setParameter('roles', '%ROLE_TEAM%')
->getQuery()
->getResult();
$array_utilisateurs = array();
for ($i=0; $i < count($utilisateurs); $i++) {
$array_utilisateurs[$utilisateurs[$i]->getUsername()] = $utilisateurs[$i]->getId();
}
$form = $this->createForm(EntrepriseType::class, $entreprise, ['utilisateurs' => $array_utilisateurs]);
$form->handleRequest($request);
$entreprise_entity = [ 'raison_sociale' => $entreprise->getRaisonSociale(),
'siret' => $entreprise->getSiret(),
'naf' => $entreprise->getNaf(),
'rcs' => $entreprise->getRcs(),
'num_voie' => $entreprise->getNumVoie(),
'adresse' => $entreprise->getAdresse(),
'code_postal' => $entreprise->getCodePostal(),
'commune' => $entreprise->getCommune(),
'code_insee' => $entreprise->getCodeInsee(),
'statut' => $entreprise->getStatut(),
'utilisateur' => $entreprise->getUtilisateur(),
];
if ($form->isSubmitted() && $form->isValid()) {
$entreprisesEdit = $form->getData();
if($entreprisesEdit->getRaisonSociale() != null){
$entreprise->setRaisonSociale($entreprisesEdit->getRaisonSociale());
}
if($entreprisesEdit->getSiret() != null){
$entreprise->setSiret($entreprisesEdit->getSiret());
}
if($entreprisesEdit->getNaf() != null){
$entreprise->setNaf($entreprisesEdit->getNaf());
}
if($entreprisesEdit->getRcs() != null){
$entreprise->setRcs($entreprisesEdit->getRcs());
}
if($entreprisesEdit->getNumVoie() != null){
$entreprise->setNumVoie($entreprisesEdit->getNumVoie());
}
if($entreprisesEdit->getAdresse() != null){
$entreprise->setAdresse($entreprisesEdit->getAdresse());
}
if($entreprisesEdit->getCodePostal() != null){
$entreprise->setCodePostal($entreprisesEdit->getCodePostal());
}
if($entreprisesEdit->getCommune() != null){
$entreprise->setCommune($entreprisesEdit->getCommune());
}
if($entreprisesEdit->getCodeInsee() != null){
$entreprise->setCodeInsee($entreprisesEdit->getCodeInsee());
}
if($entreprisesEdit->getStatut() != null){
$entreprise->setStatut($entreprisesEdit->getStatut());
}
if($entreprisesEdit->getUtilisateur() != null){
$entreprise->setUtilisateur($entreprisesEdit->getUtilisateur());
}
$entityManager->persist($entreprise);
$entityManager->flush();
return $this->redirectToRoute('app_entreprise');
}
return $this->render('entreprise/edit.html.twig', [
'entrepriseForm' => $form->createView(),
'entreprise' => $entreprise_entity
]);
}
/**
* @Route("/entreprise/suppr/{id}", name="app_entreprise_suppr")
*/
public function suppr(int $id, Request $request, EntityManagerInterface $entityManager, ManagerRegistry $doctrine): Response
{
$notes = $doctrine->getRepository(Note::class)->findBy(['entreprise_id' => $id]);
for ($i=0; $i < count($notes); $i++) {
$entityManager->remove($notes[$i]);
$entityManager->flush();
};
$rappels = $doctrine->getRepository(Rappel::class)->findBy(['entreprise_id' => $id]);
for ($i=0; $i < count($rappels); $i++) {
$entityManager->remove($rappels[$i]);
$entityManager->flush();
};
$electric_meters = $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id]);
for ($i=0; $i < count($electric_meters); $i++) {
$entityManager->remove($electric_meters[$i]);
$entityManager->flush();
};
$gas_meters = $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id]);
for ($i=0; $i < count($gas_meters); $i++) {
$entityManager->remove($gas_meters[$i]);
$entityManager->flush();
};
$cspes = $doctrine->getRepository(CSPE::class)->findBy(['entreprise_id' => $id]);
for ($i=0; $i < count($cspes); $i++) {
$entityManager->remove($cspes[$i]);
$entityManager->flush();
};
$espace_clients = $doctrine->getRepository(EspaceClient::class)->findBy(['entreprise_id' => $id]);
for ($i=0; $i < count($espace_clients); $i++) {
$entityManager->remove($espace_clients[$i]);
$entityManager->flush();
};
$contacts = $doctrine->getRepository(Contact::class)->findBy(['entreprise_id' => $id]);
for ($i=0; $i < count($contacts); $i++) {
$entityManager->remove($contacts[$i]);
$entityManager->flush();
};
$entreprise = $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $id]);
$entityManager->remove($entreprise);
$entityManager->flush();
return $this->redirectToRoute('app_entreprise');
}
/**
* @Route("/entreprise/details/{id}", name="app_entreprise_details")
*/
public function details(int $id, ManagerRegistry $doctrine): Response
{
$entreprise = $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $id]);
if(!$entreprise){
return $this->redirectToRoute('app_requetes');
}
$user_name = $doctrine->getRepository(User::class)->findOneBy(['id' => $entreprise->getUtilisateur()]);
$user_name = $user_name ? $user_name->getUsername() : '';
$entreprise_entity = [ 'id' => $entreprise->getId(),
'raison_sociale' => $entreprise->getRaisonSociale(),
'siret' => $entreprise->getSiret(),
'naf' => $entreprise->getNaf(),
'rcs' => $entreprise->getRcs(),
'num_voie' => $entreprise->getNumVoie(),
'adresse' => $entreprise->getAdresse(),
'code_postal' => $entreprise->getCodePostal(),
'commune' => $entreprise->getCommune(),
'code_insee' => $entreprise->getCodeInsee(),
'statut' => $entreprise->getStatut(),
'utilisateur' => $user_name,
];
// Fetch and prepare notes data
$notes = $doctrine->getRepository(Note::class)->findBy(['entreprise_id' => $id], ['date_creation' => 'DESC']);
$array_notes = array();
foreach ($notes as $note) {
$user = $note->getUser();
$array_notes[] = [
'date_creation' => $note->getDateCreation() ? $note->getDateCreation()->format('Y-m-d H:i:s') : '',
'texte' => $note->getTexte(),
'user' => $user ? $user->getUsername() : 'Non défini',
'edit_url' => $this->generateUrl('app_note_edit', ['id' => $note->getId()]),
'delete_url' => $this->generateUrl('app_note_suppr', ['id' => $note->getId()]),
];
}
// Fetch and prepare rappels data
$rappels = $doctrine->getRepository(Rappel::class)->findBy(['entreprise_id' => $id]);
$array_rappels = array();
foreach ($rappels as $rappel) {
$array_rappels[] = [
$rappel->getTitre(),
$rappel->getDescription(),
$rappel->getEcheance()->format('d/m/Y'),
$rappel->isCompleter(),
'<a href="'.$this->generateUrl('app_rappel_edit',['id' => $rappel->getId()]).'" type="button" class="btn btn-sm btn-primary mb-1">Modifier</a>
<a href="'.$this->generateUrl('app_rappel_suppr',['id' => $rappel->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
];
}
// Fetch only PDLs for electric meters
$electric_meters = $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id]);
$array_electric_meters = array_map(function($meter) {
return [
'pdl' => $meter->getPDL(),
'id' => $meter->getId(),
];
}, $electric_meters);
// Fetch only PDLs for gas meters
$gas_meters = $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id]);
$array_gas_meters = array_map(function($meter) {
return [
'pdl' => $meter->getPDL(),
'id' => $meter->getId(),
];
}, $gas_meters);
$cspes = $doctrine->getRepository(CSPE::class)->findBy(['entreprise_id' => $id]);
$array_cspes = array();
for ($i=0; $i < count($cspes); $i++) {
$array_cspes[$i] = [
$cspes[$i]->getNotes(),
date_format($cspes[$i]->getDate(),'d/m/Y'),
$cspes[$i]->getValeur(),
'<a href="'.$this->generateUrl('app_cspe_edit',['id' => $cspes[$i]->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
<a href="'.$this->generateUrl('app_cspe_suppr',['id' => $cspes[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
];
};
$espace_clients = $doctrine->getRepository(EspaceClient::class)->findBy(['entreprise_id' => $id]);
$array_espace_clients = array();
for ($i=0; $i < count($espace_clients); $i++) {
if(strpos($espace_clients[$i]->getLien(), "http://") === false && strpos($espace_clients[$i]->getLien(), "https://") === false ){
$lien = "http://".$espace_clients[$i]->getLien();
}else{
$lien = $espace_clients[$i]->getLien();
}
$array_espace_clients[$i] = [
$espace_clients[$i]->getFournisseur(),
$espace_clients[$i]->getLogin(),
$espace_clients[$i]->getMdp(),
'<a href='.$lien.' target="_blank" type="button" class="btn btn-primary">'.explode(".", $espace_clients[$i]->getLien())[1].'</a>',
'<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>
<a href="'.$this->generateUrl('app_espace_client_suppr',['id' => $espace_clients[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
];
};
$contacts = $doctrine->getRepository(Contact::class)->findBy(['entreprise_id' => $id]);
$array_contacts = array();
for ($i=0; $i < count($contacts); $i++) {
$array_contacts[$i] = [
$contacts[$i]->getNom(),
$contacts[$i]->getPrenom(),
$contacts[$i]->getCivilite(),
$contacts[$i]->getFonction(),
$contacts[$i]->getFixe(),
$contacts[$i]->getEmail(),
$contacts[$i]->getPortable(),
'<a href="'.$this->generateUrl('app_contact_edit',['id' => $contacts[$i]->getId()]).'" type="button" class="btn btn-sm btn-warning mb-1">Modifier</a>
<a href="'.$this->generateUrl('app_contact_suppr',['id' => $contacts[$i]->getId()]).'" type="button" class="btn btn-sm btn-danger ">Supprimer</a>',
];
};
$contrats = $doctrine->getRepository(Contrat::class)->findBy(['entreprise' => $entreprise]);
$array_contrats = array();
foreach ($contrats as $contrat) {
$array_contrats[] = [
"id" => $contrat->getId(),
"duree" => $contrat->getDuree(),
"valeur" => $contrat->getValeur(),
"pdl" => $contrat->getPdl(),
"car" => $contrat->getCar(),
"prix_moyen" => $contrat->getPrixMoyen(),
"fournisseur" => $contrat->getFournisseur(),
"date_debut" => $contrat->getDateDebut() ? $contrat->getDateDebut()->format('d/m/Y') : '',
"date_fin" => $contrat->getDateFin() ? $contrat->getDateFin()->format('d/m/Y') : '',
'<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>
<a href="'.$this->generateUrl('app_entreprise_delete_contrat', ['entrepriseId' => $entreprise->getId(), 'id' => $contrat->getId()]).'" type="button" class="btn btn-sm btn-danger">Supprimer</a>',
];
}
return $this->render('entreprise/details.html.twig', [
'entreprise' => $entreprise_entity,
'notes' => $array_notes,
'rappels' => $array_rappels,
'electric_meters' => $array_electric_meters,
'gas_meters' => $array_gas_meters,
'cspes' => $array_cspes,
'espace_clients' => $array_espace_clients,
'contacts' => $array_contacts,
'contrats' => $array_contrats,
]);
}
/**
* @Route("/entreprise/{id}/electric-meter-details", name="app_electric_meter_details")
*/
public function electricMeterDetails(Request $request, int $id, ManagerRegistry $doctrine): JsonResponse
{
$pdl = $request->query->get('pdl');
$electricMeter = $doctrine->getRepository(ElectricMeter::class)->findOneBy([
'entreprise_id' => $id,
'PDL' => $pdl
]);
if (!$electricMeter) {
return new JsonResponse(['error' => 'Electric meter not found'], 404);
}
$meterDetails = [
'adresseCompteur' => $electricMeter->getAdresseCompteur(),
'dateDebut' => $electricMeter->getDateDebut() ? $electricMeter->getDateDebut()->format('d/m/Y') : '',
'dateFin' => $electricMeter->getDateFin() ? $electricMeter->getDateFin()->format('d/m/Y') : '',
'PS' => $electricMeter->getPS(),
'profil' => $electricMeter->getProfil(),
'CAR' => $electricMeter->getCAR(),
'fournisseur' => $electricMeter->getFournisseur(),
'prix' => $electricMeter->getPrix(),
];
return new JsonResponse($meterDetails);
}
/**
* @Route("/entreprise/{id}/gas-meter-details", name="app_gas_meter_details")
*/
public function gasMeterDetails(Request $request, int $id, ManagerRegistry $doctrine): JsonResponse
{
$pdl = $request->query->get('pdl');
if (!$pdl) {
return new JsonResponse(['error' => 'PDL parameter is required'], 400);
}
// First verify the entreprise exists
$entreprise = $doctrine->getRepository(Entreprise::class)->find($id);
if (!$entreprise) {
return new JsonResponse(['error' => 'Entreprise not found'], 404);
}
// Use the new debug method to get detailed information
$debugResult = $doctrine->getRepository(GasMeter::class)->findWithDebug($id, $pdl);
if (!$debugResult['meter']) {
$errorResponse = [
'error' => 'Gas meter not found',
'debug_info' => [
'search_result' => $debugResult['found_by'],
'entreprise_id' => $id,
'pdl' => $pdl
]
];
// Add additional debug information based on what was found
if ($debugResult['found_by'] === 'pdl_only') {
$errorResponse['debug_info']['actual_entreprise_id'] = $debugResult['actual_entreprise_id'];
} elseif ($debugResult['found_by'] === 'entreprise_only') {
$errorResponse['debug_info']['available_pdls'] = $debugResult['available_pdls'];
}
return new JsonResponse($errorResponse, 404);
}
$gasMeter = $debugResult['meter'];
$meterDetails = [
'adresseCompteur' => $gasMeter->getAdresseCompteur(),
'dateDebut' => $gasMeter->getDateDebut() ? $gasMeter->getDateDebut()->format('d/m/Y') : '',
'dateFin' => $gasMeter->getDateFin() ? $gasMeter->getDateFin()->format('d/m/Y') : '',
'profil' => $gasMeter->getProfil(),
'CAR' => $gasMeter->getCAR(),
'fournisseur' => $gasMeter->getFournisseur(),
'prix' => $gasMeter->getPrix(),
];
return new JsonResponse($meterDetails);
}
/**
* @Route("/entreprise/infoclient", name="app_entreprise_infoclient")
*/
public function infoclient(HttpClientInterface $httpClient): JsonResponse
{
// Utilisez les paramètres appropriés pour votre requête
$url = 'https://api.societe.com/api/v1/infoclient';
$headers = [
'headers' => [
'X-Authorization' => 'socapi 8938e836988619dc20be14360fba30e3',
],
];
// Effectuez la requête
$response = $httpClient->request('GET', $url, $headers);
// Renvoie la réponse JSON
return new JsonResponse($response->toArray());
}
/**
* @Route("/entreprise/info_entreprise/{numero}", name="app_entreprise_info_entreprise")
*/
public function info_entreprise(HttpClientInterface $httpClient, ManagerRegistry $doctrine, $numero): JsonResponse
{
// Vérification que l'entreprise n'est pas déjà enregistré en BDD
$entreprise = $doctrine->getRepository(Entreprise::class)->findOneBy(['Siret' => $numero]);
if($entreprise !=null){
return new JsonResponse("existant");
}
$url = 'https://api.societe.com/api/v1/entreprise/'.$numero.'/infoslegales';
$headers = [
'headers' => [
'X-Authorization' => 'socapi 8938e836988619dc20be14360fba30e3',
],
];
// Effectuez la requête
$response = $httpClient->request('GET', $url, $headers);
// Renvoie la réponse JSON
return new JsonResponse($response->toArray());
}
/**
* @Route("/entreprise/{id}/new-contrat", name="app_entreprise_new_contrat")
*/
public function newContrat(Request $request, EntityManagerInterface $entityManager, ManagerRegistry $doctrine, int $id): Response
{
$entreprise = $doctrine->getRepository(Entreprise::class)->find($id);
if (!$entreprise) {
throw $this->createNotFoundException('Entreprise not found');
}
$contrat = new Contrat();
$contrat->setEntreprise($entreprise);
$meterId = $request->query->get('meterId');
$meterType = $request->query->get('meterType');
if ($meterId && $meterType) {
$meter = null;
if ($meterType === 'electric') {
$meter = $doctrine->getRepository(ElectricMeter::class)->find($meterId);
} elseif ($meterType === 'gas') {
$meter = $doctrine->getRepository(GasMeter::class)->find($meterId);
}
if ($meter) {
$contrat->setPdl($meter->getPDL());
$contrat->setCar($meter->getCAR());
$contrat->setPrixMoyen($meter->getPrix());
$contrat->setFournisseur($meter->getFournisseur());
$contrat->setDateDebut($meter->getDateDebut());
$contrat->setDateFin($meter->getDateFin());
}
}
$pdlChoices = $this->getPDLChoicesForEntreprise($doctrine, $entreprise);
$form = $this->createForm(ContratType::class, $contrat, [
'pdl_choices' => $pdlChoices
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Calculate the contract value
$contratValue = $contrat->getCar() * $contrat->getPrixMoyen();
$contrat->setValeur($contratValue);
// Calculate duration in months
$duration = $this->calculateDurationInMonths($contrat->getDateDebut(), $contrat->getDateFin());
$contrat->setDuree($duration);
// Fetch the User object and set it as the collaborateur
$userId = $entreprise->getUtilisateur();
if ($userId) {
$user = $doctrine->getRepository(User::class)->find($userId);
if ($user) {
$contrat->setCollaborateur($user);
}
}
$entityManager->persist($contrat);
$entityManager->flush();
return $this->redirectToRoute('app_entreprise_details', ['id' => $entreprise->getId()]);
}
return $this->render('entreprise/new_contrat.html.twig', [
'entreprise' => $entreprise,
'form' => $form->createView(),
]);
}
/**
* @Route("/entreprise/{entrepriseId}/edit-contrat/{id}", name="app_entreprise_edit_contrat")
*/
public function editContrat(Request $request, EntityManagerInterface $entityManager, ManagerRegistry $doctrine, int $entrepriseId, int $id): Response
{
$entreprise = $doctrine->getRepository(Entreprise::class)->find($entrepriseId);
$contrat = $doctrine->getRepository(Contrat::class)->find($id);
if (!$entreprise) {
throw $this->createNotFoundException('Entreprise not found');
}
if (!$contrat) {
throw $this->createNotFoundException('Contrat not found');
}
// S'assurer que l'entreprise est définie sur le contrat
$contrat->setEntreprise($entreprise);
$pdlChoices = $this->getPDLChoicesForEntreprise($doctrine, $entreprise);
$form = $this->createForm(ContratType::class, $contrat, [
'pdl_choices' => $pdlChoices
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// S'assurer que l'entreprise est toujours définie après la soumission du formulaire
$contrat->setEntreprise($entreprise);
// Recalculate the contract value
$contratValue = $contrat->getCar() * $contrat->getPrixMoyen();
$contrat->setValeur($contratValue);
// Recalculate duration in months
$duration = $this->calculateDurationInMonths($contrat->getDateDebut(), $contrat->getDateFin());
$contrat->setDuree($duration);
$entityManager->flush();
return $this->redirectToRoute('app_entreprise_details', ['id' => $entreprise->getId()]);
}
return $this->render('entreprise/edit_contrat.html.twig', [
'entreprise' => $entreprise,
'contrat' => $contrat,
'form' => $form->createView(),
]);
}
/**
* @Route("/entreprise/{entrepriseId}/delete-contrat/{id}", name="app_entreprise_delete_contrat")
*/
public function deleteContrat(Request $request, EntityManagerInterface $entityManager, ManagerRegistry $doctrine, int $entrepriseId, int $id): Response
{
$entreprise = $doctrine->getRepository(Entreprise::class)->find($entrepriseId);
$contrat = $doctrine->getRepository(Contrat::class)->find($id);
if (!$entreprise) {
throw $this->createNotFoundException('Entreprise not found');
}
if (!$contrat) {
throw $this->createNotFoundException('Contrat not found');
}
if ($this->isCsrfTokenValid('delete'.$contrat->getId(), $request->request->get('_token'))) {
$entityManager->remove($contrat);
$entityManager->flush();
}
return $this->redirectToRoute('app_entreprise_details', ['id' => $entreprise->getId()]);
}
private function calculateDurationInMonths(?\DateTimeInterface $dateDebut, ?\DateTimeInterface $dateFin): ?int
{
if (!$dateDebut || !$dateFin) {
return null;
}
$interval = $dateDebut->diff($dateFin);
return $interval->y * 12 + $interval->m;
}
private function getPDLChoicesForEntreprise(ManagerRegistry $doctrine, Entreprise $entreprise): array
{
$electricMeters = $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $entreprise->getId()]);
$gasMeters = $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $entreprise->getId()]);
$pdlChoices = [];
foreach ($electricMeters as $meter) {
$pdlChoices[$meter->getPDL()] = $meter->getPDL();
}
foreach ($gasMeters as $meter) {
$pdlChoices[$meter->getPDL()] = $meter->getPDL();
}
return $pdlChoices;
}
}