<?php
namespace App\Controller;
use App\Controller\AbstractController;
use App\Entity\CreditPack;
use App\Entity\Demande;
use App\Entity\Departement;
use App\Entity\Prestataire;
use App\Entity\RefundRequest;
use App\Entity\Transaction;
use App\Entity\User;
use App\Form\AnnuaireType;
use App\Form\RefundType;
use App\Form\ResetRequestType;
use App\Misc\EntityUrlGenerator;
use App\Misc\EntityWatcher;
use App\Misc\Flashes;
use App\Misc\Geoloc;
use App\Misc\StringUtils;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Spipu\Html2Pdf\Html2Pdf;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\String\Slugger\SluggerInterface;
class PrestataireController extends AbstractController
{
public function __construct(
private TokenStorageInterface $tokenStorage,
protected MailerInterface $mailer,
private EntityUrlGenerator $entityUrlGenerator,
private RouterInterface $router,
private RequestStack $requestStack,
private EntityManagerInterface $entityManager
) {
parent::__construct($mailer, $entityUrlGenerator, $router, $requestStack, $entityManager);
}
public function prestataires(Request $request, PaginatorInterface $paginator)
{
$annuaireForm = $this->createForm(AnnuaireType::class, null, array(
'action' => $this->generateUrl('public_prestataires'),
'method' => 'GET'
));
$annuaireForm->handleRequest($request);
$repo = $this->getPrestataireRepository();
$diagnosticsGroupId = $this->getParameter('group_diagnostics');
$builder = $repo->getSearchQuery($annuaireForm->getData(), $diagnosticsGroupId);
$data = $paginator->paginate(
$builder,
$request->get('page', 1),
$this->getParameter('presta_page_size')
);
$categories = $repo->getCategoriesForAll($data);
return $this->render('Public/annuaire.html.twig', array(
'form' => $annuaireForm->createView(),
'data' => $data,
'categories' => $categories,
));
}
public function prestataire(int $id, string $entreprise)
{
$repo = $this->getPrestataireRepository();
/** @var Prestataire $prestataire */
$prestataire = $repo->find($id);
if (!$prestataire || $prestataire->isDeleted()) {
return $this->throw404();
}
// 301 redirect if $title is different from the actual sanitized title
$sanitized = StringUtils::sanitizeString($prestataire->getEntreprise());
if ($sanitized != $entreprise) {
return $this->redirectToRoute('public_prestataire', array(
'id' => $id,
'entreprise' => $sanitized
), Response::HTTP_MOVED_PERMANENTLY);
}
$categories = $repo->getCategoriesForOne($prestataire->getId());
return $this->render('Public/prestataire.html.twig', array(
'prestataire' => $prestataire,
'categories' => $categories
));
}
public function index()
{
$prestataire = $this->getPrestataire();
$repo = $this->getPrestataireRepository();
$categories = $repo->getCategoriesForOne($prestataire->getId());
return $this->render('Presta/index.html.twig', array(
'prestataire' => $prestataire,
'categories' => $categories
));
}
public function access(Session $session, Request $request, UserPasswordHasherInterface $passwordHasher, MailerInterface $mailer, SluggerInterface $slugger, Geoloc $geoloc)
{
if ($request->server->get('HTTP_REFERER') !== $this->generateUrl('presta_access', [], UrlGeneratorInterface::ABSOLUTE_URL)):
$session->set('last_url', $request->server->get('HTTP_REFERER'));
endif;
if ($request->getMethod() === 'POST') {
if ($request->get('login_submit')):
$user = $this->getEm()->getRepository(User::class)->findOneBy(['email' => strtolower($request->get('email'))]);
if ($user):
$password_validation = $passwordHasher->isPasswordValid($user, $request->get('password'));
if ($password_validation):
if ($user->isEmailValid()):
if ($user->getPrestataire()->getStatus() === 'valid'):
$token = new UsernamePasswordToken($user, null, $user->isAdmin() ? 'admin' : 'presta', $user->getRoles());
$this->tokenStorage->setToken($token);
$this->getSession()->set('_security_main', serialize($token));
if ($session->get('last_url')):
return $this->redirect($session->get('last_url'));
else:
return $this->redirectToRoute('presta_index');
endif;
else:
$this->addFlash(Flashes::ERROR, "Vous devez attendre que votre compte soit validé par l'administrateur.");
endif;
else:
$this->addFlash(Flashes::ERROR, "Vous devez valider votre email avant de pouvoir utiliser votre compte.");
endif;
else:
$this->addFlash(Flashes::ERROR, 'Mauvais identifiant.');
endif;
else:
$this->addFlash(Flashes::ERROR, 'Mauvais identifiant.');
endif;
elseif ($request->get('register_submit')):
$emailDuplicate = $this->getEm()->getRepository(User::class)->findOneBy(['email' => $email = strtolower($request->get('email'))]);
if ($emailDuplicate):
$this->addFlash(Flashes::ERROR, 'Cet email est déjà utilisé.');
return $this->redirectToRoute('presta_access');
endif;
$user = new User();
$user->setEmail($email);
$user->setPassword($passwordHasher->hashPassword($user, $request->get('password')));
$prestataire = new Prestataire();
$prestataire->setEntreprise($request->get('entreprise'));
if (!$this->isValidSiretChecksum((int) $request->get('siret'))) {
$this->addFlash(Flashes::ERROR, 'Numéro SIRET invalide.');
return $this->redirectToRoute('presta_access');
}
$prestataire->setSiret((int) $request->get('siret'));
$prestataire->setNom($request->get('responsable'));
$prestataire->setWebsite($request->get('website'));
$prestataire->setAdresse($request->get('address'));
$prestataire->setCodePostal($request->get('zipcode'));
$prestataire->setVille($request->get('city'));
$geoloc = $geoloc->getCoordinates($prestataire->getAdresse(), $prestataire->getCodePostal(), $prestataire->getVille());
if ($geoloc === false) {
$this->addFlash(Flashes::ERROR, 'Impossible de récupérer les coordonnées de l\'adresse.');
return $this->redirectToRoute('presta_access');
}
$prestataire->setCoordinates(json_encode(['lat' => $geoloc['lat'], 'lng' => $geoloc['lng']]));
$prestataire->setTelephone($request->get('phone'));
$prestataire->setFax($request->get('fax'));
foreach ($request->get('departements') ?? [] as $departement):
$prestataire->addDepartement($this->getEm()->getRepository(Departement::class)->find($departement));
endforeach;
foreach ($request->get('categories') ?? [] as $categorie):
$prestataire->addCategorie($this->getCategorieRepository()->find($categorie));
endforeach;
// Logo upload
if ($logo = $request->files->get('logo')):
$filename = $slugger->slug('logo-' . $prestataire->getEntreprise() . '-' . uniqid()) . '.' . $logo->guessExtension();
$logo->move($this->getParameter('kernel.project_dir') . '/public/' . $this->getParameter('prestataire_files_path'), $filename);
$prestataire->setLogo($filename);
$prestataire->setLogoPath($filename);
endif;
// generate a signed url and email it to the user
$user->setEmailValidationCode($token = bin2hex(random_bytes(10)));
$email = (new TemplatedEmail())
->from(new Address($this->getParameter('email_from'), $this->getParameter('name_from')))
->to(new Address($user->getEmail()))
->subject($this->getOption('email_validation_message_subject'))
->htmlTemplate('Email/email_validation.html.twig')
->context([
'token' => $token,
])
;
$mailer->send($email);
$prestataire->setUser($user);
$this->getEm()->persist($prestataire);
$this->getEm()->flush();
// Authentification
// $token = new UsernamePasswordToken($user, null, $user->isAdmin() ? 'admin' : 'presta', $user->getRoles());
// $this->tokenStorage->setToken($token);
// $this->getSession()->set('_security_main', serialize($token));
// $this->addFlash(Flashes::SUCCESS, $this->getOption('register_confirmation'));
// return $this->redirectToRoute('presta_index');
$this->addFlash(Flashes::SUCCESS, $this->getOption('register_confirmation'));
return $this->redirectToRoute('presta_access');
endif;
}
$categories = [
// 'diagnotics' => $this->getCategorieRepository()->getChildren(72),
'expertises' => $this->getCategorieRepository()->getChildren(73),
'etudes' => $this->getCategorieRepository()->getChildren(74),
'solutions' => $this->getCategorieRepository()->getChildren(75),
'energies' => $this->getCategorieRepository()->getChildren(76),
];
return $this->render('Presta/access.html.twig', [
'departements' => $this->getEm()->getRepository(Departement::class)->findAll(),
'categories' => $categories,
'error' => $error ?? null
]);
}
public function edit(Request $request, MailerInterface $mailer, UserPasswordHasherInterface $passwordHasher, SluggerInterface $slugger, Geoloc $geoloc)
{
$prestataire = $this->getPrestataire();
if ($request->getMethod() === 'POST'):
$watcher = new EntityWatcher($prestataire, $this->getParameter('presta_watched_properties'));
$email = strtolower($request->get('email'));
if ($email !== strtolower($prestataire->getUser()->getEmail())):
$emailDuplicate = $this->getEm()->getRepository(User::class)->findOneBy(['email' => $email]);
if ($emailDuplicate):
$this->addFlash(Flashes::ERROR, 'Cet email est déjà utilisé.');
return $this->redirectToRoute('presta_edit');
endif;
$prestataire->getUser()->setEmail($request->get('email'));
endif;
if ($request->get('password') && $request->get('password') === $request->get('password_verification')):
$prestataire->getUser()->setPassword($passwordHasher->hashPassword($prestataire->getUser(), $request->get('password')));
endif;
$prestataire->setEntreprise($request->get('entreprise'));
if (!$this->isValidSiretChecksum((int) $request->get('siret'))) {
$this->addFlash(Flashes::ERROR, 'Numéro SIRET invalide.');
return $this->redirectToRoute('presta_edit');
}
$prestataire->setSiret((string) $request->get('siret'));
$prestataire->setNom($request->get('responsable'));
$prestataire->setWebsite($request->get('website'));
$address_updated = false;
if ($request->get('address') !== $prestataire->getAdresse()):
$prestataire->setAdresse($request->get('address'));
$address_updated = true;
endif;
if ($request->get('zipcode') !== $prestataire->getCodePostal()):
$prestataire->setCodePostal($request->get('zipcode'));
$address_updated = true;
endif;
if ($request->get('city') !== $prestataire->getVille()):
$prestataire->setVille($request->get('city'));
$address_updated = true;
endif;
if ($address_updated):
$geoloc = $geoloc->getCoordinates($prestataire->getAdresse(), $prestataire->getCodePostal(), $prestataire->getVille());
if ($geoloc === false) {
$this->addFlash(Flashes::ERROR, 'Impossible de récupérer les coordonnées de l\'adresse.');
return $this->redirectToRoute('presta_edit');
}
$prestataire->setCoordinates(json_encode(['lat' => $geoloc['lat'], 'lng' => $geoloc['lng']]));
endif;
$prestataire->setTelephone($request->get('phone'));
$prestataire->setFax($request->get('fax'));
$prestataire->getDepartements()->clear();
foreach ($request->get('departements') ?? [] as $departement):
$prestataire->addDepartement($this->getEm()->getRepository(Departement::class)->find($departement));
endforeach;
$prestataire->getCategories()->clear();
foreach ($request->get('categories') ?? [] as $categorie):
$prestataire->addCategorie($this->getCategorieRepository()->find($categorie));
endforeach;
// Logo upload
if ($logo = $request->files->get('logo')):
$filename = $slugger->slug('logo-' . $prestataire->getEntreprise() . '-' . uniqid()) . '.' . $logo->guessExtension();
$logo->move($this->getParameter('kernel.project_dir') . '/public/' . $this->getParameter('prestataire_files_path'), $filename);
$prestataire->setLogo($filename);
$prestataire->setLogoPath($filename);
endif;
if ($updated = $watcher->compute()) {
$prestataire->setModifiedDate(new DateTime());
}
$this->getEm()->persist($prestataire);
$this->getEm()->flush();
if ($updated) {
// $mail = new Mail();
// $mail
// ->setFromEmail($this->getParameter('email_from'))
// ->setFromName($this->getParameter('name_from'))
// ->setToEmail($this->getParameter('admin_email'))
// ->setSubject('Un prestataire a modifié ses informations')
// ->setContent($this->render('Email/prestataire_modified.html.twig', [
// 'prestataire' => $prestataire,
// 'watcher' => $watcher
// ]))
// ->setStatus('new');
// $this->getEM()->persist($mail);
// $this->getEM()->flush();
$email = (new TemplatedEmail())
->from(new Address($this->getParameter('email_from'), $this->getParameter('name_from')))
->to($this->getParameter('admin_email'))
->subject('Un prestataire a modifié ses informations')
->htmlTemplate('Email/prestataire_modified.html.twig')
->context([
'prestataire' => $prestataire,
'watcher' => $watcher
]);
$mailer->send($email);
}
$this->addFlash(Flashes::SUCCESS, 'Vos modifications ont bien été prises en compte.');
return $this->redirectToRoute('presta_index');
endif;
$categories = [
'diagnostics' => $this->getCategorieRepository()->getChildren(72),
'expertises' => $this->getCategorieRepository()->getChildren(73),
'etudes' => $this->getCategorieRepository()->getChildren(74),
'solutions' => $this->getCategorieRepository()->getChildren(75),
'energies' => $this->getCategorieRepository()->getChildren(76),
];
return $this->render('Presta/edit.html.twig', array(
'prestataire' => $prestataire,
'departements' => $this->getEm()->getRepository(Departement::class)->findAll(),
'categories' => $categories,
));
}
public function buyCredits()
{
$repo = $this->getEM()->getRepository(CreditPack::class);
$packs = $repo->findBy(array(), array('prix' => 'ASC'));
$tarifs = $this->getCategorieRepository()->getTarifs();
return $this->render('Presta/buy_credits.html.twig', array(
'packs' => $packs,
'tarifs' => $tarifs,
));
}
public function transactions()
{
$prestataire = $this->getPrestataire();
/** @var TransactionRepository $repo */
$repo = $this->getEM()->getRepository(Transaction::class);
$transactions = $repo->getForPrestataire($prestataire->getId());
$totalCredits = $repo->getPrestataireTotalBoughtCredits($prestataire->getId());
$spentCredits = $repo->getPrestataireTotalSpentCredits($prestataire->getId());
/** @var Demande[] $demandes */
$demandes = $this->getPrestataireRepository()->getActiveDemandes($prestataire->getId());
return $this->render('Presta/transactions.html.twig', array(
'prestataire' => $prestataire,
'transactions' => $transactions,
'totalCredits' => $totalCredits,
'spentCredits' => $spentCredits,
'demandes' => $demandes
));
}
/**
* @param Demande $demande
* @param Prestataire $prestataire
*
* @return RedirectResponse
*/
private function actionAddToCart($demande, $prestataire)
{
$em = $this->getEM();
// try to get a previous cart
/** @var TransactionRepository $repo */
$repo = $em->getRepository(Transaction::class);
$cart = $repo->getCart($prestataire->getId());
if (!$cart) {
$cart = new Transaction();
$cart->setDate(new DateTime());
$cart->setCart(true);
$cart->setConfirmed(false);
$cart->setPrestataire($prestataire);
$em->persist($cart);
}
$cart->addDemande($demande);
$em->flush();
$this->addflash(Flashes::SUCCESS, 'La demande a bien été ajoutée à votre panier.');
return $this->redirectToRoute('presta_cart');
}
public function denied(Request $request, FlashBag $flashBag)
{
$this->addFlash('error', 'Mauvais identifiants.');
return $this->redirect($this->generateUrl('presta_access'));
}
public function failure()
{
return new Response('Login failure');
}
public function removeLogo(Request $request)
{
$prestataire = $this->getPrestataire();
$logoPath = $this->getParameter('kernel.project_dir') . '/public/'.
$this->getParameter('prestataire_files_path').'/'.
$prestataire->getLogoPath();
$prestataire->setLogoPath(null);
$this->getEM()->flush();
if (file_exists($logoPath) && is_file($logoPath)) {
unlink($logoPath);
}
$this->addFlash(Flashes::SUCCESS, 'Le logo a bien été supprimé.');
return $this->redirectToRoute('presta_index');
}
public function buyDemande(Request $request, $id)
{
/** @var Demande $demande */
$demande = $this->getDemandeRepository()->find($id);
if (!$demande) {
$this->addFlash(Flashes::ERROR, 'La demande de devis n°'. $id .' a expiré.');
return $this->throw404();
}
$prestataire = $this->getPrestataire();
if ($this->getDemandeRepository()->isBoughtBy($demande, $prestataire)) {
// bought already, redirect
return $this->getUrlGenerator()->redirectTo($demande);
}
if ($request->getMethod() === 'POST') {
switch ($request->get('action')) {
case 'stripe':
return $this->redirectToRoute('stripe_demande', ['id' => $demande->getId()]);
case 'direct':
return $this->redirectToRoute('paypal_demande', ['id' => $demande->getId()]);
case 'cart':
return $this->actionAddToCart($demande, $prestataire);
case 'use_credits':
return $this->actionBuyWithCredits($demande, $prestataire);
case 'achat_credits':
$this->getSession()->set('achat_credits_redirect', $this->generateUrl('presta_buy_demande', array('id' => $demande->getId())));
return $this->redirectToRoute('presta_buy_credits');
}
}
/** @var CreditPackRepository $packRepo */
$packRepo = $this->getEM()->getRepository(CreditPack::class);
$minPricePack = $packRepo->getMinPricePack();
/** @var TransactionRepository $transactionRepo */
$transactionRepo = $this->getEM()->getRepository(Transaction::class);
$isInCart = $transactionRepo->isInCart($demande->getId(), $prestataire->getId());
return $this->render('Presta/buy_demande.html.twig', array(
'demande' => $demande,
'prestataire' => $prestataire,
'minPricePack' => $minPricePack,
'isInCart' => $isInCart,
));
}
/**
* @param Demande $demande
* @param Prestataire $prestataire
*
* @return RedirectResponse
*/
private function actionBuyWithCredits(Demande $demande, Prestataire $prestataire)
{
if ($prestataire->getCredits() < $demande->getCredits()) {
$this->addFlash(Flashes::ERROR, "Vous n'avez pas suffisamment de crédits pour acheter ce contact.");
return $this->redirectToRoute('presta_buy_demande', array('id' => $demande->getId()));
}
$em = $this->getEM();
$em->beginTransaction();
$transaction = new Transaction();
$transaction->setDate(new DateTime());
$transaction->setPrestataire($prestataire);
$transaction->setPrix(null);
$transaction->setCredits($demande->getCredits());
$transaction->setConfirmed(true);
$transaction->addDemande($demande);
$prestataire->removeCredits($demande->getCredits());
$em->persist($transaction);
$em->flush();
$this->removeFromPrestaCart($demande, $prestataire);
$em->commit();
$this->addFlash(Flashes::SUCCESS, 'Vous avez maintenant accès aux coordonnées du contact.');
return $this->getUrlGenerator()->redirectTo($demande);
}
public function refund(Request $request)
{
$prestataire = $this->getPrestataire();
$refundRequest = new RefundRequest();
$refundRequest->setPrestataire($prestataire);
if ($request->get('id')) {
/** @var Demande $demande */
$demande = $this->getDemandeRepository()->find($request->get('id'));
if ($demande) {
if ($demande->getRefundRequest($prestataire->getId())) {
$this->addFlash(Flashes::WARNING, 'Vous avez déjà demandé une recréditation pour cette demande.');
return $this->redirectToRoute('presta_transactions');
}
$refundRequest->setDemande($demande);
}
}
$refundForm = $this->createForm(RefundType::class, $refundRequest);
if ($request->getMethod() === 'POST') {
$refundForm->handleRequest($request);
if ($refundForm->isValid()) {
$refundRequest = $refundForm->getData();
$em = $this->getEM();
$em->beginTransaction();
$em->persist($refundRequest);
$em->flush();
// notify admin with request and link to presta page
// $mail = new Mail();
// $mail
// ->setFromEmail($this->getParameter('email_from'))
// ->setFromName($this->getParameter('name_from'))
// ->setToEmail($this->getParameter('admin_email'))
// ->setSubject('Nouvelle demande de recréditation')
// ->setContent($this->render('Email/refund_request.html.twig', ['request' => $refundRequest]))
// ->setStatus('new');
// $this->getEM()->persist($mail);
// $this->getEM()->flush();
$email = (new TemplatedEmail())
->from(new Address($this->getParameter('email_from'), $this->getParameter('name_from')))
->to(new Address($this->getParameter('admin_email')))
->subject('Nouvelle demande de recréditation')
->htmlTemplate('Email/refund_request.html.twig')
->context(
[
'request' => $refundRequest,
]
);
$this->getMailer()->send($email);
$em->commit();
$this->addFlash(Flashes::SUCCESS, 'Votre demande de recréditation a bien été envoyée.');
return $this->redirectToRoute('presta_transactions');
}
}
return $this->render('Presta/refund.html.twig', array(
'refund_form' => $refundForm->createView()
));
}
public function cart(Request $request)
{
$prestataire = $this->getPrestataire();
/** @var TransactionRepository $repo */
$repo = $this->getEM()->getRepository(Transaction::class);
$cart = $repo->getCart($prestataire->getId());
// Request for remove cart
if ($request->getMethod() === 'POST') {
if ($request->request->has('remove')) {
$demande = $this->getDemandeRepository()->find($request->get('remove')['id']);
if ($demande) {
$cart->removeDemande($demande);
$this->getEM()->flush();
return $this->redirectToRoute('presta_cart');
}
}
}
return $this->render('Presta/cart.html.twig', array(
'cart' => $cart,
'prix' => $this->getCartPrix($cart),
'minPricePack' => $this->getMinPricePack()
));
}
private function getMinPricePack()
{
/** @var CreditPackRepository $packRepo */
$packRepo = $this->getEM()->getRepository(CreditPack::class);
return $packRepo->getMinPricePack();
}
public function buyCart(Request $request)
{
$prestataire = $this->getPrestataire();
/** @var TransactionRepository $repo */
$repo = $this->getEM()->getRepository(Transaction::class);
$cart = $repo->getCart($prestataire->getId());
if (!$cart || !$cart->getDemandes()) {
return $this->redirectToRoute('presta_cart');
}
if ($request->getMethod() === 'POST') {
switch ($request->get('action')) {
case 'stripe':
return $this->redirectToRoute('stripe_cart');
case 'use_credits':
return $this->actionBuyCartWithCredits($cart);
case 'achat_credits':
$this->getSession()->set('achat_credits_redirect', $this->generateUrl('presta_buy_cart'));
return $this->redirectToRoute('presta_buy_credits');
}
}
return $this->render('Presta/buy_cart.html.twig', array(
'cart' => $cart,
'prix' => $this->getCartPrix($cart),
'credits' => $this->getCartCredits($cart),
'minPricePack' => $this->getMinPricePack(),
'prestataire' => $prestataire
));
}
/**
* @param Transaction $cart
*/
private function actionBuyCartWithCredits($cart)
{
$cart->setCredits($this->getCartCredits($cart));
if ($cart->getPrestataire()->getCredits() < $cart->getCredits()) {
$this->addFlash(Flashes::ERROR, "Vous n'avez pas suffisamment de crédits pour acheter ce panier.");
return $this->redirectToRoute('presta_buy_cart');
}
$cart->setDate(new DateTime());
$cart->setPrix(null);
$cart->setConfirmed(true);
$cart->setCart(false);
$cart->getPrestataire()->removeCredits($cart->getCredits());
$this->getEM()->flush();
$this->addFlash(Flashes::SUCCESS, 'Vous avez maintenant accès aux coordonnées des contacts achetés.');
return $this->redirectToRoute('presta_transactions');
}
public function requestReset(Request $request)
{
$form = $this->createForm(ResetRequestType::class, new User());
if ($request->getMethod() === 'POST') {
$form->handleRequest($request);
$email = $form->getData()->getEmail();
/** @var User $user */
$user = $this->getEM()->getRepository(User::class)->findOneBy(array(
'email' => strtolower($email)
));
if ($user) {
$user->setResetCode($token = substr("abcdefghijklmnopqrstuvwxyz", mt_rand(0, 25), 1).substr(md5(time()), 1));
$this->getEM()->flush();
// send email
// $mail = new Mail();
// $mail
// ->setFromEmail($this->getParameter('email_from'))
// ->setFromName($this->getParameter('name_from'))
// ->setToEmail($user->getEmail())
// ->setToName($user->getPrestataire() ? $user->getPrestataire()->getNom() : '')
// ->setSubject($this->getOption('request_reset_message_subject'))
// ->setContent($this->render('Email/request_reset.html.twig', ['token' => $token]))
// ->setStatus('new');
// $this->getEM()->persist($mail);
// $this->getEM()->flush();
if ($user->getPrestataire() && $user->getPrestataire()->getNom()):
$name = $user->getPrestataire()->getNom();
endif;
$email = (new TemplatedEmail())
->from(new Address($this->getParameter('email_from'), $this->getParameter('name_from')))
->to(new Address($user->getEmail(), $name ?? ""))
->subject($this->getOption('request_reset_message_subject'))
->htmlTemplate('Email/request_reset.html.twig')
->context([
'token' => $token,
])
;
$this->getMailer()->send($email);
}
$this->addFlash(Flashes::SUCCESS, 'Si votre adresse email a été trouvée, un message contenant un lien de réinitialisation vous a été envoyé.');
return $this->redirectToRoute('presta_access');
}
return $this->render('User/request_reset.html.twig', array(
'request_form' => $form->createView()
));
}
public function reset(Request $request, $token, UserPasswordHasherInterface $passwordHasher)
{
$user = $this->getUserRepository()->findOneBy(['resetCode' => $token]);
if (!$user) {
$this->addFlash(Flashes::ERROR, "Le code fourni n'est pas valide.");
return $this->redirectToRoute('presta_access');
}
if ($request->getMethod() === 'POST') {
$user->setPassword($passwordHasher->hashPassword($user, $request->get('password')));
$user->setResetCode(null);
$this->getEM()->flush();
if ($user->isEnabled()) {
// authenticate
$token = new UsernamePasswordToken($user, null, $user->isAdmin() ? 'admin' : 'presta', $user->getRoles());
$this->tokenStorage->setToken($token);
$this->getSession()->set('_security_main', serialize($token));
}
$this->addFlash(Flashes::SUCCESS, 'Votre mot de passe a bien été modifié.');
$route = $user->isAdmin() ? 'admin_index' : 'presta_index';
return $this->redirectToRoute($route);
}
// if invalid code, redirect on request_reset with flash
return $this->render('User/reset.html.twig', array(
'user' => $user
));
}
public function invoice($number)
{
/** @var Transaction $transaction */
$transaction = $this->getTransactionRepository()->findOneBy(array(
'invoiceNumber' => $number
));
if (!$transaction) {
return $this->throw404();
}
$output = $this->getInvoicePdfContent($transaction);
$name = $transaction->getInvoiceFilename();
$response = new Response($output);
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-Type', 'application/pdf');
$response->headers->set('Content-Disposition', 'attachment; filename="'. $name .'";');
$response->headers->set('Content-Length', strlen($output));
return $response;
}
private function getInvoicePdfContent(Transaction $transaction)
{
$content = $this->renderView('Protected/invoice.html.twig', array(
'from' => $this->getOption('invoice_from'),
'to' => $transaction->getPrestataire(),
'transaction' => $transaction,
'footer' => $this->getOption('invoice_footer')
));
/** @var HTML2PDF $pdf */
$pdf = new Html2Pdf();
$pdf->pdf->SetDisplayMode('fullpage');
$pdf->writeHTML($content);
return $pdf->Output($transaction->getInvoiceFilename(), 'S');
}
}