src/Controller/Admin/VistoriaController.php line 363

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Admin;
  3. use App\Entity\Imoveis;
  4. use App\Form\ClientType;
  5. use App\Form\VistoryType;
  6. use App\Service\AlogliaHelper;
  7. use App\Service\MailService;
  8. use App\Utils\Slugger;
  9. use Dompdf\Dompdf;
  10. use Dompdf\Options;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\File\UploadedFile;
  13. use Symfony\Component\HttpFoundation\JsonResponse;
  14. use Symfony\Component\HttpFoundation\RequestStack;
  15. use Symfony\Component\HttpFoundation\UrlHelper;
  16. use Symfony\Component\Mime\Address;
  17. use Symfony\Component\Mime\NamedAddress;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\Mailer\MailerInterface;
  21. use Symfony\Component\Mime\Email;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  23. /**
  24.  * @Route("/admin/clientes/vistoria")
  25.  * @IsGranted("ROLE_ADMIN" ,"ROLE_OPERATOR")
  26.  */
  27. class VistoriaController extends AbstractController
  28. {
  29.     protected $urlHelper;
  30.     public $algoliaIndex;
  31.     public function __construct(UrlHelper $urlHelperMailService $mailer)
  32.     {
  33.         $this->urlHelper $urlHelper;
  34.         $this->mailer $mailer;
  35.         $algolia = new AlogliaHelper();
  36.         $this->algoliaIndex $algolia->client->initIndex('vistorias');
  37.     }
  38.     /**
  39.      * @Route("/lista/{id}", methods={"GET"}, name="admin_vistoria_list")
  40.      */
  41.     public function list_vistoria($id)
  42.     {
  43.         $em $this->getDoctrine()->getManager();
  44.         $imovel $em->getRepository(Imoveis::class)->findtoArray($id);
  45.         $cliente $imovel;
  46.         $vistorias $this->algoliaIndex->search('',[
  47.             'facetFilters' => [
  48.                 "client_id:".$id,
  49.             ],
  50.             'hitsPerPage' => 1000
  51.         ])['hits'];
  52.         return $this->render('admin/vistoria/edit.html.twig', [
  53.             'cliente' => $cliente,
  54.             'vistorias' => $vistorias
  55.         ]);
  56.     }
  57.     /**
  58.      * @Route("/novo/{id}", methods={"GET","POST"}, name="admin_vistoria_new")
  59.      */
  60.     public function new_vistoria(Request $request$id)
  61.     {
  62.         $em $this->getDoctrine()->getManager();
  63.         $imovel $em->getRepository(Imoveis::class)->findtoArray($id);
  64.         $cliente $imovel;
  65.         $form $this->createForm(VistoryType::class, []);
  66.         $form->handleRequest($request);
  67.         if ($form->isSubmitted() && $form->isValid()) {
  68.             $vistoria $request->request->all()['vistory'];
  69.             unset($vistoria['_token']);
  70.             $vistoria['client_id'] = $id;
  71.             $vistoria['checkin'] = \DateTime::createFromFormat('d/m/Y H:i'$vistoria['checkin'])->format('Y-m-d H:i');
  72.             $vistoria['checkout'] = \DateTime::createFromFormat('d/m/Y H:i'$vistoria['checkout'])->format('Y-m-d H:i');
  73.             $this->algoliaIndex->saveObjects([$vistoria],['autoGenerateObjectIDIfNotExist' => true])->wait();
  74.             $this->addFlash('success''Registro incluído com sucesso!');
  75.             return $this->redirectToRoute('admin_vistoria_list',['id' => $id]);
  76.         }
  77.         return $this->render('admin/vistoria/new.html.twig', [
  78.             'form' => $form->createView(),
  79.             'cliente' => $cliente
  80.         ]);
  81.     }
  82.     /**
  83.      * @Route("/editar/{id}", methods={"GET","POST"}, name="admin_vistoria_edit")
  84.      */
  85.     public function edit_vistoria(Request $request$id)
  86.     {
  87.         $algolia self::getChecklist($id);
  88.         $vistory $algolia['data'];
  89.         $vistory['checkin'] = \DateTime::createFromFormat('Y-m-d H:i'$vistory['checkin'])->format('d/m/Y H:i');
  90.         $vistory['checkout'] = \DateTime::createFromFormat('Y-m-d H:i'$vistory['checkout'])->format('d/m/Y H:i');
  91.         $em $this->getDoctrine()->getManager();
  92.         $imovel $em->getRepository(Imoveis::class)->findtoArray($vistory['client_id']);
  93.         $cliente $imovel;
  94.         $form $this->createForm(VistoryType::class, $vistory);
  95.         $form->handleRequest($request);
  96.         if ($form->isSubmitted() && $form->isValid()) {
  97.             $vistoria $request->request->all()['vistory'];
  98.             unset($vistoria['_token']);
  99.             $vistoria['checkin'] = \DateTime::createFromFormat('d/m/Y H:i'$vistoria['checkin'])->format('Y-m-d H:i');
  100.             $vistoria['checkout'] = \DateTime::createFromFormat('d/m/Y H:i'$vistoria['checkout'])->format('Y-m-d H:i');
  101.             $this->algoliaIndex->saveObjects([$vistoria],['autoGenerateObjectIDIfNotExist' => true])->wait();
  102.             $this->addFlash('success''Alteração realizada com sucesso!');
  103.             return $this->redirectToRoute('admin_vistoria_list',['id' => $vistory['client_id']]);
  104.         }
  105.         return $this->render('admin/vistoria/new.html.twig', [
  106.             'form' => $form->createView(),
  107.             'cliente' => $cliente,
  108.             'edit' => true
  109.         ]);
  110.     }
  111.     /**
  112.      * @Route("/checkin/{id}", methods={"GET","POST"}, name="admin_vistoria_checkin")
  113.      */
  114.     public function checkin_vistoria(Request $request$id)
  115.     {
  116.         $algolia self::getChecklist($id);
  117.         $vistory $algolia['data'];
  118.         $vistoryOriginal $vistory;
  119.         $vistory['checkin'] = \DateTime::createFromFormat('Y-m-d H:i'$vistory['checkin'])->format('d/m/Y H:i');
  120.         $vistory['checkout'] = \DateTime::createFromFormat('Y-m-d H:i'$vistory['checkout'])->format('d/m/Y H:i');
  121.         $em $this->getDoctrine()->getManager();
  122.         $imovel $em->getRepository(Imoveis::class)->findtoArray($vistory['client_id']);
  123.         $cliente $imovel;
  124.         $vistoriaData $request->request->all();
  125.         $updated=false;
  126.         if($vistoriaData){
  127.             $vistoryOriginal['vistoria_checkin'] = $vistoriaData['dados'];
  128.             $date = new \DateTime();
  129.             $vistoryOriginal['ultima_alteracao'] = $date->format('Y-m-d H:i:s');
  130.             $vistoryOriginal['usuario_ultima_alteracao'] = $this->getUser()->getFullname();
  131.             unset($vistoryOriginal['_highlightResult']);
  132.             $vistory['vistoria_checkin'] = $vistoriaData['dados'];
  133.             $vistory['ultima_alteracao'] = $date->format('Y-m-d H:i:s');
  134.             $vistory['usuario_ultima_alteracao'] = $this->getUser()->getFullname();
  135.             $this->algoliaIndex->saveObjects([$vistoryOriginal]);
  136.             $this->addFlash('success''Alteração realizada com sucesso!');
  137.             $updated=true;
  138.         }
  139.         $checkin_itens=[];
  140.         foreach ($vistory['vistoria_checkin'] as $cat=>$sub) {
  141.             foreach ($sub as $subCat=>$item) {
  142.                 if ($item['condicao'] || $item['observacoes'] || $item['fotos']) {
  143.                     $item['fotos'] = $item['fotos'] ? explode(','$item['fotos']) : [];
  144.                     $checkin_itens[$cat][$subCat] = $item;
  145.                 }
  146.             }
  147.         }
  148.         return $this->render('admin/vistoria/checkin.html.twig', [
  149.             'cliente' => $cliente,
  150.             'vistory' => $vistory,
  151.             'itens_checked' => $checkin_itens,
  152.             'itens_check' => self::getConferenceCheckin(),
  153.             'updated' => $updated
  154.         ]);
  155.     }
  156.     /**
  157.      * @Route("/checkout/{id}", methods={"GET","POST"}, name="admin_vistoria_checkout")
  158.      */
  159.     public function checkout_vistoria(Request $request$id)
  160.     {
  161.         $algolia self::getChecklist($id);
  162.         $vistory $algolia['data'];
  163.         $vistoryOriginal $vistory;
  164.         $vistory['checkin'] = \DateTime::createFromFormat('Y-m-d H:i'$vistory['checkin'])->format('d/m/Y H:i');
  165.         $vistory['checkout'] = \DateTime::createFromFormat('Y-m-d H:i'$vistory['checkout'])->format('d/m/Y H:i');
  166.         $em $this->getDoctrine()->getManager();
  167.         $imovel $em->getRepository(Imoveis::class)->findtoArray($vistory['client_id']);
  168.         $cliente $imovel;
  169.         $updated=false;
  170.         $vistoriaData $request->request->all();
  171.         if($vistoriaData){
  172.             $vistoryOriginal['vistoria_checkout'] = $vistoriaData['dados'];
  173.             unset($vistoryOriginal['_highlightResult']);
  174.             $date = new \DateTime();
  175.             $vistory['vistoria_checkout'] = $vistoriaData['dados'];
  176.             $vistory['ultima_alteracao'] = $date->format('Y-m-d H:i:s');
  177.             $vistory['usuario_ultima_alteracao'] = $this->getUser()->getFullname();
  178.             $vistoryOriginal['ultima_alteracao'] = $date->format('Y-m-d H:i:s');
  179.             $vistoryOriginal['usuario_ultima_alteracao'] = $this->getUser()->getFullname();
  180.             $this->algoliaIndex->saveObjects([$vistoryOriginal]);
  181.             $this->addFlash('success''Alteração realizada com sucesso!');
  182.             $updated=true;
  183.         }
  184.         $checkout_itens=[];
  185.         foreach ($vistory['vistoria_checkout'] as $cat=>$sub) {
  186.             foreach ($sub as $subCat=>$item) {
  187.                 if ($item['condicao'] || $item['observacoes'] || $item['fotos']) {
  188.                     $item['fotos'] = $item['fotos'] ? explode(','$item['fotos']) : [];
  189.                     $checkout_itens[$cat][$subCat] = $item;
  190.                 }
  191.             }
  192.         }
  193.         return $this->render('admin/vistoria/checkout.html.twig', [
  194.             'cliente' => $cliente,
  195.             'vistory' => $vistory,
  196.             'itens_checked' => $checkout_itens,
  197.             'itens_check' => self::getConferenceCheckout(),
  198.             'updated' => $updated
  199.         ]);
  200.     }
  201.     protected function generate_pdf($type,$id,$with_fotos=1,$output='browser'){
  202.         ini_set('memory_limit',-1);
  203.         $algolia self::getChecklist($id);
  204.         $vistory $algolia['data'];
  205.         $vistory['checkin'] = \DateTime::createFromFormat('Y-m-d H:i'$vistory['checkin'])->format('d/m/Y H:i');
  206.         $vistory['checkout'] = \DateTime::createFromFormat('Y-m-d H:i'$vistory['checkout'])->format('d/m/Y H:i');
  207.         $em $this->getDoctrine()->getManager();
  208.         $imovel $em->getRepository(Imoveis::class)->findtoArray($vistory['client_id']);
  209.         $cliente $imovel;
  210.         $checkin_itens=[];
  211.         $loop $type=='check-in''vistoria_checkin''vistoria_checkout';
  212.         foreach ($vistory[$loop] as $cat=>$sub) {
  213.             foreach ($sub as $subCat=>$item) {
  214.                 if ($item['condicao'] || $item['observacoes'] || $item['fotos']) {
  215.                     $item['fotos'] = $item['fotos'] ? explode(','$item['fotos']) : [];
  216.                     $checkin_itens[$cat][$subCat] = $item;
  217.                 }
  218.             }
  219.         }
  220.         $vistory['vistoria_itens'] = $checkin_itens;
  221.         unset($vistory['_highlightResult']);
  222.         ini_set('memory_limit''256M');
  223.         $pdfOptions = new Options();
  224.         $pdfOptions->setIsRemoteEnabled(true);
  225.         $dompdf = new Dompdf($pdfOptions);
  226.         if($_GET['html']){
  227.             return $this->render('admin/vistoria/pdf.html.twig', [
  228.                 'cliente' => $cliente,
  229.                 'edited' => $vistory,
  230.                 'type' => $type,
  231.                 'com_fotos' => $with_fotos
  232.             ]);
  233.         }
  234.         $html $this->renderView('admin/vistoria/pdf.html.twig', [
  235.             'cliente' => $cliente,
  236.             'edited' => $vistory,
  237.             'type' => $type,
  238.             'com_fotos' => $with_fotos
  239.         ]);
  240.         $dompdf->loadHtml($html);
  241.         $dompdf->setPaper('A4''portrait');
  242.         $dompdf->render();
  243.         if($output=='browser') {
  244.             return $dompdf->stream($type "_" $id ".pdf", [
  245.                 "Attachment" => false
  246.             ]);
  247.         }
  248.         if($output=='file'){
  249.             $file_path "/tmp/".$type."_".$id.".pdf";
  250.             $file_output $dompdf->output();
  251.             file_put_contents($file_path$file_output);
  252.             return $file_path;
  253.         }
  254.     }
  255.     /**
  256.      * @Route("/comunica-email/{type}/{id}", methods={"GET"}, name="admin_vistoria_email")
  257.      */
  258.     public function pdf_email($type,$id)
  259.     {
  260.         $with_photos 1// gera sempre com fotos para enviar no e-mail
  261.         $algolia self::getChecklist($id);
  262.         $vistory $algolia['data'];
  263.         $vistory['checkin'] = \DateTime::createFromFormat('Y-m-d H:i'$vistory['checkin'])->format('d/m/Y');
  264.         $vistory['checkout'] = \DateTime::createFromFormat('Y-m-d H:i'$vistory['checkout'])->format('d/m/Y');
  265.         $em $this->getDoctrine()->getManager();
  266.         $imovel $em->getRepository(Imoveis::class)->findtoArray($vistory['client_id']);
  267.         $cliente $imovel;
  268.         $cliente['data_evento'] = $vistory[str_replace('-','',$type)];
  269.         $pdf_path =$this->generate_pdf($type,$id,$with_photos,'file');
  270.         $error=false;
  271.         try{
  272.             $this->send_mail($cliente,$type,$pdf_path);
  273.         }
  274.         catch (\Exception $e){
  275.             $error=true;
  276.         }
  277.         return new JsonResponse(['error'=>$error]);
  278.     }
  279.     /**
  280.      * @Route("/pdf/{type}/{id}", methods={"GET"}, name="admin_vistoria_pdf")
  281.      */
  282.     public function pdf($type$id){
  283.         return $this->generate_pdf($type,$id,$_GET['com_fotos']);
  284.     }
  285.     protected function send_mail($cliente$type$pdf_path)
  286.     {
  287.         $message '<style>
  288.                             @import url(\'https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap\');
  289.                         </style>
  290.                         <table style="width: 500px; text-align: center; font-family: \'Roboto\', sans-serif;">
  291.                             <tr>
  292.                                 <td style="height: 100px; background: linear-gradient(188.93deg, #FFFFFF 0%, #E2DFFF 0.01%, #FFFFFF 105.25%);">
  293.                                     <img src="https://admin.bnbguests.com.br/imgs/logo-email.png">
  294.                                 </td>
  295.                             </tr>
  296.                             <tr>
  297.                                 <td style="padding-top: 20px; text-align: left;">
  298.                                     <p>Olá, '.$cliente['nome'].'.</p>
  299.                                     <p>Atualizamos as informações de '.$type.' ('.$cliente['data_evento'].') do seu imóvel em '.$cliente['endereco'].'.</p>
  300.                                     <p>Segue anexo para conhecimento.</p>
  301.                                     <p>Att,<br>Equipe bnbguests</p>
  302.                                     <p style="color: #cccccc"><i>*Não responda este e-mail*</i></p>
  303.                                 </td>
  304.                             </tr>
  305.                         </table>';
  306.         $cc = ['suporte@bnbguests.com.br'];
  307.         $this->mailer->sendMail($cliente['email'],"Atualização de $type - bnbguests",$message,$cc,$pdf_path);
  308.     }
  309.     public static function getConferenceCheckin(){
  310.         return[
  311.             'QUARTOS E SALAS' => [
  312.               "Limpeza piso",
  313.               "Limpeza Janelas/portas",
  314.               "Bancadas e pia",
  315.               "Papel higiênico",
  316.               "Limpeza de Piso e de Ralo",
  317.               "Espelho e box",
  318.             ],
  319.             'COZINHA' => [
  320.               "Geladeira",
  321.               "Microondas",
  322.               "Fogão",
  323.               "Bancadas e pisos",
  324.               "Móveis",
  325.               "Eletrodomésticos",
  326.               "Limpeza (detergente, bucha, pano de prato e pano de pia)",
  327.               "Alimentos básicos (café, sal, açucar, óleo)",
  328.             ],
  329.             "FUNCIONAMENTO" => [
  330.               "Ar condicionado",
  331.               "Internet",
  332.               "Piscina (aquecimento, limpeza, etc)",
  333.             ],
  334.             "HOTELARIA" => [
  335.                 "Toalhas- dobrar como hotel",
  336.                 "Toalhas- 1 toalha de banho por hóspede",
  337.                 "Toalhas- 1 toalha de rosto por banheiro",
  338.                 "Roupa de cama- verificar se tem manchas ou sujo",
  339.                 "Tapete de banheiro- 1 por banheiro",
  340.                 "Ligar gás aquecimento chuveiro",
  341.                 "Chocolate de boas vindas + recado",
  342.             ],
  343.             "OUTROS" => [
  344.                 "Qualaquer área que não esteja pré-definida"
  345.             ]
  346.         ];
  347.     }
  348.     public static function getConferenceCheckout(){
  349.         return[
  350.             "GERAL" => [
  351.                 "Objetos esquecidos pelo hóspede",
  352.                 "Objeto quebrado",
  353.                 "Eletrodomésticos e utensílios de cozinha",
  354.                 "Controles de TV",
  355.                 "Controles de ar condicionado",
  356.                 "Toalhas ",
  357.                 "Roupas de cama ",
  358.                 "Secador de cabelo",
  359.                 "Som",
  360.                 "Objetos de decoração",
  361.                 "Gás (botijão cheio)",
  362.                 "Capas de colchão e de travesseiro (se estiver suja, tirar pra lavar)",
  363.                 "Ligar e desligar (luzes, cafeteira, ar condicionado, tv, geladeira, microondas)",
  364.                 "Recolher móveis da área externa (redes, almofadas, móveis) ",
  365.                 "Conferir internet",
  366.                 "Outros"
  367.             ]
  368.         ];
  369.     }
  370.     /**
  371.      * @Route("/nova-foto", methods={"POST"}, name="admin_vistoria_nova_foto")
  372.      */
  373.     public function upload_image(Request $request){
  374.         try {
  375.             $file $request->files->get('file');
  376.             /** @var $file UploadedFile */
  377.             $id $request->request->get('id');
  378.             $dir __DIR__ '/../../../public/uploads/vistoria/' $id '/';
  379.             $newName time() . '_' $file->getClientOriginalName();
  380.             if ($file->move($dir$newName)) {
  381.                 return new JsonResponse([
  382.                     'url' => $this->urlHelper->getAbsoluteUrl(
  383.                         $this->generateUrl('fotos', [
  384.                             'indice' => 'vistoria',
  385.                             'object_id' => $id,
  386.                             'foto' => $newName
  387.                         ])
  388.                     )
  389.                 ]);
  390.             }
  391.         }
  392.         catch(\Exception $e){
  393.             return new JsonResponse([
  394.                 'error' => $e->getMessage()
  395.             ]);
  396.         }
  397.     }
  398.     public static function getChecklist($id){
  399.         $algolia = new AlogliaHelper();
  400.         $index $algolia->client->initIndex('vistorias');
  401.         $data $index->search('',[
  402.             'facetFilters' => [
  403.                 "objectID:".$id,
  404.             ],
  405.             'hitsPerPage' => 1
  406.         ]);
  407.         return [
  408.             'index' => $index,
  409.             'data' => $data['hits'][0]
  410.         ];
  411.     }
  412. }