src/Controller/PrestataireController.php line 121

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Controller\AbstractController;
  4. use App\Entity\CreditPack;
  5. use App\Entity\Demande;
  6. use App\Entity\Departement;
  7. use App\Entity\Prestataire;
  8. use App\Entity\RefundRequest;
  9. use App\Entity\Transaction;
  10. use App\Entity\User;
  11. use App\Form\AnnuaireType;
  12. use App\Form\RefundType;
  13. use App\Form\ResetRequestType;
  14. use App\Misc\EntityUrlGenerator;
  15. use App\Misc\EntityWatcher;
  16. use App\Misc\Flashes;
  17. use App\Misc\Geoloc;
  18. use App\Misc\StringUtils;
  19. use DateTime;
  20. use Doctrine\ORM\EntityManagerInterface;
  21. use Knp\Component\Pager\PaginatorInterface;
  22. use Spipu\Html2Pdf\Html2Pdf;
  23. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use Symfony\Component\HttpFoundation\RequestStack;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
  28. use Symfony\Component\HttpFoundation\Session\Session;
  29. use Symfony\Component\Mailer\MailerInterface;
  30. use Symfony\Component\Mime\Address;
  31. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  32. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  33. use Symfony\Component\Routing\RouterInterface;
  34. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  35. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  36. use Symfony\Component\String\Slugger\SluggerInterface;
  37. class PrestataireController extends AbstractController
  38. {
  39. public function __construct(
  40. private TokenStorageInterface $tokenStorage,
  41. protected MailerInterface $mailer,
  42. private EntityUrlGenerator $entityUrlGenerator,
  43. private RouterInterface $router,
  44. private RequestStack $requestStack,
  45. private EntityManagerInterface $entityManager
  46. ) {
  47. parent::__construct($mailer, $entityUrlGenerator, $router, $requestStack, $entityManager);
  48. }
  49. public function prestataires(Request $request, PaginatorInterface $paginator)
  50. {
  51. $annuaireForm = $this->createForm(AnnuaireType::class, null, array(
  52. 'action' => $this->generateUrl('public_prestataires'),
  53. 'method' => 'GET'
  54. ));
  55. $annuaireForm->handleRequest($request);
  56. $repo = $this->getPrestataireRepository();
  57. $diagnosticsGroupId = $this->getParameter('group_diagnostics');
  58. $builder = $repo->getSearchQuery($annuaireForm->getData(), $diagnosticsGroupId);
  59. $data = $paginator->paginate(
  60. $builder,
  61. $request->get('page', 1),
  62. $this->getParameter('presta_page_size')
  63. );
  64. $categories = $repo->getCategoriesForAll($data);
  65. return $this->render('Public/annuaire.html.twig', array(
  66. 'form' => $annuaireForm->createView(),
  67. 'data' => $data,
  68. 'categories' => $categories,
  69. ));
  70. }
  71. public function prestataire(int $id, string $entreprise)
  72. {
  73. $repo = $this->getPrestataireRepository();
  74. /** @var Prestataire $prestataire */
  75. $prestataire = $repo->find($id);
  76. if (!$prestataire || $prestataire->isDeleted()) {
  77. return $this->throw404();
  78. }
  79. // 301 redirect if $title is different from the actual sanitized title
  80. $sanitized = StringUtils::sanitizeString($prestataire->getEntreprise());
  81. if ($sanitized != $entreprise) {
  82. return $this->redirectToRoute('public_prestataire', array(
  83. 'id' => $id,
  84. 'entreprise' => $sanitized
  85. ), Response::HTTP_MOVED_PERMANENTLY);
  86. }
  87. $categories = $repo->getCategoriesForOne($prestataire->getId());
  88. return $this->render('Public/prestataire.html.twig', array(
  89. 'prestataire' => $prestataire,
  90. 'categories' => $categories
  91. ));
  92. }
  93. public function index()
  94. {
  95. $prestataire = $this->getPrestataire();
  96. $repo = $this->getPrestataireRepository();
  97. $categories = $repo->getCategoriesForOne($prestataire->getId());
  98. return $this->render('Presta/index.html.twig', array(
  99. 'prestataire' => $prestataire,
  100. 'categories' => $categories
  101. ));
  102. }
  103. public function access(Session $session, Request $request, UserPasswordHasherInterface $passwordHasher, MailerInterface $mailer, SluggerInterface $slugger, Geoloc $geoloc)
  104. {
  105. if ($request->server->get('HTTP_REFERER') !== $this->generateUrl('presta_access', [], UrlGeneratorInterface::ABSOLUTE_URL)):
  106. $session->set('last_url', $request->server->get('HTTP_REFERER'));
  107. endif;
  108. if ($request->getMethod() === 'POST') {
  109. if ($request->get('login_submit')):
  110. $user = $this->getEm()->getRepository(User::class)->findOneBy(['email' => strtolower($request->get('email'))]);
  111. if ($user):
  112. $password_validation = $passwordHasher->isPasswordValid($user, $request->get('password'));
  113. if ($password_validation):
  114. if ($user->isEmailValid()):
  115. if ($user->getPrestataire()->getStatus() === 'valid'):
  116. $token = new UsernamePasswordToken($user, null, $user->isAdmin() ? 'admin' : 'presta', $user->getRoles());
  117. $this->tokenStorage->setToken($token);
  118. $this->getSession()->set('_security_main', serialize($token));
  119. if ($session->get('last_url')):
  120. return $this->redirect($session->get('last_url'));
  121. else:
  122. return $this->redirectToRoute('presta_index');
  123. endif;
  124. else:
  125. $this->addFlash(Flashes::ERROR, "Vous devez attendre que votre compte soit validé par l'administrateur.");
  126. endif;
  127. else:
  128. $this->addFlash(Flashes::ERROR, "Vous devez valider votre email avant de pouvoir utiliser votre compte.");
  129. endif;
  130. else:
  131. $this->addFlash(Flashes::ERROR, 'Mauvais identifiant.');
  132. endif;
  133. else:
  134. $this->addFlash(Flashes::ERROR, 'Mauvais identifiant.');
  135. endif;
  136. elseif ($request->get('register_submit')):
  137. $emailDuplicate = $this->getEm()->getRepository(User::class)->findOneBy(['email' => $email = strtolower($request->get('email'))]);
  138. if ($emailDuplicate):
  139. $this->addFlash(Flashes::ERROR, 'Cet email est déjà utilisé.');
  140. return $this->redirectToRoute('presta_access');
  141. endif;
  142. $user = new User();
  143. $user->setEmail($email);
  144. $user->setPassword($passwordHasher->hashPassword($user, $request->get('password')));
  145. $prestataire = new Prestataire();
  146. $prestataire->setEntreprise($request->get('entreprise'));
  147. if (!$this->isValidSiretChecksum((int) $request->get('siret'))) {
  148. $this->addFlash(Flashes::ERROR, 'Numéro SIRET invalide.');
  149. return $this->redirectToRoute('presta_access');
  150. }
  151. $prestataire->setSiret((int) $request->get('siret'));
  152. $prestataire->setNom($request->get('responsable'));
  153. $prestataire->setWebsite($request->get('website'));
  154. $prestataire->setAdresse($request->get('address'));
  155. $prestataire->setCodePostal($request->get('zipcode'));
  156. $prestataire->setVille($request->get('city'));
  157. $geoloc = $geoloc->getCoordinates($prestataire->getAdresse(), $prestataire->getCodePostal(), $prestataire->getVille());
  158. if ($geoloc === false) {
  159. $this->addFlash(Flashes::ERROR, 'Impossible de récupérer les coordonnées de l\'adresse.');
  160. return $this->redirectToRoute('presta_access');
  161. }
  162. $prestataire->setCoordinates(json_encode(['lat' => $geoloc['lat'], 'lng' => $geoloc['lng']]));
  163. $prestataire->setTelephone($request->get('phone'));
  164. $prestataire->setFax($request->get('fax'));
  165. foreach ($request->get('departements') ?? [] as $departement):
  166. $prestataire->addDepartement($this->getEm()->getRepository(Departement::class)->find($departement));
  167. endforeach;
  168. foreach ($request->get('categories') ?? [] as $categorie):
  169. $prestataire->addCategorie($this->getCategorieRepository()->find($categorie));
  170. endforeach;
  171. // Logo upload
  172. if ($logo = $request->files->get('logo')):
  173. $filename = $slugger->slug('logo-' . $prestataire->getEntreprise() . '-' . uniqid()) . '.' . $logo->guessExtension();
  174. $logo->move($this->getParameter('kernel.project_dir') . '/public/' . $this->getParameter('prestataire_files_path'), $filename);
  175. $prestataire->setLogo($filename);
  176. $prestataire->setLogoPath($filename);
  177. endif;
  178. // generate a signed url and email it to the user
  179. $user->setEmailValidationCode($token = bin2hex(random_bytes(10)));
  180. $email = (new TemplatedEmail())
  181. ->from(new Address($this->getParameter('email_from'), $this->getParameter('name_from')))
  182. ->to(new Address($user->getEmail()))
  183. ->subject($this->getOption('email_validation_message_subject'))
  184. ->htmlTemplate('Email/email_validation.html.twig')
  185. ->context([
  186. 'token' => $token,
  187. ])
  188. ;
  189. $mailer->send($email);
  190. $prestataire->setUser($user);
  191. $this->getEm()->persist($prestataire);
  192. $this->getEm()->flush();
  193. // Authentification
  194. // $token = new UsernamePasswordToken($user, null, $user->isAdmin() ? 'admin' : 'presta', $user->getRoles());
  195. // $this->tokenStorage->setToken($token);
  196. // $this->getSession()->set('_security_main', serialize($token));
  197. // $this->addFlash(Flashes::SUCCESS, $this->getOption('register_confirmation'));
  198. // return $this->redirectToRoute('presta_index');
  199. $this->addFlash(Flashes::SUCCESS, $this->getOption('register_confirmation'));
  200. return $this->redirectToRoute('presta_access');
  201. endif;
  202. }
  203. $categories = [
  204. // 'diagnotics' => $this->getCategorieRepository()->getChildren(72),
  205. 'expertises' => $this->getCategorieRepository()->getChildren(73),
  206. 'etudes' => $this->getCategorieRepository()->getChildren(74),
  207. 'solutions' => $this->getCategorieRepository()->getChildren(75),
  208. 'energies' => $this->getCategorieRepository()->getChildren(76),
  209. ];
  210. return $this->render('Presta/access.html.twig', [
  211. 'departements' => $this->getEm()->getRepository(Departement::class)->findAll(),
  212. 'categories' => $categories,
  213. 'error' => $error ?? null
  214. ]);
  215. }
  216. public function edit(Request $request, MailerInterface $mailer, UserPasswordHasherInterface $passwordHasher, SluggerInterface $slugger, Geoloc $geoloc)
  217. {
  218. $prestataire = $this->getPrestataire();
  219. if ($request->getMethod() === 'POST'):
  220. $watcher = new EntityWatcher($prestataire, $this->getParameter('presta_watched_properties'));
  221. $email = strtolower($request->get('email'));
  222. if ($email !== strtolower($prestataire->getUser()->getEmail())):
  223. $emailDuplicate = $this->getEm()->getRepository(User::class)->findOneBy(['email' => $email]);
  224. if ($emailDuplicate):
  225. $this->addFlash(Flashes::ERROR, 'Cet email est déjà utilisé.');
  226. return $this->redirectToRoute('presta_edit');
  227. endif;
  228. $prestataire->getUser()->setEmail($request->get('email'));
  229. endif;
  230. if ($request->get('password') && $request->get('password') === $request->get('password_verification')):
  231. $prestataire->getUser()->setPassword($passwordHasher->hashPassword($prestataire->getUser(), $request->get('password')));
  232. endif;
  233. $prestataire->setEntreprise($request->get('entreprise'));
  234. if (!$this->isValidSiretChecksum((int) $request->get('siret'))) {
  235. $this->addFlash(Flashes::ERROR, 'Numéro SIRET invalide.');
  236. return $this->redirectToRoute('presta_edit');
  237. }
  238. $prestataire->setSiret((string) $request->get('siret'));
  239. $prestataire->setNom($request->get('responsable'));
  240. $prestataire->setWebsite($request->get('website'));
  241. $address_updated = false;
  242. if ($request->get('address') !== $prestataire->getAdresse()):
  243. $prestataire->setAdresse($request->get('address'));
  244. $address_updated = true;
  245. endif;
  246. if ($request->get('zipcode') !== $prestataire->getCodePostal()):
  247. $prestataire->setCodePostal($request->get('zipcode'));
  248. $address_updated = true;
  249. endif;
  250. if ($request->get('city') !== $prestataire->getVille()):
  251. $prestataire->setVille($request->get('city'));
  252. $address_updated = true;
  253. endif;
  254. if ($address_updated):
  255. $geoloc = $geoloc->getCoordinates($prestataire->getAdresse(), $prestataire->getCodePostal(), $prestataire->getVille());
  256. if ($geoloc === false) {
  257. $this->addFlash(Flashes::ERROR, 'Impossible de récupérer les coordonnées de l\'adresse.');
  258. return $this->redirectToRoute('presta_edit');
  259. }
  260. $prestataire->setCoordinates(json_encode(['lat' => $geoloc['lat'], 'lng' => $geoloc['lng']]));
  261. endif;
  262. $prestataire->setTelephone($request->get('phone'));
  263. $prestataire->setFax($request->get('fax'));
  264. $prestataire->getDepartements()->clear();
  265. foreach ($request->get('departements') ?? [] as $departement):
  266. $prestataire->addDepartement($this->getEm()->getRepository(Departement::class)->find($departement));
  267. endforeach;
  268. $prestataire->getCategories()->clear();
  269. foreach ($request->get('categories') ?? [] as $categorie):
  270. $prestataire->addCategorie($this->getCategorieRepository()->find($categorie));
  271. endforeach;
  272. // Logo upload
  273. if ($logo = $request->files->get('logo')):
  274. $filename = $slugger->slug('logo-' . $prestataire->getEntreprise() . '-' . uniqid()) . '.' . $logo->guessExtension();
  275. $logo->move($this->getParameter('kernel.project_dir') . '/public/' . $this->getParameter('prestataire_files_path'), $filename);
  276. $prestataire->setLogo($filename);
  277. $prestataire->setLogoPath($filename);
  278. endif;
  279. if ($updated = $watcher->compute()) {
  280. $prestataire->setModifiedDate(new DateTime());
  281. }
  282. $this->getEm()->persist($prestataire);
  283. $this->getEm()->flush();
  284. if ($updated) {
  285. // $mail = new Mail();
  286. // $mail
  287. // ->setFromEmail($this->getParameter('email_from'))
  288. // ->setFromName($this->getParameter('name_from'))
  289. // ->setToEmail($this->getParameter('admin_email'))
  290. // ->setSubject('Un prestataire a modifié ses informations')
  291. // ->setContent($this->render('Email/prestataire_modified.html.twig', [
  292. // 'prestataire' => $prestataire,
  293. // 'watcher' => $watcher
  294. // ]))
  295. // ->setStatus('new');
  296. // $this->getEM()->persist($mail);
  297. // $this->getEM()->flush();
  298. $email = (new TemplatedEmail())
  299. ->from(new Address($this->getParameter('email_from'), $this->getParameter('name_from')))
  300. ->to($this->getParameter('admin_email'))
  301. ->subject('Un prestataire a modifié ses informations')
  302. ->htmlTemplate('Email/prestataire_modified.html.twig')
  303. ->context([
  304. 'prestataire' => $prestataire,
  305. 'watcher' => $watcher
  306. ]);
  307. $mailer->send($email);
  308. }
  309. $this->addFlash(Flashes::SUCCESS, 'Vos modifications ont bien été prises en compte.');
  310. return $this->redirectToRoute('presta_index');
  311. endif;
  312. $categories = [
  313. 'diagnostics' => $this->getCategorieRepository()->getChildren(72),
  314. 'expertises' => $this->getCategorieRepository()->getChildren(73),
  315. 'etudes' => $this->getCategorieRepository()->getChildren(74),
  316. 'solutions' => $this->getCategorieRepository()->getChildren(75),
  317. 'energies' => $this->getCategorieRepository()->getChildren(76),
  318. ];
  319. return $this->render('Presta/edit.html.twig', array(
  320. 'prestataire' => $prestataire,
  321. 'departements' => $this->getEm()->getRepository(Departement::class)->findAll(),
  322. 'categories' => $categories,
  323. ));
  324. }
  325. public function buyCredits()
  326. {
  327. $repo = $this->getEM()->getRepository(CreditPack::class);
  328. $packs = $repo->findBy(array(), array('prix' => 'ASC'));
  329. $tarifs = $this->getCategorieRepository()->getTarifs();
  330. return $this->render('Presta/buy_credits.html.twig', array(
  331. 'packs' => $packs,
  332. 'tarifs' => $tarifs,
  333. ));
  334. }
  335. public function transactions()
  336. {
  337. $prestataire = $this->getPrestataire();
  338. /** @var TransactionRepository $repo */
  339. $repo = $this->getEM()->getRepository(Transaction::class);
  340. $transactions = $repo->getForPrestataire($prestataire->getId());
  341. $totalCredits = $repo->getPrestataireTotalBoughtCredits($prestataire->getId());
  342. $spentCredits = $repo->getPrestataireTotalSpentCredits($prestataire->getId());
  343. /** @var Demande[] $demandes */
  344. $demandes = $this->getPrestataireRepository()->getActiveDemandes($prestataire->getId());
  345. return $this->render('Presta/transactions.html.twig', array(
  346. 'prestataire' => $prestataire,
  347. 'transactions' => $transactions,
  348. 'totalCredits' => $totalCredits,
  349. 'spentCredits' => $spentCredits,
  350. 'demandes' => $demandes
  351. ));
  352. }
  353. /**
  354. * @param Demande $demande
  355. * @param Prestataire $prestataire
  356. *
  357. * @return RedirectResponse
  358. */
  359. private function actionAddToCart($demande, $prestataire)
  360. {
  361. $em = $this->getEM();
  362. // try to get a previous cart
  363. /** @var TransactionRepository $repo */
  364. $repo = $em->getRepository(Transaction::class);
  365. $cart = $repo->getCart($prestataire->getId());
  366. if (!$cart) {
  367. $cart = new Transaction();
  368. $cart->setDate(new DateTime());
  369. $cart->setCart(true);
  370. $cart->setConfirmed(false);
  371. $cart->setPrestataire($prestataire);
  372. $em->persist($cart);
  373. }
  374. $cart->addDemande($demande);
  375. $em->flush();
  376. $this->addflash(Flashes::SUCCESS, 'La demande a bien été ajoutée à votre panier.');
  377. return $this->redirectToRoute('presta_cart');
  378. }
  379. public function denied(Request $request, FlashBag $flashBag)
  380. {
  381. $this->addFlash('error', 'Mauvais identifiants.');
  382. return $this->redirect($this->generateUrl('presta_access'));
  383. }
  384. public function failure()
  385. {
  386. return new Response('Login failure');
  387. }
  388. public function removeLogo(Request $request)
  389. {
  390. $prestataire = $this->getPrestataire();
  391. $logoPath = $this->getParameter('kernel.project_dir') . '/public/'.
  392. $this->getParameter('prestataire_files_path').'/'.
  393. $prestataire->getLogoPath();
  394. $prestataire->setLogoPath(null);
  395. $this->getEM()->flush();
  396. if (file_exists($logoPath) && is_file($logoPath)) {
  397. unlink($logoPath);
  398. }
  399. $this->addFlash(Flashes::SUCCESS, 'Le logo a bien été supprimé.');
  400. return $this->redirectToRoute('presta_index');
  401. }
  402. public function buyDemande(Request $request, $id)
  403. {
  404. /** @var Demande $demande */
  405. $demande = $this->getDemandeRepository()->find($id);
  406. if (!$demande) {
  407. $this->addFlash(Flashes::ERROR, 'La demande de devis n°'. $id .' a expiré.');
  408. return $this->throw404();
  409. }
  410. $prestataire = $this->getPrestataire();
  411. if ($this->getDemandeRepository()->isBoughtBy($demande, $prestataire)) {
  412. // bought already, redirect
  413. return $this->getUrlGenerator()->redirectTo($demande);
  414. }
  415. if ($request->getMethod() === 'POST') {
  416. switch ($request->get('action')) {
  417. case 'stripe':
  418. return $this->redirectToRoute('stripe_demande', ['id' => $demande->getId()]);
  419. case 'direct':
  420. return $this->redirectToRoute('paypal_demande', ['id' => $demande->getId()]);
  421. case 'cart':
  422. return $this->actionAddToCart($demande, $prestataire);
  423. case 'use_credits':
  424. return $this->actionBuyWithCredits($demande, $prestataire);
  425. case 'achat_credits':
  426. $this->getSession()->set('achat_credits_redirect', $this->generateUrl('presta_buy_demande', array('id' => $demande->getId())));
  427. return $this->redirectToRoute('presta_buy_credits');
  428. }
  429. }
  430. /** @var CreditPackRepository $packRepo */
  431. $packRepo = $this->getEM()->getRepository(CreditPack::class);
  432. $minPricePack = $packRepo->getMinPricePack();
  433. /** @var TransactionRepository $transactionRepo */
  434. $transactionRepo = $this->getEM()->getRepository(Transaction::class);
  435. $isInCart = $transactionRepo->isInCart($demande->getId(), $prestataire->getId());
  436. return $this->render('Presta/buy_demande.html.twig', array(
  437. 'demande' => $demande,
  438. 'prestataire' => $prestataire,
  439. 'minPricePack' => $minPricePack,
  440. 'isInCart' => $isInCart,
  441. ));
  442. }
  443. /**
  444. * @param Demande $demande
  445. * @param Prestataire $prestataire
  446. *
  447. * @return RedirectResponse
  448. */
  449. private function actionBuyWithCredits(Demande $demande, Prestataire $prestataire)
  450. {
  451. if ($prestataire->getCredits() < $demande->getCredits()) {
  452. $this->addFlash(Flashes::ERROR, "Vous n'avez pas suffisamment de crédits pour acheter ce contact.");
  453. return $this->redirectToRoute('presta_buy_demande', array('id' => $demande->getId()));
  454. }
  455. $em = $this->getEM();
  456. $em->beginTransaction();
  457. $transaction = new Transaction();
  458. $transaction->setDate(new DateTime());
  459. $transaction->setPrestataire($prestataire);
  460. $transaction->setPrix(null);
  461. $transaction->setCredits($demande->getCredits());
  462. $transaction->setConfirmed(true);
  463. $transaction->addDemande($demande);
  464. $prestataire->removeCredits($demande->getCredits());
  465. $em->persist($transaction);
  466. $em->flush();
  467. $this->removeFromPrestaCart($demande, $prestataire);
  468. $em->commit();
  469. $this->addFlash(Flashes::SUCCESS, 'Vous avez maintenant accès aux coordonnées du contact.');
  470. return $this->getUrlGenerator()->redirectTo($demande);
  471. }
  472. public function refund(Request $request)
  473. {
  474. $prestataire = $this->getPrestataire();
  475. $refundRequest = new RefundRequest();
  476. $refundRequest->setPrestataire($prestataire);
  477. if ($request->get('id')) {
  478. /** @var Demande $demande */
  479. $demande = $this->getDemandeRepository()->find($request->get('id'));
  480. if ($demande) {
  481. if ($demande->getRefundRequest($prestataire->getId())) {
  482. $this->addFlash(Flashes::WARNING, 'Vous avez déjà demandé une recréditation pour cette demande.');
  483. return $this->redirectToRoute('presta_transactions');
  484. }
  485. $refundRequest->setDemande($demande);
  486. }
  487. }
  488. $refundForm = $this->createForm(RefundType::class, $refundRequest);
  489. if ($request->getMethod() === 'POST') {
  490. $refundForm->handleRequest($request);
  491. if ($refundForm->isValid()) {
  492. $refundRequest = $refundForm->getData();
  493. $em = $this->getEM();
  494. $em->beginTransaction();
  495. $em->persist($refundRequest);
  496. $em->flush();
  497. // notify admin with request and link to presta page
  498. // $mail = new Mail();
  499. // $mail
  500. // ->setFromEmail($this->getParameter('email_from'))
  501. // ->setFromName($this->getParameter('name_from'))
  502. // ->setToEmail($this->getParameter('admin_email'))
  503. // ->setSubject('Nouvelle demande de recréditation')
  504. // ->setContent($this->render('Email/refund_request.html.twig', ['request' => $refundRequest]))
  505. // ->setStatus('new');
  506. // $this->getEM()->persist($mail);
  507. // $this->getEM()->flush();
  508. $email = (new TemplatedEmail())
  509. ->from(new Address($this->getParameter('email_from'), $this->getParameter('name_from')))
  510. ->to(new Address($this->getParameter('admin_email')))
  511. ->subject('Nouvelle demande de recréditation')
  512. ->htmlTemplate('Email/refund_request.html.twig')
  513. ->context(
  514. [
  515. 'request' => $refundRequest,
  516. ]
  517. );
  518. $this->getMailer()->send($email);
  519. $em->commit();
  520. $this->addFlash(Flashes::SUCCESS, 'Votre demande de recréditation a bien été envoyée.');
  521. return $this->redirectToRoute('presta_transactions');
  522. }
  523. }
  524. return $this->render('Presta/refund.html.twig', array(
  525. 'refund_form' => $refundForm->createView()
  526. ));
  527. }
  528. public function cart(Request $request)
  529. {
  530. $prestataire = $this->getPrestataire();
  531. /** @var TransactionRepository $repo */
  532. $repo = $this->getEM()->getRepository(Transaction::class);
  533. $cart = $repo->getCart($prestataire->getId());
  534. // Request for remove cart
  535. if ($request->getMethod() === 'POST') {
  536. if ($request->request->has('remove')) {
  537. $demande = $this->getDemandeRepository()->find($request->get('remove')['id']);
  538. if ($demande) {
  539. $cart->removeDemande($demande);
  540. $this->getEM()->flush();
  541. return $this->redirectToRoute('presta_cart');
  542. }
  543. }
  544. }
  545. return $this->render('Presta/cart.html.twig', array(
  546. 'cart' => $cart,
  547. 'prix' => $this->getCartPrix($cart),
  548. 'minPricePack' => $this->getMinPricePack()
  549. ));
  550. }
  551. private function getMinPricePack()
  552. {
  553. /** @var CreditPackRepository $packRepo */
  554. $packRepo = $this->getEM()->getRepository(CreditPack::class);
  555. return $packRepo->getMinPricePack();
  556. }
  557. public function buyCart(Request $request)
  558. {
  559. $prestataire = $this->getPrestataire();
  560. /** @var TransactionRepository $repo */
  561. $repo = $this->getEM()->getRepository(Transaction::class);
  562. $cart = $repo->getCart($prestataire->getId());
  563. if (!$cart || !$cart->getDemandes()) {
  564. return $this->redirectToRoute('presta_cart');
  565. }
  566. if ($request->getMethod() === 'POST') {
  567. switch ($request->get('action')) {
  568. case 'stripe':
  569. return $this->redirectToRoute('stripe_cart');
  570. case 'use_credits':
  571. return $this->actionBuyCartWithCredits($cart);
  572. case 'achat_credits':
  573. $this->getSession()->set('achat_credits_redirect', $this->generateUrl('presta_buy_cart'));
  574. return $this->redirectToRoute('presta_buy_credits');
  575. }
  576. }
  577. return $this->render('Presta/buy_cart.html.twig', array(
  578. 'cart' => $cart,
  579. 'prix' => $this->getCartPrix($cart),
  580. 'credits' => $this->getCartCredits($cart),
  581. 'minPricePack' => $this->getMinPricePack(),
  582. 'prestataire' => $prestataire
  583. ));
  584. }
  585. /**
  586. * @param Transaction $cart
  587. */
  588. private function actionBuyCartWithCredits($cart)
  589. {
  590. $cart->setCredits($this->getCartCredits($cart));
  591. if ($cart->getPrestataire()->getCredits() < $cart->getCredits()) {
  592. $this->addFlash(Flashes::ERROR, "Vous n'avez pas suffisamment de crédits pour acheter ce panier.");
  593. return $this->redirectToRoute('presta_buy_cart');
  594. }
  595. $cart->setDate(new DateTime());
  596. $cart->setPrix(null);
  597. $cart->setConfirmed(true);
  598. $cart->setCart(false);
  599. $cart->getPrestataire()->removeCredits($cart->getCredits());
  600. $this->getEM()->flush();
  601. $this->addFlash(Flashes::SUCCESS, 'Vous avez maintenant accès aux coordonnées des contacts achetés.');
  602. return $this->redirectToRoute('presta_transactions');
  603. }
  604. public function requestReset(Request $request)
  605. {
  606. $form = $this->createForm(ResetRequestType::class, new User());
  607. if ($request->getMethod() === 'POST') {
  608. $form->handleRequest($request);
  609. $email = $form->getData()->getEmail();
  610. /** @var User $user */
  611. $user = $this->getEM()->getRepository(User::class)->findOneBy(array(
  612. 'email' => strtolower($email)
  613. ));
  614. if ($user) {
  615. $user->setResetCode($token = substr("abcdefghijklmnopqrstuvwxyz", mt_rand(0, 25), 1).substr(md5(time()), 1));
  616. $this->getEM()->flush();
  617. // send email
  618. // $mail = new Mail();
  619. // $mail
  620. // ->setFromEmail($this->getParameter('email_from'))
  621. // ->setFromName($this->getParameter('name_from'))
  622. // ->setToEmail($user->getEmail())
  623. // ->setToName($user->getPrestataire() ? $user->getPrestataire()->getNom() : '')
  624. // ->setSubject($this->getOption('request_reset_message_subject'))
  625. // ->setContent($this->render('Email/request_reset.html.twig', ['token' => $token]))
  626. // ->setStatus('new');
  627. // $this->getEM()->persist($mail);
  628. // $this->getEM()->flush();
  629. if ($user->getPrestataire() && $user->getPrestataire()->getNom()):
  630. $name = $user->getPrestataire()->getNom();
  631. endif;
  632. $email = (new TemplatedEmail())
  633. ->from(new Address($this->getParameter('email_from'), $this->getParameter('name_from')))
  634. ->to(new Address($user->getEmail(), $name ?? ""))
  635. ->subject($this->getOption('request_reset_message_subject'))
  636. ->htmlTemplate('Email/request_reset.html.twig')
  637. ->context([
  638. 'token' => $token,
  639. ])
  640. ;
  641. $this->getMailer()->send($email);
  642. }
  643. $this->addFlash(Flashes::SUCCESS, 'Si votre adresse email a été trouvée, un message contenant un lien de réinitialisation vous a été envoyé.');
  644. return $this->redirectToRoute('presta_access');
  645. }
  646. return $this->render('User/request_reset.html.twig', array(
  647. 'request_form' => $form->createView()
  648. ));
  649. }
  650. public function reset(Request $request, $token, UserPasswordHasherInterface $passwordHasher)
  651. {
  652. $user = $this->getUserRepository()->findOneBy(['resetCode' => $token]);
  653. if (!$user) {
  654. $this->addFlash(Flashes::ERROR, "Le code fourni n'est pas valide.");
  655. return $this->redirectToRoute('presta_access');
  656. }
  657. if ($request->getMethod() === 'POST') {
  658. $user->setPassword($passwordHasher->hashPassword($user, $request->get('password')));
  659. $user->setResetCode(null);
  660. $this->getEM()->flush();
  661. if ($user->isEnabled()) {
  662. // authenticate
  663. $token = new UsernamePasswordToken($user, null, $user->isAdmin() ? 'admin' : 'presta', $user->getRoles());
  664. $this->tokenStorage->setToken($token);
  665. $this->getSession()->set('_security_main', serialize($token));
  666. }
  667. $this->addFlash(Flashes::SUCCESS, 'Votre mot de passe a bien été modifié.');
  668. $route = $user->isAdmin() ? 'admin_index' : 'presta_index';
  669. return $this->redirectToRoute($route);
  670. }
  671. // if invalid code, redirect on request_reset with flash
  672. return $this->render('User/reset.html.twig', array(
  673. 'user' => $user
  674. ));
  675. }
  676. public function invoice($number)
  677. {
  678. /** @var Transaction $transaction */
  679. $transaction = $this->getTransactionRepository()->findOneBy(array(
  680. 'invoiceNumber' => $number
  681. ));
  682. if (!$transaction) {
  683. return $this->throw404();
  684. }
  685. $output = $this->getInvoicePdfContent($transaction);
  686. $name = $transaction->getInvoiceFilename();
  687. $response = new Response($output);
  688. $response->headers->set('Cache-Control', 'private');
  689. $response->headers->set('Content-Type', 'application/pdf');
  690. $response->headers->set('Content-Disposition', 'attachment; filename="'. $name .'";');
  691. $response->headers->set('Content-Length', strlen($output));
  692. return $response;
  693. }
  694. private function getInvoicePdfContent(Transaction $transaction)
  695. {
  696. $content = $this->renderView('Protected/invoice.html.twig', array(
  697. 'from' => $this->getOption('invoice_from'),
  698. 'to' => $transaction->getPrestataire(),
  699. 'transaction' => $transaction,
  700. 'footer' => $this->getOption('invoice_footer')
  701. ));
  702. /** @var HTML2PDF $pdf */
  703. $pdf = new Html2Pdf();
  704. $pdf->pdf->SetDisplayMode('fullpage');
  705. $pdf->writeHTML($content);
  706. return $pdf->Output($transaction->getInvoiceFilename(), 'S');
  707. }
  708. }