src/Controller/HomeController.php line 62

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Repository\EmailInvoiceRepository;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  8. use Symfony\Component\HttpFoundation\StreamedResponse;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use App\Repository\UsersRepository;
  13. use App\Repository\ArticlesRepository;
  14. use App\Repository\InvoiceDownloadsRepository;
  15. use App\Repository\InvoiceRepository;
  16. use App\Service\S3Service;
  17. use Doctrine\ORM\EntityManagerInterface;
  18. use DateTime;
  19. use App\Service\MailerService;
  20. use App\Entity\Users;
  21. class HomeController extends AbstractController
  22. {
  23.     private $mailerService;
  24.     /**
  25.      * @var Status|MailerService
  26.      */
  27.     /**
  28.      *
  29.      */
  30.     public function __construct(
  31.         UsersRepository $usersRepository,
  32.         UserPasswordHasherInterface $passwordEncoder,
  33.         EntityManagerInterface $em,
  34.         MailerService $mailerService,
  35.         ArticlesRepository $articlesRepository,
  36.         InvoiceDownloadsRepository $invoiceDownloadsRepository,
  37.         InvoiceRepository $invoiceRepository,
  38.         S3Service $s3Service,
  39.         EmailInvoiceRepository $emailInvoiceRepository
  40.     )
  41.     {
  42.         $this->usersRepository $usersRepository;
  43.         $this->mailerService $mailerService;
  44.         $this->passwordEncoder $passwordEncoder;
  45.         $this->em $em;
  46.         $this->articlesRepository $articlesRepository;
  47.         $this->invoiceDownloadsRepository $invoiceDownloadsRepository;
  48.         $this->invoiceRepository $invoiceRepository;
  49.         $this->s3Service $s3Service;
  50.         $this->emailInvoiceRepository $emailInvoiceRepository;
  51.     }
  52.     /**
  53.      * @Route("/", name="index")
  54.      */
  55.     public function index(): Response
  56.     {
  57.         $user $this->getUser();
  58.         if ($user !== null) {
  59.             $roles $user->getRoles();
  60.             if (in_array('ROLE_ACCESS_WEB'$roles)) {
  61.                 return $this->redirect('/admin');
  62.             }
  63.             if (in_array('ROLE_CUSTOMER_PLATEFORM'$roles)) {
  64.                 return $this->redirect('/ecommerce');
  65.             }
  66.             if (in_array('ROLE_USER'$roles)) {
  67.                 return $this->redirect('/waiting');
  68.             }
  69.         }
  70.         return $this->redirectToRoute('admin_index');
  71.     }
  72.     /**
  73.      * @Route("/login-d", name="login")
  74.      */
  75.     public function login(): Response
  76.     {
  77.         return $this->render('login.html.twig');
  78.     }
  79.     /**
  80.      * @Route("/recover-pw", name="recover_pw")
  81.      */
  82.     public function recoverPw(): Response
  83.     {
  84.         return $this->render('recoverpw.html.twig');
  85.     }
  86.     /**
  87.      * @Route("/pdf-news-full", name="admin_pdf_news_full")
  88.      */
  89.     public function pdfNewsFull(): Response
  90.     {
  91.         return $this->render('PDF_Full.html.twig');
  92.     }
  93.     /**
  94.      * @Route("/reset-pw/{token}", name="reset_pw")
  95.      */
  96.     public function resetPw($token): Response
  97.     {
  98.         return $this->render('resetpw.html.twig', ['token' => $token]);
  99.     }
  100.     /**
  101.      * @Route("/password-generate-code", name="password_generate_code")
  102.      */
  103.     public function passwordGenerateCode(Request $request): Response
  104.     {
  105.         $user $this->usersRepository->findOneBy(['email'=>$request->get('email'), 'deleted'=>false]);
  106.         $random random_int(10009999);
  107.         $date = new DateTime();
  108.         if ($user !== null) {
  109.             $characters '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  110.             $charactersLength strlen($characters);
  111.             $token1 '';
  112.             $token2'';
  113.             for ($i 0$i 5$i++) {
  114.                 $token1 .= $characters[rand(0$charactersLength 1)];
  115.             }
  116.             for ($i 0$i 5$i++) {
  117.                 $token2 .= $characters[rand(0$charactersLength 1)];
  118.             }
  119.             $token $token1 $user->getId() . $token2;
  120.             $user->setNewPasswordToken($token);
  121.             $user->setNewPasswordCode($random);
  122.             $user->setNewPasswordCreatedAt($date);
  123.             $this->em->persist($user);
  124.             $this->em->flush();
  125.             $params = [
  126.                 'code' => $random
  127.             ];
  128.             $this->mailerService->load(
  129.                 $params,
  130.                 'd-bc246c84331d4d749634ac496a62751a',
  131.                 $user
  132.             );
  133.             return new JsonResponse([
  134.                 'data'=>[
  135.                     'text'=>'success',
  136.                     'token' => $user->getNewPasswordToken()
  137.                 ]
  138.             ]);
  139.         }
  140.         else{
  141.             return new JsonResponse([
  142.                 'data'=>[
  143.                     'text'=>'error'
  144.                 ]
  145.             ]);
  146.         }
  147.     }
  148.     /**
  149.      * @Route("/email-verification/{token}", name="email_verification")
  150.      */
  151.     public function emailVerification($token): Response
  152.     {
  153.         $user $this->usersRepository->findOneBy(['emailValidationToken'=>$token]);
  154.         if($user){
  155.             $user->setEmailValidated(true);
  156.             $this->em->persist($user);
  157.             $this->em->flush();
  158.             return $this->render('verified-email.html.twig',[
  159.                 'text1' => "Votre email a été bien verifié",
  160.                 'text2' => "Merci !",
  161.             ]);        }
  162.         else{
  163.             return $this->render('verified-email.html.twig',[
  164.                 'text1' => "Erreur lors de la vérification de votre email",
  165.                 'text2' => "Veuillez réessayer...",
  166.             ]);
  167.         }
  168.     }
  169.     /**
  170.      * @Route("/recover-pw-confirm/{token}", name="recover_pw_confirm")
  171.      */
  172.     public function recoverPwConfirm($token): Response
  173.     {
  174.         return $this->render('recoverpw-confirm.html.twig', ['token'=>$token]);
  175.     }
  176.     /**
  177.      * @Route("/recover-pw-verify-code", name="recover_pw_verify-code")
  178.      */
  179.     public function recoverPwVerifyCode(Request $request): Response
  180.     {
  181.         $user $this->usersRepository->findOneBy(['newPasswordToken'=>$request->get('token'), 'deleted' => false]);
  182.         $paswordTime=$user->getNewPasswordCreatedAt();
  183.         $date = new DateTime();
  184.         $timeNow $date;
  185.         $diff date_diff($timeNow$paswordTime);
  186.         if($diff->format('%h%i') < 11){
  187.             if($user->getNewPasswordCode() == $request->get('code')){
  188.                 return new JsonResponse(['comment' => 'code ok'], Response::HTTP_OK);
  189.             }
  190.             else{
  191.                 return new JsonResponse(['comment' => 'wrong code'], Response::HTTP_BAD_REQUEST);
  192.             }
  193.         }
  194.         return new JsonResponse(['comment' => 'user not found'], Response::HTTP_FORBIDDEN);
  195.     }
  196.     /**
  197.      * @Route("/password-generate-new", name="password_generate_new")
  198.      */
  199.     public function passwordGenerateNew(Request $request): Response
  200.     {
  201.         $user $this->usersRepository->findOneBy(['newPasswordToken'=>$request->get('token'), 'deleted' => false]);
  202.         $user->setPassword($this->passwordEncoder->hashPassword($user$request->get('password')));
  203.         $user->setNewPasswordToken(NULL);
  204.         $this->em->persist($user);
  205.         $this->em->flush();
  206.         return new JsonResponse(['comment' => 'password update'], Response::HTTP_OK);
  207.     }
  208.     /**
  209.      * @Route("/download-invoice-range/{id}/{token}", name="downalod_invoice_range")
  210.      */
  211.     public function downlaodInvoiceRange(int $idstring $token): Response
  212.     {
  213.         $invoiceDownload $this->invoiceDownloadsRepository->find($id);
  214.         if (!$invoiceDownload)
  215.             return new Response('Invoices not found'Response::HTTP_NOT_FOUND);
  216.         else if ($invoiceDownload->getToken() !== $token)
  217.             return new Response('Tokens do not match'Response::HTTP_CONFLICT);
  218.         else if ($invoiceDownload->isDeleted())
  219.             return new Response('This link expired'Response::HTTP_UNAUTHORIZED);
  220.         $link $_ENV['DOMAIN_EMAIL'] . "download-zip-invoices/" $invoiceDownload->getId() . "/" $invoiceDownload->getToken();
  221.         return $this->render('downloadInvoices.html.twig', [
  222.             "range" => true,
  223.             "link" => $link
  224.         ]);
  225.     }
  226.     /**
  227.      * @Route("download-invoice/{id}/{token}", name="download_invoice")
  228.      */
  229.     public function downloadInvoice(int $idstring $token): Response
  230.     {
  231.         $emailInvoice $this->emailInvoiceRepository->find($id);
  232.         if (!$emailInvoice)
  233.             return new Response('Invoice not found'Response::HTTP_NOT_FOUND);
  234.         else if ($emailInvoice->getToken() !== $token)
  235.             return new Response('Tokens do not match'Response::HTTP_CONFLICT);
  236.         else if ($emailInvoice->isDeleted())
  237.             return new Response('No pdf file found for this invoice.'Response::HTTP_NOT_FOUND);
  238.         else if (!$emailInvoice->getInvoice()->getPdfName())
  239.             return new Response('No pdf file found for this invoice.'Response::HTTP_NOT_FOUND);
  240.         $link $_ENV['DOMAIN_EMAIL'] . "download-pdf-invoice/" $emailInvoice->getId() . "/" $emailInvoice->getToken();
  241.         return $this->render('downloadInvoices.html.twig', [
  242.             "range" => false,
  243.             "link" => $link
  244.         ]);
  245.     }
  246.     /**
  247.      * @Route("/download-zip-invoices/{id}/{token}", name="download_zip_invoices")
  248.      */
  249.     public function downloadZipInvoices(int $idstring $token): Response
  250.     {
  251.         $invoiceDownload $this->invoiceDownloadsRepository->find($id);
  252.         if (!$invoiceDownload)
  253.             return new Response('Invoices not found'Response::HTTP_NOT_FOUND);
  254.         else if ($invoiceDownload->getToken() !== $token)
  255.             return new Response('Tokens do not match'Response::HTTP_CONFLICT);
  256.         else if ($invoiceDownload->isDeleted())
  257.             return new Response('This link expired'Response::HTTP_UNAUTHORIZED);
  258.         $invoices $this->invoiceRepository->findInvoicesBetween(
  259.             $invoiceDownload->getEstablishment(),
  260.             $invoiceDownload->getStartDate(),
  261.             $invoiceDownload->getEndDate()
  262.         );
  263.         $invoices array_filter($invoices, function ($invoice) {
  264.             return $invoice->getPdfName();
  265.         });
  266.         $zipFilePath tempnam(sys_get_temp_dir(), 'invoices_zip');
  267.         $zip = new \ZipArchive();
  268.         if ($zip->open($zipFilePath, \ZipArchive::CREATE) === true)
  269.         {
  270.             foreach ($invoices as $invoice)
  271.             {
  272.                 $invoiceUrl $this->s3Service->getViewInvoice($invoice->getPdfName());
  273.                 $pdfContent file_get_contents($invoiceUrl);
  274.                 if ($pdfContent !== false)
  275.                     $zip->addFromString("invoice_{$invoice->getIdPunch()}.pdf"$pdfContent);
  276.             }
  277.             $zip->close();
  278.         }
  279.         $response = new BinaryFileResponse($zipFilePath);
  280.         $response->headers->set('Content-Type''application/zip');
  281.         $response->headers->set('Content-Disposition''attachment; filename="invoices.zip"');
  282.         return $response;
  283.     }
  284.     /**
  285.      * @Route ("/download-pdf-invoice/{id}/{token}", name="download_pdf_invoice")
  286.      */
  287.     public function downloadPdfInvoice(int $idstring $token): Response
  288.     {
  289.         $emailInvoice $this->emailInvoiceRepository->find($id);
  290.         if (!$emailInvoice)
  291.             return new Response('Invoice not found'Response::HTTP_NOT_FOUND);
  292.         else if ($emailInvoice->getToken() !== $token)
  293.             return new Response('Tokens do not match'Response::HTTP_CONFLICT);
  294.         else if ($emailInvoice->isDeleted())
  295.             return new Response('This link expired'Response::HTTP_UNAUTHORIZED);
  296.         else if (!$emailInvoice->getInvoice()->getPdfName())
  297.             return new Response('No pdf file found for this invoice.'Response::HTTP_NOT_FOUND);
  298.         $invoice $emailInvoice->getInvoice();
  299.         $invoiceUrl $this->s3Service->getViewInvoice($invoice->getPdfName());
  300.         $response = new StreamedResponse(function () use ($invoiceUrl) {
  301.             readfile($invoiceUrl);
  302.         });
  303.         $response->headers->set('Content-Type''application/pdf');
  304.         $response->headers->set('Content-Disposition''attachment; filename="invoice_' $invoice->getIdPunch() . '.pdf"');
  305.         return $response;
  306.     }
  307.     /**
  308.      * @Route("/waiting", name="admin_waiting")
  309.      */
  310.     public function blocked(): Response
  311.     {
  312.         $user $this->getUser();
  313.         if ($user !== null) {
  314.             $roles $user->getRoles();
  315.             if (in_array('ROLE_CUSTOMER_PLATEFORM'$roles)) {
  316.                 return $this->redirect('/ecommerce');
  317.             }
  318.         }
  319.         return $this->render('waiting.html.twig');
  320.     }
  321. }