src/Controller/Front/FormController.php line 88

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Front;
  3. use App\Controller\Core\BaseFrontController;
  4. use App\Entity\FormClaim;
  5. use App\Entity\FormContact;
  6. use App\Entity\FormQuotation;
  7. use App\Entity\Forms;
  8. use App\Form\Front\FormClaimType;
  9. use App\Form\Front\FormContactType;
  10. use App\Form\Front\FormQuotationType;
  11. use App\Manager\ContactManager;
  12. use App\Manager\FormClaimManager;
  13. use App\Manager\FormContactManager;
  14. use App\Manager\FormQuotationManager;
  15. use App\Manager\FormsManager;
  16. use App\Manager\QuotationManager;
  17. use App\Service\CRM\ApiCRM;
  18. use App\Service\Mail\ClaimMail;
  19. use App\Service\Mail\ContactMail;
  20. use App\Service\Mail\QuotationMail;
  21. use App\Service\Recaptcha\Validator as RecaptchaValidator;
  22. use App\Traits\FormFileTrait;
  23. use DateInterval;
  24. use DateTime;
  25. use Psr\Log\LoggerInterface;
  26. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  27. use Symfony\Component\HttpFoundation\RedirectResponse;
  28. use Symfony\Component\HttpFoundation\Request;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\Routing\Annotation\Route;
  31. class FormController extends BaseFrontController
  32. {
  33.     use FormFileTrait;
  34.     const FORM_CONTACT 'sd_form_contact_entity';
  35.     const FORM_QUOTATION 'sd_form_quotation_entity';
  36.     const FORM_CLAIM 'sd_form_claim_entity';
  37.     /**
  38.      * @Route("/contacto", name="contact", methods={"GET"})
  39.      * @Template("front/form/contact.html.twig")
  40.      */
  41.     public function contact(ContactManager $contactManager): array
  42.     {
  43.         $entity $this->getFormSession(self::FORM_CONTACT, new FormContact());
  44.         $form $this->getFormView(FormContactType::class, $entity'contact_action');
  45.         $this->locals['sd'] = $contactManager->find(1);
  46.         $this->locals['form'] = $form;
  47.         return $this->locals;
  48.     }
  49.     /**
  50.      * @Route("/contacto", name="contact_action", methods={"POST"})
  51.      */
  52.     public function contactAction(Request $requestFormContactManager $managerContactMail $mailApiCRM $apiCRMRecaptchaValidator $recaptchaValidator): RedirectResponse
  53.     {
  54.         $entity = new FormContact();
  55.         $form $this->getForm(FormContactType::class, $entity'contact_action');
  56.         $form->handleRequest($request);
  57.         if ($form->isValid() and $recaptchaValidator->validate($this->getRecaptchaToken(), $this->getClientIp())) {
  58.             $manager->save($entity);
  59.             //$mail->load($entity)->send();
  60.             $crmLead $entity->leadToCRM();
  61.             $result $apiCRM->send($crmLead);
  62.             $entity->setCrmBody($crmLead->toCRM());
  63.             $entity->setCrmResult($result);
  64.             $manager->save($entity);
  65.             return $this->redirectToRoute('thanks_slug', ['slug' => 'contacto']);
  66.         }
  67.         $this->saveFormSession(self::FORM_CONTACT$entity);
  68.         return $this->redirectToRoute('contact');
  69.     }
  70.     /**
  71.      * @Route("/cotizar", name="quotation", methods={"GET"})
  72.      * @Template("front/form/quotation.html.twig")
  73.      */
  74.     public function quotation(QuotationManager $quotationManager): array
  75.     {
  76.         $entity $this->getFormSession(self::FORM_QUOTATION, new FormQuotation());
  77.         $form $this->getFormView(FormQuotationType::class, $entity'quotation_action');
  78.         $this->locals['sd'] = $quotationManager->find(1);
  79.         $this->locals['form'] = $form;
  80.         return $this->locals;
  81.     }
  82.     /**
  83.      * @Route("/cotizar", name="quotation_action", methods={"POST"})
  84.      */
  85.     public function quotationAction(Request $requestFormQuotationManager $managerQuotationMail $mailApiCRM $apiCRMRecaptchaValidator $recaptchaValidator): RedirectResponse
  86.     {
  87.         $entity = new FormQuotation();
  88.         $form $this->getForm(FormQuotationType::class, $entity'quotation_action');
  89.         $form->handleRequest($request);
  90.         if ($form->isValid() and $recaptchaValidator->validate($this->getRecaptchaToken(), $this->getClientIp())) {
  91.             $manager->save($entity);
  92.             //$mail->load($entity)->send();
  93.             $crmLead $entity->leadToCRM();
  94.             $result $apiCRM->send($crmLead);
  95.             $entity->setCrmBody($crmLead->toCRM());
  96.             $entity->setCrmResult($result);
  97.             $manager->save($entity);
  98.             return $this->redirectToRoute('thanks_slug', ['slug' => 'cotizar']);
  99.         }
  100.         $this->saveFormSession(self::FORM_QUOTATION$entity);
  101.         return $this->redirectToRoute('quotation');
  102.     }
  103.     /**
  104.      * @Route("/libro-de-reclamaciones", name="claim", methods={"GET"})
  105.      * @Template("front/form/claim.html.twig")
  106.      */
  107.     public function claim(FormClaimManager $formClaimManagerFormsManager $formsManager): array
  108.     {
  109.         /** @var Forms $forms */
  110.         $forms $formsManager->find(1);
  111.         $responseDays = (int)$forms->getClaimResponseDays();
  112.         try {
  113.             $this->locals['answer_date'] = (new DateTime())->add(new DateInterval('P' $responseDays 'D'));
  114.         } catch (\Exception $exception) {
  115.             $this->locals['answer_date'] = new DateTime();
  116.         }
  117.         $entity = new FormClaim();
  118.         $code $this->generateCode($formClaimManager->lastCode());
  119.         $entity->setCode($code);
  120.         $entity $this->getFormSession(self::FORM_CLAIM$entity);
  121.         $form $this->getFormView(FormClaimType::class, $entity'claim_action');
  122.         $this->locals['form'] = $form;
  123.         $this->locals['entity'] = $entity;
  124.         return $this->locals;
  125.     }
  126.     /**
  127.      * @Route("/libro-de-reclamaciones", name="claim_action", methods={"POST"})
  128.      */
  129.     public function claimAction(Request $requestFormClaimManager $managerClaimMail $mailRecaptchaValidator $recaptchaValidator): RedirectResponse
  130.     {
  131.         $entity = new FormClaim();
  132.         $form $this->getForm(FormClaimType::class, $entity'claim_action');
  133.         $entity->setFile(null);
  134.         if ($request->files->get('form_file')) {
  135.             $file $this->saveFile($request->files->get('form_file'), 10000000,'reclamos');
  136.             $entity->setFile($file);
  137.         }
  138.         $code $this->generateCode($manager->lastCode());
  139.         $entity->setCode($code);
  140.         $form->handleRequest($request);
  141.         $firmaFromRequest $request->request->get('form')['firma'] ?? null;
  142.         if ($firmaFromRequest) {
  143.             $entity->setFirma($firmaFromRequest);
  144.         }
  145.         if ($form->isValid()) {
  146.             $entity->setSaved(true);
  147.             $entity->setUniq(bin2hex(random_bytes(16)));
  148.             $manager->save($entity);
  149.             $mail->load($entity)->send();
  150.             $mail->loadClient($entity)->send();
  151.             $this->saveFormSession(self::FORM_CLAIM$entity);
  152.             $this->requestStack->getSession()->remove('sd_claim_code');
  153.             return $this->redirectToRoute('thanks_claim', ['uniq' => $entity->getUniq()]);
  154.         }
  155.         $this->saveFormSession(self::FORM_CLAIM$entity);
  156.         return $this->redirectToRoute('claim');
  157.     }
  158.     /**
  159.      * @Route("/libro-de-reclamaciones/pdf/{uniq}", name="claim_pdf", methods={"GET"})
  160.      */
  161.     public function claimPdf(string $uniqFormClaimManager $formClaimManagerFormsManager $formsManager): Response
  162.     {
  163.         $claim $formClaimManager->findOneBy(['uniq' => $uniq]);
  164.         if (!$claim) {
  165.             throw $this->createNotFoundException('Reclamo no encontrado');
  166.         }
  167.         $forms $formsManager->find(1);
  168.         $html $this->renderView('front/pdf/claim_pdf.html.twig', [
  169.             'claim' => $claim,
  170.             'forms' => $forms,
  171.             'company_name' => $forms->getClaimCompanyName(),
  172.             'company_ruc' => $forms->getClaimCompanyRuc(),
  173.             'company_address' => $forms->getClaimCompanyAddress(),
  174.         ]);
  175.         // Si es PDF, generar con mPDF
  176.         if (!isset($_GET['html'])) {
  177.             $mpdf = new \Mpdf\Mpdf([
  178.                 'mode' => 'utf-8',
  179.                 'format' => 'A4',
  180.                 'margin_top' => 0,
  181.                 'margin_bottom' => 10,
  182.                 'allow_base64_images' => true,
  183.                 'img_dpi' => 96,
  184.             ]);
  185.             $mpdf->WriteHTML($html);
  186.             return new Response($mpdf->Output('libro_reclamaciones_' $claim->getCode() . '.pdf''I'));
  187.         }
  188.         // Si es HTML, mostrar directamente
  189.         return new Response($html);
  190.     }
  191.     /**
  192.      * @Route("/libro-de-reclamaciones/pdf-preview/{uniq}", name="claim_pdf_preview_html", methods={"GET"})
  193.      */
  194.     public function claimPdfPreviewHtml(string $uniqFormClaimManager $formClaimManagerFormsManager $formsManager): Response
  195.     {
  196.         $claim $formClaimManager->findOneBy(['uniq' => $uniq]);
  197.         if (!$claim) {
  198.             throw $this->createNotFoundException('Reclamo no encontrado');
  199.         }
  200.         $forms $formsManager->find(1);
  201.         $html $this->renderView('front/pdf/claim_pdf.html.twig', [
  202.             'claim' => $claim,
  203.             'forms' => $forms,
  204.             'company_name' => $forms->getClaimCompanyName(),
  205.             'company_ruc' => $forms->getClaimCompanyRuc(),
  206.             'company_address' => $forms->getClaimCompanyAddress(),
  207.         ]);
  208.         return new Response($html);
  209.     }
  210.     /**
  211.      * @Route("/admin-preview/pdf", name="claim_pdf_preview", methods={"GET"})
  212.      */
  213.     public function previewClaimPdf(FormsManager $formsManager): Response
  214.     {
  215.         $forms $formsManager->find(1);
  216.         $claim $this->createMockClaim();
  217.         $claim->setCurrency('Soles');
  218.         $html $this->renderView('front/pdf/claim_pdf.html.twig', [
  219.             'claim' => $claim,
  220.             'forms' => $forms,
  221.             'company_name' => $forms->getClaimCompanyName(),
  222.             'company_ruc' => $forms->getClaimCompanyRuc(),
  223.             'company_address' => $forms->getClaimCompanyAddress(),
  224.         ]);
  225.         $mpdf = new \Mpdf\Mpdf([
  226.             'mode' => 'utf-8',
  227.             'format' => 'A4',
  228.             'margin_top' => 0,
  229.             'margin_bottom' => 10,
  230.             'allow_base64_images' => true,
  231.             'img_dpi' => 96,
  232.         ]);
  233.         $mpdf->WriteHTML($html);
  234.         $response = new Response();
  235.         $response->setContent($mpdf->Output('preview-libro-reclamaciones.pdf''S'));
  236.         $response->headers->set('Content-Type''application/pdf');
  237.         $response->headers->set('Content-Disposition''inline; filename="preview-libro-reclamaciones.pdf"');
  238.         return $response;
  239.     }
  240.     /**
  241.      * @Route("/admin-preview/gracias", name="preview_gracias", methods={"GET"})
  242.      */
  243.     public function previewGracias(FormsManager $formsManager): Response
  244.     {
  245.         $forms $formsManager->find(1);
  246.         $claim $this->createMockClaim();
  247.         $pdfUrl $this->generateUrl('claim_pdf_preview');
  248.         return $this->render('front/preview/preview-gracias.html.twig', [
  249.             'forms' => $forms,
  250.             'claim' => $claim,
  251.             'pdf_url' => $pdfUrl,
  252.         ]);
  253.     }
  254.     /**
  255.      * @Route("/admin-preview/email", name="preview_email", methods={"GET"})
  256.      */
  257.     public function previewEmail(FormsManager $formsManager): Response
  258.     {
  259.         $forms $formsManager->find(1);
  260.         $claim $this->createMockClaim();
  261.         $nombre trim($claim->getName() . ' ' $claim->getLastname());
  262.         $emailTitulo $forms->getEmailTitulo();
  263.         $emailTitulo $emailTitulo str_replace('%nombre%'$nombre$emailTitulo) : $emailTitulo;
  264.         return $this->render('front/preview/preview-email.html.twig', [
  265.             'forms' => $forms,
  266.             'claim' => $claim,
  267.             'emailTitulo' => $emailTitulo,
  268.         ]);
  269.     }
  270.     private function createMockClaim(): FormClaim
  271.     {
  272.         $claim = new FormClaim();
  273.         $claim->setCode('R' date('Y') . date('m') . '-000001');
  274.         $claim->setUniq('preview-claim-test');
  275.         $claim->setName('Juan');
  276.         $claim->setLastname('Pérez García');
  277.         $claim->setApellidoMaterno('García');
  278.         $claim->setEmail('juan.perez@ejemplo.com');
  279.         $claim->setPhone('987654321');
  280.         $claim->setDocumentType('DNI');
  281.         $claim->setDocumentNumber('12345678');
  282.         $claim->setDepartment('Lima');
  283.         $claim->setProvince('Lima');
  284.         $claim->setDistrict('Miraflores');
  285.         $claim->setAddress('Av. Arequipa 1234');
  286.         $claim->setEstablishment('Tienda Principal');
  287.         $claim->setGood('Camión UD');
  288.         $claim->setDescription('Motor con ruido anormal');
  289.         $claim->setType('Reclamo');
  290.         $claim->setDetail('El motor presenta ruidos anormales desde hace una semana');
  291.         $claim->setDemand('Reparación gratuita del motor');
  292.         $claim->setAuthorization('Email');
  293.         $claim->setSaved(true);
  294.         return $claim;
  295.     }
  296.     public function generateCode($lastCode): string
  297.     {
  298.         $id $this->lastCodeId($lastCode);
  299.         return 'R' date('Y') . date('m') . '-' str_pad((string)($id 1), 6'0'STR_PAD_LEFT);
  300.     }
  301.     public function lastCodeId($lastCode): int
  302.     {
  303.         $code $this->lastCode($lastCode);
  304.         $array explode('-'$code);
  305.         return count($array) == ? (int)$array[1] : 0;
  306.     }
  307.     public function lastCode($lastCode): string
  308.     {
  309.         $code $lastCode;
  310.         return is_null($code) ? 'R' date('Y') . date('m') . '-' '100000' $code;
  311.     }
  312. }