<?php
namespace App\Controller;
use App\Repository\EmailInvoiceRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\UsersRepository;
use App\Repository\ArticlesRepository;
use App\Repository\InvoiceDownloadsRepository;
use App\Repository\InvoiceRepository;
use App\Service\S3Service;
use Doctrine\ORM\EntityManagerInterface;
use DateTime;
use App\Service\MailerService;
use App\Entity\Users;
class HomeController extends AbstractController
{
private $mailerService;
/**
* @var Status|MailerService
*/
/**
*
*/
public function __construct(
UsersRepository $usersRepository,
UserPasswordHasherInterface $passwordEncoder,
EntityManagerInterface $em,
MailerService $mailerService,
ArticlesRepository $articlesRepository,
InvoiceDownloadsRepository $invoiceDownloadsRepository,
InvoiceRepository $invoiceRepository,
S3Service $s3Service,
EmailInvoiceRepository $emailInvoiceRepository
)
{
$this->usersRepository = $usersRepository;
$this->mailerService = $mailerService;
$this->passwordEncoder = $passwordEncoder;
$this->em = $em;
$this->articlesRepository = $articlesRepository;
$this->invoiceDownloadsRepository = $invoiceDownloadsRepository;
$this->invoiceRepository = $invoiceRepository;
$this->s3Service = $s3Service;
$this->emailInvoiceRepository = $emailInvoiceRepository;
}
/**
* @Route("/", name="index")
*/
public function index(): Response
{
$user = $this->getUser();
if ($user !== null) {
$roles = $user->getRoles();
if (in_array('ROLE_ACCESS_WEB', $roles)) {
return $this->redirect('/admin');
}
if (in_array('ROLE_CUSTOMER_PLATEFORM', $roles)) {
return $this->redirect('/ecommerce');
}
if (in_array('ROLE_USER', $roles)) {
return $this->redirect('/waiting');
}
}
return $this->redirectToRoute('admin_index');
}
/**
* @Route("/login-d", name="login")
*/
public function login(): Response
{
return $this->render('login.html.twig');
}
/**
* @Route("/recover-pw", name="recover_pw")
*/
public function recoverPw(): Response
{
return $this->render('recoverpw.html.twig');
}
/**
* @Route("/pdf-news-full", name="admin_pdf_news_full")
*/
public function pdfNewsFull(): Response
{
return $this->render('PDF_Full.html.twig');
}
/**
* @Route("/reset-pw/{token}", name="reset_pw")
*/
public function resetPw($token): Response
{
return $this->render('resetpw.html.twig', ['token' => $token]);
}
/**
* @Route("/password-generate-code", name="password_generate_code")
*/
public function passwordGenerateCode(Request $request): Response
{
$user = $this->usersRepository->findOneBy(['email'=>$request->get('email'), 'deleted'=>false]);
$random = random_int(1000, 9999);
$date = new DateTime();
if ($user !== null) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$token1 = '';
$token2= '';
for ($i = 0; $i < 5; $i++) {
$token1 .= $characters[rand(0, $charactersLength - 1)];
}
for ($i = 0; $i < 5; $i++) {
$token2 .= $characters[rand(0, $charactersLength - 1)];
}
$token = $token1 . $user->getId() . $token2;
$user->setNewPasswordToken($token);
$user->setNewPasswordCode($random);
$user->setNewPasswordCreatedAt($date);
$this->em->persist($user);
$this->em->flush();
$params = [
'code' => $random
];
$this->mailerService->load(
$params,
'd-bc246c84331d4d749634ac496a62751a',
$user
);
return new JsonResponse([
'data'=>[
'text'=>'success',
'token' => $user->getNewPasswordToken()
]
]);
}
else{
return new JsonResponse([
'data'=>[
'text'=>'error'
]
]);
}
}
/**
* @Route("/email-verification/{token}", name="email_verification")
*/
public function emailVerification($token): Response
{
$user = $this->usersRepository->findOneBy(['emailValidationToken'=>$token]);
if($user){
$user->setEmailValidated(true);
$this->em->persist($user);
$this->em->flush();
return $this->render('verified-email.html.twig',[
'text1' => "Votre email a été bien verifié",
'text2' => "Merci !",
]); }
else{
return $this->render('verified-email.html.twig',[
'text1' => "Erreur lors de la vérification de votre email",
'text2' => "Veuillez réessayer...",
]);
}
}
/**
* @Route("/recover-pw-confirm/{token}", name="recover_pw_confirm")
*/
public function recoverPwConfirm($token): Response
{
return $this->render('recoverpw-confirm.html.twig', ['token'=>$token]);
}
/**
* @Route("/recover-pw-verify-code", name="recover_pw_verify-code")
*/
public function recoverPwVerifyCode(Request $request): Response
{
$user = $this->usersRepository->findOneBy(['newPasswordToken'=>$request->get('token'), 'deleted' => false]);
$paswordTime=$user->getNewPasswordCreatedAt();
$date = new DateTime();
$timeNow = $date;
$diff = date_diff($timeNow, $paswordTime);
if($diff->format('%h%i') < 11){
if($user->getNewPasswordCode() == $request->get('code')){
return new JsonResponse(['comment' => 'code ok'], Response::HTTP_OK);
}
else{
return new JsonResponse(['comment' => 'wrong code'], Response::HTTP_BAD_REQUEST);
}
}
return new JsonResponse(['comment' => 'user not found'], Response::HTTP_FORBIDDEN);
}
/**
* @Route("/password-generate-new", name="password_generate_new")
*/
public function passwordGenerateNew(Request $request): Response
{
$user = $this->usersRepository->findOneBy(['newPasswordToken'=>$request->get('token'), 'deleted' => false]);
$user->setPassword($this->passwordEncoder->hashPassword($user, $request->get('password')));
$user->setNewPasswordToken(NULL);
$this->em->persist($user);
$this->em->flush();
return new JsonResponse(['comment' => 'password update'], Response::HTTP_OK);
}
/**
* @Route("/download-invoice-range/{id}/{token}", name="downalod_invoice_range")
*/
public function downlaodInvoiceRange(int $id, string $token): Response
{
$invoiceDownload = $this->invoiceDownloadsRepository->find($id);
if (!$invoiceDownload)
return new Response('Invoices not found', Response::HTTP_NOT_FOUND);
else if ($invoiceDownload->getToken() !== $token)
return new Response('Tokens do not match', Response::HTTP_CONFLICT);
else if ($invoiceDownload->isDeleted())
return new Response('This link expired', Response::HTTP_UNAUTHORIZED);
$link = $_ENV['DOMAIN_EMAIL'] . "download-zip-invoices/" . $invoiceDownload->getId() . "/" . $invoiceDownload->getToken();
return $this->render('downloadInvoices.html.twig', [
"range" => true,
"link" => $link
]);
}
/**
* @Route("download-invoice/{id}/{token}", name="download_invoice")
*/
public function downloadInvoice(int $id, string $token): Response
{
$emailInvoice = $this->emailInvoiceRepository->find($id);
if (!$emailInvoice)
return new Response('Invoice not found', Response::HTTP_NOT_FOUND);
else if ($emailInvoice->getToken() !== $token)
return new Response('Tokens do not match', Response::HTTP_CONFLICT);
else if ($emailInvoice->isDeleted())
return new Response('No pdf file found for this invoice.', Response::HTTP_NOT_FOUND);
else if (!$emailInvoice->getInvoice()->getPdfName())
return new Response('No pdf file found for this invoice.', Response::HTTP_NOT_FOUND);
$link = $_ENV['DOMAIN_EMAIL'] . "download-pdf-invoice/" . $emailInvoice->getId() . "/" . $emailInvoice->getToken();
return $this->render('downloadInvoices.html.twig', [
"range" => false,
"link" => $link
]);
}
/**
* @Route("/download-zip-invoices/{id}/{token}", name="download_zip_invoices")
*/
public function downloadZipInvoices(int $id, string $token): Response
{
$invoiceDownload = $this->invoiceDownloadsRepository->find($id);
if (!$invoiceDownload)
return new Response('Invoices not found', Response::HTTP_NOT_FOUND);
else if ($invoiceDownload->getToken() !== $token)
return new Response('Tokens do not match', Response::HTTP_CONFLICT);
else if ($invoiceDownload->isDeleted())
return new Response('This link expired', Response::HTTP_UNAUTHORIZED);
$invoices = $this->invoiceRepository->findInvoicesBetween(
$invoiceDownload->getEstablishment(),
$invoiceDownload->getStartDate(),
$invoiceDownload->getEndDate()
);
$invoices = array_filter($invoices, function ($invoice) {
return $invoice->getPdfName();
});
$zipFilePath = tempnam(sys_get_temp_dir(), 'invoices_zip');
$zip = new \ZipArchive();
if ($zip->open($zipFilePath, \ZipArchive::CREATE) === true)
{
foreach ($invoices as $invoice)
{
$invoiceUrl = $this->s3Service->getViewInvoice($invoice->getPdfName());
$pdfContent = file_get_contents($invoiceUrl);
if ($pdfContent !== false)
$zip->addFromString("invoice_{$invoice->getIdPunch()}.pdf", $pdfContent);
}
$zip->close();
}
$response = new BinaryFileResponse($zipFilePath);
$response->headers->set('Content-Type', 'application/zip');
$response->headers->set('Content-Disposition', 'attachment; filename="invoices.zip"');
return $response;
}
/**
* @Route ("/download-pdf-invoice/{id}/{token}", name="download_pdf_invoice")
*/
public function downloadPdfInvoice(int $id, string $token): Response
{
$emailInvoice = $this->emailInvoiceRepository->find($id);
if (!$emailInvoice)
return new Response('Invoice not found', Response::HTTP_NOT_FOUND);
else if ($emailInvoice->getToken() !== $token)
return new Response('Tokens do not match', Response::HTTP_CONFLICT);
else if ($emailInvoice->isDeleted())
return new Response('This link expired', Response::HTTP_UNAUTHORIZED);
else if (!$emailInvoice->getInvoice()->getPdfName())
return new Response('No pdf file found for this invoice.', Response::HTTP_NOT_FOUND);
$invoice = $emailInvoice->getInvoice();
$invoiceUrl = $this->s3Service->getViewInvoice($invoice->getPdfName());
$response = new StreamedResponse(function () use ($invoiceUrl) {
readfile($invoiceUrl);
});
$response->headers->set('Content-Type', 'application/pdf');
$response->headers->set('Content-Disposition', 'attachment; filename="invoice_' . $invoice->getIdPunch() . '.pdf"');
return $response;
}
/**
* @Route("/waiting", name="admin_waiting")
*/
public function blocked(): Response
{
$user = $this->getUser();
if ($user !== null) {
$roles = $user->getRoles();
if (in_array('ROLE_CUSTOMER_PLATEFORM', $roles)) {
return $this->redirect('/ecommerce');
}
}
return $this->render('waiting.html.twig');
}
}