src/Controller/DefaultController.php line 57

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Invoice;
  4. use App\Repository\InvoiceRepository;
  5. use App\Repository\UserRepository;
  6. use App\Service\ApiOVHClient;
  7. use App\Service\FileUploader;
  8. use App\Service\FtpService;
  9. use DateTimeImmutable;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Symfony\Component\DependencyInjection\ContainerInterface;
  14. use Symfony\Component\HttpFoundation\File\File;
  15. use Symfony\Component\HttpFoundation\RedirectResponse;
  16. use Symfony\Component\HttpFoundation\RequestStack;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  20. use Symfony\Component\Security\Core\Security;
  21. use Vich\UploaderBundle\Handler\UploadHandler;
  22. class DefaultController extends AbstractController
  23. {
  24.     public function __construct(
  25.         private Security $security,
  26.         private UrlGeneratorInterface $router,
  27.         private EntityManagerInterface $em,
  28.         private RequestStack $requestStack,
  29.         private ApiOVHClient $apiOVHClient,
  30.         private EntityManagerInterface $entityManager,
  31.         private UploadHandler $uploadHandler,
  32.         private ContainerInterface $containers,
  33.     )
  34.     {
  35.     }
  36.     #[Route('/api/ovh'name'test_api_ovh'methods: ['GET'])]
  37.     public function indexApiOvh(): Response
  38.     {
  39.         // Demander les informations d'identification
  40.         $credentials $this->apiOVHClient->requestCredentials();
  41.         $validationUrl $this->apiOVHClient->getValidationUrl($credentials);
  42.         // Rediriger l'utilisateur vers la page de validation
  43.         return $this->redirect($validationUrl);
  44.         //return $this->render('default/access_denied.html.twig');
  45.     }
  46.     #[Route('/'name'app_default')]
  47.     #[IsGranted("ROLE_USER")]
  48.     public function index(InvoiceRepository $invoiceRepositoryUserRepository $userRepository): Response
  49.     {
  50.         /* $role = 'ROLE_SUPER_ADMIN';
  51.          $this->denyAccessUnlessGranted($role, null, 'Tentative d\'accès non autorisé au rôle ' . $role);*/
  52.         $countAll $invoiceRepository->countAllInvoices();
  53.         $countUsers $userRepository->countAllUsers();
  54.         return $this->render('default/index.html.twig', [
  55.             'countAll' => $countAll,
  56.             'countUsers' => $countUsers,
  57.         ]);
  58.     }
  59.     #[Route('/tableauBord/access_denied'name'tableauBord_access_denied'methods: ['GET'])]
  60.     public function accessDenied(): Response
  61.     {
  62.         return $this->render('default/access_denied.html.twig');
  63.     }
  64.     #[Route('/callBack/ovhautorisation'name'app_callback_ovhautorisation')]
  65.     public function callbackAction()
  66.     {
  67.         // Récupérer les informations d'autorisation dans la session
  68.         $credentials $this->apiOVHClient->getStoredCredentials();
  69.         // Vérifier si les informations d'autorisation existent
  70.         if ($credentials !== null) {
  71.             // Appel à l'API OVH pour récupérer les factures
  72.             $bills $this->apiOVHClient->getBillDetails($credentials);
  73.             // Vérifier si la réponse est une redirection
  74.             if ($bills instanceof RedirectResponse) {
  75.                 // Obtenir l'URL cible de la redirection
  76.                 $targetUrl $bills->getTargetUrl();
  77.                 // Effectuer des actions avant la redirection, si nécessaire
  78.                 // Rediriger vers l'URL cible
  79.                 return new RedirectResponse($targetUrl);
  80.             }
  81.             foreach ($bills as $invoice) {
  82.                 // Vérifier si le invoice existe déjà en base de données
  83.                 $existingInvoice $this->entityManager->getRepository(Invoice::class)->findOneBy(['reference' => $invoice["billId"]]);
  84.                 if (!$existingInvoice) {
  85.                     $pdfContent file_get_contents($invoice["pdfUrl"]);
  86.                     $tempFileName tempnam(sys_get_temp_dir(), 'pdf_');
  87.                     file_put_contents($tempFileName$pdfContent);
  88.                     $newInvoice = new Invoice();
  89.                     $newInvoice->setReference($invoice["billId"]);
  90.                     $newInvoice->setInvoiceAmount($invoice["priceWithTax"]["value"]);
  91.                     $newInvoice->setCurrency($invoice["priceWithTax"]["currencyCode"]);
  92.                     $newInvoice->setFournisseur('OVH');
  93.                     $newInvoice->setUrlInvoice($invoice["pdfUrl"]);
  94.                     $invoiceImportDate = new DateTimeImmutable($invoice["date"]);
  95.                     $newInvoice->setInvoiceImportDate($invoiceImportDate);
  96.                     $newFileName $newInvoice->getReference() . '.pdf';
  97.                     $newFilePath '../prive/document/transaction/' $newFileName;
  98.                     rename($tempFileName$newFilePath);
  99.                     $newInvoice->setPdfName($newFileName);
  100.                     file_put_contents('../prive/document/transaction/' . ($newInvoice->getReference()) . '.pdf'$pdfContent);
  101.                     $ftpTargetDirectory '/home/flanypjz/invoice_api';
  102.                    /* $ftpService = new FtpService();
  103.                     $ftpService->connect($this->containers->getParameter('ftp_host'), $this->containers->getParameter('ftp_port'), $this->containers->getParameter('ftp_ssL'));
  104.                     $ftpService->login($this->containers->getParameter('ftp_username'), $this->containers->getParameter('ftp_password'));
  105.                     $ftpService->put($newFilePath, $ftpTargetDirectory);*/
  106.                     $this->entityManager->persist($newInvoice);
  107.                 } else {
  108.                     // La facture existe déjà, ajouter sa référence au tableau des factures existantes
  109.                     $existingInvoices[] = $existingInvoice->getReference();
  110.                 }
  111.             }
  112.             // Enregistrer les factures dans la base de données
  113.             $this->entityManager->flush();
  114.             if (!empty($existingInvoices)) {
  115.                 if (count($existingInvoices) > 1) {
  116.                     $message "Les factures  de référence suivantes existent déjà : " implode(", "$existingInvoices);
  117.                     $this->addFlash('success'$message);
  118.                 } elseif (count($existingInvoices) == 1) {
  119.                     $message "Le facture de référence suivante existe déjà : " implode(", "$existingInvoices);
  120.                     $this->addFlash('success'$message);
  121.                 }
  122.                 // Rediriger vers la page de succès
  123.                 return $this->redirectToRoute('app_invoice_index');
  124.             }
  125.             $redirect $this->router->generate('app_ovhautorisation_confirmation');
  126.             return new RedirectResponse($redirect);
  127.         }
  128.         // Gérer le cas où les informations d'autorisation ne sont pas présentes
  129.         // Rediriger l'utilisateur vers une page d'erreur ou autre
  130.         $redirect $this->router->generate('app_ovhautorisation_error');
  131.         return new RedirectResponse($redirect);
  132.     }
  133.     #[Route('/confirmation'name'app_ovhautorisation_confirmation')]
  134.     public function succesConfirmation()
  135.     {
  136.         return $this->render('authorized/confirmation.html.twig');
  137.     }
  138.     #[Route('/error'name'app_ovhautorisation_error')]
  139.     public function errorConfirmation()
  140.     {
  141.         return $this->render('authorized/non_autorise.html.twig');
  142.     }
  143.     public function uploadPdf(string $pdfUrl)
  144.     {
  145.         $pdfContent file_get_contents($pdfUrl);
  146.         $tempFileName tempnam(sys_get_temp_dir(), 'pdf_');
  147.         file_put_contents($tempFileName$pdfContent);
  148.         $document = new Document();
  149.         $document->setPdfFile(new File($tempFileName));
  150.         $this->uploadHandler->upload($document'pdfFile');
  151.         // Vous pouvez ensuite enregistrer l'entité Document dans la base de données
  152.         // ...
  153.     }
  154. }