src/Controller/ElectricMeterController.php line 52

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Entreprise;
  4. use App\Entity\ElectricMeter;
  5. use App\Form\ElectricMeterType;
  6. use App\Repository\ElectricMeterRepository;
  7. use Doctrine\Persistence\ManagerRegistry;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use PhpOffice\PhpSpreadsheet\IOFactory;
  16. use Dompdf\Dompdf;
  17. class ElectricMeterController extends AbstractController
  18. {
  19.     /**
  20.      * @Route("/entreprise/electric_meter/add/{id}", name="app_electric_meter_add")
  21.      */
  22.     public function add(int $idRequest $requestEntityManagerInterface $entityManager): Response
  23.     {
  24.         $electric_meters = new ElectricMeter();
  25.         $electric_meters->setEntrepriseId($id);
  26.         $form $this->createForm(ElectricMeterType::class, $electric_meters);
  27.         $form->handleRequest($request);
  28.         if ($form->isSubmitted() && $form->isValid()) {
  29.             $entityManager->persist($electric_meters);
  30.             $entityManager->flush();
  31.             
  32.             // Redirect to the new contract page
  33.             return $this->redirectToRoute('app_entreprise_new_contrat', [
  34.                 'id' => $id,
  35.                 'meterId' => $electric_meters->getId(),
  36.                 'meterType' => 'electric'
  37.             ]);
  38.         }
  39.         return $this->render('entreprise/electric_meter/add.html.twig', [
  40.             'electric_meterForm' => $form->createView(),
  41.             'entreprise_id' => $id
  42.         ]);
  43.     }
  44.     /**
  45.      * @Route("/entreprise/electric_meter/edit/{id}", name="app_electric_meter_edit")
  46.      */
  47.     public function edit(int $idRequest $requestEntityManagerInterface $entityManagerManagerRegistry $doctrine): Response
  48.     {
  49.         $electric_meter $doctrine->getRepository(ElectricMeter::class)->findOneBy(['id' => $id]);
  50.         
  51.         if (!$electric_meter) {
  52.             throw $this->createNotFoundException('Electric meter not found');
  53.         }
  54.         $form $this->createForm(ElectricMeterType::class, $electric_meter);
  55.         $form->handleRequest($request);
  56.         $electric_meter_entity = [ 
  57.             'adresse_compteur' => $electric_meter->getAdresseCompteur(),
  58.             'PDL' => $electric_meter->getPDL(),
  59.             'date_debut' => $electric_meter->getDateDebut() ? date_format($electric_meter->getDateDebut(),"Y-m-d") : "",
  60.             'date_fin' => $electric_meter->getDateFin() ? date_format($electric_meter->getDateFin(),"Y-m-d") : "",
  61.             'PS' => $electric_meter->getPS(),
  62.             'Profil' => $electric_meter->getProfil(),
  63.             'CAR' => $electric_meter->getCAR(),
  64.             'fournisseur' => $electric_meter->getFournisseur(),
  65.             'prix' => $electric_meter->getPrix(),
  66.         ];
  67.         if ($form->isSubmitted() && $form->isValid()) {
  68.             $entityManager->flush();
  69.             return $this->redirectToRoute('app_entreprise_details',['id' => $electric_meter->getEntrepriseId()]);
  70.         }
  71.         return $this->render('entreprise/electric_meter/edit.html.twig', [
  72.             'electric_meterForm' => $form->createView(),
  73.             'electric_meter' => $electric_meter_entity,
  74.             'entreprise_id' => $electric_meter->getEntrepriseId()
  75.         ]);
  76.     }
  77.     /**
  78.      * @Route("/entreprise/electric_meter/suppr/{id}", name="app_electric_meter_suppr")
  79.      */
  80.     public function suppr(int $idRequest $requestEntityManagerInterface $entityManagerManagerRegistry $doctrine): Response
  81.     {
  82.         $electric_meter $doctrine->getRepository(ElectricMeter::class)->findOneBy(['id' => $id]);
  83.         
  84.         if (!$electric_meter) {
  85.             throw $this->createNotFoundException('Electric meter not found');
  86.         }
  87.         $entreprise_id $electric_meter->getEntrepriseId();
  88.         $entityManager->remove($electric_meter);
  89.         $entityManager->flush();
  90.         return $this->redirectToRoute('app_entreprise_details',['id' => $entreprise_id]);
  91.     }
  92.     /**
  93.      * @Route("/entreprise/electric_meter/check_pdl/{pdl}", name="app_electric_meter_check_pdl")
  94.      */
  95.     public function checkPDL($pdlManagerRegistry $doctrine): Response
  96.     {
  97.         $electric_meter $doctrine->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $pdl]);
  98.         if($electric_meter){
  99.             return new Response("exist");
  100.         }
  101.         return new Response("available");
  102.     }
  103.     /**
  104.      * @Route("/entreprise/electric_meter/generate_study/{pdl}/{type}", name="app_electric_meter_generate_study")
  105.      */
  106.     public function generateStudy(string $pdl=nullstring $type=nullManagerRegistry $doctrine): Response
  107.     {
  108.         if (!in_array($type, ['C5''C4'])) {
  109.             throw new \Exception('Type d\'étude non supporté: ' $type);
  110.         }
  111.         $electric_meter $doctrine->getRepository(ElectricMeter::class)->findOneBy(['PDL' => $pdl]);
  112.         
  113.         if (!$electric_meter) {
  114.             throw $this->createNotFoundException('Electric meter not found');
  115.         }
  116.         $entreprise $doctrine->getRepository(Entreprise::class)->findOneBy(['id' => $electric_meter->getEntrepriseId()]);
  117.         
  118.         if (!$entreprise) {
  119.             throw $this->createNotFoundException('Entreprise not found');
  120.         }
  121.         // Use template based on requested type
  122.         if ($type === 'C5') {
  123.             $templatePath $this->getParameter('kernel.project_dir') . '/assets/templates/Résultat d\'étude C5 4 Index.xlsx';
  124.             $studyType 'C5';
  125.         } else {
  126.             $templatePath $this->getParameter('kernel.project_dir') . '/assets/templates/Résultat d\'étude C4_C3_C2 5 Index.xlsx';
  127.             $studyType 'C4_C3_C2';
  128.         }
  129.         // Process address
  130.         $address $electric_meter->getAdresseCompteur() ?? '';
  131.         $address_with_no_postal_code_and_city '';
  132.         $postal_code '';
  133.         $city '';
  134.         if ($address) {
  135.             if (preg_match('/\b\d{5}\b/'$address$matches)) {
  136.                 $postal_code $matches[0];
  137.                 $postal_code_position strpos($address$postal_code);
  138.                 $city trim(substr($address$postal_code_position strlen($postal_code)));
  139.                 $address_with_no_postal_code_and_city trim(substr($address0$postal_code_position));
  140.             }
  141.         }
  142.         // Create temporary file and copy template
  143.         $tempFile tempnam(sys_get_temp_dir(), 'excel');
  144.         copy($templatePath$tempFile);
  145.         
  146.         // Load the copy with specific settings
  147.         $reader IOFactory::createReader('Xlsx');
  148.         $reader->setReadDataOnly(false);
  149.         $reader->setIncludeCharts(true);
  150.         $spreadsheet $reader->load($tempFile);
  151.         
  152.         // Get active sheet
  153.         $sheet $spreadsheet->getActiveSheet();
  154.         // Set values based on study type
  155.         if ($type === 'C4') {
  156.             $sheet->setCellValue('B2'$entreprise->getRaisonSociale() ?? '');
  157.             $sheet->setCellValue('C5'$entreprise->getSIRET() ?? '');
  158.             $sheet->setCellValue('C6'$electric_meter->getPDL() ?? '');
  159.             foreach (['C7''D7''E7''F7''G7'] as $cell) {
  160.                 $sheet->setCellValue($cell$electric_meter->getPS() ?? '');
  161.             }
  162.             $sheet->setCellValue('C8'$electric_meter->getProfil() ?? '');
  163.             $sheet->setCellValue('C11'$address_with_no_postal_code_and_city);
  164.             $sheet->setCellValue('C12', ($postal_code && $city) ? $postal_code ' ' $city '');
  165.             $sheet->setCellValue('H5'$entreprise->getNaf() ?? '');
  166.             $naf $entreprise->getNaf() ?? '';
  167.             $nafNumeric preg_replace('/[^0-9]/'''$naf);
  168.             $sheet->setCellValue('K6'intval($nafNumeric) > 4500 'Oui' 'Non');
  169.             $sheet->setCellValue('K8'$electric_meter->getDateFin() ? date_format($electric_meter->getDateFin(),"d/m/Y") : "");
  170.         } else {
  171.             $sheet->setCellValue('B2'$entreprise->getRaisonSociale() ?? '');
  172.             $sheet->setCellValue('C5'$entreprise->getSIRET() ?? '');
  173.             $sheet->setCellValue('C6'$electric_meter->getPDL() ?? '');
  174.             $sheet->setCellValue('C7'$electric_meter->getPS() ?? '');
  175.             $sheet->setCellValue('C8'$electric_meter->getProfil() ?? '');
  176.             $sheet->setCellValue('C11'$address_with_no_postal_code_and_city);
  177.             $sheet->setCellValue('C12', ($postal_code && $city) ? $postal_code ' ' $city '');
  178.             $sheet->setCellValue('H5'$entreprise->getNaf() ?? '');
  179.             
  180.             // Handle NAF condition (K6)
  181.             $naf $entreprise->getNaf() ?? '';
  182.             $nafNumeric preg_replace('/[^0-9]/'''$naf);
  183.             $sheet->setCellValue('K6'intval($nafNumeric) > 4500 'Oui' 'Non');
  184.             
  185.             $sheet->setCellValue('K8'$electric_meter->getDateFin() ? date_format($electric_meter->getDateFin(),"d/m/Y") : "");
  186.         }
  187.         // Create response
  188.         $response = new Response();
  189.         // Save with specific settings to preserve formulas
  190.         $writer IOFactory::createWriter($spreadsheet'Xlsx');
  191.         $writer->setOffice2003Compatibility(false);
  192.         $writer->setPreCalculateFormulas(false); // Let Excel calculate formulas
  193.         $writer->setIncludeCharts(true);
  194.         
  195.         // Save directly to the original temp file
  196.         $writer->save($tempFile);
  197.         
  198.         // Read the file and clean up
  199.         $excelData file_get_contents($tempFile);
  200.         unlink($tempFile);
  201.         // Set response headers
  202.         $RaisonSociale str_replace(' ''_'$entreprise->getRaisonSociale() ?? 'unknown');
  203.         $pdl_last_4_digits substr($electric_meter->getPDL() ?? '', -4);
  204.         
  205.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  206.         $response->headers->set('Content-Disposition''attachment;filename="Etude_'.$pdl_last_4_digits.'_'.$RaisonSociale.'-'.time().'.xlsx"');
  207.         $response->headers->set('Cache-Control''max-age=0');
  208.         $response->headers->set('Pragma''public');
  209.         
  210.         // Set content and return
  211.         $response->setContent($excelData);
  212.         return $response;
  213.     }
  214. }