<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Entity\Entreprise;
use App\Entity\Contact;
use App\Entity\ElectricMeter;
use App\Entity\GasMeter;
use App\Entity\User;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Dompdf\Dompdf;
use Dompdf\Options;
class DocumentController extends AbstractController
{
private $httpClient;
public function __construct(HttpClientInterface $httpClient)
{
$this->httpClient = $httpClient;
}
/**
* @Route("/document", name="app_document")
*/
public function index(): Response
{
$entreprises = $this->getDoctrine()->getRepository(Entreprise::class)->findBy([], ['RaisonSociale' => 'ASC'] );
return $this->render('documents/index.html.twig', [
'controller_name' => 'DocumentController',
'entreprises' => $entreprises,
]);
}
/**
* @Route("/document/filter/{id}", name="app_document_filter")
*/
public function filter(Request $request, $id): JsonResponse
{
$entreprise = $this->getDoctrine()->getRepository(Entreprise::class)->find($id);
$contacts = $this->getDoctrine()->getRepository(Contact::class)->findBy(['entreprise_id' => $id], ['nom' => 'ASC']);
$electric_meters = $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id], ['PDL' => 'ASC']);
$gas_meters = $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id], ['PDL' => 'ASC']);
$array_contacts = [];
foreach ($contacts as $contact) {
$array_contacts[] = [
'id' => $contact->getId(),
'civilite' => $contact->getCivilite(),
'nom' => $contact->getPrenom().' '.$contact->getNom(),
'fonction' => $contact->getFonction(),
];
}
$array_electric_meters = [];
foreach ($electric_meters as $electric_meter) {
$array_electric_meters[] = [
'id' => $electric_meter->getId(),
'PDL' => $electric_meter->getPDL(),
'adresse_compteur' => $electric_meter->getAdresseCompteur(),
];
}
$array_gas_meters = [];
foreach ($gas_meters as $gas_meter) {
$array_gas_meters[] = [
'id' => $gas_meter->getId(),
'PDL' => $gas_meter->getPDL(),
'adresse_compteur' => $gas_meter->getAdresseCompteur(),
];
}
// Get all users for this company
$userIds = $entreprise->getUtilisateur();
$user_names = [];
if (!empty($userIds)) {
foreach ($userIds as $userId) {
$user = $this->getDoctrine()->getRepository(User::class)->find((int)$userId);
if ($user) {
$user_names[] = $user->getUsername();
}
}
}
$data = [
'contacts' => $array_contacts,
'electric_meters' => $array_electric_meters,
'gas_meters' => $array_gas_meters,
'adresse' => [ $entreprise->getNumVoie() . ' ' . $entreprise->getAdresse() . ' ' . $entreprise->getCodePostal() . ' ' . $entreprise->getCommune() ],
'siret' => [ $entreprise->getSiret() ],
'naf' => [ $entreprise->getNaf()],
'rcs' => [ $entreprise->getRcs() ],
'utilisateur' => $user_names,
];
return new JsonResponse($data);
}
// Route pour générer l'autorisation de communication des données de consommation
/**
* @Route("/document/acd", name="app_document_acd")
*/
public function acd(Request $request): Response
{
$entreprise = $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
if($request->request->get('contact') != null)
$contact = $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
else
$contact = null;
if($request->request->get('electricMeters') != null){
$requestElectricMeters = explode(',', $request->request->get('electricMeters'));
$electricMeters = $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['PDL' => $requestElectricMeters]);
}
else
$electricMeters = null;
if($request->request->get('gasMeters') != null){
$requestGasMeters = explode(',', $request->request->get('gasMeters'));
$gasMeters = $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['PDL' => $requestGasMeters]);
}
else
$gasMeters = null;
$userIds = $entreprise->getUtilisateur();
$user_names = [];
if (!empty($userIds)) {
foreach ($userIds as $userId) {
$user = $this->getDoctrine()->getRepository(User::class)->find((int)$userId);
if ($user) {
$user_names[] = $user->getUsername();
}
}
}
$imagePage1Path = $this->getParameter('kernel.project_dir') . '/assets/images/bordure_logo.jpg';
$imageOtherPath = $this->getParameter('kernel.project_dir') . '/assets/images/bordure.jpg';
$fondBase64Page1 = file_exists($imagePage1Path)
? 'data:image/jpg;base64,' . base64_encode(file_get_contents($imagePage1Path))
: '';
$fondBase64Other = file_exists($imageOtherPath)
? 'data:image/jpg;base64,' . base64_encode(file_get_contents($imageOtherPath))
: '';
$html = $this->renderView('documents/acd_document.html.twig', [
'entreprise' => $entreprise,
'contact' => $contact,
'electricMeters' => $electricMeters,
'gasMeters' => $gasMeters,
'date' => (new \DateTime())->format('d/m/Y'),
'user_names' => $user_names,
'acd'=> $request->request->get('acd') == "flex" ? "FLEX ENERGIE" : "203 ENERGY S.R.O",
'fondBase64Page1' => $fondBase64Page1,
'fondBase64Other' => $fondBase64Other,
]);
$filename = sprintf(
"acd_%s_%s.pdf",
str_replace([' ', '/'], '_', $entreprise->getRaisonSociale()),
(new \DateTime())->format('Y-m-d')
);
$dompdf = new Dompdf();
$options = $dompdf->getOptions();
$options->set('isHtml5ParserEnabled', true);
$dompdf->set_option('isPhpEnabled', true);
$options->set('isRemoteEnabled', true);
$dompdf->setOptions($options);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
return new Response($dompdf->output(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
]);
}
// Route pour générer le document Excel de demande d'offre ENGIE
/**
* @Route("/document/ics/{engie?}", name="app_document_ics")
*/
public function ics(Request $request,string $engie=null): Response
{
$entreprise = $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
if($request->request->get('contact') != null)
$contact = $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
else
$contact = null;
if($request->request->get('electricMeters') != null){
$requestElectricMeters = explode(',', $request->request->get('electricMeters'));
$electricMeters = $this->getDoctrine()->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $requestElectricMeters]);
}
else
$electricMeters = null;
if($request->request->get('gasMeters') != null){
$requestGasMeters = explode(',', $request->request->get('gasMeters'));
$gasMeters = $this->getDoctrine()->getRepository(GasMeter::class)->findOneBy(['PDL' => $requestGasMeters]);
}
else
$gasMeters = null;
$templatePath = $engie ? $this->getParameter('kernel.project_dir') . '/assets/templates/fiche_ICS_Engie.xlsx' : $this->getParameter('kernel.project_dir') . '/assets/templates/fiche_ICS.xlsx';
$spreadsheet = IOFactory::load($templatePath);
$sheet = $spreadsheet->getActiveSheet();
$contactPhone = $contact->getPortable() != null ? $contact->getPortable() : $contact->getFixe();
// adresse de l'electricMeters ou gasMeters séparé
$sheet->setCellValue('B3', $contact->getCivilite());
$sheet->setCellValue('B4', $contact->getPrenom());
$sheet->setCellValue('B5', $contact->getNom());
$sheet->setCellValue('B6', $contact->getFonction());
$sheet->setCellValue('B7', $contactPhone);
$sheet->setCellValue('B8', $contact->getEmail());
$sheet->setCellValue('B10', $entreprise->getRaisonSociale());
$sheet->setCellValue('B12', $entreprise->getSiret());
$sheet->setCellValue('B13', $entreprise->getNumVoie());
$sheet->setCellValue('B14', $entreprise->getAdresse());
$sheet->setCellValue('B15', $entreprise->getCodePostal());
$sheet->setCellValue('B16', $entreprise->getCommune());
// ajout du compteur éléctrique ou gaz
if($electricMeters != null){
$sheet->setCellValue('B19', $electricMeters->getPDL());
$sheet->setCellValue('B20', "Electricité");
if($electricMeters->getAdresseCompteur() == "/"){
$sheet->setCellValue('B22', $entreprise->getNumVoie());
$sheet->setCellValue('B23', $entreprise->getAdresse());
$sheet->setCellValue('B24', $entreprise->getCodePostal());
$sheet->setCellValue('B25', $entreprise->getCommune());
}
else{
preg_match('/\b\d{5}\b/', $electricMeters->getAdresseCompteur(), $matches);
$postal_code = $matches[0];
$postal_code_position = strpos($electricMeters->getAdresseCompteur(), $postal_code);
$city = trim(substr($electricMeters->getAdresseCompteur(), $postal_code_position + strlen($postal_code)));
$address_with_no_postal_code_and_city = trim(substr($electricMeters->getAdresseCompteur(), 0, $postal_code_position));
preg_match('/^\d+/', $address_with_no_postal_code_and_city, $matches);
$street_number = $matches[0];
$street_name = trim(substr($address_with_no_postal_code_and_city, strlen($street_number)));
$sheet->setCellValue('B22', $street_number);
$sheet->setCellValue('B23', $street_name);
$sheet->setCellValue('B24', $postal_code);
$sheet->setCellValue('B25', $city);
}
}
else if($gasMeters != null){
$sheet->setCellValue('B19', $gasMeters->getPDL());
$sheet->setCellValue('B20', "Gaz");
if($gasMeters->getAdresseCompteur() == "/"){
$sheet->setCellValue('B22', $entreprise->getNumVoie());
$sheet->setCellValue('B23', $entreprise->getAdresse());
$sheet->setCellValue('B24', $entreprise->getCodePostal());
$sheet->setCellValue('B25', $entreprise->getCommune());
}
else{
preg_match('/\b\d{5}\b/', $gasMeters->getAdresseCompteur(), $matches);
$postal_code = $matches[0];
$postal_code_position = strpos($gasMeters->getAdresseCompteur(), $postal_code);
$city = trim(substr($gasMeters->getAdresseCompteur(), $postal_code_position + strlen($postal_code)));
$address_with_no_postal_code_and_city = trim(substr($gasMeters->getAdresseCompteur(), 0, $postal_code_position));
preg_match('/^\d+/', $address_with_no_postal_code_and_city, $matches);
$street_number = $matches[0];
$street_name = trim(substr($address_with_no_postal_code_and_city, strlen($street_number)));
$sheet->setCellValue('B22', $street_number);
$sheet->setCellValue('B23', $street_name);
$sheet->setCellValue('B24', $postal_code);
$sheet->setCellValue('B25', $city);
}
}
// Générer la réponse pour le téléchargement du fichier
$response = new Response();
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
ob_start();
$writer->save('php://output');
$excelData = ob_get_contents();
ob_end_clean();
// Définir les en-têtes pour le téléchargement
$RaisonSociale = str_replace(' ', '_', $entreprise->getRaisonSociale());
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
// Créer un nom de fichier détaillé
$pdl = $electricMeters ? $electricMeters->getPDL() : ($gasMeters ? $gasMeters->getPDL() : 'no_pdl');
$type = $engie ? 'engie' : 'standard';
$energyType = $electricMeters ? 'elec' : ($gasMeters ? 'gaz' : 'no_energy');
$filename = sprintf(
"demande_offre_%s_%s_%s_%s_%s.xlsx",
$type,
str_replace([' ', '/'], '_', $RaisonSociale),
$pdl,
$energyType,
(new \DateTime())->format('Y-m-d')
);
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filename.'"');
$response->headers->set('Cache-Control', 'max-age=0');
// Envoyer le contenu généré en tant que réponse
$response->setContent($excelData);
return $response;
}
// Route pour générer la lettre de résiliation
/**
* @Route("/document/lettre_resi", name="app_document_lettre_resi")
*/
public function lettre_resi(Request $request): Response
{
$entreprise = $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
if($request->request->get('contact') != null)
$contact = $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
else
$contact = null;
if($request->request->get('electricMeters') != null){
$requestElectricMeters = explode(',', $request->request->get('electricMeters'));
$electricMeter = $this->getDoctrine()->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $requestElectricMeters]);
}
else
$electricMeter = null;
if($request->request->get('gasMeters') != null){
$requestGasMeters = explode(',', $request->request->get('gasMeters'));
$gasMeter = $this->getDoctrine()->getRepository(GasMeter::class)->findOneBy(['PDL' => $requestGasMeters]);
}
else
$gasMeter = null;
//génération du pdf en utilisant le template documents/lettre_resi.html.twig et Dompdf
if($electricMeter != null)
$PDL = $electricMeter->getPDL();
else if($gasMeter != null)
$PDL = $gasMeter->getPDL();
else
$PDL = "";
if($electricMeter != null)
$DateFin = $electricMeter->getDateFin();
else if($gasMeter != null)
$DateFin = $gasMeter->getDateFin();
else
$DateFin = null;
$imagePath = $this->getParameter('kernel.project_dir') . '/assets/images/fond_doc.png';
if (file_exists($imagePath)) {
$fondBase64 = 'data:image/png;base64,' . base64_encode(file_get_contents($imagePath));
} else {
$fondBase64 = ''; // sécurité : vide si le fichier n'existe pas
}
$filename = sprintf(
"lettre_resiliation_%s_%s_%s.pdf",
str_replace([' ', '/'], '_', $entreprise->getRaisonSociale()),
$PDL,
(new \DateTime())->format('Y-m-d')
);
$dompdf = new Dompdf();
$dompdf->loadHtml($this->renderView('documents/lettre_resi.html.twig', [
'entreprise' => $entreprise,
'contact' => $contact,
'PDL' => $PDL,
'DateFin' => ($DateFin != null) ? $DateFin->format('d/m/Y') : "",
'date' => (new \DateTime())->format('d/m/Y'),
'fondBase64' => $fondBase64,
]));
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
return new Response($dompdf->output(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
]);
}
/**
* @Route("/document/mandat", name="app_document_mandat")
*/
public function mandat(Request $request): Response
{
$entreprise = $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
if($request->request->get('contact') != null)
$contact = $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
else
$contact = null;
$adresse = $request->request->get('adresse');
$siret = $request->request->get('siret');
$imagePage1Path = $this->getParameter('kernel.project_dir') . '/assets/images/bordure_logo.jpg';
$fondBase64Page1 = file_exists($imagePage1Path)
? 'data:image/jpg;base64,' . base64_encode(file_get_contents($imagePage1Path))
: '';
$filename = sprintf(
"mandat_representant_%s_%s.pdf",
str_replace([' ', '/'], '_', $entreprise->getRaisonSociale()),
(new \DateTime())->format('Y-m-d')
);
$dompdf = new Dompdf();
$dompdf->loadHtml($this->renderView('documents/mandat.html.twig', [
'entreprise' => $entreprise,
'adresse' => $adresse,
'siret' => $siret,
'contact' => $contact,
'date' => (new \DateTime())->format('d/m/Y'),
'fondBase64Page1' => $fondBase64Page1,
]));
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
return new Response($dompdf->output(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
]);
}
/**
* @Route("/document/contrat_mission_pdf", name="app_document_contrat_mission")
*/
public function contratMission(Request $request): Response
{
{
$entreprise = $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
if($request->request->get('contact') != null)
$contact = $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
else
$contact = null;
$adresse = $request->request->get('adresse');
$siret = $request->request->get('siret');
if($request->request->get('electricMeters') != null){
$requestElectricMeters = explode(',', $request->request->get('electricMeters'));
$electricMeters = $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['PDL' => $requestElectricMeters]);
}
else
$electricMeters = null;
if($request->request->get('gasMeters') != null){
$requestGasMeters = explode(',', $request->request->get('gasMeters'));
$gasMeters = $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['PDL' => $requestGasMeters]);
}
else
$gasMeters = null;
$userIds = $entreprise->getUtilisateur();
$user_names = [];
if (!empty($userIds)) {
foreach ($userIds as $userId) {
$user = $this->getDoctrine()->getRepository(User::class)->find((int)$userId);
if ($user) {
$user_names[] = $user->getUsername();
}
}
}
$imagePage1Path = $this->getParameter('kernel.project_dir') . '/assets/images/bordure_logo.jpg';
$imageOtherPath = $this->getParameter('kernel.project_dir') . '/assets/images/bordure.jpg';
$fondBase64Page1 = file_exists($imagePage1Path)
? 'data:image/jpg;base64,' . base64_encode(file_get_contents($imagePage1Path))
: '';
$fondBase64Other = file_exists($imageOtherPath)
? 'data:image/jpg;base64,' . base64_encode(file_get_contents($imageOtherPath))
: '';
$logoPath = $this->getParameter('kernel.project_dir') . '/assets/images/image4.png';
$logoBase64 = '';
if (file_exists($logoPath)) {
$logoBase64 = 'data:image/png;base64,' . base64_encode(file_get_contents($logoPath));
}
$html = $this->renderView('documents/contrat_mission.html.twig', [
'entreprise' => $entreprise,
'contact' => $contact,
'adresse' => $adresse,
'siret' => $siret,
'electricMeters' => $electricMeters,
'gasMeters' => $gasMeters,
'user_names' => $user_names,
'date' => (new \DateTime())->format('d/m/Y'),
'fondBase64Page1' => $fondBase64Page1,
'fondBase64Other' => $fondBase64Other,
'logoBase64' => $logoBase64,
]);
$filename = sprintf(
"contrat_seul_%s_%s.pdf",
str_replace([' ', '/'], '_', $entreprise->getRaisonSociale()),
(new \DateTime())->format('Y-m-d')
);
$options = new Options();
$options->set('defaultFont', 'DejaVu Sans');
$options->set('isFontSubsettingEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
// Récupère le canvas
$canvas = $dompdf->getCanvas();
// Définit la police
$font = $dompdf->getFontMetrics()->getFont('DejaVu Sans', 'italic');
$fontSize = 7;
// Définis texte
$text = 'FLEX ENERGIE SARL au capital de 2000€ immatriculée au RCS de Chalon-sur-Saône au numéro SIRET 91289481300019 – Page {PAGE_NUM} / {PAGE_COUNT}';
// Ajoute un footer sur chaque page
$canvas->page_script(function ($pageNumber, $pageCount, $canvas, $fontMetrics) use ($font, $fontSize, $text) {
$text = str_replace(['{PAGE_NUM}', '{PAGE_COUNT}'], [$pageNumber, $pageCount], $text);
$width = $fontMetrics->getTextWidth($text, $font, $fontSize);
$x = ($canvas->get_width() - $width) / 2;
$y = $canvas->get_height() - 30;
$canvas->text($x, $y, $text, $font, $fontSize);
});
return new Response($dompdf->output(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
]);
}}
/**
* @Route("/document/contrat_mission_complet_pdf", name="app_document_contrat_mission_complet")
*/
public function contratMissionComplet(Request $request): Response
{
{
$entreprise = $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
if($request->request->get('contact') != null)
$contact = $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
else
$contact = null;
$adresse = $request->request->get('adresse');
$siret = $request->request->get('siret');
if($request->request->get('electricMeters') != null){
$requestElectricMeters = explode(',', $request->request->get('electricMeters'));
$electricMeters = $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['PDL' => $requestElectricMeters]);
}
else
$electricMeters = null;
if($request->request->get('gasMeters') != null){
$requestGasMeters = explode(',', $request->request->get('gasMeters'));
$gasMeters = $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['PDL' => $requestGasMeters]);
}
else
$gasMeters = null;
$userIds = $entreprise->getUtilisateur();
$user_names = [];
if (!empty($userIds)) {
foreach ($userIds as $userId) {
$user = $this->getDoctrine()->getRepository(User::class)->find((int)$userId);
if ($user) {
$user_names[] = $user->getUsername();
}
}
}
$imagePage1Path = $this->getParameter('kernel.project_dir') . '/assets/images/bordure_logo.jpg';
$imageOtherPath = $this->getParameter('kernel.project_dir') . '/assets/images/bordure.jpg';
$fondBase64Page1 = file_exists($imagePage1Path)
? 'data:image/jpg;base64,' . base64_encode(file_get_contents($imagePage1Path))
: '';
$fondBase64Other = file_exists($imageOtherPath)
? 'data:image/jpg;base64,' . base64_encode(file_get_contents($imageOtherPath))
: '';
$logoPath = $this->getParameter('kernel.project_dir') . '/assets/images/image4.png';
$logoBase64 = '';
if (file_exists($logoPath)) {
$logoBase64 = 'data:image/png;base64,' . base64_encode(file_get_contents($logoPath));
}
$html = $this->renderView('documents/contrat_mission_complet.html.twig', [
'entreprise' => $entreprise,
'contact' => $contact,
'adresse' => $adresse,
'siret' => $siret,
'electricMeters' => $electricMeters,
'gasMeters' => $gasMeters,
'user_names' => $user_names,
'date' => (new \DateTime())->format('d/m/Y'),
'fondBase64Page1' => $fondBase64Page1,
'fondBase64Other' => $fondBase64Other,
'logoBase64' => $logoBase64,
]);
$filename = sprintf(
"contrat_complet_%s_%s.pdf",
str_replace([' ', '/'], '_', $entreprise->getRaisonSociale()),
(new \DateTime())->format('Y-m-d')
);
$options = new Options();
$options->set('defaultFont', 'DejaVu Sans');
$options->set('isFontSubsettingEnabled', true);
$options->set('isHtml5ParserEnabled', true);
$options->set('isRemoteEnabled', true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($html, 'UTF-8');
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
// Récupère le canvas
$canvas = $dompdf->getCanvas();
// Définit la police
$font = $dompdf->getFontMetrics()->getFont('DejaVu Sans', 'italic');
$fontSize = 7;
// Définis texte
$text = 'FLEX ENERGIE SARL au capital de 2000€ immatriculée au RCS de Chalon-sur-Saône au numéro SIRET 91289481300019 – Page {PAGE_NUM} / {PAGE_COUNT}';
// Ajoute un footer sur chaque page
$canvas->page_script(function ($pageNumber, $pageCount, $canvas, $fontMetrics) use ($font, $fontSize, $text) {
$text = str_replace(['{PAGE_NUM}', '{PAGE_COUNT}'], [$pageNumber, $pageCount], $text);
$width = $fontMetrics->getTextWidth($text, $font, $fontSize);
$x = ($canvas->get_width() - $width) / 2;
$y = $canvas->get_height() - 30;
$canvas->text($x, $y, $text, $font, $fontSize);
});
return new Response($dompdf->output(), 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
]);
}}
// Route pour générer le document Excel de demande de devis
/**
* @Route("/document/devis", name="app_document_devis")
*/
public function devis(Request $request,string $engie=null): Response
{
$entreprise = $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
if($request->request->get('contact') != null)
$contact = $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
else
$contact = null;
if($request->request->get('electricMeters') != null){
$requestElectricMeters = explode(',', $request->request->get('electricMeters'));
$electricMeters = $this->getDoctrine()->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $requestElectricMeters]);
}
else
$electricMeters = null;
if($request->request->get('gasMeters') != null){
$requestGasMeters = explode(',', $request->request->get('gasMeters'));
$gasMeters = $this->getDoctrine()->getRepository(GasMeter::class)->findOneBy(['PDL' => $requestGasMeters]);
}
else
$gasMeters = null;
$templatePath = $engie ? $this->getParameter('kernel.project_dir') . '/assets/templates/devis.xlsx' : $this->getParameter('kernel.project_dir') . '/assets/templates/devis.xlsx';
$spreadsheet = IOFactory::load($templatePath);
// Devis 8L - feuille 1
$sheet = $spreadsheet->getSheet(0);
$sheet->setCellValue('F13', $entreprise->getRaisonSociale());
$sheet->setCellValue('F14', $entreprise->getAdresse());
$adresseComplete = $entreprise->getCodePostal() . ', ' . $entreprise->getCommune();
$sheet->setCellValue('F15', $adresseComplete);
$sheet->setCellValue('F16', $entreprise->getSiret());
// Devis 25L - feuille 2
$sheet = $spreadsheet->getSheet(1);
$sheet->setCellValue('F13', $entreprise->getRaisonSociale());
$sheet->setCellValue('F14', $entreprise->getAdresse());
$adresseComplete = $entreprise->getCodePostal() . ', ' . $entreprise->getCommune();
$sheet->setCellValue('F15', $adresseComplete);
$sheet->setCellValue('F16', $entreprise->getSiret());
// Devis remise 8L - feuille 3
$sheet = $spreadsheet->getSheet(2);
$sheet->setCellValue('E13', $entreprise->getRaisonSociale());
$sheet->setCellValue('E14', $entreprise->getAdresse());
$adresseComplete = $entreprise->getCodePostal() . ', ' . $entreprise->getCommune();
$sheet->setCellValue('E15', $adresseComplete);
$sheet->setCellValue('E16', $entreprise->getSiret());
// Devis remise 25L - feuille 4
$sheet = $spreadsheet->getSheet(3);
$sheet->setCellValue('E13', $entreprise->getRaisonSociale());
$sheet->setCellValue('E14', $entreprise->getAdresse());
$adresseComplete = $entreprise->getCodePostal() . ', ' . $entreprise->getCommune();
$sheet->setCellValue('E15', $adresseComplete);
$sheet->setCellValue('E16', $entreprise->getSiret());
// Générer la réponse pour le téléchargement du fichier
$response = new Response();
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
ob_start();
$writer->save('php://output');
$excelData = ob_get_contents();
ob_end_clean();
// Définir les en-têtes pour le téléchargement
$RaisonSociale = str_replace(' ', '_', $entreprise->getRaisonSociale());
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$filename = sprintf(
"devis_%s_%s.xlsx",
str_replace([' ', '/'], '_', $RaisonSociale),
(new \DateTime())->format('Y-m-d')
);
$response->headers->set('Content-Disposition', 'attachment;filename="'.$filename.'"');
$response->headers->set('Cache-Control', 'max-age=0');
// Envoyer le contenu généré en tant que réponse
$response->setContent($excelData);
return $response;
}
/**
* @Route("/document/contrat_mission_complet/preview/{id}", name="app_document_contrat_mission_complet_preview")
*/
public function contrat_mission_completPreview(Request $request, int $id): Response
{
$entreprise = $this->getDoctrine()->getRepository(Entreprise::class)->find($id);
if (!$entreprise) {
throw $this->createNotFoundException('Entreprise non trouvée.');
}
$contact = $this->getDoctrine()->getRepository(Contact::class)->findOneBy(['entreprise_id' => $id]);
$electricMeters = $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id]);
$gasMeters = $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id]);
$userIds = $entreprise->getUtilisateur();
$user_names = [];
if (!empty($userIds)) {
foreach ($userIds as $userId) {
$user = $this->getDoctrine()->getRepository(User::class)->find((int)$userId);
if ($user) {
$user_names[] = $user->getUsername();
}
}
}
$imagePage1Path = $this->getParameter('kernel.project_dir') . '/assets/images/bordure_logo.jpg';
$imageOtherPath = $this->getParameter('kernel.project_dir') . '/assets/images/bordure.jpg';
$fondBase64Page1 = file_exists($imagePage1Path)
? 'data:image/jpg;base64,' . base64_encode(file_get_contents($imagePage1Path))
: '';
$fondBase64Other = file_exists($imageOtherPath)
? 'data:image/jpg;base64,' . base64_encode(file_get_contents($imageOtherPath))
: '';
$logoPath = $this->getParameter('kernel.project_dir') . '/assets/images/image4.png';
$logoBase64 = '';
if (file_exists($logoPath)) {
$logoBase64 = 'data:image/png;base64,' . base64_encode(file_get_contents($logoPath));
}
return $this->render('documents/contrat_mission_complet.html.twig', [
'entreprise' => $entreprise,
'adresse' => $entreprise->getNumVoie() . ' ' . $entreprise->getAdresse() . ' ' . $entreprise->getCodePostal() . ' ' . $entreprise->getCommune(),
'siret' => $entreprise->getSiret(),
'contact' => $contact,
'electricMeters' => $electricMeters,
'gasMeters' => $gasMeters,
'user_names' => $user_names,
'acd'=> $request->request->get('acd') == "flex" ? "FLEX ENERGIE" : "203 ENERGY S.R.O",
'fondBase64Page1' => $fondBase64Page1,
'fondBase64Other' => $fondBase64Other,
'logoBase64' => $logoBase64,
'date' => (new \DateTime())->format('d/m/Y'),
]);
}
}