src/Controller/DocumentController.php line 48

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.         $array_electric_meters = [];
  55.         foreach ($electric_meters as $electric_meter) {
  56.             $array_electric_meters[] = [
  57.                 'id'               => $electric_meter->getId(),
  58.                 'PDL'              => $electric_meter->getPDL(),
  59.                 'adresse_compteur' => $electric_meter->getAdresseCompteur(),
  60.             ];
  61.         }
  62.         $array_gas_meters = [];
  63.         foreach ($gas_meters as $gas_meter) {
  64.             $array_gas_meters[] = [
  65.                 'id'               => $gas_meter->getId(),
  66.                 'PDL'              => $gas_meter->getPDL(),
  67.                 'adresse_compteur' => $gas_meter->getAdresseCompteur(),
  68.             ];
  69.         }
  70.         // utilisation du helper pour les utilisateurs
  71.         $user_names $this->getUsernamesForEntreprise($entreprise);
  72.         $data = [
  73.             'contacts'        => $array_contacts,
  74.             'electric_meters' => $array_electric_meters,
  75.             'gas_meters'      => $array_gas_meters,
  76.             'adresse'         => [$entreprise->getNumVoie() . ' ' $entreprise->getAdresse() . ' ' $entreprise->getCodePostal() . ' ' $entreprise->getCommune()],
  77.             'siret'           => [$entreprise->getSiret()],
  78.             'naf'             => [$entreprise->getNaf()],
  79.             'rcs'             => [$entreprise->getRcs()],
  80.             'utilisateur'     => $user_names,
  81.         ];
  82.         return new JsonResponse($data);
  83.     }
  84.     /**
  85.      * @Route("/document/acd", name="app_document_acd")
  86.      */
  87.     public function acd(Request $request): Response
  88.     {
  89.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  90.         if (!$entreprise) {
  91.             throw $this->createNotFoundException('Entreprise non trouvée.');
  92.         }
  93.         $contact null;
  94.         if ($request->request->get('contact') !== null) {
  95.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  96.         }
  97.         $electricMeters null;
  98.         if ($request->request->get('electricMeters') !== null) {
  99.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  100.             $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['PDL' => $requestElectricMeters]);
  101.         }
  102.         $gasMeters null;
  103.         if ($request->request->get('gasMeters') !== null) {
  104.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  105.             $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['PDL' => $requestGasMeters]);
  106.         }
  107.         $user_names $this->getUsernamesForEntreprise($entreprise);
  108.         $fondBase64Page1 $this->getBase64Image('/assets/images/bordure_logo.jpg');
  109.         $fondBase64Other $this->getBase64Image('/assets/images/bordure.jpg');
  110.         $html $this->renderView('documents/acd_document.html.twig', [
  111.             'entreprise'      => $entreprise,
  112.             'contact'         => $contact,
  113.             'electricMeters'  => $electricMeters,
  114.             'gasMeters'       => $gasMeters,
  115.             'date'            => (new \DateTime())->format('d/m/Y'),
  116.             'user_names'      => $user_names,
  117.             'acd'             => $request->request->get('acd') == "flex" "FLEX ENERGIE" "203 ENERGY S.R.O",
  118.             'fondBase64Page1' => $fondBase64Page1,
  119.             'fondBase64Other' => $fondBase64Other,
  120.         ]);
  121.         $filename sprintf(
  122.             "acd_%s_%s.pdf",
  123.             str_replace([' ''/'], '_'$entreprise->getRaisonSociale()),
  124.             (new \DateTime())->format('Y-m-d')
  125.         );
  126.         $dompdf $this->createConfiguredDompdf();
  127.         $dompdf->loadHtml($html'UTF-8');
  128.         $dompdf->setPaper('A4''portrait');
  129.         $dompdf->render();
  130.         return new Response($dompdf->output(), 200, [
  131.             'Content-Type'        => 'application/pdf',
  132.             'Content-Disposition' => 'attachment; filename="' $filename '"',
  133.         ]);
  134.     }
  135.     /**
  136.      * @Route("/document/ics/{engie?}", name="app_document_ics")
  137.      */
  138.     public function ics(Request $requeststring $engie null): Response
  139.     {
  140.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  141.         if (!$entreprise) {
  142.             throw $this->createNotFoundException('Entreprise non trouvée.');
  143.         }
  144.         $contact null;
  145.         if ($request->request->get('contact') !== null) {
  146.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  147.         }
  148.         // Si jamais contact est obligatoire, sinon ton code planterait de toute façon
  149.         if (!$contact) {
  150.             throw $this->createNotFoundException('Contact requis pour le document ICS.');
  151.         }
  152.         $electricMeters null;
  153.         if ($request->request->get('electricMeters') !== null) {
  154.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  155.             $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $requestElectricMeters]);
  156.         }
  157.         $gasMeters null;
  158.         if ($request->request->get('gasMeters') !== null) {
  159.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  160.             $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findOneBy(['PDL' => $requestGasMeters]);
  161.         }
  162.         $templatePath $engie
  163.             $this->getParameter('kernel.project_dir') . '/assets/templates/fiche_ICS_Engie.xlsx'
  164.             $this->getParameter('kernel.project_dir') . '/assets/templates/fiche_ICS.xlsx';
  165.         $spreadsheet IOFactory::load($templatePath);
  166.         $sheet $spreadsheet->getActiveSheet();
  167.         $contactPhone $contact->getPortable() != null $contact->getPortable() : $contact->getFixe();
  168.         // Infos contact
  169.         $sheet->setCellValue('B3'$contact->getCivilite());
  170.         $sheet->setCellValue('B4'$contact->getPrenom());
  171.         $sheet->setCellValue('B5'$contact->getNom());
  172.         $sheet->setCellValue('B6'$contact->getFonction());
  173.         $sheet->setCellValue('B7'$contactPhone);
  174.         $sheet->setCellValue('B8'$contact->getEmail());
  175.         // Infos entreprise
  176.         $sheet->setCellValue('B10'$entreprise->getRaisonSociale());
  177.         $sheet->setCellValue('B12'$entreprise->getSiret());
  178.         $sheet->setCellValue('B13'$entreprise->getNumVoie());
  179.         $sheet->setCellValue('B14'$entreprise->getAdresse());
  180.         $sheet->setCellValue('B15'$entreprise->getCodePostal());
  181.         $sheet->setCellValue('B16'$entreprise->getCommune());
  182.         // Compteur
  183.         if ($electricMeters !== null) {
  184.             $sheet->setCellValue('B19'$electricMeters->getPDL());
  185.             $sheet->setCellValue('B20'"Electricité");
  186.             if ($electricMeters->getAdresseCompteur() == "/") {
  187.                 $sheet->setCellValue('B22'$entreprise->getNumVoie());
  188.                 $sheet->setCellValue('B23'$entreprise->getAdresse());
  189.                 $sheet->setCellValue('B24'$entreprise->getCodePostal());
  190.                 $sheet->setCellValue('B25'$entreprise->getCommune());
  191.             } else {
  192.                 preg_match('/\b\d{5}\b/'$electricMeters->getAdresseCompteur(), $matches);
  193.                 $postal_code $matches[0];
  194.                 $postal_code_position strpos($electricMeters->getAdresseCompteur(), $postal_code);
  195.                 $city trim(substr($electricMeters->getAdresseCompteur(), $postal_code_position strlen($postal_code)));
  196.                 $address_with_no_postal_code_and_city trim(substr($electricMeters->getAdresseCompteur(), 0$postal_code_position));
  197.                 preg_match('/^\d+/'$address_with_no_postal_code_and_city$matches);
  198.                 $street_number $matches[0];
  199.                 $street_name trim(substr($address_with_no_postal_code_and_citystrlen($street_number)));
  200.                 $sheet->setCellValue('B22'$street_number);
  201.                 $sheet->setCellValue('B23'$street_name);
  202.                 $sheet->setCellValue('B24'$postal_code);
  203.                 $sheet->setCellValue('B25'$city);
  204.             }
  205.         } elseif ($gasMeters !== null) {
  206.             $sheet->setCellValue('B19'$gasMeters->getPDL());
  207.             $sheet->setCellValue('B20'"Gaz");
  208.             if ($gasMeters->getAdresseCompteur() == "/") {
  209.                 $sheet->setCellValue('B22'$entreprise->getNumVoie());
  210.                 $sheet->setCellValue('B23'$entreprise->getAdresse());
  211.                 $sheet->setCellValue('B24'$entreprise->getCodePostal());
  212.                 $sheet->setCellValue('B25'$entreprise->getCommune());
  213.             } else {
  214.                 preg_match('/\b\d{5}\b/'$gasMeters->getAdresseCompteur(), $matches);
  215.                 $postal_code $matches[0];
  216.                 $postal_code_position strpos($gasMeters->getAdresseCompteur(), $postal_code);
  217.                 $city trim(substr($gasMeters->getAdresseCompteur(), $postal_code_position strlen($postal_code)));
  218.                 $address_with_no_postal_code_and_city trim(substr($gasMeters->getAdresseCompteur(), 0$postal_code_position));
  219.                 preg_match('/^\d+/'$address_with_no_postal_code_and_city$matches);
  220.                 $street_number $matches[0];
  221.                 $street_name trim(substr($address_with_no_postal_code_and_citystrlen($street_number)));
  222.                 $sheet->setCellValue('B22'$street_number);
  223.                 $sheet->setCellValue('B23'$street_name);
  224.                 $sheet->setCellValue('B24'$postal_code);
  225.                 $sheet->setCellValue('B25'$city);
  226.             }
  227.         }
  228.         $response = new Response();
  229.         $writer IOFactory::createWriter($spreadsheet'Xlsx');
  230.         ob_start();
  231.         $writer->save('php://output');
  232.         $excelData ob_get_contents();
  233.         ob_end_clean();
  234.         $RaisonSociale str_replace(' ''_'$entreprise->getRaisonSociale());
  235.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  236.         $pdl $electricMeters $electricMeters->getPDL() : ($gasMeters $gasMeters->getPDL() : 'no_pdl');
  237.         $type $engie 'engie' 'standard';
  238.         $energyType $electricMeters 'elec' : ($gasMeters 'gaz' 'no_energy');
  239.         $filename sprintf(
  240.             "demande_offre_%s_%s_%s_%s_%s.xlsx",
  241.             $type,
  242.             str_replace([' ''/'], '_'$RaisonSociale),
  243.             $pdl,
  244.             $energyType,
  245.             (new \DateTime())->format('Y-m-d')
  246.         );
  247.         $response->headers->set('Content-Disposition''attachment;filename="' $filename '"');
  248.         $response->headers->set('Cache-Control''max-age=0');
  249.         $response->setContent($excelData);
  250.         return $response;
  251.     }
  252.     /**
  253.      * @Route("/document/lettre_resi", name="app_document_lettre_resi")
  254.      */
  255.     public function lettre_resi(Request $request): Response
  256.     {
  257.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  258.         if (!$entreprise) {
  259.             throw $this->createNotFoundException('Entreprise non trouvée.');
  260.         }
  261.         $contact null;
  262.         if ($request->request->get('contact') !== null) {
  263.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  264.         }
  265.         $electricMeter null;
  266.         if ($request->request->get('electricMeters') !== null) {
  267.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  268.             $electricMeter $this->getDoctrine()->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $requestElectricMeters]);
  269.         }
  270.         $gasMeter null;
  271.         if ($request->request->get('gasMeters') !== null) {
  272.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  273.             $gasMeter $this->getDoctrine()->getRepository(GasMeter::class)->findOneBy(['PDL' => $requestGasMeters]);
  274.         }
  275.         $PDL "";
  276.         $DateFin null;
  277.         if ($electricMeter !== null) {
  278.             $PDL $electricMeter->getPDL();
  279.             $DateFin $electricMeter->getDateFin();
  280.         } elseif ($gasMeter !== null) {
  281.             $PDL $gasMeter->getPDL();
  282.             $DateFin $gasMeter->getDateFin();
  283.         }
  284.         $fondBase64 $this->getBase64Image('/assets/images/fond_doc.png');
  285.         $filename sprintf(
  286.             "lettre_resiliation_%s_%s_%s.pdf",
  287.             str_replace([' ''/'], '_'$entreprise->getRaisonSociale()),
  288.             $PDL,
  289.             (new \DateTime())->format('Y-m-d')
  290.         );
  291.         $html $this->renderView('documents/lettre_resi.html.twig', [
  292.             'entreprise' => $entreprise,
  293.             'contact'    => $contact,
  294.             'PDL'        => $PDL,
  295.             'DateFin'    => ($DateFin !== null) ? $DateFin->format('d/m/Y') : "",
  296.             'date'       => (new \DateTime())->format('d/m/Y'),
  297.             'fondBase64' => $fondBase64,
  298.         ]);
  299.         $dompdf $this->createConfiguredDompdf();
  300.         $dompdf->loadHtml($html'UTF-8');
  301.         $dompdf->setPaper('A4''portrait');
  302.         $dompdf->render();
  303.         return new Response($dompdf->output(), 200, [
  304.             'Content-Type'        => 'application/pdf',
  305.             'Content-Disposition' => 'attachment; filename="' $filename '"',
  306.         ]);
  307.     }
  308.     /**
  309.      * @Route("/document/mandat", name="app_document_mandat")
  310.      */
  311.     public function mandat(Request $request): Response
  312.     {
  313.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  314.         if (!$entreprise) {
  315.             throw $this->createNotFoundException('Entreprise non trouvée.');
  316.         }
  317.         $contact null;
  318.         if ($request->request->get('contact') !== null) {
  319.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  320.         }
  321.         $adresse $request->request->get('adresse');
  322.         $siret   $request->request->get('siret');
  323.         $fondBase64Page1 $this->getBase64Image('/assets/images/bordure_logo.jpg');
  324.         $filename sprintf(
  325.             "mandat_representant_%s_%s.pdf",
  326.             str_replace([' ''/'], '_'$entreprise->getRaisonSociale()),
  327.             (new \DateTime())->format('Y-m-d')
  328.         );
  329.         $html $this->renderView('documents/mandat.html.twig', [
  330.             'entreprise'      => $entreprise,
  331.             'adresse'         => $adresse,
  332.             'siret'           => $siret,
  333.             'contact'         => $contact,
  334.             'date'            => (new \DateTime())->format('d/m/Y'),
  335.             'fondBase64Page1' => $fondBase64Page1,
  336.         ]);
  337.         $dompdf $this->createConfiguredDompdf();
  338.         $dompdf->loadHtml($html'UTF-8');
  339.         $dompdf->setPaper('A4''portrait');
  340.         $dompdf->render();
  341.         return new Response($dompdf->output(), 200, [
  342.             'Content-Type'        => 'application/pdf',
  343.             'Content-Disposition' => 'attachment; filename="' $filename '"',
  344.         ]);
  345.     }
  346.     /**
  347.      * @Route("/document/contrat_mission_pdf", name="app_document_contrat_mission")
  348.      */
  349.     public function contratMission(Request $request): Response
  350.     {
  351.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  352.         if (!$entreprise) {
  353.             throw $this->createNotFoundException('Entreprise non trouvée.');
  354.         }
  355.         $contact null;
  356.         if ($request->request->get('contact') !== null) {
  357.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  358.         }
  359.         $adresse $request->request->get('adresse');
  360.         $siret   $request->request->get('siret');
  361.         $electricMeters null;
  362.         if ($request->request->get('electricMeters') !== null) {
  363.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  364.             $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['PDL' => $requestElectricMeters]);
  365.         }
  366.         $gasMeters null;
  367.         if ($request->request->get('gasMeters') !== null) {
  368.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  369.             $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['PDL' => $requestGasMeters]);
  370.         }
  371.         $user_names $this->getUsernamesForEntreprise($entreprise);
  372.         $fondBase64Page1 $this->getBase64Image('/assets/images/bordure_logo.jpg');
  373.         $fondBase64Other $this->getBase64Image('/assets/images/bordure.jpg');
  374.         $logoBase64      $this->getBase64Image('/assets/images/image4.png');
  375.         $html $this->renderView('documents/contrat_mission.html.twig', [
  376.             'entreprise'      => $entreprise,
  377.             'contact'         => $contact,
  378.             'adresse'         => $adresse,
  379.             'siret'           => $siret,
  380.             'electricMeters'  => $electricMeters,
  381.             'gasMeters'       => $gasMeters,
  382.             'user_names'      => $user_names,
  383.             'date'            => (new \DateTime())->format('d/m/Y'),
  384.             'fondBase64Page1' => $fondBase64Page1,
  385.             'fondBase64Other' => $fondBase64Other,
  386.             'logoBase64'      => $logoBase64,
  387.         ]);
  388.         $filename sprintf(
  389.             "contrat_seul_%s_%s.pdf",
  390.             str_replace([' ''/'], '_'$entreprise->getRaisonSociale()),
  391.             (new \DateTime())->format('Y-m-d')
  392.         );
  393.         $dompdf $this->createConfiguredDompdf();
  394.         $dompdf->loadHtml($html'UTF-8');
  395.         $dompdf->setPaper('A4''portrait');
  396.         $dompdf->render();
  397.         $canvas $dompdf->getCanvas();
  398.         $font   $dompdf->getFontMetrics()->getFont('DejaVu Sans''italic');
  399.         $fontSize 7;
  400.         $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}';
  401.         $canvas->page_script(function ($pageNumber$pageCount$canvas$fontMetrics) use ($font$fontSize$text) {
  402.             $finalText str_replace(['{PAGE_NUM}''{PAGE_COUNT}'], [$pageNumber$pageCount], $text);
  403.             $width $fontMetrics->getTextWidth($finalText$font$fontSize);
  404.             $x = ($canvas->get_width() - $width) / 2;
  405.             $y $canvas->get_height() - 30;
  406.             $canvas->text($x$y$finalText$font$fontSize);
  407.         });
  408.         return new Response($dompdf->output(), 200, [
  409.             'Content-Type'        => 'application/pdf',
  410.             'Content-Disposition' => 'attachment; filename="' $filename '"',
  411.         ]);
  412.     }
  413.     /**
  414.      * @Route("/document/contrat_mission_complet_pdf", name="app_document_contrat_mission_complet")
  415.      */
  416.     public function contratMissionComplet(Request $request): Response
  417.     {
  418.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  419.         if (!$entreprise) {
  420.             throw $this->createNotFoundException('Entreprise non trouvée.');
  421.         }
  422.         $contact null;
  423.         if ($request->request->get('contact') !== null) {
  424.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  425.         }
  426.         $adresse $request->request->get('adresse');
  427.         $siret   $request->request->get('siret');
  428.         $electricMeters null;
  429.         if ($request->request->get('electricMeters') !== null) {
  430.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  431.             $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['PDL' => $requestElectricMeters]);
  432.         }
  433.         $gasMeters null;
  434.         if ($request->request->get('gasMeters') !== null) {
  435.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  436.             $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['PDL' => $requestGasMeters]);
  437.         }
  438.         $user_names $this->getUsernamesForEntreprise($entreprise);
  439.         $fondBase64Page1 $this->getBase64Image('/assets/images/bordure_logo.jpg');
  440.         $fondBase64Other $this->getBase64Image('/assets/images/bordure.jpg');
  441.         $logoBase64      $this->getBase64Image('/assets/images/image4.png');
  442.         $html $this->renderView('documents/contrat_mission_complet.html.twig', [
  443.             'entreprise'      => $entreprise,
  444.             'contact'         => $contact,
  445.             'adresse'         => $adresse,
  446.             'siret'           => $siret,
  447.             'electricMeters'  => $electricMeters,
  448.             'gasMeters'       => $gasMeters,
  449.             'user_names'      => $user_names,
  450.             'date'            => (new \DateTime())->format('d/m/Y'),
  451.             'fondBase64Page1' => $fondBase64Page1,
  452.             'fondBase64Other' => $fondBase64Other,
  453.             'logoBase64'      => $logoBase64,
  454.         ]);
  455.         $filename sprintf(
  456.             "contrat_complet_%s_%s.pdf",
  457.             str_replace([' ''/'], '_'$entreprise->getRaisonSociale()),
  458.             (new \DateTime())->format('Y-m-d')
  459.         );
  460.         $dompdf $this->createConfiguredDompdf();
  461.         $dompdf->loadHtml($html'UTF-8');
  462.         $dompdf->setPaper('A4''portrait');
  463.         $dompdf->render();
  464.         $canvas $dompdf->getCanvas();
  465.         $font   $dompdf->getFontMetrics()->getFont('DejaVu Sans''italic');
  466.         $fontSize 7;
  467.         $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}';
  468.         $canvas->page_script(function ($pageNumber$pageCount$canvas$fontMetrics) use ($font$fontSize$text) {
  469.             $finalText str_replace(['{PAGE_NUM}''{PAGE_COUNT}'], [$pageNumber$pageCount], $text);
  470.             $width $fontMetrics->getTextWidth($finalText$font$fontSize);
  471.             $x = ($canvas->get_width() - $width) / 2;
  472.             $y $canvas->get_height() - 30;
  473.             $canvas->text($x$y$finalText$font$fontSize);
  474.         });
  475.         return new Response($dompdf->output(), 200, [
  476.             'Content-Type'        => 'application/pdf',
  477.             'Content-Disposition' => 'attachment; filename="' $filename '"',
  478.         ]);
  479.     }
  480.     /**
  481.      * @Route("/document/devis", name="app_document_devis")
  482.      */
  483.     public function devis(Request $requeststring $engie null): Response
  484.     {
  485.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($request->request->get('entreprise'));
  486.         if (!$entreprise) {
  487.             throw $this->createNotFoundException('Entreprise non trouvée.');
  488.         }
  489.         $contact null;
  490.         if ($request->request->get('contact') !== null) {
  491.             $contact $this->getDoctrine()->getRepository(Contact::class)->find($request->request->get('contact'));
  492.         }
  493.         $electricMeters null;
  494.         if ($request->request->get('electricMeters') !== null) {
  495.             $requestElectricMeters explode(','$request->request->get('electricMeters'));
  496.             $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $requestElectricMeters]);
  497.         }
  498.         $gasMeters null;
  499.         if ($request->request->get('gasMeters') !== null) {
  500.             $requestGasMeters explode(','$request->request->get('gasMeters'));
  501.             $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findOneBy(['PDL' => $requestGasMeters]);
  502.         }
  503.         $templatePath $this->getParameter('kernel.project_dir') . '/assets/templates/devis.xlsx';
  504.         $spreadsheet IOFactory::load($templatePath);
  505.         // Devis 8L - feuille 1
  506.         $sheet $spreadsheet->getSheet(0);
  507.         $sheet->setCellValue('F13'$entreprise->getRaisonSociale());
  508.         $sheet->setCellValue('F14'$entreprise->getAdresse());
  509.         $adresseComplete $entreprise->getCodePostal() . ', ' $entreprise->getCommune();
  510.         $sheet->setCellValue('F15'$adresseComplete);
  511.         $sheet->setCellValue('F16'$entreprise->getSiret());
  512.         // Devis 25L - feuille 2
  513.         $sheet $spreadsheet->getSheet(1);
  514.         $sheet->setCellValue('F13'$entreprise->getRaisonSociale());
  515.         $sheet->setCellValue('F14'$entreprise->getAdresse());
  516.         $sheet->setCellValue('F15'$adresseComplete);
  517.         $sheet->setCellValue('F16'$entreprise->getSiret());
  518.         // Devis remise 8L - feuille 3
  519.         $sheet $spreadsheet->getSheet(2);
  520.         $sheet->setCellValue('E13'$entreprise->getRaisonSociale());
  521.         $sheet->setCellValue('E14'$entreprise->getAdresse());
  522.         $sheet->setCellValue('E15'$adresseComplete);
  523.         $sheet->setCellValue('E16'$entreprise->getSiret());
  524.         // Devis remise 25L - feuille 4
  525.         $sheet $spreadsheet->getSheet(3);
  526.         $sheet->setCellValue('E13'$entreprise->getRaisonSociale());
  527.         $sheet->setCellValue('E14'$entreprise->getAdresse());
  528.         $sheet->setCellValue('E15'$adresseComplete);
  529.         $sheet->setCellValue('E16'$entreprise->getSiret());
  530.         $response = new Response();
  531.         $writer IOFactory::createWriter($spreadsheet'Xlsx');
  532.         ob_start();
  533.         $writer->save('php://output');
  534.         $excelData ob_get_contents();
  535.         ob_end_clean();
  536.         $RaisonSociale str_replace(' ''_'$entreprise->getRaisonSociale());
  537.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  538.         $filename sprintf(
  539.             "devis_%s_%s.xlsx",
  540.             str_replace([' ''/'], '_'$RaisonSociale),
  541.             (new \DateTime())->format('Y-m-d')
  542.         );
  543.         $response->headers->set('Content-Disposition''attachment;filename="' $filename '"');
  544.         $response->headers->set('Cache-Control''max-age=0');
  545.         $response->setContent($excelData);
  546.         return $response;
  547.     }
  548.     /**
  549.      * @Route("/document/contrat_mission_complet/preview/{id}", name="app_document_contrat_mission_complet_preview")
  550.      */
  551.     public function contrat_mission_completPreview(Request $requestint $id): Response
  552.     {
  553.         $entreprise $this->getDoctrine()->getRepository(Entreprise::class)->find($id);
  554.         if (!$entreprise) {
  555.             throw $this->createNotFoundException('Entreprise non trouvée.');
  556.         }
  557.         $contact $this->getDoctrine()->getRepository(Contact::class)->findOneBy(['entreprise_id' => $id]);
  558.         $electricMeters $this->getDoctrine()->getRepository(ElectricMeter::class)->findBy(['entreprise_id' => $id]);
  559.         $gasMeters $this->getDoctrine()->getRepository(GasMeter::class)->findBy(['entreprise_id' => $id]);
  560.         $user_names $this->getUsernamesForEntreprise($entreprise);
  561.         $fondBase64Page1 $this->getBase64Image('/assets/images/bordure_logo.jpg');
  562.         $fondBase64Other $this->getBase64Image('/assets/images/bordure.jpg');
  563.         $logoBase64      $this->getBase64Image('/assets/images/image4.png');
  564.         return $this->render('documents/contrat_mission_complet.html.twig', [
  565.             'entreprise'      => $entreprise,
  566.             'adresse'         => $entreprise->getNumVoie() . ' ' $entreprise->getAdresse() . ' ' $entreprise->getCodePostal() . ' ' $entreprise->getCommune(),
  567.             'siret'           => $entreprise->getSiret(),
  568.             'contact'         => $contact,
  569.             'electricMeters'  => $electricMeters,
  570.             'gasMeters'       => $gasMeters,
  571.             'user_names'      => $user_names,
  572.             'acd'             => $request->request->get('acd') == "flex" "FLEX ENERGIE" "203 ENERGY S.R.O",
  573.             'fondBase64Page1' => $fondBase64Page1,
  574.             'fondBase64Other' => $fondBase64Other,
  575.             'logoBase64'      => $logoBase64,
  576.             'date'            => (new \DateTime())->format('d/m/Y'),
  577.         ]);
  578.     }
  579.     /**
  580.      * Retourne la liste des usernames liés à une entreprise
  581.      */
  582.     private function getUsernamesForEntreprise(Entreprise $entreprise): array
  583.     {
  584.         $userIds $entreprise->getUtilisateur();
  585.         $user_names = [];
  586.         if (!empty($userIds)) {
  587.             $userRepo $this->getDoctrine()->getRepository(User::class);
  588.             foreach ($userIds as $userId) {
  589.                 $user $userRepo->find((int) $userId);
  590.                 if ($user) {
  591.                     $user_names[] = $user->getUsername();
  592.                 }
  593.             }
  594.         }
  595.         return $user_names;
  596.     }
  597.     /**
  598.      * Charge une image en base64 avec petit cache en mémoire (pour le process PHP)
  599.      */
  600.     private function getBase64Image(string $relativePath): string
  601.     {
  602.         static $cache = [];
  603.         if (isset($cache[$relativePath])) {
  604.             return $cache[$relativePath];
  605.         }
  606.         $imagePath $this->getParameter('kernel.project_dir') . $relativePath;
  607.         if (!file_exists($imagePath)) {
  608.             return $cache[$relativePath] = '';
  609.         }
  610.         $ext strtolower(pathinfo($imagePathPATHINFO_EXTENSION));
  611.         $mime $ext === 'png' 'image/png' 'image/jpeg';
  612.         $cache[$relativePath] = 'data:' $mime ';base64,' base64_encode(file_get_contents($imagePath));
  613.         return $cache[$relativePath];
  614.     }
  615.     /**
  616.      * Crée un Dompdf préconfiguré
  617.      */
  618.     private function createConfiguredDompdf(): Dompdf
  619.     {
  620.         $options = new Options();
  621.         $options->set('defaultFont''DejaVu Sans');
  622.         $options->set('isFontSubsettingEnabled'true);
  623.         $options->set('isHtml5ParserEnabled'true);
  624.         $options->set('isRemoteEnabled'true);
  625.         return new Dompdf($options);
  626.     }
  627. }