<?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\Form\UserEntrepriseType;
use App\Service\PricingService;
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;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Psr\Log\LoggerInterface;
class EntrepriseController extends AbstractController
{
private $pricingService;
private $logger;
public function __construct(PricingService $pricingService, LoggerInterface $logger)
{
$this->pricingService = $pricingService;
$this->logger = $logger;
}
/**
* @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));
// Get electric meters PDLs
$electric_meters = $doctrine->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $entreprises[$i]->getId()]);
$electric_pdls = array_map(function($meter) {
return $meter->getPDL();
}, $electric_meters);
// Get gas meters PDLs
$gas_meters = $doctrine->getRepository(GasMeter::class)->findBy(['entreprise_id' => $entreprises[$i]->getId()]);
$gas_pdls = array_map(function($meter) {
return $meter->getPDL();
}, $gas_meters);
// Combine all PDLs into a searchable string
$all_pdls = implode(' ', array_merge($electric_pdls, $gas_pdls));
$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>',
$all_pdls, // Hidden column containing all PDLs
$entreprises[$i]->getNaf(), // Hidden column containing NAF code
];
};
return $this->render('entreprise/index.html.twig', [
'entreprises' => $array_entreprises,
]);
}
/**
* @Route("/entreprise/calculate-value", name="app_entreprise_calculate_value", methods={"POST"})
*/
public function calculateValue(Request $request, ManagerRegistry $doctrine): JsonResponse
{
$this->logger->debug('Received calculate value request', [
'car' => $request->request->get('car'),
'dateDebut' => $request->request->get('dateDebut'),
'dateFin' => $request->request->get('dateFin'),
'pdl' => $request->request->get('pdl'),
'raw_request' => $request->request->all()
]);
// Validate CSRF token
$submittedToken = $request->headers->get('X-CSRF-Token');
if (!$this->isCsrfTokenValid('calculate-value', $submittedToken)) {
$this->logger->error('Invalid CSRF token');
return new JsonResponse(['error' => 'Invalid CSRF token'], 403);
}
try {
$car = floatval($request->request->get('car'));
if ($car <= 0) {
throw new \InvalidArgumentException('CAR must be greater than 0');
}
// Parse dates and set time to start of day
$dateDebut = new \DateTime($request->request->get('dateDebut'));
$dateDebut->setTime(0, 0, 0);
$dateFin = new \DateTime($request->request->get('dateFin'));
$dateFin->setTime(0, 0, 0);
if ($dateDebut > $dateFin) {
throw new \InvalidArgumentException('Start date must be before end date');
}
// Check if this is a gas contract by looking up the PDL
$pdl = $request->request->get('pdl');
$isGasContract = false;
if ($pdl) {
$gasMeter = $doctrine->getRepository(GasMeter::class)->findOneBy(['PDL' => $pdl]);
if ($gasMeter) {
$isGasContract = true;
// For gas contracts, adjust the start date
$dateDebut->modify('+1 day');
}
}
// Create a temporary contract object to calculate the value
$contrat = new Contrat();
$contrat->setCar($car);
$contrat->setDateDebut($dateDebut);
$contrat->setDateFin($dateFin);
if ($pdl) {
$contrat->setPdl($pdl);
}
// Calculate the annual value using the pricing service
$value = $this->pricingService->calculateAnnualValue($contrat);
$this->logger->debug('Calculated contract value', [
'car' => $car,
'dateDebut' => $dateDebut->format('d/m/Y'),
'dateFin' => $dateFin->format('d/m/Y'),
'isGasContract' => $isGasContract,
'value' => $value
]);
return new JsonResponse([
'value' => $value,
'debug' => [
'car' => $car,
'dateDebut' => $dateDebut->format('d/m/Y'),
'dateFin' => $dateFin->format('d/m/Y'),
'isGasContract' => $isGasContract
]
]);
} catch (\Exception $e) {
$this->logger->error('Error calculating contract value', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return new JsonResponse(['error' => 'Error calculating value: ' . $e->getMessage()], 500);
}
}
/**
* @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('d/m/Y') : '',
'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 electric meters and their PDLs
$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);
$electric_pdls = array_map(function($meter) {
return $meter->getPDL();
}, $electric_meters);
// Fetch gas meters and their PDLs
$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);
$gas_pdls = array_map(function($meter) {
return $meter->getPDL();
}, $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++) {
$lien = $espace_clients[$i]->getLien();
// Add http:// if no protocol specified
if (!preg_match("~^(?:f|ht)tps?://~i", $lien)) {
$lien = "http://" . $lien;
}
// Extract domain name for button text
$domain = parse_url($lien, PHP_URL_HOST) ?: $lien;
$domainParts = explode('.', $domain);
$buttonText = count($domainParts) > 1 ? $domainParts[1] : $domain;
$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">'.$buttonText.'</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') : '',
"date_signature" => $contrat->getDateSignature() ? $contrat->getDateSignature()->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,
'electric_pdls' => $electric_pdls,
'gas_pdls' => $gas_pdls,
'cspes' => $array_cspes,
'espace_clients' => $array_espace_clients,
'contacts' => $array_contacts,
'contrats' => $array_contrats,
]);
}
/**
* @Route("/entreprise/electric_meter/details/{id}", name="app_electric_meter_details")
*/
public function electricMeterDetails(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);
}
// Find the electric meter using standard findOneBy method
$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(),
'PDL' => $electricMeter->getPDL(),
'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);
}
// Find the gas meter using standard findOneBy method
$gasMeter = $doctrine->getRepository(GasMeter::class)->findOneBy([
'entreprise_id' => $id,
'PDL' => $pdl
]);
if (!$gasMeter) {
return new JsonResponse(['error' => 'Gas meter not found'], 404);
}
$meterDetails = [
'adresseCompteur' => $gasMeter->getAdresseCompteur(),
'PDL' => $gasMeter->getPDL(), // Added PDL field
'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());
// For both types, set the dates
$contrat->setDateDebut($meter->getDateDebut());
$contrat->setDateFin($meter->getDateFin());
// Calculate initial duration and value
if ($meter->getDateDebut() && $meter->getDateFin()) {
$dateDebut = $meter->getDateDebut();
if ($dateDebut) {
if ($meterType === 'gas') {
$dateDebut->modify('+1 day');
}
}
$duration = $this->calculateDurationInMonths($dateDebut, $meter->getDateFin());
$contrat->setDuree($duration);
$annualValue = $this->pricingService->calculateAnnualValue($contrat);
$contrat->setValeur($annualValue);
}
}
}
$pdlChoices = $this->getPDLChoicesForEntreprise($doctrine, $entreprise);
$form = $this->createForm(ContratType::class, $contrat, [
'pdl_choices' => $pdlChoices
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Calculate duration in months
$duration = $this->calculateDurationInMonths($contrat->getDateDebut(), $contrat->getDateFin());
$contrat->setDuree($duration);
// Only calculate value if not manually set
$submittedValue = $form->get('valeur')->getData();
if ($submittedValue === null || $submittedValue === 0.0) {
$annualValue = $this->pricingService->calculateAnnualValue($contrat);
$contrat->setValeur($annualValue);
}
// 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();
if ($request->isXmlHttpRequest()) {
return new JsonResponse([
'success' => true,
'contractId' => $contrat->getId(),
'message' => 'Le contrat a été créé avec succès.'
]);
}
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');
}
// Determine if this is a gas contract
$isGasContract = false;
$gasMeter = $doctrine->getRepository(GasMeter::class)->findOneBy([
'entreprise_id' => $entrepriseId,
'PDL' => $contrat->getPdl()
]);
if ($gasMeter) {
$isGasContract = true;
}
// 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);
// For gas contracts, ensure the start date is adjusted
$dateDebut = $contrat->getDateDebut();
if ($dateDebut) {
if ($isGasContract) {
$dateDebut->modify('+1 day');
}
}
// Recalculate duration in months
$duration = $this->calculateDurationInMonths($dateDebut, $contrat->getDateFin());
$contrat->setDuree($duration);
// Only calculate value if not manually set
$submittedValue = $form->get('valeur')->getData();
if ($submittedValue === null || $submittedValue === 0.0) {
$annualValue = $this->pricingService->calculateAnnualValue($contrat);
$contrat->setValeur($annualValue);
}
$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;
}
/**
* @Route("/entreprise/associate-user", name="app_entreprise_associate_user")
*/
public function associateUser(Request $request, EntityManagerInterface $entityManager): Response
{
$this->denyAccessUnlessGranted('ROLE_COMPTA');
try {
$form = $this->createForm(UserEntrepriseType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$user = $data['user'];
$entreprises = $data['entreprises'];
// Vérification des données
if (!$user || !$entreprises || empty($entreprises)) {
throw new \InvalidArgumentException('Utilisateur et entreprises sont requis');
}
// Add ROLE_CLIENT_PRO if user doesn't have it
if (!$user->hasRole('ROLE_CLIENT_PRO')) {
$roles = $user->getRoles();
$roles[] = 'ROLE_CLIENT_PRO';
$user->setRoles(array_unique($roles));
}
// Associate user with enterprises
foreach ($entreprises as $entreprise) {
if (!$user->getEntreprises()->contains($entreprise)) {
$user->addEntreprise($entreprise);
$entreprise->setUtilisateur($user->getId());
}
}
$entityManager->persist($user);
$entityManager->flush();
$this->addFlash('success', sprintf(
'L\'utilisateur %s a été associé avec succès à %d entreprise(s)',
$user->getUsername(),
count($entreprises)
));
return $this->redirectToRoute('app_entreprise');
}
return $this->render('entreprise/associate_user.html.twig', [
'form' => $form->createView(),
]);
} catch (\Exception $e) {
$this->addFlash('error', 'Une erreur est survenue lors de l\'association : ' . $e->getMessage());
return $this->redirectToRoute('app_entreprise_associate_user');
}
}
}