<?php
namespace App\Controller;
use App\Entity\Invoice;
use App\Repository\InvoiceRepository;
use App\Repository\UserRepository;
use App\Service\ApiOVHClient;
use App\Service\FileUploader;
use App\Service\FtpService;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
use Vich\UploaderBundle\Handler\UploadHandler;
class DefaultController extends AbstractController
{
public function __construct(
private Security $security,
private UrlGeneratorInterface $router,
private EntityManagerInterface $em,
private RequestStack $requestStack,
private ApiOVHClient $apiOVHClient,
private EntityManagerInterface $entityManager,
private UploadHandler $uploadHandler,
private ContainerInterface $containers,
)
{
}
#[Route('/api/ovh', name: 'test_api_ovh', methods: ['GET'])]
public function indexApiOvh(): Response
{
// Demander les informations d'identification
$credentials = $this->apiOVHClient->requestCredentials();
$validationUrl = $this->apiOVHClient->getValidationUrl($credentials);
// Rediriger l'utilisateur vers la page de validation
return $this->redirect($validationUrl);
//return $this->render('default/access_denied.html.twig');
}
#[Route('/', name: 'app_default')]
#[IsGranted("ROLE_USER")]
public function index(InvoiceRepository $invoiceRepository, UserRepository $userRepository): Response
{
/* $role = 'ROLE_SUPER_ADMIN';
$this->denyAccessUnlessGranted($role, null, 'Tentative d\'accès non autorisé au rôle ' . $role);*/
$countAll = $invoiceRepository->countAllInvoices();
$countUsers = $userRepository->countAllUsers();
return $this->render('default/index.html.twig', [
'countAll' => $countAll,
'countUsers' => $countUsers,
]);
}
#[Route('/tableauBord/access_denied', name: 'tableauBord_access_denied', methods: ['GET'])]
public function accessDenied(): Response
{
return $this->render('default/access_denied.html.twig');
}
#[Route('/callBack/ovhautorisation', name: 'app_callback_ovhautorisation')]
public function callbackAction()
{
// Récupérer les informations d'autorisation dans la session
$credentials = $this->apiOVHClient->getStoredCredentials();
// Vérifier si les informations d'autorisation existent
if ($credentials !== null) {
// Appel à l'API OVH pour récupérer les factures
$bills = $this->apiOVHClient->getBillDetails($credentials);
// Vérifier si la réponse est une redirection
if ($bills instanceof RedirectResponse) {
// Obtenir l'URL cible de la redirection
$targetUrl = $bills->getTargetUrl();
// Effectuer des actions avant la redirection, si nécessaire
// Rediriger vers l'URL cible
return new RedirectResponse($targetUrl);
}
foreach ($bills as $invoice) {
// Vérifier si le invoice existe déjà en base de données
$existingInvoice = $this->entityManager->getRepository(Invoice::class)->findOneBy(['reference' => $invoice["billId"]]);
if (!$existingInvoice) {
$pdfContent = file_get_contents($invoice["pdfUrl"]);
$tempFileName = tempnam(sys_get_temp_dir(), 'pdf_');
file_put_contents($tempFileName, $pdfContent);
$newInvoice = new Invoice();
$newInvoice->setReference($invoice["billId"]);
$newInvoice->setInvoiceAmount($invoice["priceWithTax"]["value"]);
$newInvoice->setCurrency($invoice["priceWithTax"]["currencyCode"]);
$newInvoice->setFournisseur('OVH');
$newInvoice->setUrlInvoice($invoice["pdfUrl"]);
$invoiceImportDate = new DateTimeImmutable($invoice["date"]);
$newInvoice->setInvoiceImportDate($invoiceImportDate);
$newFileName = $newInvoice->getReference() . '.pdf';
$newFilePath = '../prive/document/transaction/' . $newFileName;
rename($tempFileName, $newFilePath);
$newInvoice->setPdfName($newFileName);
file_put_contents('../prive/document/transaction/' . ($newInvoice->getReference()) . '.pdf', $pdfContent);
$ftpTargetDirectory = '/home/flanypjz/invoice_api';
/* $ftpService = new FtpService();
$ftpService->connect($this->containers->getParameter('ftp_host'), $this->containers->getParameter('ftp_port'), $this->containers->getParameter('ftp_ssL'));
$ftpService->login($this->containers->getParameter('ftp_username'), $this->containers->getParameter('ftp_password'));
$ftpService->put($newFilePath, $ftpTargetDirectory);*/
$this->entityManager->persist($newInvoice);
} else {
// La facture existe déjà, ajouter sa référence au tableau des factures existantes
$existingInvoices[] = $existingInvoice->getReference();
}
}
// Enregistrer les factures dans la base de données
$this->entityManager->flush();
if (!empty($existingInvoices)) {
if (count($existingInvoices) > 1) {
$message = "Les factures de référence suivantes existent déjà : " . implode(", ", $existingInvoices);
$this->addFlash('success', $message);
} elseif (count($existingInvoices) == 1) {
$message = "Le facture de référence suivante existe déjà : " . implode(", ", $existingInvoices);
$this->addFlash('success', $message);
}
// Rediriger vers la page de succès
return $this->redirectToRoute('app_invoice_index');
}
$redirect = $this->router->generate('app_ovhautorisation_confirmation');
return new RedirectResponse($redirect);
}
// Gérer le cas où les informations d'autorisation ne sont pas présentes
// Rediriger l'utilisateur vers une page d'erreur ou autre
$redirect = $this->router->generate('app_ovhautorisation_error');
return new RedirectResponse($redirect);
}
#[Route('/confirmation', name: 'app_ovhautorisation_confirmation')]
public function succesConfirmation()
{
return $this->render('authorized/confirmation.html.twig');
}
#[Route('/error', name: 'app_ovhautorisation_error')]
public function errorConfirmation()
{
return $this->render('authorized/non_autorise.html.twig');
}
public function uploadPdf(string $pdfUrl)
{
$pdfContent = file_get_contents($pdfUrl);
$tempFileName = tempnam(sys_get_temp_dir(), 'pdf_');
file_put_contents($tempFileName, $pdfContent);
$document = new Document();
$document->setPdfFile(new File($tempFileName));
$this->uploadHandler->upload($document, 'pdfFile');
// Vous pouvez ensuite enregistrer l'entité Document dans la base de données
// ...
}
}