src/Controller/FrontendController.php line 424

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Service\ServiceSTMP;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use App\Service\UtilsTablesDataBase;
  8. use App\Service\Utils;
  9. use Doctrine\Persistence\ManagerRegistry;
  10. use Symfony\Component\HttpFoundation\JsonResponse;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  13. use Symfony\Component\String\Slugger\AsciiSlugger;
  14. use Dompdf\Dompdf;
  15. class FrontendController extends AbstractController
  16. {
  17. /**
  18. * @Route("/frontend", name="frontend")
  19. */
  20. public function index(): Response
  21. {
  22. return $this->render('frontend/index.html.twig');
  23. }
  24. /**
  25. * @Route("/frontend/preview-document-firmar",
  26. * name="preview_document_firmar")
  27. */
  28. public function previewDocumentFirmar(Request $request, ManagerRegistry $managerRegistry, UtilsTablesDataBase $utilsTablesDataBase, Utils $utils)
  29. {
  30. $oEm = $managerRegistry->getManager();
  31. $oUser = $this->getUser();
  32. $docFinal = '';
  33. $btoken = $request->request->get('tokendoc');
  34. $btype = $request->request->get('btype');
  35. $btabla = $request->request->get('btabla');
  36. $bentityId = $request->request->get('bentityid');
  37. $bclienteId = $request->request->get('bclienteid');
  38. $bdocclienteId = $request->request->get('bdoc');
  39. $token = $utils->base64_url_decode($btoken);
  40. $type = $utils->base64_url_decode($btype);
  41. $tabla = $utils->base64_url_decode($btabla);
  42. $entityId = $utils->base64_url_decode($bentityId);
  43. $clienteId = $utils->base64_url_decode($bclienteId);
  44. $docclienteId = $utils->base64_url_decode($bdocclienteId);
  45. $oDocumentos = $oEm->getRepository('App\Entity\Documentos')
  46. ->getDocumentos();
  47. $oDocumentoClientes = $oEm->getRepository('App\Entity\DocumentosClientes')
  48. ->findOneBy(['id' => $docclienteId]);
  49. $is_signed = $oDocumentoClientes->isIsSigned();
  50. $slugger = new AsciiSlugger();
  51. $docId = 0;
  52. $docFinal = "";
  53. $fields = explode(":", $token);
  54. if (isset($fields[0])) {
  55. $docId = $fields[0];
  56. }
  57. /*if (!empty($oDocumentos)) {
  58. foreach ($oDocumentos as $oDocumento) {
  59. $docname = $oDocumento->getNombre();
  60. $docname = $slugger->slug($docname)->lower();
  61. $docname .= ".pdf";
  62. $documentoId = $oDocumento->getId();
  63. $dockey = $documentoId.":".$docname;
  64. $hashed = hash("sha512", $dockey);
  65. if ($hashed == $token){
  66. $docId = $documentoId;
  67. break;
  68. }
  69. }
  70. } */
  71. //$emailsCliente = $utilsTablesDataBase->getDestinatarioEmails($type, $tabla, $entityId);
  72. //$contenido = $this->generateDocument($request, $managerRegistry,$utilsTablesDataBase, $oEmpresa, $type, $tabla, $entityId);
  73. $mensaje = "En la parte inferior de la pantalla puede firmar este documento";
  74. if ($is_signed) {
  75. $mensaje = "El documento ha sido firmado con anterioridad";
  76. }
  77. $datos = [
  78. 'is_front' => true,
  79. 'ruta_doc' => $docFinal,
  80. 'type' => $type,
  81. 'tabla' => $tabla,
  82. 'entityId' => $entityId,
  83. 'clienteId' => $clienteId,
  84. 'documentoId' => $docId,
  85. 'documentoClienteId' => $docclienteId,
  86. 'is_signed' => $is_signed,
  87. 'mensaje' => $mensaje
  88. ];
  89. return $this->render('documentos/modal-content-preview-doc-firmar.html.twig', $datos);
  90. }
  91. /**
  92. * @Route("/frontend/generadocument",
  93. * name="frontend_generadocument")
  94. */
  95. public function generateDocument(Request $request, ManagerRegistry $managerRegistry, UtilsTablesDataBase $utilsTablesDataBase)
  96. {
  97. $oEm = $managerRegistry->getManager();
  98. $oUser = $this->getUser();
  99. $oEmpresa = '';
  100. if (!empty($oUser) && !in_array('ROLE_SUPER_ADMIN', $oUser->getRoles())) {
  101. $oEmpresa = $oUser->getEmpresa();
  102. }
  103. $type = $request->request->get('type');
  104. $tabla = $request->request->get('tabla');
  105. $entityId = $request->request->get('entityid');
  106. $documentoId = $request->request->get('documentoid');
  107. $documentoClienteId = $request->request->get('documentoClienteId');
  108. $oDocumento = $oEm->getRepository('App\Entity\Documentos')
  109. ->findOneBy(['id' => $documentoId]);
  110. if (!is_null($oDocumento->getEmpresa()) && $oEmpresa == '') {
  111. $oEmpresa = $oDocumento->getEmpresa();
  112. }
  113. $host = $request->getHost();
  114. /*$contenido = $utilsTablesDataBase->generateDocument($oEmpresa,$type,$documentoId,$tabla, $entityId, null, $host);
  115. $dompdf = new Dompdf();
  116. $dompdf->set_option('isRemoteEnabled', TRUE);
  117. $dompdf->loadHtml($contenido);
  118. // (Optional) Setup the paper size and orientation
  119. if ($oDocumento->getOrientacion() == 'horizontal'){
  120. $dompdf->setPaper('A4', 'landscape');
  121. }
  122. else{
  123. $dompdf->setPaper('A4');
  124. }
  125. // Render the HTML as PDF
  126. $dompdf->render();
  127. // Output the generated PDF to Browser
  128. $file_content = $dompdf->output(); //$dompdf->stream();*/
  129. $rutapublic = $this->getParameter('kernel.project_dir') . '/public/';
  130. $rutapdf = $rutapublic;
  131. $oDocumentosClientes = $oEm->getRepository('App\Entity\DocumentosClientes')
  132. ->findOneBy(['id' => $documentoClienteId]);
  133. $rutapdf .= $oDocumentosClientes->getUrl();
  134. $file_content = file_get_contents($rutapdf);
  135. $status = false;
  136. $message = '';
  137. return new Response($file_content,
  138. 200,
  139. );
  140. }
  141. /**
  142. * @Route("/frontent/documento_ajax_save_firma", name="frontend_documento_ajax_save_firma")
  143. */
  144. public function saveFirma(Request $request, ManagerRegistry $managerRegistry, UtilsTablesDataBase $utilsTablesDataBase)
  145. {
  146. $rutapdf = "documentos/clientes/";
  147. $isSecure = $request->isSecure();
  148. $oEm = $managerRegistry->getManager();
  149. $status = false;
  150. $message = '';
  151. $oUser = $this->getUser();
  152. $documentoIdResponse = '';
  153. $oEmpresa = '';
  154. if (!empty($oUser) && !in_array('ROLE_SUPER_ADMIN', $oUser->getRoles())) {
  155. $oEmpresa = $oUser->getEmpresa();
  156. }
  157. try {
  158. $type = $request->request->get('type');
  159. $tabla = $request->request->get('tabla');
  160. $entityId = $request->request->get('entityid');
  161. $documentoId = $request->request->get('documentoid');
  162. $clienteId = $request->request->get('clienteid'); //destinatario email
  163. $imageb64 = $request->request->get('imageb64');
  164. $documentoClienteId = $request->request->get('documentoClienteId');
  165. $cid = $request->request->get('cid');
  166. if (!empty($cid)) {
  167. $clienteId = $cid;
  168. }
  169. $documentName = "";
  170. $oDocumento = $oEm->getRepository('App\Entity\Documentos')
  171. ->findOneBy(['id' => $documentoId]);
  172. if (!empty($oDocumento)) {
  173. $documentName = $oDocumento->getNombre();
  174. }
  175. $did = "";
  176. $rutapdf = "documentos/clientes/";
  177. if ($tabla == 'animales') {
  178. $rutapdf = "documentos/animales/";
  179. $oAnimalesPropietarios = $oEm->getRepository('App\Entity\AnimalesClientes')
  180. ->findBy(['animales' => $entityId]);
  181. $did = $entityId;
  182. foreach ($oAnimalesPropietarios as $animalesPropietario) {
  183. if (!is_null($animalesPropietario->getClientes())) {
  184. if (!$animalesPropietario->getIsDeleted()) {
  185. $cliente = $animalesPropietario->getClientes();
  186. $clienteId = $cliente->getId();
  187. $clienteName = $cliente->getNombreCompleto();
  188. break;
  189. }
  190. }
  191. }
  192. } else if ($tabla == "clientes") {
  193. $did = $entityId;
  194. if (!empty($oCliente)) {
  195. $clienteName = $oCliente->getNombreCompleto();
  196. }
  197. } else if ($tabla == "visitas_tratamiento" || $tabla == "visitas") {
  198. $infoVisitas = $utilsTablesDataBase->infoVisitasData($entityId);
  199. $animalId = $infoVisitas['animal_id'];
  200. $oAnimalesPropietarios = $oEm->getRepository('App\Entity\AnimalesClientes')
  201. ->findBy(['animales' => $animalId]);
  202. foreach ($oAnimalesPropietarios as $animalesPropietario) {
  203. if (!is_null($animalesPropietario->getClientes())) {
  204. if (!$animalesPropietario->getIsDeleted()) {
  205. $cliente = $animalesPropietario->getClientes();
  206. $clienteId = $cliente->getId();
  207. $clienteName = $cliente->getNombreCompleto();
  208. break;
  209. }
  210. }
  211. }
  212. $did = $entityId;
  213. } else if ($tabla == "receta_individual") {
  214. $infoRecetas = $utilsTablesDataBase->infoRecetasData($entityId);
  215. $animalId = $infoRecetas['animal_id'];
  216. $oAnimalesPropietarios = $oEm->getRepository('App\Entity\AnimalesClientes')
  217. ->findBy(['animales' => $animalId]);
  218. foreach ($oAnimalesPropietarios as $animalesPropietario) {
  219. if (!is_null($animalesPropietario->getClientes())) {
  220. if (!$animalesPropietario->getIsDeleted()) {
  221. $cliente = $animalesPropietario->getClientes();
  222. $clienteId = $cliente->getId();
  223. $clienteName = $cliente->getNombreCompleto();
  224. break;
  225. }
  226. }
  227. }
  228. $did = $entityId;
  229. } else if ($tabla == "presupuesto") {
  230. $clienteId = $utilsTablesDataBase->getDataColumnTable("presupuesto", "cliente_id", $entityId);
  231. $did = $utilsTablesDataBase->getDataColumnTable("presupuesto", "numero_presupuesto", $entityId);
  232. $oCliente = $oEm->getRepository('App\Entity\Clientes')
  233. ->findOneBy(['id' => $clienteId]);
  234. if (!empty($oCliente)) {
  235. $clienteName = $oCliente->getNombreCompleto();
  236. }
  237. } else if ($tabla == "albaran_venta") {
  238. $dname = strtoupper($documentName);
  239. $isFactura = false;
  240. if (stripos($dname, "factura") !== FALSE) {
  241. $isFactura = true;
  242. }
  243. $clienteId = $utilsTablesDataBase->getDataColumnTable("albaran_venta", "cliente_id", $entityId);
  244. $propietarioId = $utilsTablesDataBase->getDataColumnTable("albaran_venta", "propietario_id", $entityId);
  245. if (!empty($clienteId)) {
  246. $oCliente = $oEm->getRepository('App\Entity\Clientes')
  247. ->findOneBy(['id' => $clienteId]);
  248. } else if (!empty($propietarioId)) {
  249. $oCliente = $oEm->getRepository('App\Entity\Clientes')
  250. ->findOneBy(['id' => $propietarioId]);
  251. $clienteId = $propietarioId;
  252. }
  253. if (!empty($oCliente)) {
  254. $clienteName = $oCliente->getNombreCompleto();
  255. }
  256. $oAlbaran = $oEm->getRepository('App\Entity\AlbaranVenta')->findOneBy(['id' => $entityId]);
  257. $did = "";
  258. if (!empty($oAlbaran)) {
  259. if (!empty($oAlbaran->getNumeroFactura())) {
  260. $did = $oAlbaran->getNumeroFactura();
  261. } else {
  262. $did = $oAlbaran->getNumeroAlbaran();
  263. }
  264. }
  265. $did = str_replace('/', '-', $did);
  266. }
  267. $nombreFinal = $did . "-" . $documentName . ".pdf";
  268. if (!empty($clienteName)) {
  269. $nombreFinal = $did . "-" . $documentName . "-" . $clienteName . ".pdf";
  270. }
  271. $nombreFinal = trim($nombreFinal, "-");
  272. if (empty($documentoClienteId)) {
  273. $oAnimal = null;
  274. $oDocumento = $oEm->getRepository('App\Entity\Documentos')
  275. ->findOneBy(['id' => $documentoId]);
  276. $oCliente = $oEm->getRepository('App\Entity\Clientes')
  277. ->findOneBy(['id' => $clienteId]);
  278. $oDocumentoClientes = new \App\Entity\DocumentosClientes();
  279. $oDocumentoClientes->setClientes($oCliente);
  280. $oDocumentoClientes->setDocumentos($oDocumento);
  281. $oDocumentoClientes->setAnimales($oAnimal);
  282. $oDocumentoClientes->setUrl("");
  283. $oDocumentoClientes->setIsActive(true);
  284. $oDocumentoClientes->setIsDeleted(false);
  285. $oDocumentoClientes->setIsSigned(false);
  286. $oDocumentoClientes->setIsSend(true);
  287. $oDocumentoClientes->setFechaSend(new \DateTime('now'));
  288. $oDocumentoClientes->setFechaActualizacion(new \DateTime('now'));
  289. $oDocumentoClientes->setFechaCreacion(new \DateTime('now'));
  290. $oDocumentoClientes->setFechaSigned(null);
  291. $oEm->persist($oDocumentoClientes);
  292. $oEm->flush();
  293. $documentoClienteId = $oDocumentoClientes->getId();
  294. }
  295. if (!empty($documentoId) && !empty($documentoClienteId)) {
  296. $oDocumento = $oEm->getRepository('App\Entity\Documentos')
  297. ->findOneBy(['id' => $documentoId]);
  298. if (!empty($oDocumento->getEmpresa())) {
  299. $oEmpresa = $oDocumento->getEmpresa();
  300. }
  301. $filename = $nombreFinal;//$oDocumento->getNombre().".pdf";
  302. $host = $request->getHost();
  303. $rutapublic = $this->getParameter('kernel.project_dir') . '/public/';
  304. $contenido = $utilsTablesDataBase->generateDocument($oEmpresa, $type, $documentoId, $tabla, $entityId, null, $host, false, $rutapublic,0,$isSecure);
  305. $contenido = $utilsTablesDataBase->replaceFirma($contenido, $imageb64);
  306. $dompdf = new Dompdf();
  307. $dompdf->set_option('isRemoteEnabled', TRUE);
  308. $dompdf->loadHtml($contenido);
  309. if ($oDocumento->getOrientacion() == 'horizontal') {
  310. $dompdf->setPaper('A4', 'landscape');
  311. } else {
  312. $dompdf->setPaper('A4');
  313. }
  314. if ($tabla == 'animales') {
  315. $rutapdf = "documentos/animales/";
  316. $rutapdf .= "$entityId";
  317. } else {
  318. $rutapdf .= "$clienteId";
  319. }
  320. if (!file_exists($rutapdf)) {
  321. mkdir($rutapdf, 0755, true);
  322. }
  323. $rutapdf .= "/$filename";
  324. // (Optional) Setup the paper size and orientation
  325. if ($oDocumento->getOrientacion() == 'horizontal') {
  326. $dompdf->setPaper('A4', 'landscape');
  327. } else {
  328. $dompdf->setPaper('A4');
  329. }
  330. // Render the HTML as PDF
  331. $dompdf->render();
  332. //
  333. $file_content = $dompdf->output();
  334. @unlink($rutapdf);//borrar documento sin firmar
  335. file_put_contents($rutapdf, $file_content);
  336. $oDocumentoClientes = $oEm->getRepository('App\Entity\DocumentosClientes')
  337. ->findOneBy(['id' => $documentoClienteId]);
  338. $oDocumentoClientes->setUrl($rutapdf);
  339. $oDocumentoClientes->setIsSigned(true);
  340. $oDocumentoClientes->setFechaActualizacion(new \DateTime('now'));
  341. $oDocumentoClientes->setFechaSigned(new \DateTime('now'));
  342. $oEm->persist($oDocumentoClientes);
  343. $oEm->flush();
  344. }
  345. $status = true;
  346. $message = 'Documento guardado correctamente';
  347. } catch (\Exception $exception) {
  348. $status = false;
  349. $message = $exception->getMessage();
  350. }
  351. return new JsonResponse(['status' => $status, 'message' => $message, 'documentoId' => $documentoIdResponse]);
  352. }
  353. /**
  354. * @Route("/restart-password", name="restart_password")
  355. */
  356. public function restartPassword(Request $request, ManagerRegistry $managerRegistry)
  357. {
  358. return $this->render('security/restart-password.html.twig');
  359. }
  360. /**
  361. * @Route("/validated-send-password", name="validated_send_password")
  362. */
  363. public function validatedSendPassword(Request $request, ManagerRegistry $managerRegistry, Utils $utils, ServiceSTMP $serviceSTMP)
  364. {
  365. $oEm = $managerRegistry->getManager();
  366. $status = false;
  367. $message = '';
  368. try {
  369. $email = $request->request->get('email');
  370. $userName = $request->request->get('username');
  371. $oUser = $oEm->getRepository('App\Entity\User')
  372. ->findOneBy(['email' => $email, 'username' => $userName]);
  373. if (is_null($oUser)) {
  374. return new JsonResponse(['status' => false,
  375. 'message' => 'El email y el username que has introducido no existe en el sistema']);
  376. }
  377. $fechaActual = new \DateTime(); // Obtiene la fecha y hora actual
  378. $fechaActual->add(new \DateInterval("PT1H"));
  379. $token = $utils->generateToken();
  380. $oUser->setTokenValidation($token);
  381. $oUser->setDateTokenValidation($fechaActual);
  382. $oEm->persist($oUser);
  383. $oEm->flush();
  384. $host = $request->getHost();
  385. $urlRestartPassword = "https://" . $host . $this->generateUrl('validated_restart_password', ['token' => $token]);
  386. $contentEmail = $this->renderView('templates-emails/restart-password.html.twig', ['reset_url' => $urlRestartPassword]);
  387. $aEmailSend[] = $oUser->getEmail();
  388. $aSendEmail = $serviceSTMP->sendEmailPlatform($aEmailSend, $contentEmail, 'Restablecer contraseña');
  389. if (!$aSendEmail['status']) {
  390. return new JsonResponse(['status' => $aSendEmail['status'], 'message' => $aSendEmail['message']]);
  391. }
  392. $status = true;
  393. $message = 'Se ha enviado al correo eléctronico los paso a realizar para restablecer la contraseña';
  394. } catch (\Exception $exception) {
  395. $status = false;
  396. $message = $exception->getMessage();
  397. }
  398. return new JsonResponse(['status' => $status, 'message' => $message]);
  399. }
  400. /**
  401. * @Route("/validated-restart-password/{token}", name="validated_restart_password")
  402. */
  403. public function validatedRestartPassword(Request $request, ManagerRegistry $managerRegistry, $token = '')
  404. {
  405. $oEm = $managerRegistry->getManager();
  406. $fechaActual = new \DateTime();
  407. $estado = 0;
  408. $oUser = $oEm->getRepository('App\Entity\User')
  409. ->findOneBy(['tokenValidation' => $token]);
  410. if (is_null($oUser)) {
  411. $estado = 1; //No existe ningun usuario con este token
  412. } else if ($fechaActual > $oUser->getDateTokenValidation()) {
  413. $estado = 2; //Enlace no ha expirado
  414. }
  415. $datos = [
  416. 'estado' => $estado,
  417. 'tokenValidation' => $oUser->getTokenValidation()
  418. ];
  419. return $this->render('security/change-password.html.twig', $datos);
  420. }
  421. /**
  422. * @Route("/change-password", name="change_password")
  423. */
  424. public function changePassword(Request $request, ManagerRegistry $managerRegistry, UserPasswordEncoderInterface $encoder)
  425. {
  426. $oEm = $managerRegistry->getManager();
  427. $status = false;
  428. $message = '';
  429. try {
  430. $token = $request->request->get('token');
  431. $password = $request->request->get('password');
  432. $oUser = $oEm->getRepository('App\Entity\User')
  433. ->findOneBy(['tokenValidation' => $token]);
  434. if (is_null($oUser)) {
  435. return new JsonResponse(['status' => false, 'message' => 'Usuario no existe']);
  436. }
  437. $encodePassword = $encoder->encodePassword($oUser, $password);
  438. $oUser->setPassword($encodePassword);
  439. $oUser->setFechaActualizacion(new \DateTime('now'));
  440. $oUser->setDateTokenValidation(null);
  441. $oUser->setTokenValidation(null);
  442. $oEm->persist($oUser);
  443. $oEm->flush();
  444. $status = true;
  445. $message = 'Contraseña modificada correctamente';
  446. } catch (\Exception $exception) {
  447. $status = false;
  448. $message = $exception->getMessage();
  449. }
  450. return new JsonResponse(['status' => $status, 'message' => $message]);
  451. }
  452. }