src/Controller/DocumentController.php line 49

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use App\Entity\Entreprise;
  5. use App\Entity\Contact;
  6. use App\Entity\ElectricMeter;
  7. use App\Entity\GasMeter;
  8. use App\Entity\User;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\HttpFoundation\JsonResponse;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Contracts\HttpClient\HttpClientInterface;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\IOFactory;
  16. use Dompdf\Dompdf;
  17. use Dompdf\Options;
  18. class DocumentController extends AbstractController
  19. {
  20.     private $httpClient;
  21.     public function __construct(HttpClientInterface $httpClient)
  22.     {
  23.         $this->httpClient $httpClient;
  24.     }
  25.     /**
  26.      * @Route("/document", name="app_document")
  27.      */
  28.     public function index(): Response
  29.     {
  30.         $entreprises $this->getDoctrine()->getRepository(Entreprise::class)->findBy([], ['RaisonSociale' => 'ASC'] );
  31.         return $this->render('documents/index.html.twig', [
  32.             'controller_name' => 'DocumentController',
  33.             'entreprises' => $entreprises,
  34.         ]);
  35.     }
  36.     /**
  37.      * @Route("/document/filter/{id}", name="app_document_filter")
  38.      */
  39.     public function filter(Request $request$id): JsonResponse
  40.     {
  41.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($id);
  42.         $contacts $this->getDoctrine()->getRepository(Contact::class)->findBy(['entreprise_id' => $id], ['nom' => 'ASC']);
  43.         $electric_meters $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id], ['PDL' => 'ASC']);
  44.         $gas_meters $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id], ['PDL' => 'ASC']);
  45.         $array_contacts = [];
  46.         foreach ($contacts as $contact) {
  47.             $array_contacts[] = [
  48.                 'id' => $contact->getId(),
  49.                 'civilite' => $contact->getCivilite(),
  50.                 'nom' => $contact->getPrenom().' '.$contact->getNom(),
  51.                 'fonction' => $contact->getFonction(),
  52.             ];
  53.         }
  54.         
  55.         $array_electric_meters = [];
  56.         foreach ($electric_meters as $electric_meter) {
  57.             $array_electric_meters[] = [
  58.                 'id' => $electric_meter->getId(),
  59.                 'PDL' => $electric_meter->getPDL(),
  60.                 'adresse_compteur' => $electric_meter->getAdresseCompteur(),
  61.             ];
  62.         }
  63.         $array_gas_meters = [];
  64.         foreach ($gas_meters as $gas_meter) {
  65.             $array_gas_meters[] = [
  66.                 'id' => $gas_meter->getId(),
  67.                 'PDL' => $gas_meter->getPDL(),
  68.                 'adresse_compteur' => $gas_meter->getAdresseCompteur(),
  69.             ];
  70.         }
  71.         // Get all users for this company
  72.         $userIds $entreprise->getUtilisateur();
  73.         
  74.         $user_names = [];
  75.         if (!empty($userIds)) {
  76.             foreach ($userIds as $userId) {
  77.                 $user $this->getDoctrine()->getRepository(User::class)->find((int)$userId);
  78.                 if ($user) {
  79.                     $user_names[] = $user->getUsername();
  80.                 }
  81.             }
  82.         }
  83.         $data = [
  84.             'contacts' => $array_contacts,
  85.             'electric_meters' => $array_electric_meters,
  86.             'gas_meters' => $array_gas_meters,
  87.             'adresse' => [ $entreprise->getNumVoie() . ' ' $entreprise->getAdresse() . ' ' $entreprise->getCodePostal() . ' ' $entreprise->getCommune() ],
  88.             'siret' => [ $entreprise->getSiret() ],
  89.             'naf' => [ $entreprise->getNaf()],
  90.             'rcs' => [ $entreprise->getRcs() ],
  91.             'utilisateur' => $user_names,
  92.         ];
  93.         return new JsonResponse($data);
  94.     }
  95.     // Route pour générer l'autorisation de communication des données de consommation
  96.     /**
  97.      * @Route("/document/acd", name="app_document_acd")
  98.      */
  99.     
  100.      public function acd(Request $request): Response
  101.     {
  102.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  103.         if($request->request->get('contact') != null)
  104.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  105.         else
  106.             $contact null;
  107.         if($request->request->get('electricMeters') != null){
  108.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  109.             $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['PDL' => $requestElectricMeters]);
  110.         }
  111.         else
  112.             $electricMeters null;
  113.         if($request->request->get('gasMeters') != null){
  114.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  115.             $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['PDL' => $requestGasMeters]);
  116.         }
  117.         else
  118.             $gasMeters null;
  119.         $userIds $entreprise->getUtilisateur();
  120.         $user_names = [];
  121.         if (!empty($userIds)) {
  122.             foreach ($userIds as $userId) {
  123.                 $user $this->getDoctrine()->getRepository(User::class)->find((int)$userId);
  124.                 if ($user) {
  125.                     $user_names[] = $user->getUsername();
  126.                 }
  127.             }
  128.         }
  129.         $imagePage1Path $this->getParameter('kernel.project_dir') . '/assets/images/bordure_logo.jpg';
  130.         $imageOtherPath $this->getParameter('kernel.project_dir') . '/assets/images/bordure.jpg';
  131.         $fondBase64Page1 file_exists($imagePage1Path)
  132.             ? 'data:image/jpg;base64,' base64_encode(file_get_contents($imagePage1Path))
  133.             : '';
  134.         $fondBase64Other file_exists($imageOtherPath)
  135.             ? 'data:image/jpg;base64,' base64_encode(file_get_contents($imageOtherPath))
  136.             : '';
  137.         $html $this->renderView('documents/acd_document.html.twig', [
  138.             'entreprise' => $entreprise,
  139.             'contact' => $contact,
  140.             'electricMeters' => $electricMeters,
  141.             'gasMeters' => $gasMeters,
  142.             'date' => (new \DateTime())->format('d/m/Y'),
  143.             'user_names' => $user_names,
  144.             'acd'=> $request->request->get('acd') == "flex" "FLEX ENERGIE" "203 ENERGY S.R.O",
  145.             'fondBase64Page1' => $fondBase64Page1,
  146.             'fondBase64Other' => $fondBase64Other,
  147.         ]);
  148.         $filename sprintf(
  149.             "acd_%s_%s.pdf",
  150.             str_replace([' ''/'], '_'$entreprise->getRaisonSociale()),
  151.             (new \DateTime())->format('Y-m-d')
  152.         );
  153.         $dompdf = new Dompdf();
  154.         $options $dompdf->getOptions();
  155.         $options->set('isHtml5ParserEnabled'true);
  156.         $dompdf->set_option('isPhpEnabled'true);
  157.         $options->set('isRemoteEnabled'true);
  158.         $dompdf->setOptions($options);
  159.         $dompdf->loadHtml($html);
  160.         $dompdf->setPaper('A4''portrait');
  161.         $dompdf->render();
  162.         return new Response($dompdf->output(), 200, [
  163.             'Content-Type' => 'application/pdf',
  164.             'Content-Disposition' => 'attachment; filename="' $filename '"',
  165.         ]);
  166.     }
  167.     // Route pour générer le document Excel de demande d'offre ENGIE
  168.     /**
  169.      * @Route("/document/ics/{engie?}", name="app_document_ics")
  170.      */
  171.     public function ics(Request $request,string $engie=null): Response
  172.     {
  173.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  174.         if($request->request->get('contact') != null)
  175.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  176.         else
  177.             $contact null;
  178.         if($request->request->get('electricMeters') != null){
  179.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  180.             $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $requestElectricMeters]);
  181.         }
  182.         else
  183.             $electricMeters null;
  184.         if($request->request->get('gasMeters') != null){
  185.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  186.             $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findOneBy(['PDL' => $requestGasMeters]);
  187.         }
  188.         else
  189.             $gasMeters null;
  190.         $templatePath $engie $this->getParameter('kernel.project_dir') . '/assets/templates/fiche_ICS_Engie.xlsx' $this->getParameter('kernel.project_dir') . '/assets/templates/fiche_ICS.xlsx';
  191.         $spreadsheet IOFactory::load($templatePath);
  192.         $sheet $spreadsheet->getActiveSheet();
  193.         $contactPhone $contact->getPortable() != null $contact->getPortable() : $contact->getFixe();
  194.         // adresse de l'electricMeters ou gasMeters séparé
  195.         $sheet->setCellValue('B3'$contact->getCivilite());
  196.         $sheet->setCellValue('B4'$contact->getPrenom());
  197.         $sheet->setCellValue('B5'$contact->getNom());
  198.         $sheet->setCellValue('B6'$contact->getFonction());
  199.         $sheet->setCellValue('B7'$contactPhone);
  200.         $sheet->setCellValue('B8'$contact->getEmail());
  201.         $sheet->setCellValue('B10'$entreprise->getRaisonSociale());
  202.         $sheet->setCellValue('B12'$entreprise->getSiret());
  203.         $sheet->setCellValue('B13'$entreprise->getNumVoie());
  204.         $sheet->setCellValue('B14'$entreprise->getAdresse());
  205.         $sheet->setCellValue('B15'$entreprise->getCodePostal());
  206.         $sheet->setCellValue('B16'$entreprise->getCommune());
  207.         // ajout du compteur éléctrique ou gaz
  208.         if($electricMeters != null){
  209.             $sheet->setCellValue('B19'$electricMeters->getPDL());
  210.             $sheet->setCellValue('B20'"Electricité");
  211.             if($electricMeters->getAdresseCompteur() == "/"){
  212.                 $sheet->setCellValue('B22'$entreprise->getNumVoie());
  213.                 $sheet->setCellValue('B23'$entreprise->getAdresse());
  214.                 $sheet->setCellValue('B24'$entreprise->getCodePostal());
  215.                 $sheet->setCellValue('B25'$entreprise->getCommune());
  216.             }
  217.             else{
  218.                 preg_match('/\b\d{5}\b/'$electricMeters->getAdresseCompteur(), $matches);
  219.                 $postal_code $matches[0];
  220.                 $postal_code_position strpos($electricMeters->getAdresseCompteur(), $postal_code);
  221.                 $city trim(substr($electricMeters->getAdresseCompteur(), $postal_code_position strlen($postal_code)));
  222.                 $address_with_no_postal_code_and_city trim(substr($electricMeters->getAdresseCompteur(), 0$postal_code_position));
  223.                 preg_match('/^\d+/'$address_with_no_postal_code_and_city$matches);
  224.                 $street_number $matches[0];
  225.                 $street_name trim(substr($address_with_no_postal_code_and_citystrlen($street_number)));
  226.                 $sheet->setCellValue('B22'$street_number);
  227.                 $sheet->setCellValue('B23'$street_name);
  228.                 $sheet->setCellValue('B24'$postal_code);
  229.                 $sheet->setCellValue('B25'$city);
  230.             }
  231.         }
  232.         else if($gasMeters != null){
  233.             $sheet->setCellValue('B19'$gasMeters->getPDL());
  234.             $sheet->setCellValue('B20'"Gaz");
  235.             if($gasMeters->getAdresseCompteur() == "/"){
  236.                 $sheet->setCellValue('B22'$entreprise->getNumVoie());
  237.                 $sheet->setCellValue('B23'$entreprise->getAdresse());
  238.                 $sheet->setCellValue('B24'$entreprise->getCodePostal());
  239.                 $sheet->setCellValue('B25'$entreprise->getCommune());
  240.             }
  241.             else{
  242.                 preg_match('/\b\d{5}\b/'$gasMeters->getAdresseCompteur(), $matches);
  243.                 $postal_code $matches[0];
  244.                 $postal_code_position strpos($gasMeters->getAdresseCompteur(), $postal_code);
  245.                 $city trim(substr($gasMeters->getAdresseCompteur(), $postal_code_position strlen($postal_code)));
  246.                 $address_with_no_postal_code_and_city trim(substr($gasMeters->getAdresseCompteur(), 0$postal_code_position));
  247.                 preg_match('/^\d+/'$address_with_no_postal_code_and_city$matches);
  248.                 $street_number $matches[0];
  249.                 $street_name trim(substr($address_with_no_postal_code_and_citystrlen($street_number)));
  250.                 $sheet->setCellValue('B22'$street_number);
  251.                 $sheet->setCellValue('B23'$street_name);
  252.                 $sheet->setCellValue('B24'$postal_code);
  253.                 $sheet->setCellValue('B25'$city);
  254.             }
  255.         }
  256.         // Générer la réponse pour le téléchargement du fichier
  257.         $response = new Response();
  258.         $writer IOFactory::createWriter($spreadsheet'Xlsx');
  259.         ob_start();
  260.         $writer->save('php://output');
  261.         $excelData ob_get_contents();
  262.         ob_end_clean();
  263.         // Définir les en-têtes pour le téléchargement
  264.         $RaisonSociale str_replace(' ''_'$entreprise->getRaisonSociale());
  265.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  266.         // Créer un nom de fichier détaillé
  267.         $pdl $electricMeters $electricMeters->getPDL() : ($gasMeters $gasMeters->getPDL() : 'no_pdl');
  268.         $type $engie 'engie' 'standard';
  269.         $energyType $electricMeters 'elec' : ($gasMeters 'gaz' 'no_energy');
  270.         
  271.         $filename sprintf(
  272.             "demande_offre_%s_%s_%s_%s_%s.xlsx",
  273.             $type,
  274.             str_replace([' ''/'], '_'$RaisonSociale),
  275.             $pdl,
  276.             $energyType,
  277.             (new \DateTime())->format('Y-m-d')
  278.         );
  279.         
  280.         $response->headers->set('Content-Disposition''attachment;filename="'.$filename.'"');
  281.         $response->headers->set('Cache-Control''max-age=0');
  282.         // Envoyer le contenu généré en tant que réponse
  283.         $response->setContent($excelData);
  284.         return $response;
  285.     }
  286.     // Route pour générer la lettre de résiliation
  287.     /**
  288.      * @Route("/document/lettre_resi", name="app_document_lettre_resi")
  289.      */
  290.     public function lettre_resi(Request $request): Response
  291.     {
  292.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  293.         if($request->request->get('contact') != null)
  294.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  295.         else
  296.             $contact null;
  297.         if($request->request->get('electricMeters') != null){
  298.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  299.             $electricMeter $this->getDoctrine()->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $requestElectricMeters]);
  300.         }
  301.         else
  302.             $electricMeter null;
  303.         if($request->request->get('gasMeters') != null){
  304.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  305.             $gasMeter $this->getDoctrine()->getRepository(GasMeter::class)->findOneBy(['PDL' => $requestGasMeters]);
  306.         }
  307.         else
  308.             $gasMeter null;
  309.         //génération du pdf en utilisant le template documents/lettre_resi.html.twig et Dompdf
  310.         if($electricMeter != null)
  311.             $PDL $electricMeter->getPDL();
  312.         else if($gasMeter != null)
  313.             $PDL $gasMeter->getPDL();
  314.         else
  315.             $PDL "";
  316.         if($electricMeter != null)
  317.             $DateFin $electricMeter->getDateFin();
  318.         else if($gasMeter != null)
  319.             $DateFin $gasMeter->getDateFin();
  320.         else
  321.             $DateFin null;
  322.         $imagePath $this->getParameter('kernel.project_dir') . '/assets/images/fond_doc.png';
  323.         if (file_exists($imagePath)) {
  324.             $fondBase64 'data:image/png;base64,' base64_encode(file_get_contents($imagePath));
  325.         } else {
  326.             $fondBase64 ''// sécurité : vide si le fichier n'existe pas
  327.         }
  328.         $filename sprintf(
  329.             "lettre_resiliation_%s_%s_%s.pdf",
  330.             str_replace([' ''/'], '_'$entreprise->getRaisonSociale()),
  331.             $PDL,
  332.             (new \DateTime())->format('Y-m-d')
  333.         );
  334.         $dompdf = new Dompdf();
  335.         $dompdf->loadHtml($this->renderView('documents/lettre_resi.html.twig', [
  336.             'entreprise' => $entreprise,
  337.             'contact' => $contact,
  338.             'PDL' => $PDL,
  339.             'DateFin' => ($DateFin != null) ? $DateFin->format('d/m/Y') : "",
  340.             'date' => (new \DateTime())->format('d/m/Y'),
  341.             'fondBase64' => $fondBase64,
  342.         ]));
  343.         $dompdf->setPaper('A4''portrait');
  344.         $dompdf->render();
  345.         
  346.         return new Response($dompdf->output(), 200, [
  347.             'Content-Type' => 'application/pdf',
  348.             'Content-Disposition' => 'attachment; filename="' $filename '"',
  349.         ]);
  350.     }
  351.     /**
  352.      * @Route("/document/mandat", name="app_document_mandat")
  353.      */
  354.     public function mandat(Request $request): Response
  355.     {
  356.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  357.         if($request->request->get('contact') != null)
  358.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  359.         else
  360.             $contact null;
  361.         $adresse $request->request->get('adresse');
  362.         $siret $request->request->get('siret');
  363.         $imagePage1Path $this->getParameter('kernel.project_dir') . '/assets/images/bordure_logo.jpg';
  364.         $fondBase64Page1 file_exists($imagePage1Path)
  365.             ? 'data:image/jpg;base64,' base64_encode(file_get_contents($imagePage1Path))
  366.             : '';
  367.         $filename sprintf(
  368.             "mandat_representant_%s_%s.pdf",
  369.             str_replace([' ''/'], '_'$entreprise->getRaisonSociale()),
  370.             (new \DateTime())->format('Y-m-d')
  371.         );
  372.         $dompdf = new Dompdf();
  373.         $dompdf->loadHtml($this->renderView('documents/mandat.html.twig', [
  374.             'entreprise' => $entreprise,
  375.             'adresse' => $adresse,
  376.             'siret' => $siret,
  377.             'contact' => $contact,
  378.             'date' => (new \DateTime())->format('d/m/Y'),
  379.             'fondBase64Page1' => $fondBase64Page1,
  380.         ]));
  381.         $dompdf->setPaper('A4''portrait');
  382.         $dompdf->render();
  383.         
  384.         return new Response($dompdf->output(), 200, [
  385.             'Content-Type' => 'application/pdf',
  386.             'Content-Disposition' => 'attachment; filename="' $filename '"',
  387.         ]);
  388.     }
  389.     /**
  390.      * @Route("/document/contrat_mission_pdf", name="app_document_contrat_mission")
  391.      */
  392.     public function contratMission(Request $request): Response
  393.     {
  394.     {
  395.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  396.         if($request->request->get('contact') != null)
  397.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  398.         else
  399.             $contact null;
  400.         $adresse $request->request->get('adresse');
  401.         $siret $request->request->get('siret');
  402.         if($request->request->get('electricMeters') != null){
  403.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  404.             $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['PDL' => $requestElectricMeters]);
  405.         }
  406.         else
  407.             $electricMeters null;
  408.         if($request->request->get('gasMeters') != null){
  409.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  410.             $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['PDL' => $requestGasMeters]);
  411.         }
  412.         else
  413.             $gasMeters null;
  414.         $userIds $entreprise->getUtilisateur();
  415.         $user_names = [];
  416.         if (!empty($userIds)) {
  417.             foreach ($userIds as $userId) {
  418.                 $user $this->getDoctrine()->getRepository(User::class)->find((int)$userId);
  419.                 if ($user) {
  420.                     $user_names[] = $user->getUsername();
  421.                 }
  422.             }
  423.         }
  424.         $imagePage1Path $this->getParameter('kernel.project_dir') . '/assets/images/bordure_logo.jpg';
  425.         $imageOtherPath $this->getParameter('kernel.project_dir') . '/assets/images/bordure.jpg';
  426.         $fondBase64Page1 file_exists($imagePage1Path)
  427.             ? 'data:image/jpg;base64,' base64_encode(file_get_contents($imagePage1Path))
  428.             : '';
  429.         $fondBase64Other file_exists($imageOtherPath)
  430.             ? 'data:image/jpg;base64,' base64_encode(file_get_contents($imageOtherPath))
  431.             : '';
  432.         $logoPath $this->getParameter('kernel.project_dir') . '/assets/images/image4.png';
  433.         $logoBase64 '';
  434.         if (file_exists($logoPath)) {
  435.             $logoBase64 'data:image/png;base64,' base64_encode(file_get_contents($logoPath));
  436.         }
  437.         $html $this->renderView('documents/contrat_mission.html.twig', [
  438.             'entreprise' => $entreprise,
  439.             'contact' => $contact,
  440.             'adresse' => $adresse,
  441.             'siret' => $siret,
  442.             'electricMeters' => $electricMeters,
  443.             'gasMeters' => $gasMeters,
  444.             'user_names' => $user_names,
  445.             'date' => (new \DateTime())->format('d/m/Y'),
  446.             'fondBase64Page1' => $fondBase64Page1,
  447.             'fondBase64Other' => $fondBase64Other,
  448.             'logoBase64' => $logoBase64,
  449.         ]);
  450.             
  451.         $filename sprintf(
  452.             "contrat_seul_%s_%s.pdf",
  453.             str_replace([' ''/'], '_'$entreprise->getRaisonSociale()),
  454.             (new \DateTime())->format('Y-m-d')
  455.         );
  456.         $options = new Options();
  457.         $options->set('defaultFont''DejaVu Sans');
  458.         $options->set('isFontSubsettingEnabled'true);
  459.         $options->set('isHtml5ParserEnabled'true);
  460.         $options->set('isRemoteEnabled'true);
  461.         $dompdf = new Dompdf($options);
  462.         $dompdf->loadHtml($html'UTF-8');
  463.         $dompdf->setPaper('A4''portrait');
  464.         $dompdf->render();
  465.         
  466.         // Récupère le canvas
  467.         $canvas $dompdf->getCanvas();
  468.         // Définit la police
  469.         $font $dompdf->getFontMetrics()->getFont('DejaVu Sans''italic');
  470.         $fontSize 7;
  471.         // Définis texte
  472.         $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}';
  473.         // Ajoute un footer sur chaque page
  474.         $canvas->page_script(function ($pageNumber$pageCount$canvas$fontMetrics) use ($font$fontSize$text) {
  475.             $text str_replace(['{PAGE_NUM}''{PAGE_COUNT}'], [$pageNumber$pageCount], $text);
  476.             $width $fontMetrics->getTextWidth($text$font$fontSize);
  477.             $x = ($canvas->get_width() - $width) / 2;
  478.             $y $canvas->get_height() - 30;
  479.             $canvas->text($x$y$text$font$fontSize);
  480.         });
  481.         return new Response($dompdf->output(), 200, [
  482.             'Content-Type' => 'application/pdf',
  483.             'Content-Disposition' => 'attachment; filename="' $filename '"',
  484.         ]);
  485.     }}
  486.     /**
  487.      * @Route("/document/contrat_mission_complet_pdf", name="app_document_contrat_mission_complet")
  488.      */
  489.     public function contratMissionComplet(Request $request): Response
  490.     {
  491.     {
  492.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  493.         if($request->request->get('contact') != null)
  494.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  495.         else
  496.             $contact null;
  497.         $adresse $request->request->get('adresse');
  498.         $siret $request->request->get('siret');
  499.         if($request->request->get('electricMeters') != null){
  500.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  501.             $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['PDL' => $requestElectricMeters]);
  502.         }
  503.         else
  504.             $electricMeters null;
  505.         if($request->request->get('gasMeters') != null){
  506.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  507.             $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['PDL' => $requestGasMeters]);
  508.         }
  509.         else
  510.             $gasMeters null;
  511.         $userIds $entreprise->getUtilisateur();
  512.         $user_names = [];
  513.         if (!empty($userIds)) {
  514.             foreach ($userIds as $userId) {
  515.                 $user $this->getDoctrine()->getRepository(User::class)->find((int)$userId);
  516.                 if ($user) {
  517.                     $user_names[] = $user->getUsername();
  518.                 }
  519.             }
  520.         }
  521.         $imagePage1Path $this->getParameter('kernel.project_dir') . '/assets/images/bordure_logo.jpg';
  522.         $imageOtherPath $this->getParameter('kernel.project_dir') . '/assets/images/bordure.jpg';
  523.         $fondBase64Page1 file_exists($imagePage1Path)
  524.             ? 'data:image/jpg;base64,' base64_encode(file_get_contents($imagePage1Path))
  525.             : '';
  526.         $fondBase64Other file_exists($imageOtherPath)
  527.             ? 'data:image/jpg;base64,' base64_encode(file_get_contents($imageOtherPath))
  528.             : '';
  529.         $logoPath $this->getParameter('kernel.project_dir') . '/assets/images/image4.png';
  530.         $logoBase64 '';
  531.         if (file_exists($logoPath)) {
  532.             $logoBase64 'data:image/png;base64,' base64_encode(file_get_contents($logoPath));
  533.         }
  534.         $html $this->renderView('documents/contrat_mission_complet.html.twig', [
  535.             'entreprise' => $entreprise,
  536.             'contact' => $contact,
  537.             'adresse' => $adresse,
  538.             'siret' => $siret,
  539.             'electricMeters' => $electricMeters,
  540.             'gasMeters' => $gasMeters,
  541.             'user_names' => $user_names,
  542.             'date' => (new \DateTime())->format('d/m/Y'),
  543.             'fondBase64Page1' => $fondBase64Page1,
  544.             'fondBase64Other' => $fondBase64Other,
  545.             'logoBase64' => $logoBase64,
  546.         ]);
  547.         $filename sprintf(
  548.             "contrat_complet_%s_%s.pdf",
  549.             str_replace([' ''/'], '_'$entreprise->getRaisonSociale()),
  550.             (new \DateTime())->format('Y-m-d')
  551.         );
  552.         $options = new Options();
  553.         $options->set('defaultFont''DejaVu Sans');
  554.         $options->set('isFontSubsettingEnabled'true);
  555.         $options->set('isHtml5ParserEnabled'true);
  556.         $options->set('isRemoteEnabled'true);
  557.         $dompdf = new Dompdf($options);
  558.         $dompdf->loadHtml($html'UTF-8');
  559.         $dompdf->setPaper('A4''portrait');
  560.         $dompdf->render();
  561.         // Récupère le canvas
  562.         $canvas $dompdf->getCanvas();
  563.         // Définit la police
  564.         $font $dompdf->getFontMetrics()->getFont('DejaVu Sans''italic');
  565.         $fontSize 7;
  566.         // Définis texte
  567.         $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}';
  568.         // Ajoute un footer sur chaque page
  569.         $canvas->page_script(function ($pageNumber$pageCount$canvas$fontMetrics) use ($font$fontSize$text) {
  570.             $text str_replace(['{PAGE_NUM}''{PAGE_COUNT}'], [$pageNumber$pageCount], $text);
  571.             $width $fontMetrics->getTextWidth($text$font$fontSize);
  572.             $x = ($canvas->get_width() - $width) / 2;
  573.             $y $canvas->get_height() - 30;
  574.             $canvas->text($x$y$text$font$fontSize);
  575.         });
  576.         return new Response($dompdf->output(), 200, [
  577.             'Content-Type' => 'application/pdf',
  578.             'Content-Disposition' => 'attachment; filename="' $filename '"',
  579.         ]);
  580.     }}
  581.     // Route pour générer le document Excel de demande de devis
  582.     /**
  583.      * @Route("/document/devis", name="app_document_devis")
  584.      */
  585.     public function devis(Request $request,string $engie=null): Response
  586.     {
  587.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  588.         if($request->request->get('contact') != null)
  589.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  590.         else
  591.             $contact null;
  592.         if($request->request->get('electricMeters') != null){
  593.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  594.             $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $requestElectricMeters]);
  595.         }
  596.         else
  597.             $electricMeters null;
  598.         if($request->request->get('gasMeters') != null){
  599.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  600.             $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findOneBy(['PDL' => $requestGasMeters]);
  601.         }
  602.         else
  603.         $gasMeters null;
  604.         $templatePath $engie $this->getParameter('kernel.project_dir') . '/assets/templates/devis.xlsx' $this->getParameter('kernel.project_dir') . '/assets/templates/devis.xlsx';
  605.         $spreadsheet IOFactory::load($templatePath);
  606.         // Devis 8L - feuille 1 
  607.         $sheet $spreadsheet->getSheet(0);
  608.         $sheet->setCellValue('F13'$entreprise->getRaisonSociale());
  609.         $sheet->setCellValue('F14'$entreprise->getAdresse());
  610.         $adresseComplete $entreprise->getCodePostal() . ', ' $entreprise->getCommune();
  611.         $sheet->setCellValue('F15'$adresseComplete);
  612.         $sheet->setCellValue('F16'$entreprise->getSiret());
  613.         // Devis 25L - feuille 2
  614.         $sheet $spreadsheet->getSheet(1);
  615.         $sheet->setCellValue('F13'$entreprise->getRaisonSociale());
  616.         $sheet->setCellValue('F14'$entreprise->getAdresse());
  617.         $adresseComplete $entreprise->getCodePostal() . ', ' $entreprise->getCommune();
  618.         $sheet->setCellValue('F15'$adresseComplete);
  619.         $sheet->setCellValue('F16'$entreprise->getSiret());
  620.         // Devis remise 8L - feuille 3 
  621.         $sheet $spreadsheet->getSheet(2);
  622.         $sheet->setCellValue('E13'$entreprise->getRaisonSociale());
  623.         $sheet->setCellValue('E14'$entreprise->getAdresse());
  624.         $adresseComplete $entreprise->getCodePostal() . ', ' $entreprise->getCommune();
  625.         $sheet->setCellValue('E15'$adresseComplete);
  626.         $sheet->setCellValue('E16'$entreprise->getSiret());
  627.         // Devis remise 25L - feuille 4 
  628.         $sheet $spreadsheet->getSheet(3);
  629.         $sheet->setCellValue('E13'$entreprise->getRaisonSociale());
  630.         $sheet->setCellValue('E14'$entreprise->getAdresse());
  631.         $adresseComplete $entreprise->getCodePostal() . ', ' $entreprise->getCommune();
  632.         $sheet->setCellValue('E15'$adresseComplete);
  633.         $sheet->setCellValue('E16'$entreprise->getSiret());
  634.         
  635.         // Générer la réponse pour le téléchargement du fichier
  636.         $response = new Response();
  637.         $writer IOFactory::createWriter($spreadsheet'Xlsx');
  638.         ob_start();
  639.         $writer->save('php://output');
  640.         $excelData ob_get_contents();
  641.         ob_end_clean();
  642.         // Définir les en-têtes pour le téléchargement
  643.         $RaisonSociale str_replace(' ''_'$entreprise->getRaisonSociale());
  644.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  645.         
  646.         $filename sprintf(
  647.             "devis_%s_%s.xlsx",
  648.             str_replace([' ''/'], '_'$RaisonSociale),
  649.             (new \DateTime())->format('Y-m-d')
  650.         );
  651.         
  652.         $response->headers->set('Content-Disposition''attachment;filename="'.$filename.'"');
  653.         $response->headers->set('Cache-Control''max-age=0');
  654.         // Envoyer le contenu généré en tant que réponse
  655.         $response->setContent($excelData);
  656.         return $response;
  657.     }
  658.     /**
  659.      * @Route("/document/contrat_mission_complet/preview/{id}", name="app_document_contrat_mission_complet_preview")
  660.      */
  661.     public function contrat_mission_completPreview(Request $requestint $id): Response
  662.     {
  663.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($id);
  664.         if (!$entreprise) {
  665.             throw $this->createNotFoundException('Entreprise non trouvée.');
  666.         }
  667.         $contact $this->getDoctrine()->getRepository(Contact::class)->findOneBy(['entreprise_id' => $id]);
  668.         $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id]);
  669.         $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id]);
  670.         
  671.         $userIds $entreprise->getUtilisateur();
  672.         $user_names = [];
  673.         if (!empty($userIds)) {
  674.             foreach ($userIds as $userId) {
  675.                 $user $this->getDoctrine()->getRepository(User::class)->find((int)$userId);
  676.                 if ($user) {
  677.                     $user_names[] = $user->getUsername();
  678.                 }
  679.             }
  680.         }
  681.         $imagePage1Path $this->getParameter('kernel.project_dir') . '/assets/images/bordure_logo.jpg';
  682.         $imageOtherPath $this->getParameter('kernel.project_dir') . '/assets/images/bordure.jpg';
  683.         $fondBase64Page1 file_exists($imagePage1Path)
  684.             ? 'data:image/jpg;base64,' base64_encode(file_get_contents($imagePage1Path))
  685.             : '';
  686.         $fondBase64Other file_exists($imageOtherPath)
  687.             ? 'data:image/jpg;base64,' base64_encode(file_get_contents($imageOtherPath))
  688.             : '';
  689.         $logoPath $this->getParameter('kernel.project_dir') . '/assets/images/image4.png';
  690.         $logoBase64 '';
  691.         if (file_exists($logoPath)) {
  692.             $logoBase64 'data:image/png;base64,' base64_encode(file_get_contents($logoPath));
  693.         }
  694.         
  695.         return $this->render('documents/contrat_mission_complet.html.twig', [
  696.             'entreprise' => $entreprise,
  697.             'adresse' => $entreprise->getNumVoie() . ' ' $entreprise->getAdresse() . ' ' $entreprise->getCodePostal() . ' ' $entreprise->getCommune(),
  698.             'siret' => $entreprise->getSiret(),
  699.             'contact' => $contact,
  700.             'electricMeters' => $electricMeters,
  701.             'gasMeters' => $gasMeters,
  702.             'user_names' => $user_names,
  703.             'acd'=> $request->request->get('acd') == "flex" "FLEX ENERGIE" "203 ENERGY S.R.O",
  704.             'fondBase64Page1' => $fondBase64Page1,
  705.             'fondBase64Other' => $fondBase64Other,
  706.             'logoBase64' => $logoBase64,
  707.             'date' => (new \DateTime())->format('d/m/Y'),
  708.         ]);
  709.     }
  710. }